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:org.ala.harvester.IdentifyLifeHarvester.java
/** * Harvest a document and update the repository. * //from ww w .j av a 2 s. c o m * @param infosourceId * @param url * @throws Exception */ private void harvestDoc(int infosourceId, String url) throws Exception { byte[] content = null; System.out.println("******** request: " + url); Object[] resp = restfulClient.restGet(url); if ((Integer) resp[0] == HttpStatus.SC_OK) { content = resp[1].toString().getBytes("UTF-8"); } if (content != null) { List<String> ids = new ArrayList<String>(); String keyUrl = connectionParams.get(KEY_END_POINT_ATTR_NAME); // Instantiates a DOM builder to create a DOM of the response. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // return a parsed Document Document doc = builder.parse(new ByteArrayInputStream(content)); XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); XPathExpression xe = xpath.compile("//keys/key[@id]"); NodeList nodeSet = (NodeList) xe.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodeSet.getLength(); i++) { NamedNodeMap map = nodeSet.item(i).getAttributes(); ids.add(map.getNamedItem("id").getNodeValue()); } for (int i = 0; i < ids.size(); i++) { Object[] res = restfulClient.restGet(keyUrl + "/" + ids.get(i)); if ((Integer) res[0] == HttpStatus.SC_OK) { //map the document List<ParsedDocument> pds = documentMapper.map(keyUrl + ids.get(i), res[1].toString().getBytes()); //store the results for (ParsedDocument pd : pds) { //debugParsedDoc(pd); repository.storeDocument(infosourceId, pd); logger.debug("Parent guid for stored doc: " + pd.getParentGuid()); } } } } else { logger.warn("Unable to process url: " + url); } }
From source file:no.digipost.signature.client.asice.signature.CreateXAdESProperties.java
private void markAsIdProperty(final Document document, final String elementName, final String property) { XPath xPath = XPathFactory.newInstance().newXPath(); try {/* w w w. j a v a2 s . c o m*/ Element idElement = (Element) xPath.evaluate("//*[local-name()='" + elementName + "']", document, XPathConstants.NODE); idElement.setIdAttribute(property, true); } catch (XPathExpressionException e) { throw new XmlConfigurationException("XPath on generated XML failed.", e); } }
From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java
/** * very useful: {@link http/*ww w. j a v a 2 s. com*/ * ://www.ibm.com/developerworks/library/x-javaxpathapi.html} * * @param doc * @param path * @param scale * @return * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws XPathExpressionException */ private String extractTextInternal(Document doc, String path) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(namespaceContext); XPathExpression expr = xpath.compile(path); try { String result = (String) expr.evaluate(doc, XPathConstants.STRING); return result; } catch (Exception e) { log.error("XML extraction for path " + path + " failed: " + e.getMessage(), e); return "XML extraction for path " + path + " failed: " + e.getMessage(); } }
From source file:com.hygenics.parser.ManualReplacement.java
private void transform() { log.info("Transforming"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); for (String fpath : fpaths) { log.info("FILE: " + fpath); try {/* w w w . ja v a 2s. co m*/ // TRANSFORM DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new File(fpath)); Node root = doc.getFirstChild(); XPathFactory xfactory = XPathFactory.newInstance(); XPath xpath = xfactory.newXPath(); String database = null; String path = "//transformation/connection"; log.info("Removing"); for (String dbname : remove) { log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]"); XPathExpression xepr = xpath .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]"); Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (conn != null) { root.removeChild(conn); } } log.info("Transforming"); for (String key : databaseAttributes.keySet()) { database = key; log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]"); XPathExpression xepr = xpath .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]"); Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (conn != null) { if (remove.contains(key)) { root.removeChild(conn); } else { Map<String, String> attrs = databaseAttributes.get(database); NodeList nl = conn.getChildNodes(); Set<String> keys = databaseAttributes.get(key).keySet(); for (int i = 0; i < nl.getLength(); i++) { org.w3c.dom.Node n = nl.item(i); if (keys.contains(n.getNodeName().trim())) { n.setNodeValue(attrs.get(n.getNodeName())); } } } } if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) { log.info("Logging Manipulation"); log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null ? "Removing Logging Data" : "Adding Logging data"); String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table", "step-log-table", "metrics-log-table" }; for (String section : sections) { log.info("Changing Settings for " + section); xepr = xpath.compile("//" + section + "/field/enabled"); NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); log.info("Nodes Found: " + Integer.toString(nodes.getLength())); for (int i = 0; i < nodes.getLength(); i++) { if (!this.log_to_table) { nodes.item(i).setNodeValue("N"); } else { nodes.item(i).setNodeValue("Y"); } } for (String nodeName : new String[] { "schema", "connection", "table", "size_limit_lines", "interval", "timeout_days" }) { if (!this.log_to_table) { log.info("Changing Settings for Node: " + nodeName); xepr = xpath.compile("//" + section + "/" + nodeName); Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (node != null) { if (!this.log_to_table) { node.setNodeValue(null); } else if (this.loggingTables.containsKey(section) && this.loggingTables.get(section).containsKey(nodeName)) { node.setNodeValue(this.loggingTables.get(section).get(nodeName)); } } } } } } } // SET MAIN CONNECTION if (mainConnection != null) { XPathExpression xepr = xpath.compile(path); NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of // org.w3c it is // actually a NodeList for (int i = 0; i < conns.getLength(); i++) { if (!conns.item(i).hasChildNodes()) {// only connection // elements // without child // nodes have // text content conns.item(i).setNodeValue(mainConnection); } } } if (this.replacements != null) { for (String key : this.replacements.keySet()) { XPathExpression xepr = xpath.compile(key); Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE); if (node != null) { for (String attrVal : this.replacements.get(key).keySet()) { log.info("Replacing Information at " + key + "at " + attrVal); log.info("Replacement Will Be: " + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal))); if (attrVal.toLowerCase().trim().equals("text")) { node.setNodeValue( StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal))); if (node.getNodeValue() == null) { node.setTextContent(StringEscapeUtils .escapeXml11(this.replacements.get(key).get(attrVal))); } } else { NamedNodeMap nattrs = node.getAttributes(); Node n = nattrs.getNamedItem(attrVal); if (n != null) { n.setNodeValue(StringEscapeUtils .escapeXml11(this.replacements.get(key).get(attrVal))); } else { log.warn("Attribute Not Found " + attrVal); } } } } else { log.warn("Node not found for " + key); } } } // WRITE TO FILE log.info("Writing to File"); TransformerFactory tfact = TransformerFactory.newInstance(); Transformer transformer = tfact.newTransformer(); DOMSource source = new DOMSource(doc); try (FileOutputStream stream = new FileOutputStream(new File(fpath))) { StreamResult result = new StreamResult(stream); transformer.transform(source, result); stream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } } }
From source file:eu.planets_project.tb.impl.services.EvaluationTestbedServiceTemplateImpl.java
/** * Method for applying the XPathForBMGoalRootNodes on a given DOM Document * @param doc//w ww . j a va2s . c om * @return * @throws XPathExpressionException */ public NodeList getAllEvalResultsRootNodes(Document doc) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xpath.evaluate(sXPathForBMGoalRootNodes, doc, XPathConstants.NODESET); return nodes; }
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 a v a2 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.concursive.connect.cms.portal.dao.DashboardTemplateList.java
private void parseLibrary(XMLUtils library) { LOG.debug("objectType=" + objectType); LOG.debug("has xml? " + (library != null)); if (LOG.isTraceEnabled()) { LOG.trace(library.toString());//from w w w . j a v a 2s .com } // Use XPath for querying xml elements XPath xpath = XPathFactory.newInstance().newXPath(); // Build a list of dashboard pages ArrayList<Element> pageElements = new ArrayList<Element>(); XMLUtils.getAllChildren(XMLUtils.getFirstChild(library.getDocumentElement(), objectType), "page", pageElements); Iterator i = pageElements.iterator(); int count = 0; while (i.hasNext()) { ++count; Element el = (Element) i.next(); DashboardTemplate thisTemplate = new DashboardTemplate(); thisTemplate.setId(count); thisTemplate.setName(el.getAttribute("name")); // Check for xml included fragments declaration // <xml-include fragment="portal-fragments-id"/> // NOTE: since the document is being read as a resource, xinclude and xpointer could not be used // mainly due to xpointer not being implemented try { NodeList includeList = (NodeList) xpath.evaluate("row/column/portlet/xml-include", el, XPathConstants.NODESET); // XML Include found, so find all the fragments for (int nodeIndex = 0; nodeIndex < includeList.getLength(); nodeIndex++) { Node xmlInclude = includeList.item(nodeIndex); String fragmentId = ((Element) xmlInclude).getAttribute("fragment"); NodeList fragmentNodeList = (NodeList) xpath.evaluate( "*/fragment[@id=\"" + fragmentId + "\"]/*", library.getDocumentElement(), XPathConstants.NODESET); if (LOG.isDebugEnabled() && fragmentNodeList.getLength() == 0) { LOG.error("Could not find fragment with id: " + fragmentId); } for (int prefIndex = 0; prefIndex < fragmentNodeList.getLength(); prefIndex++) { xmlInclude.getParentNode().appendChild(fragmentNodeList.item(prefIndex).cloneNode(true)); } // Remove the XML Include declaration xmlInclude.getParentNode().removeChild(xmlInclude); } } catch (Exception e) { LOG.error("Replace xml fragments", e); } // Set the completed xml layout thisTemplate.setXmlDesign(XMLUtils.toString(el)); // Check for properties that affect the rendering of the portal page if (el.hasAttribute("permission")) { thisTemplate.setPermission(el.getAttribute("permission")); } if (el.hasAttribute("title")) { thisTemplate.setTitle(el.getAttribute("title")); } if (el.hasAttribute("description")) { thisTemplate.setDescription(el.getAttribute("description")); } if (el.hasAttribute("keywords")) { thisTemplate.setKeywords(el.getAttribute("keywords")); } if (el.hasAttribute("category")) { thisTemplate.setCategory(el.getAttribute("category")); } this.add(thisTemplate); } }
From source file:de.iteratec.iteraplan.businesslogic.exchange.common.informationflow.VisioInformationFlowTemplateParser.java
public void parseTemplate() { Document dom = parseXmlFile(); XPath xPath = XPathFactory.newInstance().newXPath(); String xPathFirstLevelApplicationNodesExpression = "/VisioDocument/Pages/Page[1]/" + APPLICATION_SHAPE_XPATH;//from w w w . ja va 2 s. c om parsedNodes = Maps.newHashMap(); try { NodeList firstLevelApplicationNodes = (NodeList) xPath .evaluate(xPathFirstLevelApplicationNodesExpression, dom, XPathConstants.NODESET); for (int i = 0; i < firstLevelApplicationNodes.getLength(); i++) { Node node = firstLevelApplicationNodes.item(i); parseNodeAndAddToMap(node, null); } } catch (XPathExpressionException e) { LOGGER.error("XPath-error during parsing of template '" + templateFile.getName() + "'.", e); throw new IteraplanTechnicalException(IteraplanErrorMessages.INTERNAL_ERROR); } }
From source file:no.difi.sdp.client.asice.signature.CreateXAdESProperties.java
private void markAsIdProperty(Document document, final String elementName, String property) { XPath xPath = XPathFactory.newInstance().newXPath(); try {//from w w w .j a va 2 s . c om Element idElement = (Element) xPath.evaluate("//*[local-name()='" + elementName + "']", document, XPathConstants.NODE); idElement.setIdAttribute(property, true); } catch (XPathExpressionException e) { throw new XmlKonfigurasjonException("XPath p generert XML feilet.", e); } }
From source file:com.gisgraphy.fulltext.SolrClient.java
public boolean isServerAlive() { try {//from w w w.j av a 2 s . com DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XPath xpath = XPathFactory.newInstance().newXPath(); if (xpath == null || builder == null) { throw new RuntimeException("Can not determine if fulltext engine is alive"); } SolrPingResponse response = getServer().ping(); if (response == null) { return false; } return ((String) response.getResponse().get("status")).equals("OK"); } catch (Exception e) { logger.error("can not determine if fulltext engine is alive " + e.getMessage(), e); return false; } }