List of usage examples for javax.xml.xpath XPathFactory newInstance
public static XPathFactory newInstance()
Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.
This method is functionally equivalent to:
newInstance(DEFAULT_OBJECT_MODEL_URI)
Since the implementation for the W3C DOM is always available, this method will never fail.
From source file:de.dplatz.padersprinter.control.TripService.java
Optional<Trip> parseTrip(Node node) { final XPath xpath = XPathFactory.newInstance().newXPath(); final LocalTime begin; final LocalTime end; final String duration; final int transferCount; try {//from ww w . ja va 2 s . co m begin = LocalTime.parse(parseStringNode(node, "./div[contains(@class, 'panel-heading')]/table[contains(@class, 'tripTable')]//tbody/tr/td[2]/text()", xpath)); end = LocalTime.parse(parseStringNode(node, "./div[contains(@class, 'panel-heading')]/table[contains(@class, 'tripTable')]//tbody/tr/td[3]/text()", xpath)); duration = parseStringNode(node, "./div[contains(@class, 'panel-heading')]/table[contains(@class, 'tripTable')]//tbody/tr/td[4]/text()", xpath); transferCount = parseIntegerNode(node, "./div[contains(@class, 'panel-heading')]/table[contains(@class, 'tripTable')]//tbody/tr/td[5]/text()", xpath); } catch (Exception ex) { logger.log(Level.ERROR, null, ex); return Optional.empty(); } Optional<List<Leg>> legs = parseLegs(node); if (legs.isPresent()) { Trip t = new Trip(begin, end, duration, transferCount, legs.get()); logger.debug("Parsed trip: " + t); return Optional.of(t); } else { return Optional.empty(); } }
From source file:it.acubelab.batframework.systemPlugins.TagmeAnnotator.java
private String getConfigValue(String setting, String name, Document doc) throws XPathExpressionException { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression userExpr = xpath .compile("tagme/setting[@name=\"" + setting + "\"]/param[@name=\"" + name + "\"]/@value"); return userExpr.evaluate(doc); }
From source file:it.acubelab.batframework.systemPlugins.AIDAAnnotator.java
private String getConfigValue(String setting, String name, Document doc) throws XPathExpressionException { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression userExpr = xpath .compile("aida/setting[@name=\"" + setting + "\"]/param[@name=\"" + name + "\"]/@value"); return userExpr.evaluate(doc); }
From source file:ru.itdsystems.alfresco.persistence.CrudPost.java
@Override public void execute(WebScriptRequest req, WebScriptResponse res) throws WebScriptException { // construct path elements array from request parameters List<String> pathElements = new ArrayList<String>(); Map<String, String> templateVars = req.getServiceMatch().getTemplateVars(); pathElements.add(templateVars.get("application_name")); pathElements.add(templateVars.get("form_name")); doBefore(pathElements, null);/* w ww. j av a2s . c o m*/ // parse xml from request and perform a search Document searchXML; DocumentBuilder xmlBuilder; DocumentBuilderFactory xmlFact; try { xmlFact = DocumentBuilderFactory.newInstance(); xmlFact.setNamespaceAware(true); xmlBuilder = xmlFact.newDocumentBuilder(); searchXML = xmlBuilder.parse(req.getContent().getInputStream()); } catch (Exception e) { throw new WebScriptException(500, "Error occured while parsing XML from request.", e); } XPath xpath = XPathFactory.newInstance().newXPath(); Integer pageSize; Integer pageNumber; String lang; // String applicationName; // String formName; NodeList queries; // extract search details try { pageSize = new Integer( ((Node) xpath.evaluate("/search/page-size/text()", searchXML, XPathConstants.NODE)) .getNodeValue()); pageNumber = new Integer( ((Node) xpath.evaluate("/search/page-number/text()", searchXML, XPathConstants.NODE)) .getNodeValue()); lang = ((Node) xpath.evaluate("/search/lang/text()", searchXML, XPathConstants.NODE)).getNodeValue(); // applicationName = ((Node) xpath.evaluate("/search/app/text()", // searchXML, XPathConstants.NODE)).getNodeValue(); // formName = ((Node) xpath.evaluate("/search/form/text()", // searchXML, // XPathConstants.NODE)).getNodeValue(); queries = (NodeList) xpath.evaluate("/search/query", searchXML, XPathConstants.NODESET); if (queries.getLength() == 0) throw new Exception("No queries found."); } catch (Exception e) { throw new WebScriptException(500, "XML in request is malformed.", e); } // check if requested query is supported if (!"".equals(queries.item(0).getTextContent())) throw new WebScriptException(500, "Freetext queries are not supported at the moment."); // resolve path to root data pathElements.add("data"); NodeRef nodeRef = getRootNodeRef(); // resolve path to file FileInfo fileInfo = null; Integer totalForms = 0; try { // fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements, false); fileInfo = fileFolderService.resolveNamePath(nodeRef, pathElements); } catch (FileNotFoundException e) { // do nothing here } if (fileInfo != null) { // iterate through all forms List<ChildAssociationRef> assocs = nodeService.getChildAssocs(fileInfo.getNodeRef()); List<String> details = new ArrayList<String>(); Document resultXML; try { resultXML = xmlBuilder.newDocument(); } catch (Exception e) { throw new WebScriptException(500, "Smth really strange happened o.O", e); } Element rootElement = resultXML.createElement("documents"); rootElement.setAttribute("page-size", pageSize.toString()); rootElement.setAttribute("page-number", pageNumber.toString()); rootElement.setAttribute("query", ""); resultXML.appendChild(rootElement); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"); int skip = pageSize * (pageNumber - 1); Integer found = 0; Integer searchTotal = 0; for (ChildAssociationRef assoc : assocs) { if ((nodeRef = nodeService.getChildByName(assoc.getChildRef(), ContentModel.ASSOC_CONTAINS, "data.xml")) != null) { // parse file Document dataXML; try { dataXML = xmlBuilder.parse(fileFolderService.getReader(nodeRef).getContentInputStream()); } catch (Exception e) { throw new WebScriptException(500, "Form file is malformed.", e); } totalForms++; details.clear(); xpath.setNamespaceContext(new OrbeonNamespaceContext()); // execute search queries for (int i = 1; i < queries.getLength(); i++) { Node query = queries.item(i); String path = query.getAttributes().getNamedItem("path").getNodeValue(); String match = query.getAttributes().getNamedItem("match").getNodeValue(); String queryString = query.getTextContent(); if (path == null || match == null || queryString == null) throw new WebScriptException(500, "Search query XML is malformed."); path = path.replace("$fb-lang", "'" + lang + "'"); boolean exactMatch = "exact".equals(match); Node queryResult; try { queryResult = (Node) xpath.evaluate(path, dataXML.getDocumentElement(), XPathConstants.NODE); } catch (Exception e) { throw new WebScriptException(500, "Error in query xpath expression.", e); } if (queryResult == null) break; String textContent = queryResult.getTextContent(); // TODO // check type while comparing values if (exactMatch && queryString.equals(textContent) || !exactMatch && textContent != null && textContent.contains(queryString) || queryString.isEmpty()) details.add(textContent); else break; } // add document to response xml if (details.size() == queries.getLength() - 1) { searchTotal++; if (skip > 0) skip--; else if (++found <= pageSize) { Element item = resultXML.createElement("document"); String createdText = dateFormat .format(fileFolderService.getFileInfo(nodeRef).getCreatedDate()); item.setAttribute("created", createdText.substring(0, 26) + ":" + createdText.substring(26)); String modifiedText = dateFormat .format(fileFolderService.getFileInfo(nodeRef).getModifiedDate()); item.setAttribute("last-modified", modifiedText.substring(0, 26) + ":" + modifiedText.substring(26)); item.setAttribute("name", fileFolderService.getFileInfo(assoc.getChildRef()).getName()); resultXML.getDocumentElement().appendChild(item); Element detailsElement = resultXML.createElement("details"); item.appendChild(detailsElement); for (String detail : details) { Element detailElement = resultXML.createElement("detail"); detailElement.appendChild(resultXML.createTextNode(detail)); detailsElement.appendChild(detailElement); } } /* * else break; */ } } } rootElement.setAttribute("total", totalForms.toString()); rootElement.setAttribute("search-total", searchTotal.toString()); // stream output to client try { TransformerFactory.newInstance().newTransformer().transform(new DOMSource(resultXML), new StreamResult(res.getOutputStream())); } catch (Exception e) { throw new WebScriptException(500, "Error occured while streaming output to client.", e); } } }
From source file:org.ambraproject.solr.SolrMostViewedArticleService.java
@Override public List<Pair<String, String>> getMostViewedArticles(String journal, int limit, Integer numDays) throws SolrException { //check if we still have valid results in the cache MostViewedCache cache = cachedMostViewedResults.get(journal); if (cache != null && cache.isValid()) { return cache.getArticles(); }/*from www . j av a2s. c om*/ Map<String, String> params = new HashMap<String, String>(); params.put("fl", DOI_ATTR + "," + TITLE_ATTR); params.put("fq", "doc_type:full AND !article_type_facet:\"Issue Image\" AND cross_published_journal_key:" + journal); params.put("start", "0"); params.put("rows", String.valueOf(limit)); params.put("indent", "off"); String sortField = (numDays != null) ? solrFieldConverter.getViewCountingFieldName(numDays) : solrFieldConverter.getAllTimeViewsField(); params.put("sort", sortField + " desc"); Document doc = solrHttpService.makeSolrRequest(params); List<Pair<String, String>> articles = new ArrayList<Pair<String, String>>(limit); //get the children of the "result" node XPath xPath = XPathFactory.newInstance().newXPath(); try { Integer count = Integer.valueOf(xPath.evaluate("count(//result/doc)", doc)); for (int i = 1; i <= count; i++) { String doi = xPath.evaluate("//result/doc[" + i + "]/str[@name = '" + DOI_ATTR + "']/text()", doc); String title = xPath.evaluate("//result/doc[" + i + "]/str[@name = '" + TITLE_ATTR + "']/text()", doc); articles.add(new Pair<String, String>(doi, title)); } } catch (XPathExpressionException e) { throw new SolrException("Error parsing solr xml response", e); } //cache the results cachedMostViewedResults.put(journal, new MostViewedCache(articles)); return articles; }
From source file:com.intel.hadoop.graphbuilder.demoapps.wikipedia.docwordgraph.WordCountGraphTokenizer.java
public void parse(String s) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//ww w .ja va 2 s . c om DocumentBuilder builder; counts = new HashMap<String, Integer>(); try { builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(s))); XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); title = xpath.evaluate("//page/title/text()", doc); title = title.replaceAll("\\s", "_"); // title = title.replaceAll("^[^a-zA-Z0-9]", "#"); // title = title.replaceAll("[^a-zA-Z0-9.]", "_"); id = xpath.evaluate("//page/id/text()", doc); String text = xpath.evaluate("//page/revision/text/text()", doc); if (!text.isEmpty()) { Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30); TokenStream stream = analyzer.tokenStream(null, new StringReader(text)); while (stream.incrementToken()) { String token = stream.getAttribute(TermAttribute.class).term(); if (dictionary != null && !dictionary.contains(token)) continue; if (counts.containsKey(token)) counts.put(token, counts.get(token) + 1); else counts.put(token, 1); } } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } }
From source file:com.mirth.connect.plugins.datatypes.hl7v2.HL7v2ResponseValidator.java
@Override public Response validate(Response response, ConnectorMessage connectorMessage) { HL7v2ResponseValidationProperties responseValidationProperties = getReplacedResponseValidationProperties( connectorMessage);/*from www .j av a 2s. c om*/ String[] successfulACKCodes = StringUtils.split(responseValidationProperties.getSuccessfulACKCode(), ','); String[] errorACKCodes = StringUtils.split(responseValidationProperties.getErrorACKCode(), ','); String[] rejectedACKCodes = StringUtils.split(responseValidationProperties.getRejectedACKCode(), ','); boolean validateMessageControlId = responseValidationProperties.isValidateMessageControlId(); String responseData = response.getMessage(); if (StringUtils.isNotBlank(responseData)) { try { if (responseData.trim().startsWith("<")) { // XML response received Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new CharArrayReader(responseData.toCharArray()))); String ackCode = XPathFactory.newInstance().newXPath().compile("//MSA.1/text()").evaluate(doc) .trim(); boolean rejected = Arrays.asList(rejectedACKCodes).contains(ackCode); boolean error = rejected || Arrays.asList(errorACKCodes).contains(ackCode); if (error || rejected) { String msa3 = StringUtils.trim( XPathFactory.newInstance().newXPath().compile("//MSA.3/text()").evaluate(doc)); String err1 = StringUtils.trim( XPathFactory.newInstance().newXPath().compile("//ERR.1/text()").evaluate(doc)); handleNACK(response, rejected, msa3, err1); } else if (Arrays.asList(successfulACKCodes).contains(ackCode)) { if (validateMessageControlId) { String msa2 = StringUtils.trim( XPathFactory.newInstance().newXPath().compile("//MSA.2/text()").evaluate(doc)); String originalControlID = getOriginalControlId(connectorMessage); if (!StringUtils.equals(msa2, originalControlID)) { handleInvalidControlId(response, originalControlID, msa2); } else { response.setStatus(Status.SENT); } } else { response.setStatus(Status.SENT); } } } else { // ER7 response received if (serializationProperties.isConvertLineBreaks()) { responseData = StringUtil.convertLineBreaks(responseData, serializationSegmentDelimiter); } int index = -1; boolean valid = true; // Attempt to find the MSA segment using the segment delimiters in the serialization properties if ((index = responseData.indexOf(serializationSegmentDelimiter + "MSA")) >= 0) { // MSA found; add the length of the segment delimiter, MSA, and field separator to get to the index of MSA.1 index += serializationSegmentDelimiter.length() + 4; if (index < responseData.length()) { boolean rejected = startsWithAny(responseData, rejectedACKCodes, index); boolean error = rejected || startsWithAny(responseData, errorACKCodes, index); char fieldSeparator = responseData.charAt(index - 1); if (error || rejected) { String msa3 = null; String err1 = null; // Index of MSA.2 index = responseData.indexOf(fieldSeparator, index); if (index >= 0) { // Index of MSA.3 index = responseData.indexOf(fieldSeparator, index + 1); if (index >= 0) { // Find the next index of either the field separator or segment delimiter, and then the resulting substring String tempSegment = StringUtils.substring(responseData, index + 1); index = StringUtils.indexOfAny(tempSegment, fieldSeparator + serializationSegmentDelimiter); if (index >= 0) { msa3 = StringUtils.substring(tempSegment, 0, index); } else { msa3 = StringUtils.substring(tempSegment, 0); } } } if ((index = responseData.indexOf(serializationSegmentDelimiter + "ERR")) >= 0) { // ERR found; add the length of the segment delimiter, ERR, and field separator to get to the index of ERR.1 index += serializationSegmentDelimiter.length() + 4; // Find the next index of either the field separator or segment delimiter, and then the resulting substring String tempSegment = StringUtils.substring(responseData, index); index = StringUtils.indexOfAny(tempSegment, fieldSeparator + serializationSegmentDelimiter); if (index >= 0) { err1 = StringUtils.substring(tempSegment, 0, index); } else { err1 = StringUtils.substring(tempSegment, 0); } } handleNACK(response, rejected, msa3, err1); } else if (startsWithAny(responseData, successfulACKCodes, index)) { if (validateMessageControlId) { String msa2 = ""; index = responseData.indexOf(fieldSeparator, index); if (index >= 0) { String tempSegment = StringUtils.substring(responseData, index + 1); index = StringUtils.indexOfAny(tempSegment, fieldSeparator + serializationSegmentDelimiter); if (index >= 0) { msa2 = StringUtils.substring(tempSegment, 0, index); } else { msa2 = StringUtils.substring(tempSegment, 0); } } String originalControlID = getOriginalControlId(connectorMessage); if (!StringUtils.equals(msa2, originalControlID)) { handleInvalidControlId(response, originalControlID, msa2); } else { response.setStatus(Status.SENT); } } else { response.setStatus(Status.SENT); } } else { valid = false; } } else { valid = false; } } else { valid = false; } if (!valid) { response.setStatus(Status.QUEUED); response.setStatusMessage("Invalid HL7 v2.x acknowledgement received."); response.setError(response.getStatusMessage()); } } } catch (Exception e) { response.setStatus(Status.QUEUED); response.setStatusMessage("Error validating response: " + e.getMessage()); response.setError(ErrorMessageBuilder.buildErrorMessage(this.getClass().getSimpleName(), response.getStatusMessage(), e)); } } else { response.setStatus(Status.QUEUED); response.setStatusMessage("Empty or blank response received."); response.setError(response.getStatusMessage()); } return response; }
From source file:org.opencastproject.remotetest.util.Utils.java
public static Object xpath(InputStream is, String path, QName returnType) throws XPathExpressionException { try {//from w ww . j av a 2s.c om XPath xPath = XPathFactory.newInstance().newXPath(); return xPath.compile(path).evaluate(is, returnType); } finally { IOUtils.closeQuietly(is); } }
From source file:dk.statsbiblioteket.doms.iprolemapper.webservice.IPRangesConfigReader.java
/** * Produce a <code>List</code> of <code>IPRangeRoles</code> instances * constructed from the information read from the XML configuration * specified by <code>rangesConfigFile</code>. * /* w w w . j a v a 2s . co m*/ * @param rangesConfigFile * a <code>File</code> instance configured with the path to the * XML configuration file to read. * @return a list of <code>IPRangeRoles</code> instances, produced from the * contents of the configuration file. * @throws IOException * if any errors are encountered while reading the configuration * file. */ public List<IPRangeRoles> readFromXMLConfigFile(File rangesConfigFile) throws IOException { if (log.isTraceEnabled()) { log.trace("readFromXMLConfigFile(): Called with file path: " + rangesConfigFile); } final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); NodeList ipRangeNodes = null; try { final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); final Document configuationDocument = documentBuilder.parse(rangesConfigFile); final XPathFactory xPathFactory = XPathFactory.newInstance(); final XPath xPath = xPathFactory.newXPath(); ipRangeNodes = (NodeList) xPath.evaluate("/ipranges/iprange", configuationDocument, XPathConstants.NODESET); } catch (ParserConfigurationException parserConfigException) { throw new IOException("Failed setting up parser", parserConfigException); } catch (SAXException saxException) { throw new IOException("Failed parsing configuration file '" + rangesConfigFile + "'", saxException); } catch (XPathExpressionException xPathExpressionException) { throw new IOException("Failed parsing (evaluating) configuration" + " file '" + rangesConfigFile + "'", xPathExpressionException); } final List<IPRangeRoles> ipRangeList = new LinkedList<IPRangeRoles>(); for (int nodeIdx = 0; nodeIdx < ipRangeNodes.getLength(); nodeIdx++) { try { ipRangeList.add(produceIPRangeInstance(ipRangeNodes.item(nodeIdx))); } catch (Exception cause) { String ipRangeNodeXMLString = "Malformed IpRange."; try { ipRangeNodeXMLString = DOM.domToString(ipRangeNodes.item(nodeIdx)); } catch (Exception eTwo) { // Exception being ignored } Logs.log(log, Logs.Level.WARN, "readFromXMLConfigFile() failed to read IPRange: ", ipRangeNodeXMLString, cause); } } if (log.isTraceEnabled()) { log.trace("readFromXMLConfigFile(): Returning IP address ranges: " + ipRangeList); } return ipRangeList; }
From source file:org.nira.wso2.nexus.ComponentVersion.java
/** * Loads the List of all the Dependencies in the DependencyManagement from the root * pom.xml/* w w w.j a v a2 s . co m*/ * * @param pomFilePath : The path to the root pom.xml * @throws ComponentException */ private static void getDependencyManagement(String pomFilePath) throws ComponentException { String nodeName, nodeValue; DependencyComponent dependencyComponent; NodeList dependenciesList = Utils.getNodeListFromXPath(pomFilePath, Constants.DEPENDENCY_MANAGEMENT_XPATH); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); try { for (int i = 0; i < dependenciesList.getLength(); ++i) { Node dependency = dependenciesList.item(i); if (dependency != null && dependency.getNodeType() == Node.ELEMENT_NODE) { NodeList nodes = (NodeList) xpath.evaluate(Constants.SELECT_ALL, dependency, XPathConstants.NODESET); dependencyComponent = new DependencyComponent(); for (int j = 0; j < nodes.getLength(); ++j) { nodeName = nodes.item(j).getNodeName(); nodeValue = nodes.item(j).getTextContent(); if (nodeValue == null) { throw new ComponentException("Dependency value is NULL for " + nodeName + "!"); } switch (nodeName) { case Constants.GROUPID: dependencyComponent.setGroupId(nodeValue); break; case Constants.ARTIFACTID: dependencyComponent.setArtifactId(nodeValue); break; case Constants.VERSION: if (Constants.PROJECT_VERSION.equalsIgnoreCase(nodeValue)) { break; } //ToDo: Check for values like the one below: //<version.tomcat>7.0.59</version.tomcat> //<orbit.version.tomcat>${version.tomcat}.wso2v3</orbit.version.tomcat> while (!Character.isDigit(nodeValue.charAt(0))) { nodeValue = nodeValue.substring(2, nodeValue.length() - 1); nodeValue = dependencyComponentVersions.get(nodeValue); if (nodeValue == null) { throw new ComponentException("Dependency Version cannot be NULL!"); } } dependencyComponent.setVersion(nodeValue); break; } } if (dependencyComponent.getGroupId() != null && dependencyComponent.getArtifactId() != null && dependencyComponent.getVersion() != null) { getLatestComponentVersion(dependencyComponent); dependencyComponentList.add(dependencyComponent); } } } } catch (XPathExpressionException e) { throw new ComponentException("XPath Exception when retrieving Dependency Components!", e); } Collections.sort(dependencyComponentList, DependencyComponent.GroupIdArifactIdComparator); }