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:it.cloudicaro.disit.kb.BusinessConfigurationResource.java
static public String putBusinessConfiguration(String name, String content, HttpServletRequest request) throws Exception { Date start = new Date(); String op = (name.equals("") ? "POST" : "PUT"); Configuration conf = Configuration.getInstance(); String validationResult = null; String bcAbout = ""; boolean check = (request != null || conf.get("kb.recover.force_checkBC", "false").equals("true")); if (check) {//w w w . j a va 2 s. c o m //validate 'content' using xml schema validationResult = ValidateResource.validateContent(content, "schema-icaro-kb-businessConfiguration.xsd"); if (validationResult != null) { IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-XML-VALIDATION", validationResult, content, request); throw new KbException(validationResult, 400); } } //get the BusinessConfiguration rdf:about and check if the resource name from the url is the ending part of the rdf:about Document doc = ValidateResource.parseXml(content); NodeList bc = doc.getElementsByTagNameNS(IcaroKnowledgeBase.NS_ICARO_CORE, "BusinessConfiguration"); if (bc.getLength() == 1) bcAbout = bc.item(0).getAttributes().getNamedItemNS(IcaroKnowledgeBase.NS_RDF, "about").getNodeValue(); String bcPrefix = conf.get("kb.bcPrefix", "urn:cloudicaro:BusinessConfiguration:"); if (check && name.equals("")) { if (!bcAbout.startsWith(bcPrefix)) { String error = "BusinessConfiguration rdf:about='" + bcAbout + "' does not start with '" + bcPrefix + "'"; IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-ID-CHECK1", error, content, request); throw new KbException(error, 400); } name = bcAbout.substring(bcPrefix.length()); } if (check && conf.get("kb.validateBCAbout", "true").equalsIgnoreCase("true") && !bcAbout.endsWith(name)) { String error = "BusinessConfiguration rdf:about='" + bcAbout + "' does not end with '" + name + "'"; IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-ID-CHECK2", error, content, request); throw new KbException(error, 400); } RDFStoreInterface rdfStore = RDFStore.getInstance(); //check if the business configuration is already present or not Boolean toUpdate = false; QueryResult qr = rdfStore.query("SELECT * WHERE { <" + bcAbout + "> ?p ?o } LIMIT 1"); toUpdate = (qr.results().size() >= 1); //upload to a new temporary context, if ok rename the context otherwise remove String tmpGraph = "urn:cloudicaro:context:BusinessConfiguration:tmp:" + UUID.randomUUID(); String graph = "urn:cloudicaro:context:BusinessConfiguration:" + name; String data = ValidateResource.transformBlankNodes(doc); rdfStore.addStatements(data, "application/rdf+xml", tmpGraph); try { if (check) validationResult = ValidateResource.validateBusinessConfigurationGraph(tmpGraph); } finally { if (validationResult != null) { rdfStore.removeGraph(tmpGraph); IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-KB-VALIDATION", validationResult, content, request); throw new KbException(validationResult, 400); } else { //remove context associated with id and then rename the graph to the new one rdfStore.removeGraph(graph); if (conf.get("kb.bcUpdateFix", "false").equals("false")) rdfStore.update("MOVE <" + tmpGraph + "> TO <" + graph + ">"); else { rdfStore.removeGraph(tmpGraph); rdfStore.addStatements(data, "application/rdf+xml", graph); } } } Date mid = new Date(); //post content on RDF store in the context //???rdfStore.addStatements(content, "application/rdf+xml", graph); if (request != null) { rdfStore.flush(); // save the request to disk IcaroKnowledgeBase.storePut(start, content, name, "BC"); if (conf.get("kb.sm.forward.BusinessConfiguration", "false").equals("true")) { try { String smUrl = conf.get("kb.sm.url", "http://192.168.0.37/icaro/api/configurator"); if (toUpdate) smUrl = smUrl + "/" + bcAbout; ServerMonitoringClient client = new ServerMonitoringClient(smUrl); client.setUsernamePassword(conf.get("kb.sm.user", "test"), conf.get("kb.sm.passwd", "12345")); String result; if (toUpdate) { System.out.println("PUT BC " + bcAbout + " to SM"); result = client.putXml(content); } else { System.out.println("POST BC to SM"); result = client.postXml(content); } System.out.println("SM result:\n" + result); client.close(); Date end = new Date(); System.out.println(start + " KB-PERFORMANCE " + op + " BC " + name + " kb:" + (mid.getTime() - start.getTime()) + "ms sm:" + (end.getTime() - mid.getTime()) + "ms"); IcaroKnowledgeBase.log(start, op, "BC", name, "OK", request); /*if(conf.get("kb.sce.forward.BusinessConfiguration", "false").equals("true")) { try { String sceUrl=conf.get("kb.sce.url", ""); } catch(Exception e) { e.printStackTrace(); IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-SCE", e.getLocalizedMessage(), content, request); } }*/ return result; } catch (Exception e) { e.printStackTrace(); IcaroKnowledgeBase.error(start, op, "BC", name, "FAILED-SM", e.getLocalizedMessage(), content, request); throw new KbException("Failed setting monitoring: " + e.getLocalizedMessage(), 400); } } IcaroKnowledgeBase.log(start, op, "BC", name, "OK", request); } return ""; }
From source file:gov.niem.ws.util.SecurityUtil.java
public static boolean validateDocumentSignature(Document signedDoc, Key publicKey) throws MarshalException, XMLSignatureException { if (signedDoc == null) throw new IllegalArgumentException("Signed Document is null"); NodeList nl = signedDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl == null || nl.getLength() == 0) { throw new IllegalArgumentException("Cannot find Signature element"); }/*w ww. j a v a 2s. c o m*/ if (publicKey == null) throw new IllegalArgumentException("Public Key is null"); DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0)); XMLSignature signature = signatureFactory.unmarshalXMLSignature(valContext); boolean coreValidity = signature.validate(valContext); if (!coreValidity) { boolean sv = signature.getSignatureValue().validate(valContext); log.fine("Signature validation status: " + sv); } return coreValidity; }
From source file:com.bcmcgroup.flare.client.ClientUtil.java
/** * Validate each Content block in a TAXII document (against the STIX schema files) * * @param taxiiDoc The TAXII document containing the STIX to be validated * @return true if all STIX validates, false otherwise * *///from www .ja v a2 s . co m public static boolean validateStix(Document taxiiDoc) { try { NodeList bindings = taxiiDoc.getElementsByTagNameNS("*", "Content_Binding"); NodeList contents = taxiiDoc.getElementsByTagNameNS("*", "Content"); int numBindings = bindings.getLength(); if (numBindings != contents.getLength()) { logger.warn("STIX Validation mismatch for number of Content_Bindings and Contents. Message failed"); return false; } for (int i = 0; i < numBindings; i++) { Node binding = bindings.item(i); String stixVersion = getStixVersion(binding); logger.debug("STIX Version: " + stixVersion); Node stix = contents.item(i).getFirstChild(); Source source = new DOMSource(stix); if (!stixVersion.isEmpty() && stixVersions.contains(stixVersion)) { StixValidator sv = new StixValidator(stixVersion); List<SchemaError> errors = sv.validate(source); if (errors.size() > 0) { logger.warn("STIX Validation Errors: " + errors.size()); for (SchemaError error : errors) { logger.debug("SchemaError Category: " + error.getCategory()); logger.debug("SchemaError Message: " + error.getMessage()); } logger.warn("Message failed due to STIX " + stixVersion + " content validation errors! Please check content and try again."); return false; } } else { throw new SAXException( "Error: No STIX version number is specified by the Content_Binding urn."); } } } catch (SAXException e) { logger.debug("SAX Exception when attempting to validate STIX content. "); return false; } catch (IOException e) { logger.debug("IOException when attempting to validate STIX content. "); return false; } logger.debug("All STIX has been validated successfully."); return true; }
From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java
/** * Used to verify an enveloped digital signature * * @param doc a Document object containing the xml with the signature * @param keyStorePath a String containing the path to the KeyStore * @param keyStorePW a String containing the KeyStore password * @param verifyAlias a String containing the alias of the public key used for verification * @return True if signature passes verification, False otherwise *//*from ww w. ja v a 2 s . co m*/ public static boolean verifySignature(Document doc, String keyStorePath, String keyStorePW, String verifyAlias) { boolean coreValidation = false; PublicKey publicKey = ClientUtil.getPublicKeyByAlias(keyStorePath, keyStorePW, verifyAlias); if (publicKey == null) { logger.error( "Public key was null when verifying signature. Ensure keystore configuration values are set properly."); return false; } try { NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { logger.error("No XML Digital Signature was found. The document was discarded."); return false; } Node signatureNode = nl.item(nl.getLength() - 1); DOMValidateContext valContext = new DOMValidateContext(publicKey, signatureNode); valContext.setURIDereferencer(new MyURIDereferencer(signatureNode.getParentNode())); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); XMLSignature signature = fac.unmarshalXMLSignature(valContext); coreValidation = signature.validate(valContext); if (!coreValidation) { // for testing/debugging when validation fails... logger.error("Digital Signature Core Validation failed."); boolean signatureValidation = signature.getSignatureValue().validate(valContext); logger.debug("Digital Signature Validation: " + signatureValidation); @SuppressWarnings("rawtypes") Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { Reference ref = (Reference) i.next(); boolean referenceValidation = ref.validate(valContext); logger.debug("Digital Signature Reference Validation: " + referenceValidation); byte[] calculatedDigestValue = ref.getCalculatedDigestValue(); byte[] digestValue = ref.getDigestValue(); String cdvString = new String(Base64.encodeBase64(calculatedDigestValue)); logger.debug("Digital Signature Calculated Digest Value: " + cdvString); String dvString = new String(Base64.encodeBase64(digestValue)); logger.debug("Digital Signature Digest Value: " + dvString); } } } catch (MarshalException e) { logger.error("MarshalException when attempting to verify a digital signature."); } catch (XMLSignatureException e) { logger.error("XMLSignature Exception when attempting to verify a digital signature."); } return coreValidation; }
From source file:eu.elf.license.LicenseParser.java
public static List<LicenseModelGroup> parseListOfLicensesAsLicenseModelGroupList(String xml) throws Exception { try {/*from ww w.j a va 2s . c o m*/ Document xmlDoc = createXMLDocumentFromString(xml); NodeList productGroupElementList = xmlDoc.getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productGroup"); return createLicenseModelGroupList(productGroupElementList); } catch (Exception e) { throw e; } }
From source file:eu.elf.license.LicenseParser.java
/** * Parses a list of active licenses from GetLicenseReferences response string * /* w ww . j av a 2 s . c om*/ * @param xml - xml response * @return - ArrayList of license identifiers that are active * @throws Exception */ public static ArrayList<String> parseActiveLicensesFromGetLicenseReferencesResponse(String xml) throws Exception { ArrayList<String> activeLicenses = new ArrayList<String>(); try { Document xmlDoc = createXMLDocumentFromString(xml); NodeList licenseReferenceList = xmlDoc.getElementsByTagNameNS("http://www.52north.org/license/0.3.2", "LicenseReference"); for (int i = 0; i < licenseReferenceList.getLength(); i++) { Element licenseReferenceElement = (Element) licenseReferenceList.item(i); NodeList attributeElementList = licenseReferenceElement .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute"); for (int j = 0; j < attributeElementList.getLength(); j++) { Element attributeElement = (Element) attributeElementList.item(j); Element attributeValueElement = (Element) attributeElement .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeValue") .item(0); NamedNodeMap attributeMap = attributeElement.getAttributes(); for (int k = 0; k < attributeMap.getLength(); k++) { Attr attrs = (Attr) attributeMap.item(k); if (attrs.getNodeName().equals("Name")) { if (attrs.getNodeValue().equals("urn:opengeospatial:ows4:geodrm:LicenseID")) { activeLicenses.add(attributeValueElement.getTextContent()); } } } } } } catch (Exception e) { throw e; } return activeLicenses; }
From source file:eu.elf.license.LicenseParser.java
/** * Creates LicenseConcludeResponseObject from the concludeLicense operation's response string * //ww w .j a va 2s . c o m * @param response * @return * @throws Exception */ public static LicenseConcludeResponseObject parseConcludeLicenseResponse(String response) throws Exception { LicenseConcludeResponseObject lcro = new LicenseConcludeResponseObject(); try { Document xmlDoc = LicenseParser.createXMLDocumentFromString(response); NodeList LicenseReferenceNL = xmlDoc.getElementsByTagNameNS("http://www.52north.org/license/0.3.2", "LicenseReference"); for (int i = 0; i < LicenseReferenceNL.getLength(); i++) { Element attributeStatementElement = (Element) LicenseReferenceNL.item(i); NodeList attributeElementList = attributeStatementElement .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute"); for (int j = 0; j < attributeElementList.getLength(); j++) { Element attributeElement = (Element) attributeElementList.item(j); Element AttributeValueElement = (Element) attributeElement .getElementsByTagName("AttributeValue").item(0); NamedNodeMap licenseReferenceElementAttributeMap = attributeElement.getAttributes(); for (int k = 0; k < licenseReferenceElementAttributeMap.getLength(); k++) { Attr attrs = (Attr) licenseReferenceElementAttributeMap.item(k); if (attrs.getNodeName().equals("Name")) { if (attrs.getNodeValue().equals("urn:opengeospatial:ows4:geodrm:NotOnOrAfter")) { lcro.setValidTo(AttributeValueElement.getTextContent()); } if (attrs.getNodeValue().equals("urn:opengeospatial:ows4:geodrm:ProductID")) { lcro.setProductId(AttributeValueElement.getTextContent()); } if (attrs.getNodeValue().equals("urn:opengeospatial:ows4:geodrm:LicenseID")) { lcro.setLicenseId(AttributeValueElement.getTextContent()); } } } } } } catch (Exception e) { throw e; } return lcro; }
From source file:eu.elf.license.LicenseParser.java
public static UserLicenses parseUserLicensesAsLicenseModelGroupList(String xml, String userid) throws Exception { UserLicenses userLicenses = new UserLicenses(); try {// w w w . j ava2s . c o m Document xmlDoc = createXMLDocumentFromString(xml); Element ordersElement = (Element) xmlDoc .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "orders").item(0); NodeList orderList = ordersElement.getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "order"); for (int i = 0; i < orderList.getLength(); i++) { UserLicense userLicense = new UserLicense(); try { Element orderElement = (Element) orderList.item(i); Element productionElement = (Element) orderElement .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "production").item(0); Element productionItemElement = (Element) productionElement .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productionItem").item(0); Element LicenseReferenceElement = (Element) productionItemElement .getElementsByTagNameNS("http://www.52north.org/license/0.3.2", "LicenseReference") .item(0); Element attributeStatementElement = (Element) LicenseReferenceElement .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeStatement") .item(0); NodeList attributeElementList = attributeStatementElement .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Attribute"); for (int j = 0; j < attributeElementList.getLength(); j++) { Element attributeElement = (Element) attributeElementList.item(j); Element AttributeValueElement = (Element) attributeElement .getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeValue") .item(0); NamedNodeMap attributeMap = attributeElement.getAttributes(); for (int k = 0; k < attributeMap.getLength(); k++) { Attr attrs = (Attr) attributeMap.item(k); if ("Name".equals(attrs.getNodeName())) { if ("urn:opengeospatial:ows4:geodrm:NotOnOrAfter".equals(attrs.getNodeValue())) { userLicense.setValidTo(AttributeValueElement.getTextContent()); } if ("urn:opengeospatial:ows4:geodrm:LicenseID".equals(attrs.getNodeValue())) { userLicense.setLicenseId(AttributeValueElement.getTextContent()); } } } userLicense.setSecureServiceURL("/httpauth/licid-" + userLicense.getLicenseId()); } Element orderContentElement = (Element) orderElement .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "orderContent").item(0); Element catalogElement = (Element) orderContentElement .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "catalog").item(0); NodeList productGroupElementList = catalogElement .getElementsByTagNameNS("http://www.conterra.de/xcpf/1.1", "productGroup"); // setup user license flags in models List<LicenseModelGroup> list = createLicenseModelGroupList(productGroupElementList); for (LicenseModelGroup group : list) { group.setUserLicense(true); } userLicense.setLmgList(list); String WSS_URL = findWssUrlFromUserLicenseParamList(userLicense.getLmgList()); //Remove WSS from the WSS-url string WSS_URL = WSS_URL.substring(0, WSS_URL.lastIndexOf("/")); userLicense.setSecureServiceURL(WSS_URL + userLicense.getSecureServiceURL()); userLicenses.addUserLicense(userLicense); } catch (Exception e) { // Sometimes we get results without LicenseReference element: order/production/productionItem/LicenseReference // there might be valid results in the same response. Skipping the invalid ones. LOG.warn("Error while parsing user licenses"); } } return userLicenses; } catch (Exception e) { throw e; } }
From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java
/** * * @param url/*ww w . j av a 2 s. co m*/ * @param serviceName * @param xml * @return */ public static String executeMobyCgiAsyncService(String url, String serviceName, String xml) throws MobyException { // First, let's get the queryIds org.w3c.dom.Document message = null; try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); message = db.parse(new InputSource(new StringReader(xml))); } catch (Throwable t) { throw new MobyException("Error while parsing input query", t); } NodeList l_data = message.getElementsByTagNameNS(MobyPrefixResolver.MOBY_XML_NAMESPACE, MobyTags.MOBYDATA); if (l_data == null || l_data.getLength() == 0) { l_data = message.getElementsByTagNameNS(MobyPrefixResolver.MOBY_XML_NAMESPACE_INVALID, MobyTags.MOBYDATA); } // Freeing resources message = null; if (l_data == null || l_data.getLength() == 0) { throw new MobyException("Empty asynchronous MOBY query!"); } int nnode = l_data.getLength(); String[] queryIds = new String[nnode]; String[] tmpQueryIds = new String[nnode]; String[] results = new String[nnode]; for (int inode = 0; inode < nnode; inode++) { String queryId = null; org.w3c.dom.Element mdata = (org.w3c.dom.Element) l_data.item(inode); queryId = mdata.getAttribute(MobyTags.QUERYID); if (queryId == null || queryId.length() == 0) queryId = mdata.getAttributeNS(MobyPrefixResolver.MOBY_XML_NAMESPACE, MobyTags.QUERYID); if (queryId == null || queryId.length() == 0) queryId = mdata.getAttributeNS(MobyPrefixResolver.MOBY_XML_NAMESPACE_INVALID, MobyTags.QUERYID); if (queryId == null || queryId.length() == 0) { throw new MobyException("Unable to extract queryId for outgoing MOBY message"); } tmpQueryIds[inode] = queryIds[inode] = queryId; results[inode] = null; } // Freeing resources l_data = null; // Second, let's launch EndpointReference epr = launchCgiAsyncService(url, xml); // Third, waiting for the results try { // FIXME - add appropriate values here long pollingInterval = 1000L; double backoff = 1.0; // Max: one minute pollings long maxPollingInterval = 60000L; // Min: one second if (pollingInterval <= 0L) pollingInterval = 1000L; // Backoff: must be bigger than 1.0 if (backoff <= 1.0) backoff = 1.5; do { try { Thread.sleep(pollingInterval); } catch (InterruptedException ie) { // DoNothing(R) } if (pollingInterval != maxPollingInterval) { pollingInterval = (long) ((double) pollingInterval * backoff); if (pollingInterval > maxPollingInterval) { pollingInterval = maxPollingInterval; } } } while (pollAsyncCgiService(serviceName, url, epr, tmpQueryIds, results)); } finally { // Call destroy on this service .... freeCgiAsyncResources(url, epr); } // Fourth, assembling back the results // Results array already contains mobyData Element[] mobydatas = new Element[results.length]; for (int x = 0; x < results.length; x++) { // TODO remove the extra wrapping from our result try { Element inputElement = XMLUtilities.getDOMDocument(results[x]).getRootElement(); if (inputElement.getName().indexOf("GetMultipleResourcePropertiesResponse") >= 0) if (inputElement.getChildren().size() > 0) inputElement = (Element) inputElement.getChildren().get(0); if (inputElement.getName().indexOf("result_") >= 0) if (inputElement.getChildren().size() > 0) inputElement = (Element) inputElement.getChildren().get(0); // replace results[x] mobydatas[x] = inputElement; } catch (MobyException e) { // TODO what should i do? } } Element e = null; try { e = XMLUtilities.createMultipleInvokations(mobydatas); } catch (Exception ex) { logger.error("There was a problem creating our XML message ...", ex); } // Fifth, returning results return e == null ? "" : new XMLOutputter(Format.getPrettyFormat()).outputString(e); }
From source file:eu.europa.esig.dss.DSSXMLUtils.java
/** * This method retrieves an element based on its ID * * @param currentDom the DOM in which the element has to be retrieved * @param elementId the specified ID// ww w .j av a 2s. c o m * @param namespace the namespace to take into account * @param tagName the tagName of the element to find * @return the * @throws NullPointerException */ public static Element getElementById(Document currentDom, String elementId, String namespace, String tagName) throws NullPointerException { Element element = null; NodeList nodes = currentDom.getElementsByTagNameNS(namespace, tagName); for (int i = 0; i < nodes.getLength(); i++) { element = (Element) nodes.item(i); if (elementId.equals(DSSXMLUtils.getIDIdentifier(element))) { return element; } } if (element == null) { throw new NullPointerException(); } return null; }