List of usage examples for javax.xml.xpath XPath evaluate
public Object evaluate(String expression, InputSource source, QName returnType) throws XPathExpressionException;
From source file:com.comcast.magicwand.spells.web.iexplore.IePhoenixDriver.java
/** * {@inheritDoc}//from w w w . ja va 2s. co m */ public boolean verify(PhoenixDriverIngredients i) { boolean rv = false; Map<String, Object> configs = i.getDriverConfigs(); LOGGER.debug("[version_property, arch_property] = [{}, {}]", (String) configs.get(IE_DRIVER_VERSION_KEY), (String) configs.get(IE_DRIVER_ARCH_KEY)); IePlatformSpecifics ips = this.createIePlatformSpecifics((String) configs.get(IE_DRIVER_VERSION_KEY), (String) configs.get(IE_DRIVER_ARCH_KEY)); if (!ips.isValid()) { LOGGER.error("The IePlatformSpecifics retrieved are not valid."); return false; } try { XPath xpath = XPathFactory.newInstance().newXPath(); String pwd = System.getProperty("user.dir"); String version = ips.getVersion(); String arch = ips.getArch(); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(IE_XML_DRIVER_LISTING_URL); NodeList nodes = (NodeList) xpath.evaluate(IE_XML_DRIVER_LISTING_XPATH, doc, XPathConstants.NODESET); String highestVersion = null; String needle = version + "/IEDriverServer_" + arch + "_"; for (int idx = 0; idx < nodes.getLength(); idx++) { Node n = nodes.item(idx); String text = n.getTextContent(); if (text.startsWith(needle)) { text = text.substring(needle.length(), text.length()); if (IePhoenixDriver.versionGreater(highestVersion, text)) { highestVersion = text; } } } if (null != highestVersion) { highestVersion = FilenameUtils.removeExtension(highestVersion); URL url = new URL(String.format(IE_HTTP_DRIVER_PATH_FORMAT, version, arch, highestVersion)); String zipName = String.format(IE_ZIP_FILE_FORMAT, arch, highestVersion); File ieSaveDir = new File(Paths.get(pwd, "target", "drivers", "iexplore", version).toString()); LOGGER.debug("Will read from \"{}\"", url); File zipFile = new File( Paths.get(pwd, "target", "drivers", "iexplore", version, zipName).toString()); FileUtils.copyURLToFile(url, zipFile); extract(zipFile, ieSaveDir.getAbsolutePath()); File exe = Paths.get(pwd, "target", "drivers", "iexplore", version, IE_EXE_FILE_NAME).toFile(); if (exe.exists()) { exe.setExecutable(true); systemSetProperty("webdriver.ie.driver", exe.getAbsolutePath()); this.webDriver = this.createDriver(i.getDriverCapabilities()); rv = true; } else { LOGGER.error("Extracted zip archive did nto contain \"{}\".", IE_EXE_FILE_NAME); } } else { LOGGER.error("Unable to find any IE Drivers from [{}]", IE_XML_DRIVER_LISTING_XPATH); } } catch (ParserConfigurationException | SAXException | XPathExpressionException err) { throw new RuntimeException(err); } catch (IOException ioe) { LOGGER.error("IO failure: {}", ioe); } return rv; }
From source file:org.ligoj.app.plugin.vm.aws.VmAwsPluginResource.java
/** * Fill the given VM networks with its network details. *///from w ww.j av a 2 s . c o m protected void addNetworkDetails(final Element networkNode, final Collection<VmNetwork> networks) { // Private IP (optional) addNetworkDetails(networkNode, networks, "private", "privateIpAddress", "privateDnsName"); // Public IP (optional) addNetworkDetails(networkNode, networks, "public", "ipAddress", "dnsName"); // IPv6 (optional) final XPath xPath = xml.xpathFactory.newXPath(); try { final NodeList ipv6 = (NodeList) xPath.evaluate("networkInterfaceSet/item/ipv6AddressesSet", networkNode, XPathConstants.NODESET); IntStream.range(0, ipv6.getLength()).mapToObj(ipv6::item) .forEach(i -> addNetworkDetails((Element) i, networks, "public", "item", "dnsName")); } catch (final XPathExpressionException e) { log.warn("Unable to evaluate IPv6", e); } }
From source file:com.esri.gpt.server.openls.provider.services.poi.DirectoryProvider.java
/** * Parse directory request//from ww w .ja va2s . c o m * @param context * @param ndReq * @param xpath * @throws XPathExpressionException */ private void parseRequest(OperationContext context, Node ndReq, XPath xpath) throws XPathExpressionException { DirectoryParams params = context.getRequestOptions().getDirectoryOptions(); HashMap<String, String> poiProperties = null; HashMap<String, Object> poiLocations = null; Node ndPoiLoc = (Node) xpath.evaluate("xls:POILocation", ndReq, XPathConstants.NODE); if (ndPoiLoc != null) { poiLocations = new HashMap<String, Object>(); Node ndPos = (Node) xpath.evaluate("xls:Nearest/xls:Position/gml:Point/gml:pos", ndPoiLoc, XPathConstants.NODE); if (ndPos != null) { String[] xy = ndPos.getTextContent().split(" "); Point loc = new Point(xy[0], xy[1]); poiLocations.put("nearest", loc); } @SuppressWarnings("unused") Node ndWDAL = (Node) xpath.evaluate("xls:WithinDistance/xls:POI/xls:POIAttributeList/xls:POIInfoList", ndPoiLoc, XPathConstants.NODE); String maxDist = (String) xpath.evaluate("xls:WithinDistance/xls:MaximumDistance/@value", ndPoiLoc, XPathConstants.STRING); if (maxDist != null) { poiLocations.put("withinDistance", maxDist); } } Node ndPoiProp = (Node) xpath.evaluate("xls:POIProperties", ndReq, XPathConstants.NODE); if (ndPoiProp != null) { NodeList nlProp = (NodeList) xpath.evaluate("xls:POIProperty", ndPoiProp, XPathConstants.NODESET); if (nlProp != null) { for (int j = 0; j < nlProp.getLength(); j++) { Node ndProp = nlProp.item(j); poiProperties = new HashMap<String, String>(); String name = (String) xpath.evaluate("@name", ndProp, XPathConstants.STRING); String param = context.getRequestContext().getApplicationConfiguration() .getCatalogConfiguration().getParameters().getValue(name); String value = (String) xpath.evaluate("@value", ndProp, XPathConstants.STRING); poiProperties.put(param, value); } } } params.setPoiLocations(poiLocations); params.setPoiProperties(poiProperties); }
From source file:io.fabric8.tooling.archetype.generator.ArchetypeHelper.java
/** * Extracts properties declared in "META-INF/maven/archetype-metadata.xml" file * * @param zip/* www.jav a 2 s .com*/ * @param replaceProperties * @throws IOException */ protected void parseReplaceProperties(ZipInputStream zip, Map<String, String> replaceProperties) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); copy(zip, bos); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource inputSource = new InputSource(new ByteArrayInputStream(bos.toByteArray())); Document document = db.parse(inputSource); XPath xpath = XPathFactory.newInstance().newXPath(); SimpleNamespaceContext nsContext = new SimpleNamespaceContext(); nsContext.registerMapping("ad", archetypeDescriptorUri); xpath.setNamespaceContext(nsContext); NodeList properties = (NodeList) xpath.evaluate(requiredPropertyXPath, document, XPathConstants.NODESET); for (int p = 0; p < properties.getLength(); p++) { Element requiredProperty = (Element) properties.item(p); String key = requiredProperty.getAttribute("key"); NodeList children = requiredProperty.getElementsByTagNameNS(archetypeDescriptorUri, "defaultValue"); String value = ""; if (children.getLength() == 1 && children.item(0).hasChildNodes()) { value = children.item(0).getTextContent(); } else { if ("name".equals(key) && value.isEmpty()) { value = "HelloWorld"; } } replaceProperties.put(key, value); } }
From source file:ru.itdsystems.alfresco.persistence.CrudPost.java
@Override public void execute(WebScriptRequest req, WebScriptResponse res) throws WebScriptException { // construct path elements array from request parameters List<String> pathElements = new ArrayList<String>(); Map<String, String> templateVars = req.getServiceMatch().getTemplateVars(); pathElements.add(templateVars.get("application_name")); pathElements.add(templateVars.get("form_name")); doBefore(pathElements, null);/* w w w . j a v a 2s . co m*/ // parse xml from request and perform a search Document searchXML; DocumentBuilder xmlBuilder; DocumentBuilderFactory xmlFact; try { xmlFact = DocumentBuilderFactory.newInstance(); xmlFact.setNamespaceAware(true); xmlBuilder = xmlFact.newDocumentBuilder(); searchXML = xmlBuilder.parse(req.getContent().getInputStream()); } catch (Exception e) { throw new WebScriptException(500, "Error occured while parsing XML from request.", e); } XPath xpath = XPathFactory.newInstance().newXPath(); Integer pageSize; Integer pageNumber; String lang; // String applicationName; // String formName; NodeList queries; // extract search details try { pageSize = new Integer( ((Node) xpath.evaluate("/search/page-size/text()", searchXML, XPathConstants.NODE)) .getNodeValue()); pageNumber = new Integer( ((Node) xpath.evaluate("/search/page-number/text()", searchXML, XPathConstants.NODE)) .getNodeValue()); lang = ((Node) xpath.evaluate("/search/lang/text()", searchXML, XPathConstants.NODE)).getNodeValue(); // applicationName = ((Node) xpath.evaluate("/search/app/text()", // searchXML, XPathConstants.NODE)).getNodeValue(); // formName = ((Node) xpath.evaluate("/search/form/text()", // searchXML, // XPathConstants.NODE)).getNodeValue(); queries = (NodeList) xpath.evaluate("/search/query", searchXML, XPathConstants.NODESET); if (queries.getLength() == 0) throw new Exception("No queries found."); } catch (Exception e) { throw new WebScriptException(500, "XML in request is malformed.", e); } // check if requested query is supported if (!"".equals(queries.item(0).getTextContent())) throw new WebScriptException(500, "Freetext queries are not supported at the moment."); // resolve path to root data pathElements.add("data"); NodeRef nodeRef = getRootNodeRef(); // resolve path to file FileInfo fileInfo = null; Integer totalForms = 0; try { // fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements, false); fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements); } catch (FileNotFoundException e) { // do nothing here } if (fileInfo != null) { // iterate through all forms List<ChildAssociationRef> assocs = nodeService.getChildAssocs(fileInfo.getNodeRef()); List<String> details = new ArrayList<String>(); Document resultXML; try { resultXML = xmlBuilder.newDocument(); } catch (Exception e) { throw new WebScriptException(500, "Smth really strange happened o.O", e); } Element rootElement = resultXML.createElement("documents"); rootElement.setAttribute("page-size", pageSize.toString()); rootElement.setAttribute("page-number", pageNumber.toString()); rootElement.setAttribute("query", ""); resultXML.appendChild(rootElement); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"); int skip = pageSize * (pageNumber - 1); Integer found = 0; Integer searchTotal = 0; for (ChildAssociationRef assoc : assocs) { if ((nodeRef = nodeService.getChildByName(assoc.getChildRef(), ContentModel.ASSOC_CONTAINS, "data.xml")) != null) { // parse file Document dataXML; try { dataXML = xmlBuilder.parse(fileFolderService.getReader(nodeRef).getContentInputStream()); } catch (Exception e) { throw new WebScriptException(500, "Form file is malformed.", e); } totalForms++; details.clear(); xpath.setNamespaceContext(new OrbeonNamespaceContext()); // execute search queries for (int i = 1; i < queries.getLength(); i++) { Node query = queries.item(i); String path = query.getAttributes().getNamedItem("path").getNodeValue(); String match = query.getAttributes().getNamedItem("match").getNodeValue(); String queryString = query.getTextContent(); if (path == null || match == null || queryString == null) throw new WebScriptException(500, "Search query XML is malformed."); path = path.replace("$fb-lang", "'" + lang + "'"); boolean exactMatch = "exact".equals(match); Node queryResult; try { queryResult = (Node) xpath.evaluate(path, dataXML.getDocumentElement(), XPathConstants.NODE); } catch (Exception e) { throw new WebScriptException(500, "Error in query xpath expression.", e); } if (queryResult == null) break; String textContent = queryResult.getTextContent(); // TODO // check type while comparing values if (exactMatch && queryString.equals(textContent) || !exactMatch && textContent != null && textContent.contains(queryString) || queryString.isEmpty()) details.add(textContent); else break; } // add document to response xml if (details.size() == queries.getLength() - 1) { searchTotal++; if (skip > 0) skip--; else if (++found <= pageSize) { Element item = resultXML.createElement("document"); String createdText = dateFormat .format(fileFolderService.getFileInfo(nodeRef).getCreatedDate()); item.setAttribute("created", createdText.substring(0, 26) + ":" + createdText.substring(26)); String modifiedText = dateFormat .format(fileFolderService.getFileInfo(nodeRef).getModifiedDate()); item.setAttribute("last-modified", modifiedText.substring(0, 26) + ":" + modifiedText.substring(26)); item.setAttribute("name", fileFolderService.getFileInfo(assoc.getChildRef()).getName()); resultXML.getDocumentElement().appendChild(item); Element detailsElement = resultXML.createElement("details"); item.appendChild(detailsElement); for (String detail : details) { Element detailElement = resultXML.createElement("detail"); detailElement.appendChild(resultXML.createTextNode(detail)); detailsElement.appendChild(detailElement); } } /* * else break; */ } } } rootElement.setAttribute("total", totalForms.toString()); rootElement.setAttribute("search-total", searchTotal.toString()); // stream output to client try { TransformerFactory.newInstance().newTransformer().transform(new DOMSource(resultXML), new StreamResult(res.getOutputStream())); } catch (Exception e) { throw new WebScriptException(500, "Error occured while streaming output to client.", e); } } }
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionServiceIntermediaryTest.java
/** * Test the entity resolution service.//from w w w . j ava2 s .c o m * * @throws Exception */ @Test @DirtiesContext public void testEntityResolution() throws Exception { // Read the er search request file from the file system File inputFile = new File("src/test/resources/xml/EntityMergeRequestMessageWithAttributeParameters.xml"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document inputDocument = dbf.newDocumentBuilder().parse(inputFile); // Set it as the message message body senderExchange.getIn().setBody(inputDocument); // Send the one-way exchange. Using template.send will send an one way message Exchange returnExchange = template.send("direct:entityResolutionRequestServiceEndpoint", senderExchange); // Use getException to see if we received an exception if (returnExchange.getException() != null) { throw new Exception(returnExchange.getException()); } // Sleep while a response is generated Thread.sleep(3000); // Assert that the mock endpoint is satisfied entityResolutionResponseMock.assertIsSatisfied(); // We should get one message entityResolutionResponseMock.expectedMessageCount(1); // Get the first exchange (the only one) Exchange ex = entityResolutionResponseMock.getExchanges().get(0); // Get the actual response Document actualResponse = ex.getIn().getBody(Document.class); log.info("Input document: " + new XmlConverter().toString(inputDocument, null)); log.info("Body recieved by Mock: " + new XmlConverter().toString(actualResponse, ex)); XPath xp = XPathFactory.newInstance().newXPath(); xp.setNamespaceContext(testNamespaceContext); // note: slash-slash xpaths are ok here because in tests we don't really care about performance... int inputEntityNodeCount = ((NodeList) xp.evaluate("//er-ext:Entity", inputDocument, XPathConstants.NODESET)).getLength(); int outputEntityNodeCount = ((NodeList) xp.evaluate("//merge-result-ext:Entity", actualResponse, XPathConstants.NODESET)).getLength(); NodeList outputOriginalRecordReferenceNodeList = (NodeList) xp .evaluate("//merge-result-ext:OriginalRecordReference", actualResponse, XPathConstants.NODESET); int outputOriginalRecordReferenceNodeCount = outputOriginalRecordReferenceNodeList.getLength(); assertEquals(inputEntityNodeCount, outputEntityNodeCount); assertEquals(inputEntityNodeCount, outputOriginalRecordReferenceNodeCount); NodeList inputPersonNodes = (NodeList) xp.evaluate("//ext:Person", inputDocument, XPathConstants.NODESET); for (int i = 0; i < inputPersonNodes.getLength(); i++) { String inputLastName = xp.evaluate("nc:PersonName/nc:PersonSurName/text()", inputPersonNodes.item(i)); if (inputLastName != null) { String xpathExpression = "//ext:Person[nc:PersonName/nc:PersonSurName/text()='" + inputLastName + "']"; assertNotNull(xp.evaluate(xpathExpression, actualResponse, XPathConstants.NODE)); } String inputFirstName = xp.evaluate("nc:PersonName/nc:PersonGivenName/text()", inputPersonNodes.item(i)); if (inputFirstName != null) { String xpathExpression = "//ext:Person[nc:PersonName/nc:PersonGivenName/text()='" + inputFirstName + "']"; log.info("xpathExpression=" + xpathExpression); assertNotNull(xp.evaluate(xpathExpression, actualResponse, XPathConstants.NODE)); } String inputId = xp.evaluate( "jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID", inputPersonNodes.item(i)); if (inputId != null) { String xpathExpression = "//ext:Person[jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID/text()='" + inputId + "']"; assertNotNull(xp.evaluate(xpathExpression, actualResponse, XPathConstants.NODE)); } } for (int i = 0; i < outputOriginalRecordReferenceNodeCount; i++) { String nodeRef = ((Element) outputOriginalRecordReferenceNodeList.item(i)) .getAttributeNS("http://niem.gov/niem/structures/2.0", "ref"); assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + nodeRef + "']", actualResponse, XPathConstants.NODE)); } }
From source file:org.ala.harvester.FlickrHarvester.java
/** * Parses the XML listing of images to obtain data necessary for future data * extraction. Specifically, the current page number, current images per * page and total number of pages./*from w ww. j av a 2 s . c o m*/ * * @since v0.4 */ private int[] parseDataFragmentationInfo(Document currentResDom) throws Exception { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); try { int currentPageNum = Integer .parseInt((String) xpath.evaluate("/rsp/photos/@page", currentResDom, XPathConstants.STRING)); int totalPages = Integer .parseInt((String) xpath.evaluate("/rsp/photos/@pages", currentResDom, XPathConstants.STRING)); int actualRecordsPerPage = Integer.parseInt( (String) xpath.evaluate("count(/rsp/photos/photo)", currentResDom, XPathConstants.STRING)); logger.debug("Extracted and set current page number to " + currentPageNum); logger.debug("Extracted and set total page number to " + totalPages); logger.debug("Actual number of records returned is " + actualRecordsPerPage); return new int[] { currentPageNum, totalPages, actualRecordsPerPage }; } catch (XPathExpressionException getPageFragmentationError) { String errMsg = "Failed to obtain data fragmentation information from Flickr's REST response."; throw new Exception(errMsg, getPageFragmentationError); } }
From source file:it.ciroppina.idol.generic.tunnel.IdolOEMTunnel.java
/** * executes the IDOL Server GetVersion action * @return a String containing the Json compact response * // w ww. j a va2 s . c om * @throws XPathExpressionException */ @WebMethod(operationName = "getversion") public String getversion() { // We'll issue a GetVersion action and use the supplied DOM Document processor to process the response... Document response = this.aciService.executeAction(new AciParameters(AciConstants.ACTION_GET_VERSION), new DocumentProcessor()); // Use XPath to pull out the value of the field the contains the type of the ACI server... try { final XPath xpath = XPathFactory.newInstance().newXPath(); return (String) xpath.evaluate("/autnresponse/responsedata/producttypecsv", response, XPathConstants.STRING) + ", version: " + (String) xpath.evaluate("/autnresponse/responsedata/version", response, XPathConstants.STRING) + " - " + (String) xpath.evaluate("/autnresponse/responsedata/aciversion", response, XPathConstants.STRING); } catch (XPathExpressionException xpe) { xpe.printStackTrace(); return "IdolOEMTunnel - getversion: Error Occurred - not a valid XML autnresponse"; } catch (Exception e) { e.printStackTrace(); return "IdolOEMTunnel - getversion: unexpected Error Occurred"; } }
From source file:org.syncope.core.workflow.ActivitiUserWorkflowAdapter.java
@Override public List<String> getDefinedTasks() throws WorkflowException { List<String> result = new ArrayList<String>(); ProcessDefinition procDef;//w ww . j av a 2 s .c o m try { procDef = repositoryService.createProcessDefinitionQuery() .processDefinitionKey(ActivitiUserWorkflowAdapter.WF_PROCESS_ID).latestVersion().singleResult(); } catch (ActivitiException e) { throw new WorkflowException(e); } InputStream procDefIS = repositoryService.getResourceAsStream(procDef.getDeploymentId(), WF_PROCESS_RESOURCE); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(procDefIS); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xpath.evaluate("//userTask | //serviceTask | //scriptTask", doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { result.add(nodeList.item(i).getAttributes().getNamedItem("id").getNodeValue()); } } catch (Exception e) { throw new WorkflowException(e); } finally { try { procDefIS.close(); } catch (IOException ioe) { LOG.error("While closing input stream for {}", procDef.getKey(), ioe); } } return result; }
From source file:org.apache.flex.utilities.converter.retrievers.download.DownloadRetriever.java
public Map<DefaultArtifactVersion, Collection<PlatformType>> getAvailableVersions(SdkType type) { Map<DefaultArtifactVersion, Collection<PlatformType>> result = new HashMap<DefaultArtifactVersion, Collection<PlatformType>>(); try {//from w w w .ja va 2 s . c o m final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(getFlexInstallerConfigUrl()); final XPath xPath = XPathFactory.newInstance().newXPath(); String expression; NodeList nodes = null; switch (type) { case FLEX: expression = "/config/products/ApacheFlexSDK/versions/*"; nodes = (NodeList) xPath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET); break; case FLASH: expression = "/config/flashsdk/versions/*"; nodes = (NodeList) xPath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET); break; case AIR: expression = "/config/airsdk/*/versions/*"; nodes = (NodeList) xPath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET); break; } if (nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); DefaultArtifactVersion version = new DefaultArtifactVersion(element.getAttribute("version")); if (type == SdkType.AIR) { PlatformType platformType = PlatformType .valueOf(element.getParentNode().getParentNode().getNodeName().toUpperCase()); if (!result.containsKey(version)) { result.put(version, new ArrayList<PlatformType>()); } result.get(version).add(platformType); } else { result.put(version, null); } } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return result; }