List of usage examples for javax.xml.xpath XPathConstants NODESET
QName NODESET
To view the source code for javax.xml.xpath XPathConstants NODESET.
Click Source Link
The XPath 1.0 NodeSet data type.
Maps to Java org.w3c.dom.NodeList .
From source file:com.cordys.coe.ac.httpconnector.samples.JIRAResponseHandler.java
/** * This method checks the HTML for errors during processing. * /* w w w . j a v a 2s . co m*/ * @param document * The HTML document. * @param httpMethod * The actual HTTP method that was executed. * * @throws HandlerException * In case the response contains any functional errors. * @throws XPathExpressionException * In case one of the XPaths fail. */ protected void checkErrors(org.w3c.dom.Document document, HttpMethod httpMethod) throws HandlerException, XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xpath.evaluate("//span[@class='errMsg']/text()", document, XPathConstants.NODESET); int length = nodeList.getLength(); if (length != 0) { // The first error message found will be used. HandlerException he = new HandlerException( HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML, nodeList.item(0).getNodeValue()); for (int i = 0; i < length; i++) { Node node = nodeList.item(i); he.addAdditionalErrorMessage(node.getNodeValue()); } throw he; } // There is another possibility of which errors might be returned. There // is a td with // class formErrors. And it that holds the errors as list items. nodeList = (NodeList) xpath.evaluate("//td[@class='formErrors']/div[@class='errorArea']/ul/li/text()", document, XPathConstants.NODESET); length = nodeList.getLength(); if (length != 0) { // The first error message found will be used. HandlerException he = new HandlerException( HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML, nodeList.item(0).getNodeValue()); for (int i = 0; i < length; i++) { Node node = nodeList.item(i); he.addAdditionalErrorMessage(node.getNodeValue()); } throw he; } if (httpMethod.getStatusCode() == 500) { // Find the short description Node n = (Node) xpath.evaluate("//b[.='Cause: ']", document, XPathConstants.NODE); String shortError = n.getNextSibling().getNextSibling().getNodeValue().trim(); // The first error message found will be used. HandlerException he = new HandlerException( HandlerExceptionMessages.ERROR_CONVERTING_THE_RESPONSE_TO_PROPER_XML, "System Error: " + shortError); // Find the stacktrace if available. he.addAdditionalErrorMessage( (String) xpath.evaluate("//pre[@id='stacktrace']/text()", document, XPathConstants.STRING)); throw he; } }
From source file:net.sourceforge.dita4publishers.impl.ditabos.DitaTreeWalkerBase.java
/** * @param bos//from w w w . jav a 2 s .com * @param member * @throws Exception */ protected void walkMapGetDependencies(BoundedObjectSet bos, DitaMapBosMember member) throws Exception { NodeList topicrefs; try { topicrefs = (NodeList) DitaUtil.allTopicrefs.evaluate(member.getElement(), XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new BosException("Unexcepted exception evaluating xpath " + DitaUtil.allTopicrefs); } Set<BosMember> newMembers = new HashSet<BosMember>(); for (int i = 0; i < topicrefs.getLength(); i++) { Element topicref = (Element) topicrefs.item(i); Document targetDoc = null; URI targetUri = null; // For now, only consider local resources. if (!DitaUtil.isLocalScope(topicref)) continue; // If there is a key reference, attempt to resolve it, // then fall back to href, if any. String href = null; try { if (bosConstructionOptions.isMapTreeOnly()) { if (DitaUtil.targetIsADitaMap(topicref) && topicref.hasAttribute("href")) { href = topicref.getAttribute("href"); // Don't bother resolving pointers to the same doc. // We don't record dependencies on ourself. if (!href.startsWith("#")) targetDoc = AddressingUtil.resolveHrefToDoc(topicref, href, bosConstructionOptions, this.failOnAddressResolutionFailure); } } else if (DitaUtil.targetIsADitaFormat(topicref)) { if (topicref.hasAttribute("keyref")) { targetDoc = resolveKeyrefToDoc(topicref.getAttribute("keyref")); } if (targetDoc == null && topicref.hasAttribute("href")) { href = topicref.getAttribute("href"); // Don't bother resolving pointers to the same doc. // We don't record dependencies on ourself. if (!href.startsWith("#")) targetDoc = AddressingUtil.resolveHrefToDoc(topicref, href, bosConstructionOptions, this.failOnAddressResolutionFailure); } } else { if (topicref.hasAttribute("keyref")) { targetUri = resolveKeyrefToUri(topicref.getAttribute("keyref")); } if (targetUri == null && topicref.hasAttribute("href")) { href = topicref.getAttribute("href"); // Don't bother resolving pointers to the same doc. // We don't record dependencies on ourself. if (!href.startsWith("#")) targetUri = AddressingUtil.resolveHrefToUri(topicref, href, this.failOnAddressResolutionFailure); } } } catch (AddressingException e) { if (this.failOnAddressResolutionFailure) { throw new BosException( "Failed to resolve href \"" + topicref.getAttribute("href") + "\" to a managed object", e); } } BosMember childMember = null; if (targetDoc != null) { childMember = bos.constructBosMember(member, targetDoc); } if (targetUri != null) { childMember = bos.constructBosMember(member, targetUri); } if (childMember != null) { bos.addMember(member, childMember); newMembers.add((BosMember) childMember); if (href != null) member.registerDependency(href, childMember, Constants.TOPICREF_DEPENDENCY); } } // Now walk the new members: for (BosMember newMember : newMembers) { if (!walkedMembers.contains(newMember)) walkMemberGetDependencies(bos, newMember); } }
From source file:eu.planets_project.tb.impl.services.EvaluationTestbedServiceTemplateImpl.java
/** * Method for applying the XPathForBMGoalRootNodes on a given DOM Document * @param doc/* www . j a v a 2 s . co m*/ * @return * @throws XPathExpressionException */ public NodeList getAllEvalResultsRootNodes(Document doc) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xpath.evaluate(sXPathForBMGoalRootNodes, doc, XPathConstants.NODESET); return nodes; }
From source file:org.ala.harvester.IdentifyLifeHarvester.java
/** * Harvest a document and update the repository. * /*from w w w. ja v a 2 s . c o m*/ * @param infosourceId * @param url * @throws Exception */ private void harvestDoc(int infosourceId, String url) throws Exception { byte[] content = null; System.out.println("******** request: " + url); Object[] resp = restfulClient.restGet(url); if ((Integer) resp[0] == HttpStatus.SC_OK) { content = resp[1].toString().getBytes("UTF-8"); } if (content != null) { List<String> ids = new ArrayList<String>(); String keyUrl = connectionParams.get(KEY_END_POINT_ATTR_NAME); // Instantiates a DOM builder to create a DOM of the response. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // return a parsed Document Document doc = builder.parse(new ByteArrayInputStream(content)); XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); XPathExpression xe = xpath.compile("//keys/key[@id]"); NodeList nodeSet = (NodeList) xe.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodeSet.getLength(); i++) { NamedNodeMap map = nodeSet.item(i).getAttributes(); ids.add(map.getNamedItem("id").getNodeValue()); } for (int i = 0; i < ids.size(); i++) { Object[] res = restfulClient.restGet(keyUrl + "/" + ids.get(i)); if ((Integer) res[0] == HttpStatus.SC_OK) { //map the document List<ParsedDocument> pds = documentMapper.map(keyUrl + ids.get(i), res[1].toString().getBytes()); //store the results for (ParsedDocument pd : pds) { //debugParsedDoc(pd); repository.storeDocument(infosourceId, pd); logger.debug("Parent guid for stored doc: " + pd.getParentGuid()); } } } } else { logger.warn("Unable to process url: " + url); } }
From source file:com.esri.gpt.catalog.search.SearchFilterSpatial.java
/** * Instantiates a new search filter spatial. *//*from w w w . ja va2s.com*/ public SearchFilterSpatial() { super(); reset(); // Load a fioel with predefined extents (bookmarks) Document domFe; XPath xpathFe; try { String sPredefinedExtents = PREDEFINED_EXTENTS_FILE; LogUtil.getLogger().log(Level.FINE, "Loading Predefined extents file: {0}", sPredefinedExtents); domFe = DomUtil.makeDomFromResourcePath(sPredefinedExtents, false); xpathFe = XPathFactory.newInstance().newXPath(); } catch (Exception e) { LogUtil.getLogger().log(Level.FINE, "No predefined extents file"); domFe = null; xpathFe = null; } // predefined extent file root Node rootFe = null; try { if (domFe != null) rootFe = (Node) xpathFe.evaluate("/extents", domFe, XPathConstants.NODE); } catch (Exception e) { rootFe = null; LogUtil.getLogger().log(Level.FINE, "Xpath problem for predefined extents file"); } /** * Reads Bookmarks and load an array */ NodeList extents; ArrayList extentsList = new ArrayList(); if (rootFe != null) { try { extents = (NodeList) xpathFe.evaluate("extent", rootFe, XPathConstants.NODESET); for (Node extent : new NodeListAdapter(extents)) { String extPlace = (String) xpathFe.evaluate("@place", extent, XPathConstants.STRING); String extValue = (String) xpathFe.evaluate("@ext", extent, XPathConstants.STRING); LogUtil.getLogger().log(Level.FINE, "Element added:" + extPlace + "," + extValue); SelectItem extElement = new SelectItem(extValue, extPlace); extentsList.add(extElement); } } catch (Exception e) { extentsList = null; LogUtil.getLogger().log(Level.FINE, "Xpath problem for predefined extents file"); } } else extentsList = null; this._predefinedExtents = extentsList; }
From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceProviderCatalogTests.java
public static Collection<Object[]> getReferencedCatalogUrls(String base) throws IOException, ParserConfigurationException, SAXException, XPathException { Properties setupProps = SetupProperties.setup(null); String userId = setupProps.getProperty("userId"); String pw = setupProps.getProperty("pw"); HttpResponse resp = OSLCUtils.getResponseFromUrl(base, base, new UsernamePasswordCredentials(userId, pw), OSLCConstants.CT_DISC_CAT_XML); //If we're not looking at a catalog, return empty list. if (!resp.getEntity().getContentType().getValue().contains(OSLCConstants.CT_DISC_CAT_XML)) { System.out.println("The url: " + base + " does not refer to a ServiceProviderCatalog."); System.out.println(//from ww w . ja v a2 s . c o m "The content-type of a ServiceProviderCatalog should be " + OSLCConstants.CT_DISC_CAT_XML); System.out.println("The content-type returned was " + resp.getEntity().getContentType()); EntityUtils.consume(resp.getEntity()); return new ArrayList<Object[]>(); } Document baseDoc = OSLCUtils.createXMLDocFromResponseBody(EntityUtils.toString(resp.getEntity())); //ArrayList to contain the urls from all SPCs Collection<Object[]> data = new ArrayList<Object[]>(); data.add(new Object[] { base }); //Get all ServiceProviderCatalog urls from the base document in order to test them as well, //recursively checking them for other ServiceProviderCatalogs further down. NodeList spcs = (NodeList) OSLCUtils.getXPath().evaluate( "//oslc_disc:entry/oslc_disc:ServiceProviderCatalog/@rdf:about", baseDoc, XPathConstants.NODESET); for (int i = 0; i < spcs.getLength(); i++) { String uri = spcs.item(i).getNodeValue(); uri = OSLCUtils.absoluteUrlFromRelative(base, uri); if (!uri.equals(base)) { Collection<Object[]> subCollection = getReferencedCatalogUrls(uri); Iterator<Object[]> iter = subCollection.iterator(); while (iter.hasNext()) { data.add(iter.next()); } } } return data; }
From source file:org.eclipse.lyo.testsuite.oslcv2.SimplifiedQueryXmlTests.java
protected void validateNonEmptyResponse(String query) throws XPathExpressionException, IOException, ParserConfigurationException, SAXException { String queryUrl = OSLCUtils.addQueryStringToURL(currentUrl, query); HttpResponse response = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, basicCreds, OSLCConstants.CT_XML, headers); int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK != statusCode) { EntityUtils.consume(response.getEntity()); throw new IOException("Response code: " + statusCode + " for " + queryUrl); }/*www .j a v a2s .c o m*/ String responseBody = EntityUtils.toString(response.getEntity()); Document doc = OSLCUtils.createXMLDocFromResponseBody(responseBody); Node results = (Node) OSLCUtils.getXPath().evaluate("//oslc:ResponseInfo/@rdf:about", doc, XPathConstants.NODE); // Only test oslc:ResponseInfo if found if (results != null) { assertEquals("Expended ResponseInfo/@rdf:about to equal request URL", queryUrl, results.getNodeValue()); results = (Node) OSLCUtils.getXPath().evaluate("//oslc:totalCount", doc, XPathConstants.NODE); if (results != null) { int totalCount = Integer.parseInt(results.getTextContent()); assertTrue("Expected oslc:totalCount > 0", totalCount > 0); } NodeList resultList = (NodeList) OSLCUtils.getXPath().evaluate("//rdf:Description/rdfs:member", doc, XPathConstants.NODESET); assertNotNull("Expected rdfs:member(s)", resultList); assertNotNull("Expected > 1 rdfs:member(s)", resultList.getLength() > 0); } }
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;// ww w . j a v a 2s.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:de.egore911.versioning.deployer.Main.java
private static void perform(String arg, CommandLine line) throws IOException { URL url;/* w ww . j a va 2 s .c om*/ try { url = new URL(arg); } catch (MalformedURLException e) { LOG.error("Invalid URI: {}", e.getMessage(), e); System.exit(1); return; } HttpURLConnection connection; try { connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); if (response != HttpURLConnection.HTTP_OK) { LOG.error("Could not download {}", url); connection.disconnect(); System.exit(1); return; } } catch (ConnectException e) { LOG.error("Error during download from URI {}: {}", url, e.getMessage()); System.exit(1); return; } XmlHolder xmlHolder = XmlHolder.getInstance(); DocumentBuilder documentBuilder = xmlHolder.documentBuilder; XPath xPath = xmlHolder.xPath; try { XPathExpression serverNameXpath = xPath.compile("/server/name/text()"); XPathExpression serverTargetdirXpath = xPath.compile("/server/targetdir/text()"); XPathExpression serverDeploymentsDeploymentXpath = xPath.compile("/server/deployments/deployment"); Document doc = documentBuilder.parse(connection.getInputStream()); connection.disconnect(); String serverName = (String) serverNameXpath.evaluate(doc, XPathConstants.STRING); LOG.info("Deploying {}", serverName); boolean shouldPerformCopy = !line.hasOption('r'); PerformCopy performCopy = new PerformCopy(xPath); boolean shouldPerformExtraction = !line.hasOption('r'); PerformExtraction performExtraction = new PerformExtraction(xPath); boolean shouldPerformCheckout = !line.hasOption('r'); PerformCheckout performCheckout = new PerformCheckout(xPath); boolean shouldPerformReplacement = true; PerformReplacement performReplacement = new PerformReplacement(xPath); String targetdir = (String) serverTargetdirXpath.evaluate(doc, XPathConstants.STRING); FileUtils.forceMkdir(new File(targetdir)); NodeList serverDeploymentsDeploymentNodes = (NodeList) serverDeploymentsDeploymentXpath.evaluate(doc, XPathConstants.NODESET); int max = serverDeploymentsDeploymentNodes.getLength(); for (int i = 0; i < serverDeploymentsDeploymentNodes.getLength(); i++) { Node serverDeploymentsDeploymentNode = serverDeploymentsDeploymentNodes.item(i); // Copy if (shouldPerformCopy) { performCopy.perform(serverDeploymentsDeploymentNode); } // Extraction if (shouldPerformExtraction) { performExtraction.perform(serverDeploymentsDeploymentNode); } // Checkout if (shouldPerformCheckout) { performCheckout.perform(serverDeploymentsDeploymentNode); } // Replacement if (shouldPerformReplacement) { performReplacement.perform(serverDeploymentsDeploymentNode); } logPercent(i + 1, max); } // validate that "${versioning:" is not present Collection<File> files = FileUtils.listFiles(new File(targetdir), TrueFileFilter.TRUE, TrueFileFilter.INSTANCE); for (File file : files) { String content; try { content = FileUtils.readFileToString(file); } catch (IOException e) { continue; } if (content.contains("${versioning:")) { LOG.error("{} contains placeholders even after applying the replacements", file.getAbsolutePath()); } } LOG.info("Done deploying {}", serverName); } catch (SAXException | IOException | XPathExpressionException e) { LOG.error("Error performing deployment: {}", e.getMessage(), e); } }
From source file:com.github.robozonky.app.version.UpdateMonitor.java
/** * Parse XML using XPath and retrieve the version string. * @param xml XML in question./* www . j av a 2s. co m*/ * @return The version string. * @throws ParserConfigurationException Failed parsing XML. * @throws IOException Failed I/O. * @throws SAXException Failed reading XML. * @throws XPathExpressionException XPath parsing problem. */ private static VersionIdentifier parseVersionString(final InputStream xml) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { final DocumentBuilderFactory factory = XmlUtil.getDocumentBuilderFactory(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(xml); final XPathFactory xPathfactory = XPathFactory.newInstance(); final XPath xpath = xPathfactory.newXPath(); final XPathExpression expr = xpath.compile("/metadata/versioning/versions/version"); return UpdateMonitor.parseNodeList((NodeList) expr.evaluate(doc, XPathConstants.NODESET)); }