List of usage examples for javax.xml.xpath XPath evaluate
public Object evaluate(String expression, InputSource source, QName returnType) throws XPathExpressionException;
From source file:de.ingrid.iplug.dscmapclient.index.producer.PlugDescriptionConfiguredWmsRecordSetProducer.java
/** * this private method does all the dirty work, read the file, parse it into * a document and find the desired ids, through the xpath expression * //from w w w .j av a 2 s.c o m * @param filePath * @param expression * @return NodeList */ private NodeList readXmlFile(String filePath, String expression) { XPath xPath = XPathFactory.newInstance().newXPath(); File fXmlFile = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; try { dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); return (NodeList) xPath.evaluate(expression, doc, XPathConstants.NODESET); } catch (ParserConfigurationException e) { log.error("Error creating record ids.", e); e.printStackTrace(); } catch (SAXException e) { log.error("Error creating record ids.", e); e.printStackTrace(); } catch (IOException e) { log.error("Error creating record ids.", e); e.printStackTrace(); } catch (XPathExpressionException e) { log.error("Error creating record ids.", e); e.printStackTrace(); } return null; }
From source file:com.messagehub.samples.servlet.KafkaServlet.java
public String toPrettyString(String xml, int indent) { try {/*ww w .ja va 2 s. c om*/ // Turn xml string into a document Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); // Remove whitespaces outside tags XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); node.getParentNode().removeChild(node); } // Setup pretty print options TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", indent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Return pretty print xml string StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.esri.gpt.server.openls.provider.services.poi.DirectoryProvider.java
/** * Handles an XML based request (normally HTTP POST). * @param context the operation context//from w w w .ja va 2s. c om * @param root the root node * @param xpath an XPath to enable queries (properly configured with name spaces) * @throws Exception if a processing exception occurs */ public void handleXML(OperationContext context, Node root, XPath xpath) throws Exception { // initialize LOGGER.finer("Handling xls:Directory request XML..."); String locator = "xls:DirectoryRequest"; Node ndReq = (Node) xpath.evaluate(locator, root, XPathConstants.NODE); if (ndReq != null) { parseRequest(context, ndReq, xpath); } try { executeRequest(context); } catch (Throwable e) { e.printStackTrace(); } generateResponse(context); }
From source file:net.firejack.platform.installation.processor.OFRInstallProcessor.java
private Module getModule(File ofr) throws IOException, XPathExpressionException { XPath xpath = factory.newXPath(); InputStream file = ArchiveUtils.getFile(ofr, PackageFileType.PACKAGE_XML.getOfrFileName()); Object evaluate = xpath.evaluate("/package", new InputSource(file), XPathConstants.NODE); String path = (String) xpath.evaluate("@path", evaluate, XPathConstants.STRING); String name = (String) xpath.evaluate("@name", evaluate, XPathConstants.STRING); String version = (String) xpath.evaluate("@version", evaluate, XPathConstants.STRING); String dependencies = (String) xpath.evaluate("@dependencies", evaluate, XPathConstants.STRING); IOUtils.closeQuietly(file);//from w w w. j a v a 2s . c om String lookup = path + "." + name; Integer ver = VersionUtils.convertToNumber(version); return new Module(ofr, lookup, ver, dependencies); }
From source file:org.apache.flex.utilities.converter.retrievers.download.DownloadRetriever.java
protected String getBinaryUrl(SdkType sdkType, String version, PlatformType platformType) throws RetrieverException { try {/* ww w . j av a2s. c o m*/ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.parse(getFlexInstallerConfigUrl()); //Evaluate XPath against Document itself final String expression = getUrlXpath(sdkType, version, platformType); final XPath xPath = XPathFactory.newInstance().newXPath(); final Element artifactElement = (Element) xPath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODE); if (artifactElement == null) { throw new RetrieverException( "Could not find " + sdkType.toString() + " SDK with version " + version); } final StringBuilder stringBuilder = new StringBuilder(); if ((sdkType == SdkType.FLEX) || (sdkType == SdkType.SWFOBJECT)) { final String path = artifactElement.getAttribute("path"); final String file = artifactElement.getAttribute("file"); if (!path.startsWith("http://")) { stringBuilder.append("http://archive.apache.org/dist/"); } stringBuilder.append(path); if (!path.endsWith("/")) { stringBuilder.append("/"); } stringBuilder.append(file); if (sdkType == SdkType.FLEX) { stringBuilder.append(".zip"); } } else { final NodeList pathElements = artifactElement.getElementsByTagName("path"); final NodeList fileElements = artifactElement.getElementsByTagName("file"); if ((pathElements.getLength() != 1) && (fileElements.getLength() != 1)) { throw new RetrieverException("Invalid document structure."); } final String path = pathElements.item(0).getTextContent(); stringBuilder.append(path); if (!path.endsWith("/")) { stringBuilder.append("/"); } stringBuilder.append(fileElements.item(0).getTextContent()); } return stringBuilder.toString(); } catch (ParserConfigurationException e) { throw new RetrieverException("Error parsing 'sdk-installer-config-4.0.xml'", e); } catch (SAXException e) { throw new RetrieverException("Error parsing 'sdk-installer-config-4.0.xml'", e); } catch (XPathExpressionException e) { throw new RetrieverException("Error parsing 'sdk-installer-config-4.0.xml'", e); } catch (IOException e) { throw new RetrieverException("Error parsing 'sdk-installer-config-4.0.xml'", e); } }
From source file:dk.dma.msinm.web.rest.LocationRestService.java
/** * Parses the KML and returns a JSON list of locations. * * TDOD: Handle MultiGeometry.//w w w.j a v a2 s . c o m * Example: http://www.microformats.dk/2008/11/02/kommunegrnserne-til-de-98-danske-kommuner/ * * @param kml the KML to parse * @return the corresponding list of locations */ @POST @Path("/parse-kml") @Produces("application/json") public List<LocationVo> parseKml(String kml) throws UnsupportedEncodingException { // Strip BOM from UTF-8 with BOM if (kml.startsWith("\uFEFF")) { kml = kml.replace("\uFEFF", ""); } // Extract the default namespace String namespace = extractDefaultNamespace(kml); List<LocationVo> result = new ArrayList<>(); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new KmlNamespaceContext(namespace)); InputSource inputSource = new InputSource(new StringReader(kml)); try { // Fetch all "Placemark" elements NodeList placemarks = (NodeList) xpath.evaluate("//kml:Placemark", inputSource, XPathConstants.NODESET); for (int i = 0; i < placemarks.getLength(); i++) { // Fetch all "Point" coordinates NodeList coordinates = (NodeList) xpath.evaluate("//kml:Point/kml:coordinates", placemarks.item(i), XPathConstants.NODESET); extractLocations(result, coordinates, Location.LocationType.POINT); // Fetch all "Polyline" coordinates coordinates = (NodeList) xpath.evaluate("//kml:LineString/kml:coordinates", placemarks.item(i), XPathConstants.NODESET); extractLocations(result, coordinates, Location.LocationType.POLYLINE); // Fetch all "Polygon" coordinates coordinates = (NodeList) xpath.evaluate( "//kml:Polygon/kml:outerBoundaryIs/kml:LinearRing/kml:coordinates", placemarks.item(i), XPathConstants.NODESET); extractLocations(result, coordinates, Location.LocationType.POLYGON); } } catch (Exception e) { log.error("Error parsing kml", e); } return result; }
From source file:org.ala.harvester.MorphbankHarvester.java
private int getResultNumber(Document currentResDom) throws Exception { int resultNum = 0; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); String xPathToResultNum = "/response/numMatches/text()"; resultNum = Integer/*from ww w .j a v a 2 s . c o m*/ .valueOf((String) xpath.evaluate(xPathToResultNum, currentResDom, XPathConstants.STRING)); return resultNum; }
From source file:io.github.bonigarcia.wdm.BrowserManager.java
public List<URL> getDriversFromXml(URL driverUrl, List<String> driverBinary) throws Exception { log.info("Reading {} to seek {}", driverUrl, getDriverName()); List<URL> urls = new ArrayList<URL>(); int retries = 1; int maxRetries = WdmConfig.getInt("wdm.seekErrorRetries"); do {// w w w . j ava2 s . c o m try { Proxy proxy = createProxy(); URLConnection conn = proxy != null ? driverUrl.openConnection(proxy) : driverUrl.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); Document xml = loadXML(reader); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate("//Contents/Key", xml.getDocumentElement(), XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); ++i) { Element e = (Element) nodes.item(i); String version = e.getChildNodes().item(0).getNodeValue(); urls.add(new URL(driverUrl + version)); } reader.close(); break; } catch (Throwable e) { log.warn("[{}/{}] Exception reading {} to seek {}: {} {}", retries, maxRetries, driverUrl, getDriverName(), e.getClass().getName(), e.getMessage(), e); retries++; if (retries > maxRetries) { throw e; } } } while (true); return urls; }
From source file:de.conterra.suite.security.portal.gpx.EmbeddedSAMLTokenIntegrationContext.java
@Override public String getUsernameFromSAMLToken(String base64EncodedToken) throws Exception { LOGGER.entering("EmbeddedSAMLTokenIntegrationContext", "getUsernameFromSAMLToken"); XPath xpath = XPathFactory.newInstance().newXPath(); Namespaces ns = new Namespaces(); ns.add("sa", org.opensaml.XML.SAML_NS); // ns.add("sp", org.opensaml.XML.SAMLP_NS); xpath.setNamespaceContext(new NamespaceContextImpl(ns)); String userId = (String) xpath.evaluate( "//sa:Assertion/sa:AuthenticationStatement/sa:Subject/sa:NameIdentifier/text()", createAndVerifySamlResponse(base64EncodedToken), XPathConstants.STRING); String s = Val.chkStr(userId); LOGGER.finest(MessageFormat.format("Returning userid '{0}' from given token.", s)); return s;/*from w w w. j av a 2 s . com*/ }
From source file:de.dplatz.padersprinter.control.TripService.java
public Observable<Trip> query(TripQuery query) { final HtmlCleaner htmlCleaner = new HtmlCleaner(); final DomSerializer domSerializer = new DomSerializer(new CleanerProperties()); final XPath xpath = XPathFactory.newInstance().newXPath(); return httpClient.get(query).map(htmlCleaner::clean).flatMap(tagNode -> { try {/*w w w . j ava 2 s. c om*/ return Observable.just(domSerializer.createDOM(tagNode)); } catch (ParserConfigurationException pce) { return Observable.error(pce); } }).flatMap(doc -> { try { return Observable.just((NodeList) xpath.evaluate(TRIP_NODES_XPATH, doc, XPathConstants.NODESET)); } catch (XPathExpressionException xee) { return Observable.error(xee); } }).flatMap(nodeList -> { List<Node> nodes = new LinkedList<>(); for (int i = 0; i < nodeList.getLength(); i++) { nodes.add(nodeList.item(i)); } logger.info("HTML contains " + nodes.size() + " result-panels."); return Observable.from(nodes); }).flatMap(tripNode -> parseTrip(tripNode).map(Observable::just).orElseGet(Observable::empty)); }