List of usage examples for javax.xml.xpath XPathExpression evaluate
public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;
From source file:ch.dbs.actions.bestellung.EZBXML.java
public List<JournalDetails> searchByJourids(final List<String> jourids, final String bibid) { final List<JournalDetails> list = new ArrayList<JournalDetails>(); final Http http = new Http(); final StringBuffer link = new StringBuffer( "http://rzblx1.uni-regensburg.de/ezeit/detail.phtml?xmloutput=1&colors=7&lang=de&bibid="); link.append(bibid);/*from w w w. j av a2 s . co m*/ link.append("&jour_id="); final StringBuffer infoLink = new StringBuffer( "http://ezb.uni-regensburg.de/ezeit/detail.phtml?colors=7&lang=de&bibid="); infoLink.append(bibid); infoLink.append("&jour_id="); try { for (final String jourid : jourids) { final JournalDetails jd = new JournalDetails(); final String content = http.getContent(link.toString() + jourid, Connect.TIMEOUT_1.getValue(), Connect.TRIES_1.getValue(), null); if (content != null) { final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); final DocumentBuilder builder = domFactory.newDocumentBuilder(); final Document doc = builder.parse(new InputSource(new StringReader(content))); final XPathFactory factory = XPathFactory.newInstance(); final XPath xpath = factory.newXPath(); final XPathExpression exprJournal = xpath.compile("//journal"); final XPathExpression exprPissns = xpath.compile("//journal/detail/P_ISSNs"); final XPathExpression exprEissns = xpath.compile("//journal/detail/E_ISSNs"); final NodeList resultJournal = (NodeList) exprJournal.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < resultJournal.getLength(); i++) { final Node firstResultNode = resultJournal.item(i); final Element journal = (Element) firstResultNode; // Title String title = getValue(journal.getElementsByTagName("title")); if (title != null) { title = Jsoup.clean(title, Whitelist.none()); title = Jsoup.parse(title).text(); } jd.setZeitschriftentitel(title); // P-ISSNs final NodeList resultPissns = (NodeList) exprPissns.evaluate(doc, XPathConstants.NODESET); // get first pissn for (int z = 0; z < resultPissns.getLength(); z++) { final Node firstPissnsNode = resultPissns.item(i); final Element pissnElement = (Element) firstPissnsNode; final String pissn = getValue(pissnElement.getElementsByTagName("P_ISSN")); jd.setIssn(pissn); } // try to get Eissn if we have no Pissn if (jd.getIssn() == null) { // E-ISSNs final NodeList resultEissns = (NodeList) exprEissns.evaluate(doc, XPathConstants.NODESET); // get first eissn for (int z = 0; z < resultEissns.getLength(); z++) { final Node firstEissnsNode = resultEissns.item(i); final Element eissnElement = (Element) firstEissnsNode; final String eissn = getValue(eissnElement.getElementsByTagName("E_ISSN")); jd.setIssn(eissn); } } // add info link jd.setLink(infoLink.toString() + jourid); list.add(jd); } } } } catch (final XPathExpressionException e) { LOG.error(e.toString()); } catch (final SAXParseException e) { LOG.error(e.toString()); } catch (final SAXException e) { LOG.error(e.toString()); } catch (final IOException e) { LOG.error(e.toString()); } catch (final ParserConfigurationException e) { LOG.error(e.toString()); } catch (final Exception e) { LOG.error(e.toString()); } return list; }
From source file:com.redhat.plugin.eap6.EAP6DeploymentStructureMojo.java
protected void buildDeploymentStructure(Document doc, Map<Artifact, String> moduleMap, List<SubDeployment> subdeployments) throws MojoFailureException, XPathExpressionException { Element root = doc.getDocumentElement(); if (!root.getTagName().equals("jboss-deployment-structure")) throw new MojoFailureException("Root element is not jboss-deployment-structure"); Element deployment = (Element) xp_deployment.evaluate(doc, XPathConstants.NODE); if (deployment == null) { deployment = doc.createElement("deployment"); root.insertBefore(deployment, root.getFirstChild()); }//from w ww .ja v a 2 s.co m Element depDependencies = (Element) xp_dependencies.evaluate(deployment, XPathConstants.NODE); if (depDependencies == null) { depDependencies = doc.createElement("dependencies"); deployment.appendChild(depDependencies); } Collection<String> mods = moduleMap.values(); getLog().debug("From project-dependencies" + mods); fillModuleEntries(doc, depDependencies, mods); getLog().debug("Element <" + depDependencies.getTagName() + ">: " + depDependencies.getChildNodes().getLength() + " elements"); if (subdeployments != null && !subdeployments.isEmpty()) { for (SubDeployment sd : subdeployments) { XPathExpression xp = xpf.newXPath() .compile("/jboss-deployment-structure/sub-deployment [@name='" + sd.getName() + "']"); Element subEl = (Element) xp.evaluate(doc, XPathConstants.NODE); if (subEl == null) { getLog().debug("Creating sub-deployment-section for <" + sd.getName() + ">"); subEl = doc.createElement("sub-deployment"); root.appendChild(subEl); subEl.setAttribute("name", sd.getName()); } Element subDependencies = (Element) xp_dependencies.evaluate(subEl, XPathConstants.NODE); if (subDependencies == null) { subDependencies = doc.createElement("dependencies"); subEl.appendChild(subDependencies); } Set<String> modules = new HashSet<String>(); xp = xpf.newXPath().compile("/jboss-deployment-structure/deployment/dependencies/module/@name"); NodeList nl = (NodeList) xp.evaluate(sd.getDocument(), XPathConstants.NODESET); int n = nl.getLength(); for (int i = 0; i < n; i++) { if (moduleMap.values().contains(nl.item(i).getTextContent())) continue; modules.add(nl.item(i).getTextContent()); } getLog().debug("From sub-deployment <" + sd.getName() + ">:" + modules); fillModuleEntries(doc, subDependencies, modules); getLog().debug("Child-Elements for <" + subEl.getAttribute("name") + ">: " + subEl.getChildNodes().getLength()); getLog().debug("Element <" + subEl.getTagName() + "." + subDependencies.getTagName() + ">: " + subDependencies.getChildNodes().getLength() + " elements"); } } NodeList nlSub = (NodeList) xp_subdeployment.evaluate(doc, XPathConstants.NODESET); int nSub = nlSub.getLength(); getLog().debug("Retrieved subdeployment-sections (" + nSub + ")"); }
From source file:com.photon.phresco.impl.ConfigManagerImpl.java
private Node getNode(String xpath) throws ConfigurationException { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath newXPath = xPathFactory.newXPath(); XPathExpression xPathExpression; Node xpathNode = null;/*w w w . ja va 2s. c o m*/ try { xPathExpression = newXPath.compile(xpath); xpathNode = (Node) xPathExpression.evaluate(document, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new ConfigurationException(e); } return xpathNode; }
From source file:org.powertac.server.CompetitionSetupService.java
private ArrayList<Object> processBootDataset(URL bootDataset) { // Read and convert the bootstrap dataset ArrayList<Object> result = new ArrayList<Object>(); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); try {/*from w w w . ja v a 2s . c o m*/ InputSource source = new InputSource(bootDataset.openStream()); // we want all the children of the bootstrap node XPathExpression exp = xPath.compile("/powertac-bootstrap-data/bootstrap/*"); NodeList nodes = (NodeList) exp.evaluate(source, XPathConstants.NODESET); log.info("Found " + nodes.getLength() + " bootstrap nodes"); // Each node is a bootstrap data item for (int i = 0; i < nodes.getLength(); i++) { String xml = nodeToString(nodes.item(i)); Object msg = messageConverter.fromXML(xml); result.add(msg); } } catch (XPathExpressionException xee) { log.error("runOnce: Error reading config file: " + xee.toString()); } catch (IOException ioe) { log.error("runOnce: reset fault: " + ioe.toString()); } return result; }
From source file:cc.siara.csv_ml_demo.MainActivity.java
/** * Evaluates given XPath from Input box against Document generated by * parsing csv_ml in input box and sets value or node list to output box. */// w w w .j a v a2 s. c o m void processXPath() { EditText etInput = (EditText) findViewById(R.id.etInput); EditText etXPath = (EditText) findViewById(R.id.etXPath); CheckBox cbPretty = (CheckBox) findViewById(R.id.cbPretty); XPath xpath = XPathFactory.newInstance().newXPath(); MultiLevelCSVParser parser = new MultiLevelCSVParser(); Document doc = null; try { doc = parser.parseToDOM(new StringReader(etInput.getText().toString()), false); } catch (IOException e1) { e1.printStackTrace(); } if (doc == null) return; StringBuffer out_str = new StringBuffer(); try { XPathExpression expr = xpath.compile(etXPath.getText().toString()); try { Document outDoc = Util.parseXMLToDOM("<output></output>"); Element rootElement = outDoc.getDocumentElement(); NodeList ret = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < ret.getLength(); i++) { Object o = ret.item(i); if (o instanceof String) { out_str.append(o); } else if (o instanceof Node) { Node n = (Node) o; short nt = n.getNodeType(); switch (nt) { case Node.TEXT_NODE: case Node.ATTRIBUTE_NODE: case Node.CDATA_SECTION_NODE: // Only one value gets // evaluated? if (out_str.length() > 0) out_str.append(','); if (nt == Node.ATTRIBUTE_NODE) out_str.append(n.getNodeValue()); else out_str.append(n.getTextContent()); break; case Node.ELEMENT_NODE: rootElement.appendChild(outDoc.importNode(n, true)); break; } } } if (out_str.length() > 0) { rootElement.setTextContent(out_str.toString()); out_str.setLength(0); } out_str.append(Util.docToString(outDoc, true)); } catch (Exception e) { // Thrown most likely because the given XPath evaluates to a // string out_str.append(expr.evaluate(doc)); } } catch (XPathExpressionException e) { e.printStackTrace(); } if (out_str.length() > 5 && out_str.substring(0, 5).equals("<?xml")) out_str.delete(0, out_str.indexOf(">") + 1); EditText etOutput = (EditText) findViewById(R.id.etOutput); etOutput.setText(out_str.toString()); // tfOutputSize.setText(String.valueOf(xmlString.length())); }
From source file:de.codesourcery.jasm16.ide.ProjectConfiguration.java
private List<String> getValues(XPathExpression expr, Document doc) throws XPathExpressionException { final NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); final List<String> result = new ArrayList<String>(); for (int i = 0; i < nodes.getLength(); i++) { final Node node = nodes.item(i); final String value = node.getTextContent(); if (value == null || StringUtils.isBlank(value)) { LOG.error("getValues(): Invalid project XML - blank/empty value"); throw new XPathExpressionException( "Invalid project XML - blank/empty value for " + " expression " + expr); }//from w w w. j a v a 2s .c om result.add(value.trim()); } return result; }
From source file:com.photon.phresco.impl.ConfigManagerImpl.java
private NodeList getNodeList(String xpath) throws ConfigurationException { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath newXPath = xPathFactory.newXPath(); XPathExpression xPathExpression; NodeList xpathNodes = null;/*from w ww. j av a 2 s. c o m*/ try { xPathExpression = newXPath.compile(xpath); xpathNodes = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new ConfigurationException(e); } return xpathNodes; }
From source file:org.powertac.server.CompetitionSetupService.java
private String getBaseTimeXML(String weatherData) { try {// w w w. ja va 2 s.c o m DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(weatherData); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); XPathExpression expr = xPath.compile("/data/weatherReports/weatherReport/@date"); String earliest = "ZZZZ-ZZ-ZZ"; NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { String date = nodes.item(i).toString().split(" ")[0].split("\"")[1]; earliest = date.compareTo(earliest) < 0 ? date : earliest; } return earliest; } catch (Exception e) { log.error("Error extracting BaseTime from : " + weatherData); e.printStackTrace(); } return null; }
From source file:org.ala.harvester.FlickrHarvester.java
/** * Retrieves a map of licences.//from w ww . j av a2s. c om * * @return */ private Map<String, Licence> getLicencesMap() throws Exception { final String flickrMethodUri = "flickr.photos.licenses.getInfo"; String urlToSearch = this.flickrRestBaseUrl + "/" + "?method=" + flickrMethodUri + "&api_key=" + this.flickrApiKey; logger.info(urlToSearch); logger.debug("URL to search is: " + "`" + urlToSearch + "`" + "\n"); // Create an instance of HttpClient. HttpClient client = new HttpClient(); // Create a method instance. GetMethod method = new GetMethod(urlToSearch); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); method.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, "UTF-8"); method.getParams().setParameter(HttpMethodParams.HTTP_URI_CHARSET, "UTF-8"); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { String errMsg = "HTTP GET to " + "`" + urlToSearch + "`" + " returned non HTTP OK code. Returned code " + statusCode + " and message " + method.getStatusLine() + "\n"; method.releaseConnection(); throw new Exception(errMsg); } //parse the response InputStream responseStream = method.getResponseBodyAsStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(responseStream); XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); XPathExpression xe = xpath.compile("/rsp/licenses/license"); NodeList nodeSet = (NodeList) xe.evaluate(doc, XPathConstants.NODESET); Map<String, Licence> licencesMap = new HashMap<String, Licence>(); for (int i = 0; i < nodeSet.getLength(); i++) { NamedNodeMap map = nodeSet.item(i).getAttributes(); String id = map.getNamedItem("id").getNodeValue(); Licence licence = new Licence(); licence.setName(map.getNamedItem("name").getNodeValue()); licence.setUrl(map.getNamedItem("url").getNodeValue()); licencesMap.put(id, licence); } return licencesMap; } catch (Exception httpErr) { String errMsg = "HTTP GET to `" + urlToSearch + "` returned HTTP error."; throw new Exception(errMsg, httpErr); } finally { // Release the connection. method.releaseConnection(); } }
From source file:eu.forgetit.middleware.component.Extractor.java
private String parseUserID(String inputFile) { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = null; try {//from ww w .j a v a2 s .c om builder = builderFactory.newDocumentBuilder(); Document document = builder.parse(new File(inputFile)); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); XPathExpression expr = xpath.compile("/Image_analysis_methods/@userID"); String userID = (String) expr.evaluate(document, XPathConstants.STRING); System.out.println("userID: " + userID); return userID; } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) { e.printStackTrace(); } return null; }