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:net.bpelunit.test.util.TestUtil.java
public static Node getNode(Element literalData, NamespaceContextImpl context, String string) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(context);//from www.ja v a 2s. c o m return (Node) xpath.evaluate(string, literalData, XPathConstants.NODE); }
From source file:de.ingrid.iplug.opensearch.query.OSDescriptorBuilder.java
/** * Request the descriptorAddress and return an OSDescriptor object. * //from w w w . j ava2s . c om * @param descriptorAddress * @return * @throws Exception */ public OSDescriptor receiveDescriptor(String descriptorAddress) throws Exception { OSCommunication comm = new OSCommunication(); OSDescriptor osDesciptor = new OSDescriptor(); try { InputStream response = comm.sendRequest(descriptorAddress); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document descriptorDoc = builder.parse(response); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList typeList = (NodeList) xpath.evaluate("/OpenSearchDescription/Url/@type", descriptorDoc, XPathConstants.NODESET); NodeList templateList = (NodeList) xpath.evaluate("/OpenSearchDescription/Url/@template", descriptorDoc, XPathConstants.NODESET); for (int i = 0; i < typeList.getLength(); i++) { osDesciptor.setTypeAndUrl(typeList.item(i).getTextContent(), templateList.item(i).getTextContent()); } } catch (ParserConfigurationException e) { log.error("Error while parsing DescriptorFile from: " + descriptorAddress); e.printStackTrace(); } catch (SAXException e) { log.error("Error while parsing DescriptorFile from: " + descriptorAddress); e.printStackTrace(); } catch (XPathExpressionException e) { log.error("Error while parsing DescriptorFile from: " + descriptorAddress); e.printStackTrace(); } finally { comm.releaseConnection(); } return osDesciptor; }
From source file:com.seer.datacruncher.validation.MacroRulesValidation.java
/** * Apply validation macro rules./*ww w. j av a 2 s . co m*/ * @param datastreamDTO * @return ResultStepValidation */ protected ResultStepValidation doValidation(DatastreamDTO datastreamDTO) { long schemaId = datastreamDTO.getIdSchema(); List<MacroEntity> list = new ArrayList<MacroEntity>(); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder .parse(new ByteArrayInputStream(schemasXSDDao.find(schemaId).getSchemaXSD().getBytes())); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//annotation/appinfo/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { String val = nodes.item(i).getNodeValue(); if (val.startsWith("@RuleCheck")) { String[] arr = val.split(";\n"); for (String s : arr) { list.add(macrosDao.getMacroEntityByName(s.trim().substring(11))); } break; } } } catch (ParserConfigurationException e) { log.error("ParserConfigurationException", e); } catch (SAXException e) { log.error("SAXException", e); } catch (IOException e) { log.error("IOException", e); } catch (XPathExpressionException e) { log.error("XPathExpressionException", e); } ResultStepValidation resultStepValidation = new ResultStepValidation(); resultStepValidation.setValid(true); resultStepValidation.setMessageResult(I18n.getMessage("success.validationOK")); List<Element> xmlTextNodes = null; try { xmlTextNodes = StreamsUtils.parseStreamXml(datastreamDTO.getOutput()); } catch (DocumentException e) { log.error("Stream parse exception", e); } JexlEngine jexl = JexlEngineFactory.getInstance(); boolean isSuccess = true; Pattern pattern = Pattern.compile(MACRO_SQL_VALIDATOR_PATTERN, Pattern.CASE_INSENSITIVE); for (MacroEntity ent : list) { if (!isSuccess) continue; String rule = ent.getRule(); List<Map<String, String>> varsList = parseVars(ent.getVars()); combineVariableLists(varsList, schemaId); Matcher matcher = pattern.matcher(rule); while (matcher.find()) { String varName = matcher.group(4); String sqlRes = "false"; for (Map<String, String> m : varsList) { if (m.get("uniqueName").equals(varName)) { for (Element el : xmlTextNodes) { int t = datastreamDTO.getIdStreamType(); String fieldPath = (t == StreamType.XML || t == StreamType.XMLEXI ? "" : "ROOT/") + m.get("nodePath"); if (fieldPath.equals(StreamsUtils.formatPathForXmlNode(el.getPath()))) { String prepSql = matcher.group().replaceAll(matcher.group(4), "\"" + el.getText() + "\""); String signum = matcher.group(3); if (signum.equals("<")) { prepSql = prepSql.replaceAll(signum, ">="); } else if (signum.equals(">")) { prepSql = prepSql.replaceAll(signum, "<="); } else if (signum.equals("!=")) { prepSql = prepSql.replaceAll(signum, "="); } Query q = entityManager.createNativeQuery(prepSql); @SuppressWarnings("rawtypes") List resList = q.getResultList(); if ((signum.equals("=") && resList.size() > 0) || (signum.equals("!=") && resList.size() == 0) || (signum.equals(">") && resList.size() == 0) || (signum.equals("<") && resList.size() == 0)) { sqlRes = "true"; } break; } } } } rule = rule.replaceAll(matcher.group(), sqlRes); } Expression e = jexl.createExpression(rule); JexlContext context = new MapContext(); for (Map<String, String> m : varsList) { for (Element el : xmlTextNodes) { int t = datastreamDTO.getIdStreamType(); String fieldPath = (t == StreamType.XML || t == StreamType.XMLEXI ? "" : "ROOT/") + m.get("nodePath"); if (fieldPath.equals(StreamsUtils.formatPathForXmlNode(el.getPath()))) { context.set(m.get("uniqueName"), JEXLFieldFactory.getField(m.get("fieldType"), el.getText()).getValue()); break; } } } Object res = e.evaluate(context); if (res != null) { isSuccess = false; resultStepValidation.setValid(false); if (ent.getErrorType() == StreamStatus.Warning.getCode()) { resultStepValidation.setWarning(true); } resultStepValidation .setMessageResult(I18n.getMessage("error.validationMacro") + ": " + res.toString()); } } return resultStepValidation; }
From source file:it.jnrpe.plugin.tomcat.TomcatDataProvider.java
private void parseMemoryData() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(tomcatXML)); Document doc = builder.parse(is); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); //Element root = (Element) xpath.compile("//status").evaluate(doc.getDocumentElement(), XPathConstants.NODE); Element memory = (Element) xpath.compile("//status/jvm/memory").evaluate(doc.getDocumentElement(), XPathConstants.NODE); long freeMem = Long.parseLong(memory.getAttribute("free")); long totalMem = Long.parseLong(memory.getAttribute("total")); long maxMem = Long.parseLong(memory.getAttribute("max")); jvmMemoryUsage = new MemoryData(freeMem, maxMem, totalMem); }
From source file:com.microsoft.samples.federation.FederationMetadataDocument.java
private String getSingleNodeText(String xpathStr) { XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); try {//from ww w . j av a2 s . c o m XPathExpression xpe = xpath.compile(xpathStr); NodeList nodeList = (NodeList) xpe.evaluate(_fmdDoc, XPathConstants.NODESET); if (nodeList.getLength() > 0) { return nodeList.item(0).getNodeValue(); } } catch (XPathExpressionException e) { //do something here } return null; }
From source file:gov.nih.nci.cacis.transform.XSLTv2TransformerTest.java
@Test public void transformStream() throws XMLStreamException, TransformerException, URISyntaxException, IOException, SAXException, ParserConfigurationException, XPathExpressionException { final ByteArrayOutputStream os = new ByteArrayOutputStream(); final Map<String, String> params = new HashMap<String, String>(); params.put("BaseURI", "http://yadda.com/someUUID"); transform.transform(params, sampleMessageIS, os); assertNotNull(os);//from w w w .j av a 2s . com assertTrue(os.size() > 0); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(os.toByteArray())); assertNotNull(doc); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); XPathExpression expr = xpath.compile("/world/country[1]/city[1]"); assertEquals("Tokyo", expr.evaluate(doc)); }
From source file:org.jboss.spring.factory.NamedXmlApplicationContext.java
private void initializeNames(Resource resource) { try {/*from w ww . j a v a 2s. c o m*/ XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(new NamespaceContext() { @Override public String getNamespaceURI(String prefix) { return "http://www.springframework.org/schema/beans"; } @Override public String getPrefix(String namespaceURI) { return "beans"; } @Override public Iterator getPrefixes(String namespaceURI) { return Collections.singleton("beans").iterator(); } }); String expression = "/beans:beans/beans:description"; InputSource inputSource = new InputSource(resource.getInputStream()); String description = xPath.evaluate(expression, inputSource); if (description != null) { Matcher bfm = Pattern.compile(Constants.BEAN_FACTORY_ELEMENT).matcher(description); if (bfm.find()) { this.name = bfm.group(1); } Matcher pbfm = Pattern.compile(Constants.PARENT_BEAN_FACTORY_ELEMENT).matcher(description); if (pbfm.find()) { String parentName = pbfm.group(1); try { this.getBeanFactory() .setParentBeanFactory((BeanFactory) Util.lookup(parentName, BeanFactory.class)); } catch (Exception e) { throw new BeanDefinitionStoreException( "Failure during parent bean factory JNDI lookup: " + parentName, e); } } } if (this.name == null || "".equals(StringUtils.trimAllWhitespace(this.name))) { this.name = this.defaultName; } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.opencastproject.remotetest.util.JobUtils.java
/** * Parses the job instance represented by <code>xml</code> and extracts the job state. * /*from www. j av a 2s.c o m*/ * @param xml * the job instance * @return the job state * @throws Exception * if parsing fails */ public static String getJobState(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8")); return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE)) .getAttribute("state"); }
From source file:nz.co.jsrsolutions.tideservice.geocoding.GoogleTideDataGeoCoder.java
@Override public GeoLocation getGeoLocation(Port port) throws TideDataGeoCoderException { URI uri;// w w w.jav a2 s .c om try { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(port.getName()); stringBuffer.append(", "); stringBuffer.append(port.getSubArea().getName()); uri = mUriBuilder.buildGetGeoLocUri(stringBuffer.toString()); HttpUriRequest request = new GoogleGeoCoderHttpGet(uri); HttpResponse response = mHttpClient.execute(request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new TideDataGeoCoderException( "HTTP GET returned: " + response.getStatusLine().getStatusCode()); } // read result and parse into XML Document HttpEntity entity = response.getEntity(); Document geocoderResultDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(entity.getContent()); // prepare XPath XPath xpath = XPathFactory.newInstance().newXPath(); // extract the result NodeList resultNodeList = null; // a) Examine the status resultNodeList = (NodeList) xpath.evaluate("/GeocodeResponse/status", geocoderResultDocument, XPathConstants.NODESET); if (resultNodeList.getLength() != 1) { throw new TideDataGeoCoderException("Couldn't parse result document."); } GoogleGeoCoderResultStatus resultStatus = GoogleGeoCoderResultStatus .valueOf(resultNodeList.item(0).getTextContent()); switch (resultStatus) { case OK: break; case ZERO_RESULTS: throw new TideDataGeoCoderException("No results found for: " + stringBuffer.toString()); case OVER_QUERY_LIMIT: throw new TideDataGeoCoderException("Over query limit (was 2500 requests per day)"); case REQUEST_DENIED: throw new TideDataGeoCoderException("Request denied (using sensor=true|false ?)"); case INVALID_REQUEST: throw new TideDataGeoCoderException("Invalid request - badly formed query"); } // c) extract the coordinates of the first result resultNodeList = (NodeList) xpath.evaluate("/GeocodeResponse/result[1]/geometry/location/*", geocoderResultDocument, XPathConstants.NODESET); float lat = Float.NaN; float lng = Float.NaN; for (int i = 0; i < resultNodeList.getLength(); ++i) { Node node = resultNodeList.item(i); if ("lat".equals(node.getNodeName())) { lat = Float.parseFloat(node.getTextContent()); } if ("lng".equals(node.getNodeName())) { lng = Float.parseFloat(node.getTextContent()); } } GeoLocation geoLocation = new GeoLocation(); geoLocation.setLatitude((long) (lat * 1e6)); geoLocation.setLongitude((long) (lng * 1e6)); return geoLocation; } catch (URISyntaxException e) { throw new TideDataGeoCoderException(e); } catch (ClientProtocolException e) { throw new TideDataGeoCoderException(e); } catch (IOException e) { throw new TideDataGeoCoderException(e); } catch (IllegalStateException e) { throw new TideDataGeoCoderException(e); } catch (SAXException e) { throw new TideDataGeoCoderException(e); } catch (ParserConfigurationException e) { throw new TideDataGeoCoderException(e); } catch (XPathExpressionException e) { throw new TideDataGeoCoderException(e); } }