List of usage examples for org.w3c.dom Document getElementsByTagNameNS
public NodeList getElementsByTagNameNS(String namespaceURI, String localName);
NodeList
of all the Elements
with a given local name and namespace URI in document order. From source file:cz.muni.fi.mir.mathmlunificator.utils.DOMBuilderTest.java
@Test public void testCreateNewDocWithNodeClone() { try {/*from w w w .ja va 2s . co m*/ String xmlString = "<math xmlns:uni=\"http://mir.fi.muni.cz/mathml-unification/\"\n" + " uni:unification-level=\"2\" uni:unification-max-level=\"4\" xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" + " <msup>\n" + " <mi>a</mi>\n" + " <mi>b</mi>\n" + " </msup>\n" + " <mo>+</mo>\n" + " <mfrac>\n" + " <mi>c</mi>\n" + " <mi>d</mi>\n" + " </mfrac>\n" + "</math>"; Document originalDoc = DOMBuilder.buildDoc(xmlString); Document doc = DOMBuilder.buildDoc(xmlString); // deep == true NodeList deepNodeList = doc.getElementsByTagNameNS("http://www.w3.org/1998/Math/MathML", "mo"); assertEquals(deepNodeList.getLength(), 1); Node deepNode = deepNodeList.item(0); Document newDeepDoc = DOMBuilder.createNewDocWithNodeClone(deepNode, true); System.out.println( "testCreateNewDocWithNodeClone deep output:\n" + XMLOut.xmlStringSerializer(newDeepDoc)); testXML("Deep clonning failed", DOMBuilder.buildDoc("<mo xmlns=\"http://www.w3.org/1998/Math/MathML\">+</mo>"), newDeepDoc); newDeepDoc.getDocumentElement().setTextContent("deep different content"); System.out.println("testCreateNewDocWithNodeClone input document DOM after deep processing:\n" + XMLOut.xmlStringSerializer(doc)); testXML("Original document DOM changed after processing", originalDoc, doc); // deep == false NodeList noDeepNodeList = doc.getElementsByTagNameNS("http://www.w3.org/1998/Math/MathML", "mfrac"); assertEquals(noDeepNodeList.getLength(), 1); Node noDeepNode = noDeepNodeList.item(0); Document newNoDeepDoc = DOMBuilder.createNewDocWithNodeClone(noDeepNode, false); System.out.println("testCreateNewDocWithNodeClone non-deep output:\n" + XMLOut.xmlStringSerializer(newNoDeepDoc)); testXML("Non-deep clonning failed", DOMBuilder.buildDoc("<mfrac xmlns=\"http://www.w3.org/1998/Math/MathML\"/>"), newNoDeepDoc); newNoDeepDoc.getDocumentElement().setTextContent("non-deep different content"); System.out.println("testCreateNewDocWithNodeClone input document DOM after non-deep processing:\n" + XMLOut.xmlStringSerializer(doc)); testXML("Original document DOM changed after processing", originalDoc, doc); } catch (ParserConfigurationException | SAXException | IOException ex) { fail(ex.getMessage()); } }
From source file:cz.muni.fi.mir.mathmlunificator.utils.DOMBuilderTest.java
@Test public void testCloneNodeToNewDoc() { try {//from w w w. java2 s. c om String xmlString = "<math xmlns:uni=\"http://mir.fi.muni.cz/mathml-unification/\"\n" + " uni:unification-level=\"2\" uni:unification-max-level=\"4\" xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" + " <msup>\n" + " <mi>a</mi>\n" + " <mi>b</mi>\n" + " </msup>\n" + " <mo>+</mo>\n" + " <mfrac>\n" + " <mi>c</mi>\n" + " <mi>d</mi>\n" + " </mfrac>\n" + "</math>"; Document originalDoc = DOMBuilder.buildDoc(xmlString); Document doc = DOMBuilder.buildDoc(xmlString); // deep == true NodeList deepNodeList = doc.getElementsByTagNameNS("http://www.w3.org/1998/Math/MathML", "mo"); assertEquals(deepNodeList.getLength(), 1); Node deepNode = deepNodeList.item(0); Node newDeepNode = DOMBuilder.cloneNodeToNewDoc(deepNode, true); System.out.println("testCloneNodeToNewDoc deep output:\n" + XMLOut.xmlStringSerializer(newDeepNode.getOwnerDocument())); testXML("Deep clonning failed", DOMBuilder.buildDoc("<mo xmlns=\"http://www.w3.org/1998/Math/MathML\">+</mo>"), newDeepNode.getOwnerDocument()); newDeepNode.setTextContent("deep different content"); System.out.println("testCloneNodeToNewDoc input document DOM after non-deep processing:\n" + XMLOut.xmlStringSerializer(doc)); testXML("Original document DOM changed after processing", originalDoc, doc); // deep == false NodeList noDeepNodeList = doc.getElementsByTagNameNS("http://www.w3.org/1998/Math/MathML", "mfrac"); assertEquals(noDeepNodeList.getLength(), 1); Node noDeepNode = noDeepNodeList.item(0); Node newNoDeepNode = DOMBuilder.cloneNodeToNewDoc(noDeepNode, false); System.out.println("testCloneNodeToNewDoc non-deep output:\n" + XMLOut.xmlStringSerializer(newNoDeepNode.getOwnerDocument())); testXML("Non-deep clonning failed", DOMBuilder.buildDoc("<mfrac xmlns=\"http://www.w3.org/1998/Math/MathML\"/>"), newNoDeepNode.getOwnerDocument()); newNoDeepNode.setTextContent("non-deep different content"); System.out.println("testCloneNodeToNewDoc input document DOM after non-deep processing:\n" + XMLOut.xmlStringSerializer(doc)); testXML("Original document DOM changed after processing", originalDoc, doc); } catch (ParserConfigurationException | SAXException | IOException ex) { fail(ex.getMessage()); } }
From source file:be.fedict.eid.dss.document.asic.ASiCDSSDocumentService.java
@Override public List<SignatureInfo> verifySignatures(byte[] document, byte[] originalDocument) throws Exception { if (null != originalDocument) { throw new IllegalArgumentException("cannot perform original document verifications"); }// w ww . ja v a2 s. c o m ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(document)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (ASiCUtil.isSignatureZipEntry(zipEntry)) { break; } } List<SignatureInfo> signatureInfos = new LinkedList<SignatureInfo>(); if (null == zipEntry) { return signatureInfos; } XAdESValidation xadesValidation = new XAdESValidation(this.documentContext); Document documentSignaturesDocument = ODFUtil.loadDocument(zipInputStream); NodeList signatureNodeList = documentSignaturesDocument.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); for (int idx = 0; idx < signatureNodeList.getLength(); idx++) { Element signatureElement = (Element) signatureNodeList.item(idx); xadesValidation.prepareDocument(signatureElement); KeyInfoKeySelector keySelector = new KeyInfoKeySelector(); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); ASiCURIDereferencer dereferencer = new ASiCURIDereferencer(document); domValidateContext.setURIDereferencer(dereferencer); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance(); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean valid = xmlSignature.validate(domValidateContext); if (!valid) { continue; } // check whether all files have been signed properly SignedInfo signedInfo = xmlSignature.getSignedInfo(); @SuppressWarnings("unchecked") List<Reference> references = signedInfo.getReferences(); Set<String> referenceUris = new HashSet<String>(); for (Reference reference : references) { String referenceUri = reference.getURI(); referenceUris.add(URLDecoder.decode(referenceUri, "UTF-8")); } zipInputStream = new ZipInputStream(new ByteArrayInputStream(document)); while (null != (zipEntry = zipInputStream.getNextEntry())) { if (ASiCUtil.isSignatureZipEntry(zipEntry)) { continue; } if (false == referenceUris.contains(zipEntry.getName())) { LOG.warn("no ds:Reference for ASiC entry: " + zipEntry.getName()); return signatureInfos; } } X509Certificate signer = keySelector.getCertificate(); SignatureInfo signatureInfo = xadesValidation.validate(documentSignaturesDocument, xmlSignature, signatureElement, signer); signatureInfos.add(signatureInfo); } return signatureInfos; }
From source file:esg.security.yadis.XrdsDoc.java
public List parse(String input, Set targetTypes) throws XrdsParseException { Document document = parseXmlInput(input); NodeList XRDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_XRD); Node lastXRD;/*from w ww.ja va2 s .c om*/ if (XRDs.getLength() < 1 || (lastXRD = XRDs.item(XRDs.getLength() - 1)) == null) throw new XrdsParseException("No XRD elements found."); // get the canonical ID, if any (needed for XRIs) String canonicalId = null; Node canonicalIdNode; NodeList canonicalIDs = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_CANONICALID); for (int i = 0; i < canonicalIDs.getLength(); i++) { canonicalIdNode = canonicalIDs.item(i); if (canonicalIdNode.getParentNode() != lastXRD) continue; if (canonicalId != null) throw new XrdsParseException("More than one Canonical ID found."); canonicalId = canonicalIdNode.getFirstChild() != null && canonicalIdNode.getFirstChild().getNodeType() == Node.TEXT_NODE ? canonicalIdNode.getFirstChild().getNodeValue() : null; } // extract the services that match the specified target types NodeList types = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_TYPE); Map serviceTypes = new HashMap(); Set selectedServices = new HashSet(); Node typeNode, serviceNode; for (int i = 0; i < types.getLength(); i++) { typeNode = types.item(i); String type = typeNode != null && typeNode.getFirstChild() != null && typeNode.getFirstChild().getNodeType() == Node.TEXT_NODE ? typeNode.getFirstChild().getNodeValue() : null; if (type == null) continue; serviceNode = typeNode.getParentNode(); if (targetTypes == null) selectedServices.add(serviceNode); else if (targetTypes.contains(type)) selectedServices.add(serviceNode); addServiceType(serviceTypes, serviceNode, type); } // extract local IDs Map serviceLocalIDs = extractElementsByParent(XRD_NS, XRD_ELEM_LOCALID, selectedServices, document); Map serviceDelegates = extractElementsByParent(OPENID_NS, OPENID_ELEM_DELEGATE, selectedServices, document); // build XrdsServiceEndpoints for all URIs in the found services List result = new ArrayList(); NodeList uris = document.getElementsByTagNameNS(XRD_NS, XRD_ELEM_URI); Node uriNode; for (int i = 0; i < uris.getLength(); i++) { uriNode = uris.item(i); if (uriNode == null || !selectedServices.contains(uriNode.getParentNode())) continue; String uri = uriNode.getFirstChild() != null && uriNode.getFirstChild().getNodeType() == Node.TEXT_NODE ? uriNode.getFirstChild().getNodeValue() : null; serviceNode = uriNode.getParentNode(); Set typeSet = (Set) serviceTypes.get(serviceNode); String localId = (String) serviceLocalIDs.get(serviceNode); String delegate = (String) serviceDelegates.get(serviceNode); XrdsServiceElem endpoint = new XrdsServiceElem(uri, typeSet, getPriority(serviceNode), getPriority(uriNode), localId, delegate, canonicalId); result.add(endpoint); } Collections.sort(result); return result; }
From source file:com.vmware.identity.wstrust.client.impl.RequestBuilderHelper.java
/** * Inserts SAML token into the SOAP message. Due to problems with JAXB * marshaling/unmarshaling SAML tokens should be added to the message after * it is marshalled to DOM. There should be only 1 * <elementNamespace:elementLocalName /> node in the request. * * @param message//from www. j a va2 s .co m * The request SoapMessage * @param elementNamespace * The namespace of the element where the SAML token should be * inserted * @param elementLocalName * The local name of the element where the SAML token should be * inserted * @param token * The SAML token that should be inserted * @throws ParserException */ protected final void insertSamlToken(SoapMessage message, String elementNamespace, String elementLocalName, SamlToken token) throws ParserException { Document messageDocument = message.getMessage().getSOAPPart(); NodeList targetElement = messageDocument.getElementsByTagNameNS(elementNamespace, elementLocalName); if (targetElement == null || targetElement.getLength() != 1) { String errMsg = "Error inserting SAML token into the SOAP message. " + "No/Too many " + elementLocalName + " found."; log.debug(errMsg); throw new ParserException(errMsg); } // only 1 target element is expected in the STS request Node copiedToken = token.importTo(messageDocument); targetElement.item(0).appendChild(copiedToken); }
From source file:module.signature.util.XAdESValidator.java
private static void validateSigner(Document document, Set<User> usersPermitted, Set<User> usersExcluded, boolean allUsersPermittedShouldBeThere) throws SignatureDataException { if (!allUsersPermittedShouldBeThere || ((usersExcluded != null) && !usersExcluded.isEmpty())) { //TODO implement it when needed throw new DomainException("method.not.yet.implemented"); }/*from w w w . jav a 2 s.c o m*/ final String ID_NR_PREFIX = "OID.2.5.4.5=BI"; ArrayList<String> usersPermittedIdNumbers = new ArrayList<String>(); for (User user : usersPermitted) { usersPermittedIdNumbers.add(user.getPerson().getRemotePerson().getDocumentIdNumber()); } //let's extract each signature // XMLDSIG NodeList nlSignature = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); //DEBUG System.out.println("Got " + nlSignature.getLength() + " signatures"); if (nlSignature.getLength() < 1) { throw new SignatureException("could.not.find.a.signature.in.incoming.data", true, null); } HashSet<String> usersFoundIdNumbers = new HashSet<String>(); for (int i = 0; i < nlSignature.getLength(); i++) { //for each signature, let's extract the ID number of who did it Element signature = (Element) nlSignature.item(i); try { XMLSignature xmlSig = new XMLSignature(signature, null); KeyInfo ki = xmlSig.getKeyInfo(); String certificateIDNr = ki.getX509Certificate().getSubjectX500Principal().getName("RFC1779"); certificateIDNr = certificateIDNr .substring(certificateIDNr.indexOf(ID_NR_PREFIX) + ID_NR_PREFIX.length()); //let's take out the virgul and the last character, which is a control one certificateIDNr = certificateIDNr.substring(0, certificateIDNr.indexOf(',') - 1); usersFoundIdNumbers.add(certificateIDNr); } catch (XMLSignatureException e) { e.printStackTrace(); throw new SignatureDataException("signature.error.XMLSignatureExceptionError", e); } catch (XMLSecurityException e) { throw new SignatureDataException("signature.error.XMLSecurityException", e); } } //now let's validate the extracted info if (allUsersPermittedShouldBeThere && usersFoundIdNumbers.containsAll(usersPermittedIdNumbers)) { return; //TODO TODO URGENT uncomment the next two lines (just made possible to be able to test it!!) } else { throw new SignatureDataException("wrong.document.signer"); } //TODO the rest of the use cases aren't implemented ATM }
From source file:fr.ortolang.diffusion.seo.SeoServiceBean.java
@Override public String prerenderSiteMap() throws SeoServiceException, ParserConfigurationException, TransformerException { LOGGER.log(Level.INFO, "Start prerendering Site Map"); Document document = generateSiteMapDocument(); NodeList nodes = document.getElementsByTagNameNS(SITEMAP_NS_URI, "loc"); Runnable command = () -> { int errors = 0; for (int i = 0; i < nodes.getLength(); i++) { String url = nodes.item(i).getTextContent(); LOGGER.log(Level.FINE, "Prerendering url: " + url); Response response = client.target(url).request().header("User-Agent", ORTOLANG_USER_AGENT).get(); response.close();/* ww w .j av a 2 s .co m*/ if (response.getStatusInfo().getStatusCode() != 200 && response.getStatusInfo().getStatusCode() != 304) { LOGGER.log(Level.SEVERE, "An unexpected issue occurred while prerendering the url " + url + " : " + response.getStatusInfo().getStatusCode() + " " + response.getStatusInfo().getReasonPhrase()); errors++; } try { Thread.sleep(200); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } if (errors > 0) { LOGGER.log(Level.SEVERE, "Site Map prerendering done with " + errors + " errors."); } else { LOGGER.log(Level.INFO, "Site Map prerendering done"); } }; executor.execute(command); return generateSiteMap(document); }
From source file:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java
private void prepareDocument(Document xkmsDocument) { Element prototypeElement = xkmsDocument.getElementById(this.prototypeKeyBindingId); if (null == prototypeElement) { LOG.warn("Prototype element not found via Id"); prototypeElement = (Element) xkmsDocument.getElementsByTagNameNS(XKMS_NAMESPACE, "Prototype").item(0); prototypeElement.setIdAttribute("Id", true); }// w w w. j a va2 s. c om }
From source file:be.e_contract.mycarenet.xkms2.ProofOfPossessionSignatureSOAPHandler.java
private void prepareDocument(Document xkmsDocument) { Element prototypeElement = xkmsDocument.getElementById(this.prototypeKeyBindingId); if (null == prototypeElement) { LOG.warn("Prototype element not found via Id"); prototypeElement = (Element) xkmsDocument .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "PrototypeKeyBinding").item(0); prototypeElement.setIdAttribute("Id", true); }//from w ww. j a v a2 s . c om }
From source file:de.unibi.techfak.bibiserv.util.codegen.Main.java
private static boolean generateAppfromXML(String fn) { long starttime = System.currentTimeMillis(); // fn must not be null or empty if (fn == null || fn.isEmpty()) { log.error("Empty filename!"); return false; }//from ww w . j av a2 s . co m // fn must be a valid file and readable File runnableitem = new File(fn); if (!runnableitem.exists() || !runnableitem.canRead()) { log.error("{} doesn't exists or can't be read! ", fn); return false; } // load as xml file, validate it, and ... Document doc; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); //dbf.setValidating(true); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(runnableitem); } catch (ParserConfigurationException | SAXException | IOException e) { log.error("{} occured: {}", e.getClass().getSimpleName(), e.getLocalizedMessage()); return false; } // extract project id, name and version from it. String projectid = doc.getDocumentElement().getAttribute("id"); if ((projectid == null) || projectid.isEmpty()) { log.error("Missing project id in description file!"); return false; } String projectname; try { projectname = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "name").item(0) .getTextContent(); } catch (NullPointerException e) { log.error("Missing project name in description file!"); return false; } String projectversion = "unknown"; try { projectversion = doc.getElementsByTagNameNS("bibiserv:de.unibi.techfak.bibiserv.cms", "version").item(0) .getTextContent(); } catch (NullPointerException e) { log.warn("Missing project version in description file!"); } File projectdir = new File( config.getProperty("project.dir", config.getProperty("target.dir") + "/" + projectid)); mkdirs(projectdir + "/src/main/java"); mkdirs(projectdir + "/src/main/config"); mkdirs(projectdir + "/src/main/libs"); mkdirs(projectdir + "/src/main/pages"); mkdirs(projectdir + "/src/main/resources"); mkdirs(projectdir + "/src/main/downloads"); // place runnableitem in config dir try { Files.copy(runnableitem.toPath(), new File(projectdir + "/src/main/config/runnableitem.xml").toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { log.error("{} occurred : {}", e.getClass().getSimpleName(), e.getLocalizedMessage()); return false; } // copy files from SKELETON to projectdir and replace wildcard expression String[] SKELETON_INPUT_ARRAY = { "/pom.xml", "/src/main/config/log4j-tool.properties" }; String SKELETON_INPUT = null; try { for (int c = 0; c < SKELETON_INPUT_ARRAY.length; c++) { SKELETON_INPUT = SKELETON_INPUT_ARRAY[c]; InputStream in = Main.class.getResourceAsStream("/SKELETON" + SKELETON_INPUT); if (in == null) { throw new IOException(); } CopyAndReplace(in, new FileOutputStream(new File(projectdir, SKELETON_INPUT)), projectid, projectname, projectversion); } } catch (IOException e) { log.error("Exception occurred while calling 'copyAndReplace(/SKELETON{},{}/{},{},{},{})'", SKELETON_INPUT, projectdir, SKELETON_INPUT, projectid, projectname, projectversion); return false; } log.info("Empty project created! "); try { // _base generate(CodeGen_Implementation.class, runnableitem, projectdir); log.info("Implementation generated!"); generate(CodeGen_Implementation_Threadworker.class, runnableitem, projectdir); log.info("Implementation_Threadworker generated!"); generate(CodeGen_Utilities.class, runnableitem, projectdir); log.info("Utilities generated!"); generate(CodeGen_Common.class, runnableitem, projectdir, "/templates/common", RESOURCETYPE.isDirectory); log.info("Common generated!"); // _REST generate(CodeGen_REST.class, runnableitem, projectdir); generate(CodeGen_REST_general.class, runnableitem, projectdir); log.info("REST generated!"); //_HTML generate(CodeGen_WebSubmissionPage.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionPage_Input.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionPage_Param.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionPage_Result.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionPage_Visualization.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionPage_Formatchooser.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionPage_Resulthandler.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionBean_Function.class, runnableitem, projectdir); generate(CodeGen_Session_Reset.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionBean_Controller.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionBean_Input.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionBean_Param.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionBean_Result.class, runnableitem, projectdir); generate(CodeGen_WebSubmissionBean_Resulthandler.class, runnableitem, projectdir); generate(CodeGen_Webstart.class, runnableitem, projectdir); // can be removed ??? generate(CodeGen_WebToolBeanContextConfig.class, runnableitem, projectdir); generate(CodeGen_WebManual.class, runnableitem, projectdir); generate(CodeGen_WebPage.class, runnableitem, projectdir, "/templates/pages", RESOURCETYPE.isDirectory); log.info("XHTML pages generated!"); long time = (System.currentTimeMillis() - starttime) / 1000; log.info("Project \"{}\" (id:{}, version:{}) created at '{}' in {} seconds.", projectname, projectid, projectversion, projectdir, time); } catch (CodeGenParserException e) { log.error("CodeGenParserException occurred :", e); return false; } return true; }