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:com.mnxfst.testing.client.TSClientPlanExecCallable.java
/** * @see java.util.concurrent.Callable#call() *//*from w w w . ja v a2 s .com*/ @SuppressWarnings("unused") public NameValuePair call() throws Exception { InputStream ptestServerInputStream = null; try { // HttpResponse response = httpClient.execute(httpHost, getMethod); HttpResponse response = httpClient.execute(httpHost, postMethod); ptestServerInputStream = response.getEntity().getContent(); XPath xpath = XPathFactory.newInstance().newXPath(); Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(ptestServerInputStream); if (response == null) throw new TSClientExecutionException( "No response document received from " + httpHost.getHostName()); // fetch root node Node rootNode = responseDoc.getFirstChild(); if (rootNode == null) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); if (rootNode.getNodeName() == null || !rootNode.getNodeName().equalsIgnoreCase(TEST_EXEC_RESPONSE_ROOT)) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); int responseCode = parseResponseCode(rootNode, xpath); switch (responseCode) { case RESPONSE_CODE_EXECUTION_STARTED: { String responseIdentifier = parseResultIdentifier(rootNode, xpath); return new BasicNameValuePair(httpHost.getHostName(), responseIdentifier); } case RESPONSE_CODE_ERROR: { List<Long> errorCodes = parseErrorCodes(rootNode, xpath); StringBuffer codes = new StringBuffer(); for (Iterator<Long> iter = errorCodes.iterator(); iter.hasNext();) { codes.append(iter.next()); if (iter.hasNext()) codes.append(","); } throw new TSClientExecutionException("Failed to execute test plan on " + httpHost.getHostName() + ":" + httpHost.getPort() + ". Error codes: " + codes.toString()); } default: { throw new TSClientExecutionException("Unexpected response code '" + responseCode + "' received from " + httpHost.getHostName() + ":" + httpHost.getPort()); } } } catch (ClientProtocolException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + postMethod.getURI() + ". Error: " + e.getMessage()); } catch (IOException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + postMethod.getURI() + ". Error: " + e.getMessage()); } finally { if (ptestServerInputStream != null) { try { ptestServerInputStream.close(); httpClient.getConnectionManager().shutdown(); } catch (Exception e) { System.out.println("Failed to close ptest-server connection"); } } } }
From source file:cz.strmik.cmmitool.cmmi.DefaultRatingScalesProvider.java
private List<RatingScale> readScales(String id, String lang) { List<RatingScale> scales = new ArrayList<RatingScale>(); try {//from ww w . j a v a2 s . c o m Document document = getScalesDocument(); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); SimpleNamespaceContext ns = new SimpleNamespaceContext(); ns.bindNamespaceUri("s", SCALES_XML_NS); xPath.setNamespaceContext(ns); XPathExpression exprScales = xPath.compile("/s:ratings/s:rating[@id='" + id + "']/s:scale"); XPathExpression exprName = xPath.compile("s:name[@lang='" + lang + "']"); XPathExpression exprColor = xPath.compile("s:color[@type='html']"); NodeList nodes = (NodeList) exprScales.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); int score = Integer.parseInt(node.getAttributes().getNamedItem("score").getTextContent()); String name = exprName.evaluate(node); String color = exprColor.evaluate(node); RatingScale rs = new RatingScale(name, i, score, color); if (i == 0) { rs.setDefaultRating(true); } scales.add(rs); } } catch (Exception ex) { _log.warn( "Unable to load default scales for id=" + id + ",lang=" + lang + " ratings from " + SCALES_XML, ex); } return scales; }
From source file:net.bulletin.pdi.xero.step.support.XMLChunkerTest.java
/** * <p>This test is checking to see that, without any container elements, the chunking will produce one * document and that single document should be the whole of the input.</p> *//* w ww . j a v a 2 s .c om*/ @Test public void testPullNextXmlChunk_withoutContainerElements() throws Exception { byte[] sampleXml = readSampleXml(); XMLChunker chunker = new XMLChunkerImpl( XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(sampleXml)), // all in-memory new Stack<String>()); // --------------------------------- String actuals[] = new String[] { chunker.pullNextXmlChunk(), chunker.pullNextXmlChunk() }; // --------------------------------- // This will work through the chunks and check specific information it knows in the sample. { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XPath xPath = XPathFactory.newInstance().newXPath(); org.w3c.dom.Document doc = documentBuilder .parse(new ByteArrayInputStream(actuals[0].getBytes(CharEncoding.UTF_8))); NodeList artistNodeList = (NodeList) xPath.evaluate("/Response/Artists/Artist", doc, XPathConstants.NODESET); Assert.assertEquals(3, artistNodeList.getLength()); } Assert.assertNull("expected the last chunk to be null", actuals[1]); }
From source file:eu.scape_project.planning.evaluation.evaluators.XmlExtractor.java
public HashMap<String, String> extractValues(Document xml, String path) { try {// w w w .j a va 2s .c o m HashMap<String, String> resultMap = new HashMap<String, String>(); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); xpath.setNamespaceContext(namespaceContext); XPathExpression expr = xpath.compile(path); NodeList list = (NodeList) expr.evaluate(xml, XPathConstants.NODESET); if (list != null) { for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); String content = n.getTextContent(); if (content != null) { resultMap.put(n.getLocalName(), content); } } } return resultMap; } catch (Exception e) { log.error("Could not parse XML " + " searching for path " + path + ": " + e.getMessage(), e); return null; } }
From source file:cz.fi.muni.xkremser.editor.server.AuthenticationServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(true); String url = (String) session.getAttribute(HttpCookies.TARGET_URL); String root = (URLS.LOCALHOST() ? "http://" : "https://") + req.getServerName() + (URLS.LOCALHOST() ? (req.getServerPort() == 80 || req.getServerPort() == 443 ? "" : (":" + req.getServerPort())) : "") + URLS.ROOT() + (URLS.LOCALHOST() ? "?gwt.codesvr=127.0.0.1:9997" : ""); String authHeader = req.getHeader("Authorization"); if (authHeader != null) { String decodedHeader = decode(req, authHeader); String pass = configuration.getHttpBasicPass(); if (pass == null || "".equals(pass.trim()) || pass.length() < 4) { requrireAuthentication(resp); }/* w w w.ja v a 2s .c om*/ if (decodedHeader.equals(ALLOWED_PREFIX + pass)) { session.setAttribute(HttpCookies.TARGET_URL, null); session.setAttribute(HttpCookies.SESSION_ID_KEY, "https://www.google.com/profiles/109255519115168093543"); session.setAttribute(HttpCookies.NAME_KEY, "admin"); session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES); ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User " + decodedHeader.substring(0, decodedHeader.indexOf(":")) + " with openID BASIC_AUTH and IP " + req.getRemoteAddr()); URLS.redirect(resp, url == null ? root : url); return; } else { requrireAuthentication(resp); return; } } session.setAttribute(HttpCookies.TARGET_URL, null); String token = req.getParameter("token"); String appID = configuration.getOpenIDApiKey(); String openIdurl = configuration.getOpenIDApiURL(); RPX rpx = new RPX(appID, openIdurl); Element e = null; try { e = rpx.authInfo(token); } catch (ConnectionException connEx) { requrireAuthentication(resp); return; } String idXPath = "//identifier"; String nameXPath = "//displayName"; XPathFactory xpfactory = XPathFactory.newInstance(); XPath xpath = xpfactory.newXPath(); String identifier = null; String name = null; try { XPathExpression expr1 = xpath.compile(idXPath); XPathExpression expr2 = xpath.compile(nameXPath); NodeList nodes1 = (NodeList) expr1.evaluate(e.getOwnerDocument(), XPathConstants.NODESET); NodeList nodes2 = (NodeList) expr2.evaluate(e.getOwnerDocument(), XPathConstants.NODESET); Element el = null; if (nodes1.getLength() != 0) { el = (Element) nodes1.item(0); } if (el != null) { identifier = el.getTextContent(); } if (nodes2.getLength() != 0) { el = (Element) nodes2.item(0); } if (el != null) { name = el.getTextContent(); } } catch (XPathExpressionException e1) { e1.printStackTrace(); } if (identifier != null && !"".equals(identifier)) { ACCESS_LOGGER.info("LOG IN: [" + FORMATTER.format(new Date()) + "] User " + name + " with openID " + identifier + " and IP " + req.getRemoteAddr()); int userStatus = UserDAO.UNKNOWN; try { userStatus = userDAO.isSupported(identifier); } catch (DatabaseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } switch (userStatus) { case UserDAO.UNKNOWN: // TODO handle DB error (inform user) break; case UserDAO.USER: // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY, // identifier); session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier); session.setAttribute(HttpCookies.NAME_KEY, name); URLS.redirect(resp, url == null ? root : url); break; case UserDAO.ADMIN: // HttpCookies.setCookie(req, resp, HttpCookies.SESSION_ID_KEY, // identifier); // HttpCookies.setCookie(req, resp, HttpCookies.ADMIN, // HttpCookies.ADMIN_YES); session.setAttribute(HttpCookies.SESSION_ID_KEY, identifier); session.setAttribute(HttpCookies.NAME_KEY, name); session.setAttribute(HttpCookies.ADMIN, HttpCookies.ADMIN_YES); URLS.redirect(resp, url == null ? root : url); break; case UserDAO.NOT_PRESENT: default: session.setAttribute(HttpCookies.UNKNOWN_ID_KEY, identifier); session.setAttribute(HttpCookies.NAME_KEY, name); URLS.redirect(resp, root + URLS.INFO_PAGE); break; } } else { URLS.redirect(resp, root + (URLS.LOCALHOST() ? URLS.LOGIN_LOCAL_PAGE : URLS.LOGIN_PAGE)); } // System.out.println("ID:" + identifier); // if user is supported redirect to homepage else show him a page that he // has to be added to system first by admin }
From source file:de.ingrid.iplug.opensearch.converter.IngridRSSConverter.java
private void setPartnerAndProvider(IngridHitDetail hitDetail, Node item) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); Node node = (Node) xpath.evaluate("provider", item, XPathConstants.NODE); if (node != null) { hitDetail.put("provider", new String[] { node.getTextContent() }); }/*from w ww . java 2 s . c o m*/ node = (Node) xpath.evaluate("partner", item, XPathConstants.NODE); if (node != null) { hitDetail.put("partner", new String[] { node.getTextContent() }); } }
From source file:org.openhim.mediator.orchestration.RepositoryActor.java
private void readSOAPHeader() throws ParserConfigurationException, IOException, SAXException, XPathExpressionException { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(messageBuffer)); XPath xpath = XPathFactory.newInstance().newXPath(); action = xpath.compile("//Envelope/Header/Action").evaluate(doc); messageID = xpath.compile("//Envelope/Header/MessageID").evaluate(doc); }
From source file:org.ala.harvester.PpmlHarvester.java
private int getCount(Document currentResDom, String xpathToCount) throws Exception { int resultNum = 0; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); resultNum = Integer.valueOf((String) xpath.evaluate(xpathToCount, currentResDom, XPathConstants.STRING)); return resultNum; }
From source file:gov.nih.nci.lmp.mimGpml.CommonHelper.java
/** * Gets the MIM-Vis XML object by ID.//from w w w . ja v a 2 s . c o m * * TODO: It does not appear possible to use the Saxon engine to process * XPath queries within Pathvisio; the plugin fails to load. The approach * taken instead relies on JDOM/Jaxen to process XPath. * * @param doc * the doc * @param elemId * the element id * @return the vis xml object by id */ public static XmlObject getVisXmlObjectById(DiagramDocument doc, String elemId) { // TODO: Account for bioId // String queryExpression = // "/mimVis:Diagram/mimVis:InteractionGlyph[@visId='" + elemId + "']"; String queryExpression = "//*[@visId='" + elemId + "']"; Logger.log.debug("elemId:" + elemId); Logger.log.debug("queryExpression:" + queryExpression); try { org.w3c.dom.Document wDoc = (org.w3c.dom.Document) doc.getDomNode(); javax.xml.xpath.XPathFactory factory = XPathFactory.newInstance(); javax.xml.xpath.XPath wXpath = factory.newXPath(); javax.xml.xpath.XPathExpression expr = wXpath.compile(queryExpression); Object result = expr.evaluate(wDoc, javax.xml.xpath.XPathConstants.NODESET); org.w3c.dom.NodeList nodes = (org.w3c.dom.NodeList) result; Logger.log.debug("NodeList size: " + nodes.getLength()); /** * If the size is not one, then there is a duplicate key issue that * needs to be dealt with. Treat it as an error and return null. */ if (nodes.getLength() == 1) { XmlObject xmlObj = XmlObject.Factory.parse(nodes.item(0)); Logger.log.debug("glyph.xmlText: " + xmlObj.xmlText(getXmlOptions())); // Logger.log.debug("doc.xmlText: " + // doc.xmlText(getXmlOptions())); String elemStr = xmlObj.xmlText(getXmlOptions()); Logger.log.debug("getVisXmlObjectById XML String:" + elemStr); /** * Sample of the way an XML fragment is represented with * <xml-fragment> tags. This necessitates a modification from * the nodes returned by selectNodes. * * <xml-fragment mimVis:visId="ca53d" mimVis:displayName="CAMK" * centerX="166.0" centerY="167.0" mimVis:width="80.0" * mimVis:height="20.0" * xmlns:mimVis="http://lmp.nci.nih.gov/mim/mimVisLevel1"> * <mimVis:mimBioRef>b9044</mimVis:mimBioRef></xml-fragment> */ // Pattern/matcher Pattern mimStartElemTag = Pattern.compile("mimVis:[A-Z][A-Za-z]+"); Matcher matcherStart = mimStartElemTag.matcher(elemStr); // System.out.println("matcherStart count: " // + matcherStart.groupCount()); String match = null; // Find all matches while (matcherStart.find()) { // Get the matching string match = matcherStart.group(); // System.out.println("matcherStart.group(): " // + matcherStart.group()); } final int prefixLength = "mimVis:".length(); // String localPart = xmlFrag + "Type"; String localPart = match.substring(prefixLength) + "Type"; // Match: mimVis:SimplePhysicalEntityGlyph // SPE URI QName: http://lmp.nci.nih.gov/mim/mimVisLevel1 // SPE Local QName: SimplePhysicalEntityGlyphType QName objQName = new QName(MIM_VIS_NS, localPart); SchemaTypeLoader schemaTypeLoader = XmlBeans.getContextTypeLoader(); SchemaType objType = schemaTypeLoader.findType(objQName); XmlOptions opts = new XmlOptions(); opts.setLoadReplaceDocumentElement(null); /** * Taken from the XMLBeans autogenerated code of a XSD complex * type. For parsing a XML fragment given the SchemaType. */ xmlObj = XmlBeans.getContextTypeLoader().parse(elemStr, objType, opts); return xmlObj; } else { Logger.log.info("ERROR: Most likely a duplicate ID."); } } catch (XmlException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return null; }