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:org.ala.harvester.FlickrHarvester.java
/** * Determines whether a Flickr photo has geo-coded location with Australia * as the country. <br />// ww w .j av a 2s. c o m * * XPath used to extract this information is * <code>/rsp/photo/location/country/text()</code> <br /> * * Non case-sensitive String comparison is performed. * * @param photoInfoXmlDom * DOM representation of XML result from calling * <code>flickr.photos.search</code> Flickr method. * * @return <code>true</code> if photo has geo-coded location for Australia, * <code>false</code> otherwise. * * @throws csiro.diasb.protocolhandlers.Exception * On error. * * @since v0.4 */ private boolean isPhotoFromAustralia(org.w3c.dom.Document photoInfoXmlDom) throws Exception { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); if (photoInfoXmlDom == null) { String errMsg = "DOM of Photo Info. XML has null reference."; logger.error(errMsg); throw new Exception(errMsg); } String photoTitle = (String) xpath.evaluate("/rsp/photo/title/text()", photoInfoXmlDom, XPathConstants.STRING); String photoDescription = (String) xpath.evaluate("/rsp/photo/description/text()", photoInfoXmlDom, XPathConstants.STRING); String photoCountry = (String) xpath.evaluate("/rsp/photo/location/country/text()", photoInfoXmlDom, XPathConstants.STRING); //check the machine tags String xPathToTags = "/rsp/photo/tags/tag/text()"; NodeList nl = (NodeList) xpath.evaluate(xPathToTags, photoInfoXmlDom, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { String content = nl.item(i).getNodeValue(); if (content != null) { content = content.toLowerCase(); if (content.contains("australia")) { return true; } } } if ("australia".compareToIgnoreCase(photoCountry) == 0 || (photoTitle != null && photoTitle.toLowerCase().contains("australia")) || (photoDescription != null && photoDescription.toLowerCase().contains("australia"))) { return true; } return false; }
From source file:org.ala.harvester.FlickrHarvester.java
private boolean isDocExtractionSuccessful(org.w3c.dom.Document resDom) throws Exception { if (resDom == null) { return false; }/* w w w.j ava 2s .c o m*/ XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // <rsp stat="fail"> // <err code="[error-code]" msg="[error-message]" /> // </rsp> String xPathToStatus = "/rsp/@stat"; String statusString = null; try { statusString = (String) xpath.evaluate(xPathToStatus, resDom, XPathConstants.STRING); } catch (XPathExpressionException getStatusStringErr) { String errMsg = "Failed to obtain Flickr REST response's status string."; logger.error(errMsg); throw new Exception(errMsg, getStatusStringErr); } logger.debug("Response status: " + statusString); if ("ok".equals(statusString)) { return true; } else { logger.error("Error response status: " + statusString); } // Status is false. String flickrErrCode = null; String flickrErrMsg = null; try { flickrErrCode = (String) xpath.evaluate("/rsp/err/@code", resDom, XPathConstants.STRING); flickrErrMsg = (String) xpath.evaluate("/rsp/err/@msg", resDom, XPathConstants.STRING); } catch (XPathExpressionException getErrDetailsErr) { String errMsg = "Failed to obtain Flickr REST response's error code and message."; logger.error(errMsg); throw new Exception(errMsg, getErrDetailsErr); } String errMsg = "Flickr REST response returned error. Code: " + flickrErrCode + " " + "Message: " + "`" + flickrErrMsg + "`" + "\n"; logger.error(errMsg); return false; }
From source file:eu.fbk.dh.tint.tokenizer.ItalianTokenizer.java
public ItalianTokenizer(@Nullable File settingFile) { Trie.TrieBuilder builder = Trie.builder().removeOverlaps(); InputStream stream = null; if (settingFile != null) { try { stream = new FileInputStream(settingFile); } catch (FileNotFoundException e) { // continue }/*from w ww . j av a 2s.c om*/ } if (stream == null) { stream = this.getClass().getResourceAsStream("/token-settings.xml"); } logger.trace("Loading model"); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr; NodeList nl; int count; Document doc = dBuilder.parse(stream); doc.getDocumentElement().normalize(); // Normalization rules expr = xpath.compile("/settings/normalization/char"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); Element element = (Element) item; String hexCode = element.getAttribute("hexcode"); String content = element.getTextContent(); // Bad: need fix if (content.equals("`")) { content = "'"; } int num = Integer.parseInt(hexCode, 16); if (content.length() == 0) { continue; } normalizedChars.put(num, content); } logger.info("Loaded {} normalization rules", normalizedChars.size()); // end sentence chars expr = xpath.compile("/settings/sentenceSplitting/char"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); Element element = (Element) item; String charID = element.getAttribute("id"); sentenceChars.add(Integer.parseInt(charID)); } logger.info("Loaded {} sentence splitting rules", sentenceChars.size()); // splitting rules expr = xpath.compile("/settings/tokenSplitting/char"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); Element element = (Element) item; String charID = element.getAttribute("id"); splittingChars.add(Integer.parseInt(charID)); } logger.info("Loaded {} token splitting rules", splittingChars.size()); // expressions expr = xpath.compile("/settings/expressions/expression"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); StringBuilder b = new StringBuilder(); b.append("("); boolean first = true; count = 0; for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); Element element = (Element) item; String regExp = element.getAttribute("find"); boolean merge = PropertiesUtils.getBoolean(element.getAttribute("merge"), true); Integer group = PropertiesUtils.getInteger(element.getAttribute("get"), 1); if (merge) { if (!first) { b.append("|"); } b.append(regExp); count++; first = false; } else { expressions.put(Pattern.compile(regExp), group); count++; } } b.append(")"); expressions.put(Pattern.compile(b.toString()), 1); logger.info("Loaded {} regular expressions", count); // abbreviations expr = xpath.compile("/settings/abbreviations/abbreviation"); nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); count = 0; for (int i = 0; i < nl.getLength(); i++) { Node item = nl.item(i); String abbr = item.getTextContent(); abbr = getString(tokenArray(abbr)); builder.addKeyword(" " + abbr + " "); count++; } logger.info("Loaded {} abbreviations", count); } catch (Exception e) { e.printStackTrace(); } trie = builder.build(); }
From source file:com.photon.phresco.impl.DrupalApplicationProcessor.java
private void storeConfigObj(List<Configuration> configs, File featureManifestXmlFile, File featureSqlDir, String environmentName) throws PhrescoException { try {//from w w w . j a v a 2s . c o m if (!featureManifestXmlFile.isFile()) { throw new PhrescoException("manifest file is not available"); } // Document DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(featureManifestXmlFile); doc.getDocumentElement().normalize(); // xpath XPathFactory factory = XPathFactory.newInstance(); XPath xPathInstance = factory.newXPath(); for (Configuration configuration : configs) { Properties properties = configuration.getProperties(); Enumeration em = properties.keys(); while (em.hasMoreElements()) { String insertQuery = ""; String insertFieldQuery = ""; String deleteQuery = ""; String deleteFieldQuery = ""; String tableName = ""; String variableName = ""; String defaultValue = ""; String constructedQuery = ""; String key = (String) em.nextElement(); Object object = properties.get(key); // get config object for this key String xPathQuery = CONFIG_XPATH + key + CONFIG_XPATH_END_TAG; XPathExpression xPathExpression = xPathInstance.compile(xPathQuery); //evalute the xpath query in the entire xml document and define the return type Object results = xPathExpression.evaluate(doc, XPathConstants.NODESET); NodeList nList = (NodeList) results; // config objects for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); // get config object values if (nNode.getNodeType() == Node.ELEMENT_NODE) { // getting child nodes to construct query NodeList childNodes = nNode.getChildNodes(); for (int temp1 = 0; temp1 < childNodes.getLength(); temp1++) { Node childNode = childNodes.item(temp1); if (childNode.getNodeType() == Node.ELEMENT_NODE) { if (TABLE_NAME.equals(childNode.getNodeName())) { tableName = childNode.getTextContent(); if (!VARIABLE_FIELD.equals(tableName)) { return; } deleteQuery = deleteQuery + DELETE_FROM + childNode.getTextContent() + WHERE + NAME_FIELD + EQUAL; insertQuery = insertQuery + INSERT_INTO + childNode.getTextContent() + VARIABLE_START_TAG + NAME_FIELD + SQL_VARIABLE_SEP + VALUE_FIELD + VARIABLE_END_TAG + VALUES_START_TAG; } else if (VARIABLE_NAME.equals(childNode.getNodeName())) { variableName = childNode.getTextContent(); deleteFieldQuery = SINGLE_QUOTE + childNode.getTextContent() + SINGLE_QUOTE + SEMI_COLON + LINE_BREAK; } else if (CURRENT_VALUE.equals(childNode.getNodeName())) { childNode.setTextContent(object.toString()); } defaultValue = object.toString(); insertFieldQuery = variableName + SQL_VALUE_SEP + defaultValue + VALUES_END_TAG; } } } } constructedQuery = deleteQuery + deleteFieldQuery + insertQuery + insertFieldQuery; List<File> sqlFolders = getSqlFolders(featureSqlDir); for (File sqlFolder : sqlFolders) { replaceSqlBlock(sqlFolder, CONFIGURATION + environmentName + DOT_SQL, key, constructedQuery); } } } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(new DOMSource(doc), new StreamResult(featureManifestXmlFile.getPath())); } catch (Exception e) { throw new PhrescoException(e); } }
From source file:de.codesourcery.jasm16.ide.ProjectConfiguration.java
private void parseXML(Document doc) throws XPathExpressionException { final XPathFactory factory = XPathFactory.newInstance(); final XPath xpath = factory.newXPath(); final XPathExpression nameExpr = xpath.compile("/project/name"); final XPathExpression outputFolderExpr = xpath.compile("/project/outputFolder"); final XPathExpression executableNameExpr = xpath.compile("/project/executableName"); final XPathExpression srcFoldersExpr = xpath.compile("/project/sourceFolders/sourceFolder"); final XPathExpression emulationOptionsExpr = xpath.compile("/project/emulationOptions"); final XPathExpression buildOptionsExpr = xpath.compile("/project/buildOptions"); final XPathExpression srcFilePatternsExpr = xpath .compile("/project/sourceFilenamePatterns/sourceFilenamePattern"); final XPathExpression compilationRootExpr = xpath.compile("/project/compilationRoot"); final XPathExpression debuggerOptionsExpr = xpath.compile("/project/debuggerOptions"); this.outputFolder = getValue(outputFolderExpr, doc); this.projectName = getValue(nameExpr, doc); this.executableName = getValue(executableNameExpr, doc); this.sourceFolders.clear(); this.sourceFolders.addAll(getValues(srcFoldersExpr, doc)); // compilation root final List<String> roots = getValues(compilationRootExpr, doc); if (!roots.isEmpty()) { if (roots.size() > 1) { throw new RuntimeException("Parse error, more than one compilation root in project config XML ?"); }/*from w w w . j a va2 s .co m*/ setCompilationRoot(new File(roots.get(0))); } // parse srcfile name patterns final List<String> patterns = getValues(srcFilePatternsExpr, doc); if (!patterns.isEmpty()) { setSourceFilenamePatterns(new HashSet<>(patterns)); } // parse emulation options Element element = getElement(emulationOptionsExpr, doc); if (element == null) { this.emulationOptions = new EmulationOptions(); } else { this.emulationOptions = EmulationOptions.loadEmulationOptions(element); } // parse build options element = getElement(buildOptionsExpr, doc); if (element == null) { this.buildOptions = new BuildOptions(); } else { this.buildOptions = BuildOptions.loadBuildOptions(element); } // parse build options element = getElement(debuggerOptionsExpr, doc); if (element == null) { this.debuggerOptions.reset(); } else { this.debuggerOptions.loadDebuggerOptions(element); } }
From source file:com.alvexcore.repo.masterdata.getConstraintWork.java
protected List<Map<String, String>> getRestXmlMasterData(NodeRef source) throws Exception { NodeService nodeService = serviceRegistry.getNodeService(); String url = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_REST_URL); String rootXPath = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_XPATH_ROOT_QUERY); String labelXPath = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_XPATH_LABEL); String valueXPath = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_XPATH_VALUE); String caching = (String) nodeService.getProperty(source, AlvexContentModel.PROP_MASTER_DATA_REST_CACHE_MODE); // Standard of reading a XML file DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//from ww w .j av a2 s.c o m DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(url); // Create a XPathFactory XPathFactory xFactory = XPathFactory.newInstance(); // Create a XPath object XPath xpath = xFactory.newXPath(); // Compile the XPath expression XPathExpression setExpr = xpath.compile(rootXPath); XPathExpression valueExpr = xpath.compile(valueXPath); XPathExpression labelExpr = xpath.compile(labelXPath); // Run the query and get a nodeset Object result = setExpr.evaluate(doc, XPathConstants.NODESET); // Cast the result to a list NodeList nodes = (NodeList) result; List<Map<String, String>> res = new ArrayList<Map<String, String>>(); for (int i = 0; i < nodes.getLength(); i++) { String value = (String) valueExpr.evaluate(nodes.item(i), XPathConstants.STRING); String label = (String) labelExpr.evaluate(nodes.item(i), XPathConstants.STRING); HashMap<String, String> resItem = new HashMap<String, String>(); resItem.put("ref", ""); resItem.put("value", value); resItem.put("label", label); res.add(resItem); } return res; }
From source file:betullam.xmlmodifier.XMLmodifier.java
private List<String> getDMDIDs(String structureType, Document xmlDoc) throws XPathExpressionException { List<String> lstDMDIDs = new ArrayList<String>(); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression xPathExpr = xPath .compile("//structMap[@TYPE=\"LOGICAL\"]//div[@DMDID][@TYPE=\"" + structureType + "\"]"); NodeList nodeList = (NodeList) xPathExpr.evaluate(xmlDoc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Element xmlElement = (Element) nodeList.item(i); String dmdId = xmlElement.getAttribute("DMDID"); //System.out.println(dmdId + " = " + xmlElement.getAttribute("TYPE")); lstDMDIDs.add(dmdId);/*from ww w . j a va2s . com*/ } return lstDMDIDs; }
From source file:org.ala.harvester.FlickrHarvester.java
/** * Retrieves a map of licences.//w w w. jav a2s. c o m * * @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 ava2 s . c o m*/ 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; }
From source file:betullam.xmlmodifier.XMLmodifier.java
private List<Node> getElementsToModify(String mdName, String mdValue, Document xmlDoc) throws XPathExpressionException { List<Node> nodeArrayList = new ArrayList<Node>(); if (!mdName.equals("null")) { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); XPathExpression xPathExpr = xPath.compile("//goobi/metadata[@name=\"" + mdName + "\"]"); NodeList nodeList = (NodeList) xPathExpr.evaluate(xmlDoc, XPathConstants.NODESET); if (mdValue.equals("null")) { for (int n = 0; n < nodeList.getLength(); n++) { nodeArrayList.add(nodeList.item(n)); }//from w w w . j a v a 2 s . co m } else { for (int n = 0; n < nodeList.getLength(); n++) { Element xmlElement = (Element) nodeList.item(n); String textContent = xmlElement.getTextContent(); if (textContent.equals(mdValue)) { nodeArrayList.add(nodeList.item(n)); } } } } return nodeArrayList; }