List of usage examples for javax.xml.xpath XPathConstants STRING
QName STRING
To view the source code for javax.xml.xpath XPathConstants STRING.
Click Source Link
The XPath 1.0 string data type.
Maps to Java String .
From source file:org.opencastproject.remotetest.server.CaptureAdminRestEndpointTest.java
@Test public void testGetAgents() throws Exception { String endpoint = "/capture-admin/agents"; HttpGet get = new HttpGet(BASE_URL + endpoint + ".xml"); String xmlResponse = EntityUtils.toString(httpClient.execute(get).getEntity()); Main.returnClient(httpClient);/*w ww .j av a2 s . c om*/ // parse the xml and extract the running clients names DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(xmlResponse, "UTF-8")); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList agents = (NodeList) xPath.compile("//*[local-name() = 'agent']").evaluate(doc, XPathConstants.NODESET); // validate the REST endpoint for each agent state is functional for (int i = 0; i < agents.getLength(); i++) { try { httpClient = Main.getClient(); String agentName = (String) xPath.evaluate("*[local-name() = 'name']/text()", agents.item(i), XPathConstants.STRING); HttpGet agentGet = new HttpGet(BASE_URL + endpoint + "/" + agentName + ".xml"); int agentResponse = httpClient.execute(agentGet).getStatusLine().getStatusCode(); assertEquals(HttpStatus.SC_OK, agentResponse); } finally { Main.returnClient(httpClient); } } }
From source file:com.thed.launcher.EggplantZBotScriptLauncher.java
@Override public void testcaseExecutionResult() { String scriptPath = LauncherUtils.getFilePathFromCommand(currentTestcaseExecution.getScriptPath()); logger.info("Script Path is " + scriptPath); File scriptFile = new File(scriptPath); String scriptName = scriptFile.getName().split("\\.")[0]; logger.info("Script Name is " + scriptName); File resultsFolder = new File( scriptFile.getParentFile().getParentFile().getAbsolutePath() + File.separator + "Results"); File statisticalFile = resultsFolder.listFiles(new FilenameFilter() { @Override/*w ww . j a v a2 s. c o m*/ public boolean accept(File file, String s) { return StringUtils.endsWith(s, "Statistics.xml"); } })[0]; try { XPath xpath = XPathFactory.newInstance().newXPath(); Document statisticalDoc = getDoc(statisticalFile); String result = xpath.compile("/statistics/script[@name='" + scriptName + "']/LastStatus/text()") .evaluate(statisticalDoc, XPathConstants.STRING).toString(); logger.info("Result is " + result); String comments; if (StringUtils.equalsIgnoreCase(result, "Success")) { logger.info("Test success detected"); status = currentTestcaseExecution.getTcId() + ": " + currentTestcaseExecution.getScriptId() + " STATUS: Script Successfully Executed"; currentTcExecutionResult = new Integer(1); comments = " Successfully executed on " + agent.getAgentHostAndIp(); } else { logger.info("Test failure detected, getting error message"); status = currentTestcaseExecution.getTcId() + ": " + currentTestcaseExecution.getScriptId() + " STATUS: Script Successfully Executed"; currentTcExecutionResult = new Integer(2); comments = " Error in test: "; String lastRunDateString = xpath .compile("/statistics/script[@name='" + scriptName + "']/LastRun/text()") .evaluate(statisticalDoc); //Date lastRunDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(lastRunDateString); File historyFile = new File(resultsFolder.getAbsolutePath() + File.separator + scriptName + File.separator + "RunHistory.xml"); Document historyDoc = getDoc(historyFile); //xpath = XPathFactory.newInstance().newXPath(); String xpathExpr = "/runHistory[@script='" + scriptName + "']/run[contains(RunDate, '" + StringUtils.substringBeforeLast(lastRunDateString, " ") + "')]/ErrorMessage/text()"; logger.info("Using xPath to find errorMessage " + xpathExpr); comments += xpath.compile(xpathExpr).evaluate(historyDoc, XPathConstants.STRING); logger.info("Sending comments: " + comments); } if (currentTcExecutionResult != null) { ScriptUtil.updateTestcaseExecutionResult(url, currentTestcaseExecution, currentTcExecutionResult, comments); } } catch (Exception e) { logger.log(Level.SEVERE, "Error in reading process steams \n", e); } }
From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java
public void perform(Node serverDeploymentsDeploymentNode) throws XPathExpressionException { NodeList extractionOperations = (NodeList) extractXpath.evaluate(serverDeploymentsDeploymentNode, XPathConstants.NODESET); for (int j = 0; j < extractionOperations.getLength(); j++) { Node extractionOperation = extractionOperations.item(j); String uri = (String) urlXpath.evaluate(extractionOperation, XPathConstants.STRING); NodeList extractions = (NodeList) extractionsExtractionXpath.evaluate(extractionOperation, XPathConstants.NODESET); List<ExtractionPair> exts = new ArrayList<>(); for (int k = 0; k < extractions.getLength(); k++) { Node extraction = extractions.item(k); String source = (String) sourceXpath.evaluate(extraction, XPathConstants.STRING); String destination = (String) destinationXpath.evaluate(extraction, XPathConstants.STRING); exts.add(new ExtractionPair(source, destination)); }//from w w w. jav a2 s .co m extract(uri, exts); } }
From source file:org.opencastproject.remotetest.server.EpisodeServiceTest.java
@Test public void testLockMediaPackage() throws Exception { // get a media package id Document r1 = doGetRequest("workflow/instances.xml", HttpStatus.SC_OK, tuple("startPage", 0), tuple("count", 1)); String id = (String) xpath(r1, "//*[local-name() = 'mediapackage']/@id", XPathConstants.STRING); ////from w w w. j a v a 2s . c o m Document r2 = doGetRequest("episode/episode.xml", HttpStatus.SC_OK, tuple("id", id), tuple("limit", 0), tuple("offset", 0)); boolean locked = Boolean .parseBoolean((String) xpath(r2, "//*[local-name() = 'ocLocked']", XPathConstants.STRING)); // un/lock this package if (locked) { doPostRequest("episode/unlock", HttpStatus.SC_NO_CONTENT, tuple("id", id)); } else { doPostRequest("episode/lock", HttpStatus.SC_NO_CONTENT, tuple("id", id)); // TODO test apply should not work } // and test it Document r3 = doGetRequest("episode/episode.xml", HttpStatus.SC_OK, tuple("id", id), tuple("limit", 0), tuple("offset", 0)); boolean newLocked = Boolean .parseBoolean((String) xpath(r3, "//*[local-name() = 'ocLocked']", XPathConstants.STRING)); System.out.println(newLocked); assertEquals(!locked, newLocked); }
From source file:org.opencastproject.remotetest.server.ServiceRegistryRestEndpointTest.java
@Test public void testGetServiceRegistrations() throws Exception { // Get a known service registration as xml HttpGet get = new HttpGet( serviceUrl + "/services.xml?serviceType=org.opencastproject.composer&host=" + remoteHost); HttpResponse response = client.execute(get); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); InputStream in = null;/* w w w .j a v a 2 s . co m*/ Document doc = null; try { in = response.getEntity().getContent(); doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in); String typeFromResponse = (String) Utils.xpath(doc, "//*[local-name() = 'type']", XPathConstants.STRING); Assert.assertEquals("org.opencastproject.composer", typeFromResponse); String hostFromResponse = (String) Utils.xpath(doc, "//*[local-name() = 'host']", XPathConstants.STRING); Assert.assertEquals(BASE_URL, hostFromResponse); } finally { IOUtils.closeQuietly(in); Main.returnClient(client); } // Get a registration that is known to not exist, and ensure we get a 404 client = Main.getClient(); get = new HttpGet(serviceUrl + "/services.xml?serviceType=foo&host=" + remoteHost); response = client.execute(get); Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode()); // Get all services on a single host client = Main.getClient(); get = new HttpGet(serviceUrl + "/services.xml?host=" + remoteHost); response = client.execute(get); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); try { in = response.getEntity().getContent(); doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in); int serviceCount = ((Number) Utils.xpath(doc, "count(//*[local-name() = 'service'])", XPathConstants.NUMBER)).intValue(); Assert.assertTrue(serviceCount > 0); } finally { IOUtils.closeQuietly(in); Main.returnClient(client); } // Get all services of a single type client = Main.getClient(); get = new HttpGet(serviceUrl + "/services.xml?serviceType=org.opencastproject.composer"); response = client.execute(get); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); try { in = response.getEntity().getContent(); doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in); int serviceCount = ((Number) Utils.xpath(doc, "count(//*[local-name() = 'service'])", XPathConstants.NUMBER)).intValue(); Assert.assertEquals(1, serviceCount); } finally { IOUtils.closeQuietly(in); Main.returnClient(client); } // Get statistics client = Main.getClient(); get = new HttpGet(serviceUrl + "/statistics.xml"); response = client.execute(get); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); try { in = response.getEntity().getContent(); doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in); int serviceCount = ((Number) Utils.xpath(doc, "count(//*[local-name() = 'service'])", XPathConstants.NUMBER)).intValue(); Assert.assertTrue(serviceCount > 0); } finally { IOUtils.closeQuietly(in); Main.returnClient(client); } }
From source file:cz.incad.cdk.cdkharvester.PidsRetriever.java
private void getDocs() throws Exception { String urlStr = harvestUrl + URIUtil.encodeQuery(actual_date); logger.log(Level.INFO, "urlStr: {0}", urlStr); org.w3c.dom.Document solrDom = solrResults(urlStr); String xPathStr = "/response/result/@numFound"; expr = xpath.compile(xPathStr);/*from w ww . j a v a 2s . com*/ int numDocs = Integer.parseInt((String) expr.evaluate(solrDom, XPathConstants.STRING)); logger.log(Level.INFO, "numDocs: {0}", numDocs); if (numDocs > 0) { xPathStr = "/response/result/doc/str[@name='PID']"; expr = xpath.compile(xPathStr); NodeList nodes = (NodeList) expr.evaluate(solrDom, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String pid = node.getFirstChild().getNodeValue(); String to = node.getNextSibling().getFirstChild().getNodeValue(); qe.add(new DocEntry(pid, to)); } } }
From source file:org.trustedanalytics.hadoop.admin.tools.HadoopClientParamsImporter.java
static Optional<Map<String, String>> scanConfigZipArchive(InputStream source) throws IOException, XPathExpressionException { InputStream zipInputStream = new ZipInputStream(new BufferedInputStream(source)); ZipEntry zipFileEntry;// w ww . jav a 2s.co m Map<String, String> ret = new HashMap<>(); while ((zipFileEntry = ((ZipInputStream) zipInputStream).getNextEntry()) != null) { if (!zipFileEntry.getName().endsWith("-site.xml")) { continue; } byte[] bytes = IOUtils.toByteArray(zipInputStream); InputSource is = new InputSource(new ByteArrayInputStream(bytes)); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate(CONF_PROPERTY_XPATH, is, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node propNode = nodeList.item(i); String key = (String) xPath.evaluate("name/text()", propNode, XPathConstants.STRING); String value = (String) xPath.evaluate("value/text()", propNode, XPathConstants.STRING); ret.put(key, value); } } return Optional.of(ret); }
From source file:com.hin.hl7messaging.InvoiceSvgService.java
@Override public String createSvgDocument(Document doc, List<Concept> invoiceServiceArray, String organizationName, String telecom, String address, String exchangeRate, String currencyCode) { String stringData = "", invoiceId = "", totalAmount = "", doctorName = "", patientName = "", discount = "", interest = ""; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null;//from w w w . j a va2 s . c o m HashMap<String, String> serviceMap = new HashMap<String, String>(); HashMap<String, String> xCoordinatesMap = new HashMap<String, String>(); String doctorPrefix = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/postingTo/patientAccount/pertinentInformation/encounterEvent/consultant/employmentStaff/employeePerson/name/prefix", XPathConstants.STRING); String doctorGiven = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/postingTo/patientAccount/pertinentInformation/encounterEvent/consultant/employmentStaff/employeePerson/name/given", XPathConstants.STRING); String doctorFamily = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/postingTo/patientAccount/pertinentInformation/encounterEvent/consultant/employmentStaff/employeePerson/name/family", XPathConstants.STRING); String doctorSuffix = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/postingTo/patientAccount/pertinentInformation/encounterEvent/consultant/employmentStaff/employeePerson/name/suffix", XPathConstants.STRING); if (doctorPrefix != null && doctorPrefix != "") doctorName = doctorName + " " + doctorPrefix; if (doctorGiven != null && doctorGiven != "") doctorName = doctorName + " " + doctorGiven; if (doctorFamily != null && doctorFamily != "") doctorName = doctorName + " " + doctorFamily; if (doctorSuffix != null && doctorSuffix != "") doctorName = doctorName + " " + doctorSuffix; NodeList idFields = (NodeList) XMLHelper.read(doc, "message/FIAB_MT020000HT02/id", XPathConstants.NODESET); int idSize = idFields.getLength(); for (int i = 1; i <= idSize; i++) { String rootNode = "message/FIAB_MT020000HT02/id[" + i + "]/root"; String root = (String) XMLHelper.read(doc, rootNode, XPathConstants.STRING); root = root.replaceAll("\\n", "").trim(); if (root.equals("INVOICE_ID")) { invoiceId = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/id[" + i + "]/extension", XPathConstants.STRING); } if (root.equals("INVOICE_AMOUNT")) { totalAmount = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/id[" + i + "]/extension", XPathConstants.STRING); } if (root.equals("DISCOUNT")) { discount = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/id[" + i + "]/extension", XPathConstants.STRING); } if (root.equals("INTEREST")) { interest = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/id[" + i + "]/extension", XPathConstants.STRING); } } String date = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/effectiveTime/value", XPathConstants.STRING); String[] myStringArray = date.split(" "); date = myStringArray[0]; String prefix = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/postingTo/patientAccount/pertinentInformation/encounterEvent/subject/patient/patientPerson/name/prefix", XPathConstants.STRING); String given = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/postingTo/patientAccount/pertinentInformation/encounterEvent/subject/patient/patientPerson/name/given", XPathConstants.STRING); String family = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/postingTo/patientAccount/pertinentInformation/encounterEvent/subject/patient/patientPerson/name/family", XPathConstants.STRING); String suffix = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/postingTo/patientAccount/pertinentInformation/encounterEvent/subject/patient/patientPerson/name/suffix", XPathConstants.STRING); if (prefix != null && prefix != "") patientName = patientName + " " + prefix; if (given != null && given != "") patientName = patientName + " " + given; if (family != null && family != "") patientName = patientName + " " + family; if (suffix != null && suffix != "") patientName = patientName + " " + suffix; //System.out.println("Patient Name: " + patientName); NodeList serviceFields = (NodeList) XMLHelper.read(doc, "message/FIAB_MT020000HT02/pertinentInformation", XPathConstants.NODESET); int serviceSize = serviceFields.getLength(); for (int i = 1; i <= serviceSize; i++) { String serviceName = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/pertinentInformation[" + i + "]/observationOrder/code/displayName", XPathConstants.STRING); serviceName = serviceName.replaceAll("\\n", "").trim(); String cost = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/component[" + i + "]/financialTransactionChargeDetail/unitPriceAmt/numerator/value", XPathConstants.STRING); cost = cost.replaceAll("\\n", "").trim(); String serviceCode = (String) XMLHelper.read(doc, "message/FIAB_MT020000HT02/pertinentInformation[" + i + "]/observationOrder/code/code", XPathConstants.STRING); serviceCode = serviceCode.replaceAll("\\n", "").trim(); serviceMap.put(serviceName, cost); if (invoiceServiceArray != null && !invoiceServiceArray.isEmpty()) { for (Concept service : invoiceServiceArray) { if (!service.getDescription().equals(serviceCode)) { serviceMap.put("---" + service.getDescription(), ""); } } } } try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document document = db.newDocument(); Element rootElement = createRootElement(document); Element g = document.createElement("g"); Element subG = document.createElement("g"); Element imageElement = createImage(document, subG); String style = "font-size:18.44000006px;font-variant:normal;font-weight:normal;writing-mode:lr-tb;fill:#500e4a;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Myriad Pro Light;-inkscape-font-specification:Myriad Pro Light"; Element organizationElement = createTestTitleElement(document, subG, organizationName, "500", "113", style); Element addressElement = createTestTitleElement(document, subG, address, "500", "133", style); Element telecomElement = createTestTitleElement(document, subG, telecom, "500", "153", style); style = "font-size:25.52000046px;font-variant:normal;font-weight:bold;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Myriad Pro Light;-inkscape-font-specification:Myriad Pro Light-Bold"; Element headerElement = createTestTitleElement(document, subG, "INVOICE", "1050", "113", style); style = "font-size:18.44000006px;font-variant:normal;font-weight:bold;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Myriad Pro Light;-inkscape-font-specification:Myriad Pro Light-Bold"; Element customerElement = createTestTitleElement(document, subG, "To: " + patientName, "100", "290", style); style = "font-size:18.44000006px;font-variant:normal;font-weight:normal;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Myriad Pro Light;-inkscape-font-specification:Myriad Pro Light"; Element invoiceNumElement = createTestTitleElement(document, subG, "Invoice Number : " + invoiceId, "930", "290", style); Element dateElement = createTestTitleElement(document, subG, "Date : " + date, "930", "310", style); Element doctorElement = createTestTitleElement(document, subG, "Doctor : " + doctorName, "930", "330", style); Element horizontalElement = createHorizontalLine(document, subG, "100", "380"); Element verticalElement = createVerticleLines(document, subG, "100", "380", serviceMap.size()); Element horizontalHeaderEndElement = createHorizontalLine(document, subG, "100", "450"); style = "font-size:18.44000006px;font-variant:normal;font-weight:bold;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Myriad Pro Light;-inkscape-font-specification:Myriad Pro Light-Bold"; Element descriptionElement = createTestTitleElement(document, subG, "Description", "400", "410", style); Element amtHeaderElement = createTestTitleElement(document, subG, "Amount in USD", "980", "410", style); style = "font-size:18.44000006px;font-variant:normal;font-weight:normal;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none;font-family:Myriad Pro Light;-inkscape-font-specification:Myriad Pro Light"; xCoordinatesMap.put("115", "1150"); Element closeElement = createEndComponent(document, subG, "100", String.valueOf(serviceYAxis + 100), totalAmount, exchangeRate, currencyCode, discount, interest); Element serviceElement = createServiceElement(document, subG, serviceMap, xCoordinatesMap, "480", style); rootElement.appendChild(g); g.appendChild(imageElement); g.appendChild(organizationElement); g.appendChild(addressElement); g.appendChild(telecomElement); g.appendChild(headerElement); g.appendChild(customerElement); g.appendChild(invoiceNumElement); g.appendChild(dateElement); g.appendChild(doctorElement); g.appendChild(horizontalElement); g.appendChild(verticalElement); g.appendChild(horizontalHeaderEndElement); g.appendChild(descriptionElement); g.appendChild(amtHeaderElement); g.appendChild(closeElement); g.appendChild(serviceElement); g.appendChild(serviceElement); document.appendChild(rootElement); stringData = XMLHelper.getXMLDocumentAsString(document); //System.out.println(stringData); return stringData; }
From source file:edu.sampleu.travel.workflow.TravelAccountRulesEngineExecutor.java
private String getElementValue(String docContent, String xpathExpression) { try {/* w w w . j ava2 s . c o m*/ Document document = XmlHelper.trimXml(new ByteArrayInputStream(docContent.getBytes())); XPath xpath = XPathHelper.newXPath(); String value = (String) xpath.evaluate(xpathExpression, document, XPathConstants.STRING); return value; } catch (Exception e) { throw new RiceRuntimeException(); } }
From source file:com.github.radium226.github.maven.MetaDataDownloader.java
public static String evaluateXPath(InputStream pomInputStream, String expression) throws XPathExpressionException { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); xPath.setNamespaceContext(new NamespaceContext() { @Override/* w w w . ja v a2s. c o m*/ public String getNamespaceURI(String prefix) { if (prefix.equals("ns")) { return "http://maven.apache.org/POM/4.0.0"; } return null; } @Override public String getPrefix(String namespaceURI) { return null; } @Override public Iterator getPrefixes(String namespaceURI) { return null; } }); XPathExpression xPathExpression = xPath.compile(expression); String version = (String) xPathExpression.evaluate(new InputSource(pomInputStream), XPathConstants.STRING); return version; }