List of usage examples for javax.xml.xpath XPathExpression evaluate
public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;
From source file:com.alliander.osgp.platform.cucumber.GetFirmwareVersion.java
@Then("^the firmware version result should be returned$") public void theFirmwareVersionResultShouldBeReturned() throws Throwable { final TestCaseResult runTestStepByName = this.testCaseRunner.runWsdlTestCase(this.testCase, this.deviceId, this.organisationId, this.correlationUid, TEST_CASE_NAME_RESPONSE); final TestStepResult runTestStepByNameResult = runTestStepByName.getRunTestStepByName(); final WsdlTestCaseRunner wsdlTestCaseRunner = runTestStepByName.getResults(); for (final TestStepResult tcr : wsdlTestCaseRunner.getResults()) { LOGGER.info(TEST_CASE_NAME_RESPONSE + " response {}", this.response = ((MessageExchange) tcr).getResponseContent()); }//from w ww .jav a2 s . c o m final XpathResult xpathResult = this.xpathResult.runXPathExpression(this.response, PATH_RESULT); final XPathExpression expr = xpathResult.getXpathExpression(); Assert.assertEquals(XPATH_MATCHER_RESULT, expr.evaluate(xpathResult.getDocument(), XPathConstants.STRING)); Assert.assertEquals(TestStepStatus.OK, runTestStepByNameResult.getStatus()); }
From source file:com.digitalpebble.storm.crawler.parse.filter.ContentFilter.java
@Override public void filter(String URL, byte[] content, DocumentFragment doc, ParseResult parse) { ParseData pd = parse.get(URL); // TODO determine how to restrict the expressions e.g. regexp on URL // or value in metadata // iterates on the expressions - stops at the first that matches for (XPathExpression expression : expressions) { try {//www . j a v a 2 s . com NodeList evalResults = (NodeList) expression.evaluate(doc, XPathConstants.NODESET); if (evalResults.getLength() == 0) { continue; } StringBuilder newText = new StringBuilder(); for (int i = 0; i < evalResults.getLength(); i++) { Node node = evalResults.item(i); newText.append(node.getTextContent()).append("\n"); } // ignore if no text captured if (StringUtils.isBlank(newText.toString())) { LOG.debug("Found match for doc {} but empty text extracted - skipping", URL); continue; } // give the doc its new text value LOG.debug("Restricted text for doc {}. Text size was {} and is now {}", URL, pd.getText().length(), newText.length()); pd.setText(newText.toString()); return; } catch (XPathExpressionException e) { LOG.error("Caught XPath expression", e); } } }
From source file:com.fluidops.iwb.deepzoom.CXMLServlet.java
static void readImageCollectionFile(String collection) { InputStream stream = null;// w ww . j av a 2s . co m try { stream = new FileInputStream(collection); Document doc = null; doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(stream); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//I"); NodeList result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < result.getLength(); i++) { Node node = result.item(i); NamedNodeMap map = node.getAttributes(); String source = map.getNamedItem("Source").getNodeValue(); String id = map.getNamedItem("Id").getNodeValue(); source = source.substring("dzimages/".length(), source.lastIndexOf(".xml")); ids.put(source, id); } } catch (RuntimeException e) { logger.error(e.getMessage(), e); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(stream); } }
From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java
public HashMap<String, String> extractValues(Document xml, String path) { try {//from w ww . jav a 2 s .c o m HashMap<String, String> resultMap = new HashMap<String, String>(); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(namespaceContext); XPathExpression expr = xpath.compile(path); NodeList list = (NodeList) expr.evaluate(xml, XPathConstants.NODESET); if (list != null) { for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); String content = n.getTextContent(); if (content != null) { resultMap.put(n.getLocalName(), content); } } } return resultMap; } catch (Exception e) { log.error("Could not parse XML " + " searching for path " + path + ": " + e.getMessage(), e); return null; } }
From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java
/** * very useful: {@link http/*from w w w .ja v a 2 s . co m*/ * ://www.ibm.com/developerworks/library/x-javaxpathapi.html} * * @param doc * @param path * @param scale * @return * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws XPathExpressionException */ private String extractTextInternal(Document doc, String path) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(namespaceContext); XPathExpression expr = xpath.compile(path); try { String result = (String) expr.evaluate(doc, XPathConstants.STRING); return result; } catch (Exception e) { log.error("XML extraction for path " + path + " failed: " + e.getMessage(), e); return "XML extraction for path " + path + " failed: " + e.getMessage(); } }
From source file:nl.surfnet.sab.SabResponseParser.java
/** * Check that response contains the success status. Throw IOException with message otherwise. *//*from w ww . j a va 2 s.c om*/ private void validateStatus(Document document, XPath xpath) throws XPathExpressionException, IOException { XPathExpression statusCodeExpression = xpath.compile(XPATH_STATUSCODE); String statusCode = (String) statusCodeExpression.evaluate(document, XPathConstants.STRING); if (SAMLP_SUCCESS.equals(statusCode)) { // Success, validation returns. return; } else { // Status message is only set if status code not 'success'. XPathExpression statusMessageExpression = xpath.compile(XPATH_STATUSMESSAGE); String statusMessage = (String) statusMessageExpression.evaluate(document, XPathConstants.STRING); if (SAMLP_RESPONDER.equals(statusCode) && statusMessage.startsWith(NOT_FOUND_MESSAGE_PREFIX)) { LOG.debug( "Given nameId not found in SAB. Is regarded by us as 'valid' response, although server response indicates a server error."); return; } else { throw new IOException("Unsuccessful status. Code: '" + statusCode + "', message: " + statusMessage); } } }
From source file:at.sti2.spark.handler.ImpactoriumHandler.java
public String extractInfoObjectIdentifier(String infoObjectResponse) { String reportId = null;/*from w w w. j a v a2s .c om*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //dbf.setNamespaceAware(true); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new ByteArrayInputStream(infoObjectResponse.getBytes("UTF-8"))); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//info-object"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; Node item = nodes.item(0); if (item != null) { NamedNodeMap attributesMap = item.getAttributes(); Node idAttribute = attributesMap.getNamedItem("id"); reportId = idAttribute.getNodeValue(); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return reportId; }
From source file:cz.incad.kramerius.security.impl.criteria.MovingWall.java
public EvaluatingResult evaluateDoc(int wallFromConf, Document xmlDoc, String xPathExpression) throws XPathExpressionException { XPath xpath = xpfactory.newXPath(); xpath.setNamespaceContext(new FedoraNamespaceContext()); XPathExpression expr = xpath.compile(xPathExpression); Object date = expr.evaluate(xmlDoc, XPathConstants.NODE); if (date != null) { String patt = ((Text) date).getData(); try {/*from w ww . j ava 2 s . c o m*/ DatesParser dateParse = new DatesParser(new DateLexer(new StringReader(patt))); Date parsed = dateParse.dates(); Calendar calFromMetadata = Calendar.getInstance(); calFromMetadata.setTime(parsed); Calendar calFromConf = Calendar.getInstance(); calFromConf.add(Calendar.YEAR, -1 * wallFromConf); return calFromMetadata.before(calFromConf) ? EvaluatingResult.TRUE : EvaluatingResult.FALSE; } catch (RecognitionException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); LOGGER.log(Level.SEVERE, "Returning NOT_APPLICABLE"); return EvaluatingResult.NOT_APPLICABLE; } catch (TokenStreamException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); LOGGER.log(Level.SEVERE, "Returning NOT_APPLICABLE"); return EvaluatingResult.NOT_APPLICABLE; } } return null; }
From source file:com.fortysevendeg.lab.WeatherTask.java
/** * Performs work in the background invoking the weather remote service and parses the xml results into temp values * @param strings the place params to search form * @return the temperature in celsius// w w w.j ava 2s . com */ @Override protected final Integer doInBackground(String... strings) { int temp = ERROR; try { String xml = fetchWeatherData(strings[0]); if (xml != null) { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile(context.getString(R.string.xpath_weather_service_temperature)); Object result = expr.evaluate(new InputSource(new StringReader(xml)), XPathConstants.NODESET); NodeList nodes = (NodeList) result; if (nodes.getLength() > 0) { temp = Integer.valueOf(nodes.item(0).getAttributes().getNamedItem("data").getNodeValue()); } } } catch (XPathExpressionException e) { Log.wtf(WeatherTask.class.toString(), e); } catch (IOException e) { Log.wtf(WeatherTask.class.toString(), e); } return temp; }
From source file:org.syncope.console.commons.XMLRolesReader.java
/** * Get all roles allowed for specific page and actio requested. * * @param pageId/* ww w.j a v a2s . c o m*/ * @param actionId * @return roles list comma separated */ public String getAllAllowedRoles(final String pageId, final String actionId) { if (doc == null) { init(); } if (doc == null) { return ""; } final StringBuilder roles = new StringBuilder(); try { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile( "//page[@id='" + pageId + "']/" + "action[@id='" + actionId + "']/" + "entitlement/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { if (i > 0) { roles.append(","); } roles.append(nodes.item(i).getNodeValue()); } } catch (XPathExpressionException e) { LOG.error("While parsing authorizations file", e); } LOG.debug("Authorizations found: {}", roles); return roles.toString(); }