List of usage examples for javax.xml.xpath XPathFactory newXPath
public abstract XPath newXPath();
Return a new XPath
using the underlying object model determined when the XPathFactory was instantiated.
From source file:com.github.robozonky.app.version.UpdateMonitor.java
/** * Parse XML using XPath and retrieve the version string. * @param xml XML in question./* w ww.ja v a2s. c o 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)); }
From source file:hoot.services.utils.XmlDocumentBuilder.java
/** * Creates an XPATH instance for querying with * //from w ww. j a v a 2 s. c om * @return an XPATH instance */ public static XPath createXPath() { XPathFactory factory = XPathFactory.newInstance(); return factory.newXPath(); }
From source file:Main.java
public static Iterable<Node> eval(Node element, String path) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // xpath.setNamespaceContext(new NamespaceContext() { ///* w w w. j a va 2 s.co m*/ // /** // * @WARNING this code will work only if the namespace is present at // * each node of the xml dom and within the xpath queries. // * Otherwise you can fix like that: // * // * <pre> // * // FIXME: this is a // * hack!! if ("atom".equals(prefix)) return // * "http://www.w3.org/2005/Atom"; but it wont work with // * </pre> // * // * different namespaces // * @see // javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String) // */ // public String getNamespaceURI(String prefix) { // String namespace = DOMUtil.lookupNamespaceURI(node, prefix); // return namespace; // } // // public String getPrefix(String namespaceURI) { // String prefix = node.lookupPrefix(namespaceURI); // return prefix; // } // // public Iterator<?> getPrefixes(final String namespaceURI) { // return new Iterator<String>() { // String ns = getPrefix(namespaceURI); // // public boolean hasNext() { // return ns != null; // } // // public String next() { // String r = ns; // ns = null; // return r; // } // // public void remove() { // } // // }; // } // }); XPathExpression expr = xpath.compile(path); final NodeList result = (NodeList) expr.evaluate(element, XPathConstants.NODESET); return new Iterable<Node>() { public Iterator<Node> iterator() { return new Iterator<Node>() { int len = result.getLength(); int pos; public boolean hasNext() { return pos < len; } public Node next() { if (pos >= len) { return null; } return result.item(pos++); } public void remove() { throw new IllegalAccessError(); } }; } }; }
From source file:com.ephesoft.dcma.util.OCREngineUtil.java
/** * To format HOCR for Tesseract./* w w w. j a va 2 s. c om*/ * @param outputFilePath {@link String} * @param actualFolderLocation {@link String} * @param pageId {@link String} * @throws XPathExpressionException if error occurs * @throws TransformerException if error occurs * @throws IOException if error occurs */ public static void formatHOCRForTesseract(final String outputFilePath, final String actualFolderLocation, final String pageId) throws XPathExpressionException, TransformerException, IOException { LOGGER.info("Entering format HOCR for tessearct . outputfilepath : " + outputFilePath); InputStream inputStream = new FileInputStream(outputFilePath); XPathFactory xFactory = new org.apache.xpath.jaxp.XPathFactoryImpl(); XPath xpath = xFactory.newXPath(); XPathExpression pageExpr = xpath.compile("//div[@class=\"ocr_page\"]"); XPathExpression wordExpr = xpath.compile("//span[@class=\"ocr_word\"]"); // Output format supported by Tesseract 3.00 XPathExpression xOcrWordExpr = xpath.compile("//span[@class=\"xocr_word\"]"); // Output format supported by Tesseract 3.01 XPathExpression ocrXWordExpr = xpath.compile("//span[@class=\"ocrx_word\"]"); org.w3c.dom.Document doc2 = null; try { doc2 = XMLUtil.createDocumentFrom(inputStream); } catch (Exception e) { LOGGER.info("Premature end of file for " + outputFilePath + e); } finally { IOUtils.closeQuietly(inputStream); } if (doc2 != null) { LOGGER.info("document is not null."); NodeList wordList = (NodeList) wordExpr.evaluate(doc2, XPathConstants.NODESET); for (int wordNodeIndex = 0; wordNodeIndex < wordList.getLength(); wordNodeIndex++) { setWordNodeTextContent(xOcrWordExpr, ocrXWordExpr, wordList, wordNodeIndex); } NodeList pageList = (NodeList) pageExpr.evaluate(doc2, XPathConstants.NODESET); for (int pageNodeIndex = 0; pageNodeIndex < pageList.getLength(); pageNodeIndex++) { Node pageNode = pageList.item(pageNodeIndex); if (pageNode != null && ((Node) pageNode.getAttributes().getNamedItem(UtilConstants.ID_ATTR)) != null) { String pageID = ((Node) pageNode.getAttributes().getNamedItem(UtilConstants.ID_ATTR)) .getTextContent(); wordExpr = xpath.compile("//div[@id='" + pageID + "']//span[@class='ocr_word']"); NodeList wordInPageList = (NodeList) wordExpr.evaluate(pageNode, XPathConstants.NODESET); Node pageNodeClone = pageNode.cloneNode(false); for (int i = 0; i < wordInPageList.getLength(); i++) { pageNodeClone.appendChild(wordInPageList.item(i)); } pageNode.getParentNode().appendChild(pageNodeClone); pageNode.getParentNode().removeChild(pageNode); } } XMLUtil.flushDocumentToFile(doc2.getDocumentElement().getOwnerDocument(), outputFilePath); File tempFile = new File(actualFolderLocation + File.separator + pageId + "_tempFile_hocr.html"); FileUtils.copyFile(new File(outputFilePath), tempFile); XMLUtil.htmlOutputStream(tempFile.getAbsolutePath(), outputFilePath); boolean isTempFileDeleted = tempFile.delete(); if (!isTempFileDeleted) { tempFile.delete(); } } LOGGER.info("Exiting format HOCR for tessearct . outputfilepath : " + outputFilePath); }
From source file:org.nira.wso2.nexus.ComponentVersion.java
/** * Loads the List of all the Dependencies in the DependencyManagement from the root * pom.xml/*ww w . ja v a 2 s . c om*/ * * @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); }
From source file:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java
public static void configurePackage(String env, File configFile) throws Exception { Transformer transformer = tltf.get(); // get the list of files in proxies folder XMLFileListUtil listFileUtil = new XMLFileListUtil(); ConfigTokens conf = FileReader.getBundleConfigs(configFile); Map<String, List<File>> filesToProcess = new HashMap<String, List<File>>(); filesToProcess.put("proxy", listFileUtil.getProxyFiles(configFile)); filesToProcess.put("policy", listFileUtil.getPolicyFiles(configFile)); filesToProcess.put("target", listFileUtil.getTargetFiles(configFile)); doTokenReplacement(env, conf, filesToProcess); // special case ... File proxyFile = listFileUtil.getAPIProxyFiles(configFile).get(0); Document xmlDoc = FileReader.getXMLDocument(proxyFile); // there would be only one file, at least one file XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expression = xpath.compile("/APIProxy/Description"); NodeList nodes = (NodeList) expression.evaluate(xmlDoc, XPathConstants.NODESET); if (nodes.item(0).hasChildNodes()) { // sets the description to whatever is in the <proxyname>.xml file nodes.item(0).setTextContent(expression.evaluate(xmlDoc)); } else {//from ww w .j a v a2s. c o m // if Description is empty, then it reverts back to appending the username, git hash, etc nodes.item(0).setTextContent(getComment(proxyFile)); } DOMSource source = new DOMSource(xmlDoc); StreamResult result = new StreamResult(proxyFile); transformer.transform(source, result); }
From source file:cz.incad.kramerius.virtualcollections.VirtualCollectionsManager.java
public static VirtualCollection doVC(String pid, FedoraAccess fedoraAccess, ArrayList<String> languages) { try {/*from w ww .ja va2 s .com*/ String xPathStr; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr; ArrayList<String> langs = new ArrayList<String>(); if (languages == null || languages.isEmpty()) { String[] ls = KConfiguration.getInstance().getPropertyList("interface.languages"); for (int i = 0; i < ls.length; i++) { String lang = ls[++i]; langs.add(lang); } } else { langs = new ArrayList<String>(languages); } String name = ""; boolean canLeave = true; fedoraAccess.getDC(pid); Document doc = fedoraAccess.getDC(pid); xPathStr = "//dc:title/text()"; expr = xpath.compile(xPathStr); Node node = (Node) expr.evaluate(doc, XPathConstants.NODE); if (node != null) { name = StringEscapeUtils.escapeXml(node.getNodeValue()); } xPathStr = "//dc:type/text()"; expr = xpath.compile(xPathStr); node = (Node) expr.evaluate(doc, XPathConstants.NODE); if (node != null) { canLeave = Boolean.parseBoolean(StringEscapeUtils.escapeXml(node.getNodeValue())); } VirtualCollection vc = new VirtualCollection(name, pid, canLeave); for (String lang : langs) { String dsName = TEXT_DS_PREFIX + lang; String value = IOUtils.readAsString(fedoraAccess.getDataStream(pid, dsName), Charset.forName("UTF8"), true); vc.addDescription(lang, value); } return vc; } catch (Exception vcex) { logger.log(Level.WARNING, "Could not get virtual collection for " + pid + ": " + vcex.toString()); return null; } }
From source file:io.apigee.buildTools.enterprise4g.utils.PackageConfigurer.java
public static Document replaceTokens(Document doc, Policy configTokens) throws XPathExpressionException, TransformerConfigurationException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(configTokens); logger.info("============= to apply the following config tokens ================\n{}", json); try {/*from w w w .j av a 2 s .c o m*/ for (int i = 0; i < configTokens.tokens.size(); i++) { logger.debug("=============Checking for Xpath Expressions {} ================\n", configTokens.tokens.get(i).xpath); XPathExpression expression = xpath.compile(configTokens.tokens.get(i).xpath); NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET); for (int j = 0; j < nodes.getLength(); j++) { if (nodes.item(j).hasChildNodes()) { logger.debug("=============Updated existing value {} to new value {} ================\n", nodes.item(j).getTextContent(), configTokens.tokens.get(i).value); nodes.item(j).setTextContent(configTokens.tokens.get(i).value); } } } return doc; } catch (XPathExpressionException e) { logger.error(String.format( "\n\n=============The Xpath Expressions in config.json are incorrect. Please check. ================\n\n%s", e.getMessage()), e); throw e; } }
From source file:com.impetus.ankush.common.utils.NmapUtil.java
/** * @throws ParserConfigurationException//from w ww.ja va 2s .c o m * @throws SAXException * @throws IOException * @throws XPathExpressionException */ private static Map<String, String> getHostIPMapping(String filePath) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { // loading the XML document from a file DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance(); builderfactory.setNamespaceAware(true); DocumentBuilder builder = builderfactory.newDocumentBuilder(); File file = new File(filePath); Document xmlDocument = builder.parse(file); XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance(); XPath xPath = factory.newXPath(); // getting the name of the book having an isbn number == ABCD7327923 XPathExpression hostXpath = xPath.compile("//host"); XPathExpression ipXpath = xPath.compile("address[@addrtype='ipv4']/@addr"); XPathExpression hostNameXpath = xPath.compile("hostnames/hostname[@type='user']/@name"); NodeList nodeListHost = (NodeList) hostXpath.evaluate(xmlDocument, XPathConstants.NODESET); Map<String, String> hostIpMapping = new HashMap<String, String>(); for (int index = 0; index < nodeListHost.getLength(); index++) { String ip = (String) ipXpath.evaluate(nodeListHost.item(index), XPathConstants.STRING); String host = (String) hostNameXpath.evaluate(nodeListHost.item(index), XPathConstants.STRING); hostIpMapping.put(host, ip); } // deleting the temporary xml file. FileUtils.deleteQuietly(file); return hostIpMapping; }
From source file:com.wso2telco.identity.application.authentication.endpoint.util.TenantDataManager.java
private static void refreshActiveTenantDomainsList() { try {/*w ww . j av a 2s . co m*/ String url = "https://" + getPropertyValue(HOST) + ":" + getPropertyValue(PORT) + "/services/TenantMgtAdminService/retrieveTenants"; String xmlString = getServiceResponse(url); if (xmlString != null && !"".equals(xmlString)) { XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); InputSource inputSource = new InputSource(new StringReader(xmlString)); String xPathExpression = "/*[local-name() = '" + RETRIEVE_TENANTS_RESPONSE + "']/*[local-name() = '" + RETURN + "']"; NodeList nodeList = (NodeList) xpath.evaluate(xPathExpression, inputSource, XPathConstants.NODESET); tenantDomainList = new ArrayList<String>(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; NodeList tenantData = element.getChildNodes(); boolean activeChecked = false; boolean domainChecked = false; boolean isActive = false; String tenantDomain = null; for (int j = 0; j < tenantData.getLength(); j++) { Node dataItem = tenantData.item(j); String localName = dataItem.getLocalName(); if (ACTIVE.equals(localName)) { activeChecked = true; if ("true".equals(dataItem.getTextContent())) { isActive = true; } } if (TENANT_DOMAIN.equals(localName)) { domainChecked = true; tenantDomain = dataItem.getTextContent(); } if (activeChecked && domainChecked) { if (isActive) { tenantDomainList.add(tenantDomain); } break; } } } } Collections.sort(tenantDomainList); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("Retrieving Active Tenant Domains Failed. Ignore this if there are no tenants : ", e); } } }