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.rippleosi.patient.contacts.search.SCCISContactSummaryTransformer.java
@Override public List<ContactSummary> transform(Node xml) { XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); List<ContactSummary> contactList = new ArrayList<ContactSummary>(); try {/*from ww w .j av a 2 s. com*/ xml.normalize(); // Retrieve contacts from Carers section of XML NodeList nodeSet = (NodeList) xpath.evaluate("/LCR/Carers/List/RelatedPerson", xml, XPathConstants.NODESET); for (int i = 0; i < nodeSet.getLength(); i++) { ContactSummary contact = new ContactSummary(); contact.setSource("SC-CIS"); Node node = nodeSet.item(i); String sourceId = (String) xpath.evaluate("identifier/value/@value", node, XPathConstants.STRING); String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING); String relationshipTeam = (String) xpath.evaluate("relationship/coding/display/@value", node, XPathConstants.STRING); contact.setSourceId(sourceId); contact.setName(name); contact.setRelationship(relationshipTeam); contactList.add(contact); } // Retrieve contacts from Allocations section of the XML nodeSet = (NodeList) xpath.evaluate("/LCR/Allocations/List/Practitioner", xml, XPathConstants.NODESET); for (int i = 0; i < nodeSet.getLength(); i++) { ContactSummary contact = new ContactSummary(); contact.setSource("SC-CIS"); Node node = nodeSet.item(i); String sourceId = (String) xpath.evaluate("identifier/value/@value", node, XPathConstants.STRING); String name = (String) xpath.evaluate("name/text/@value", node, XPathConstants.STRING); String relationshipTeam = (String) xpath.evaluate("practitionerRole/role/coding/display/@value", node, XPathConstants.STRING); contact.setSourceId(sourceId); contact.setName(name); contact.setRelationship(relationshipTeam); contactList.add(contact); } } catch (XPathExpressionException e) { e.printStackTrace(); } return contactList; }
From source file:org.roda.core.common.XMLUtility.java
/** * 20160518 hsilva: the inputStream gets closed in the end *//* ww w.j av a 2s .c o m*/ public static String getString(InputStream inputStream, String xpath) { String ret = ""; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new RodaEntityResolver()); Document doc; doc = builder.parse(inputStream); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xPath = xPathfactory.newXPath(); XPathExpression expr = xPath.compile(xpath); ret = (String) expr.evaluate(doc, XPathConstants.STRING); } catch (SAXException | ParserConfigurationException | XPathExpressionException | IOException e) { // do nothing and return already defined OTHER } finally { IOUtils.closeQuietly(inputStream); } return ret; }
From source file:org.roda_project.commons_ip.model.impl.hungarian.HungarianMETSUtils.java
public static void addAggregationDescriptiveMetadataToMETS(MetsWrapper metsWrapper, IPDescriptiveMetadata metadata) throws IPException, InterruptedException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); MdSecType dmdSec = metsWrapper.getMainDmdSec(); MdWrap mdWrap = dmdSec.getMdWrap();/* w w w . j a v a 2 s. c o m*/ mdWrap.setID(metadata.getId()); mdWrap.setMDTYPE(metadata.getMetadataType().getType().getType()); mdWrap.setMDTYPEVERSION(metadata.getMetadataVersion()); String mdOtherType = metadata.getMetadataType().getOtherType(); if (StringUtils.isNotBlank(mdOtherType)) { mdWrap.setOTHERMDTYPE(mdOtherType); } try (InputStream inputStream = Files.newInputStream(metadata.getMetadata().getPath())) { Document xmlDataContent = factory.newDocumentBuilder().parse(inputStream); try { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression levelExpression = xpath.compile("//archdesc/@level"); String level = (String) levelExpression.evaluate(xmlDataContent, XPathConstants.STRING); if (IPConstants.METS_LEVEL_OTHER.equalsIgnoreCase(level)) { XPathExpression otherExpression = xpath.compile("//archdesc/@otherlevel"); level = (String) otherExpression.evaluate(xmlDataContent, XPathConstants.STRING); } metsWrapper.getMainDiv().setTYPE(level); } catch (XPathExpressionException e) { LOGGER.error("Error getting archdesc level or otherlevel", e); } XmlData metadataContent = new XmlData(); metadataContent.getAny().add(xmlDataContent.getDocumentElement()); mdWrap.setXmlData(metadataContent); } catch (SAXException | ParserConfigurationException | IOException e) { LOGGER.error("Error adding EAD xml to xmlData", e); } }
From source file:org.sakaiproject.kernel.component.model.test.PersistenceUnitClassLoaderTest.java
/** * Check that the persistence.xml returned from the merging classloader has * some expected elements from non-kernel persistence.xml files. * /*w w w . j ava2s . c o m*/ * @throws Exception */ @Test public void verifyMergedPersistence() throws Exception { Enumeration<URL> urlEnum = pucl.getResources(PersistenceUnitClassLoader.PERSISTENCE_XML); assertTrue(urlEnum.hasMoreElements()); URL url = urlEnum.nextElement(); LOG.info("persistence.xml location: " + url); // printFile(url); final XPathFactory XPATH_FACTORY = XPathFactory.newInstance(); final XPath XPATH = XPATH_FACTORY.newXPath(); final XPathExpression XPATH_CLASS_TEXT = XPATH.compile("//persistence/persistence-unit/class/text()"); final Document doc = builder.parse(url.toExternalForm()); NodeList nodes = (NodeList) XPATH_CLASS_TEXT.evaluate(doc, XPathConstants.NODESET); // this should be 2 but will need to change if class nodes are added // persistence.xml of kernel assertTrue(nodes.getLength() > 2); final XPathExpression XPATH_MAPPING_TEXT = XPATH .compile("//persistence/persistence-unit/mapping-file/text()"); nodes = (NodeList) XPATH_MAPPING_TEXT.evaluate(doc, XPathConstants.NODESET); // this should be 4 but will need to change if mapping-file nodes are added // persistence.xml of kernel assertEquals(4, nodes.getLength()); }
From source file:org.sakaiproject.kernel.component.model.test.PersistenceUnitClassLoaderTest.java
/** * Check that the orm.xml returned from the merging classloader has some * expected elements from non-kernel orm.xml files. * /*from w w w . j a v a 2 s .com*/ * @throws Exception */ @Test public void verifyMergedOrm() throws Exception { Enumeration<URL> urlEnum = pucl.getResources(PersistenceUnitClassLoader.ORM_XML); assertTrue(urlEnum.hasMoreElements()); URL url = urlEnum.nextElement(); LOG.info("orm.xml location: " + url); // printFile(url); final XPathFactory XPATH_FACTORY = XPathFactory.newInstance(); final XPath XPATH = XPATH_FACTORY.newXPath(); final XPathExpression XPATH_ENTITY = XPATH.compile("//entity-mappings/entity"); final Document doc = builder.parse(url.toExternalForm()); NodeList nodes = (NodeList) XPATH_ENTITY.evaluate(doc, XPathConstants.NODESET); // this should be 9 but will need to change if any entities are added to the // orm.xml files used in this test. assertTrue(nodes.getLength() > 1); }
From source file:org.sakaiproject.mediasite.tool.MediasiteLTI.java
public String runMainJspPage(String LaunchEndpoint) { String message = "Mediasite content is loading..."; String sakaiHome = System.getProperty("sakai.home"); String catalinaBase = System.getenv("CATALINA_BASE"); String catalinaHome = System.getenv("CATALINA_HOME"); String appPath = ""; if (sakaiHome != null && sakaiHome != "") { appPath = sakaiHome;/*from www .jav a2s . c o m*/ } else if (catalinaBase != null && catalinaBase != "") { appPath = catalinaBase + File.separator + "sakai"; } else { appPath = catalinaHome + File.separator + "sakai"; } String XmlPath = File.separator + "portlets" + File.separator + "imsblti" + File.separator + "IMSBLTIPortlet.xml"; String newpage = ""; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; Document doc = null; try { newpage = ServerConfigurationService.getString("mediasite.NewPageOverride"); } catch (Exception e) { newpage = ""; } String secret = "error"; String key = "error"; String launch = null; try { builder = dbf.newDocumentBuilder(); doc = builder.parse(appPath + XmlPath); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); secret = getConfigValue(doc, xpath, "com.sonicfoundry.mediasite.lti", "imsti.secret"); key = getConfigValue(doc, xpath, "com.sonicfoundry.mediasite.lti", "imsti.key"); launch = getConfigValue(doc, xpath, "com.sonicfoundry.mediasite.lti", "imsti.launch"); } catch (Exception e) { message += "<BR />Sakai cannot process your IMSBLTIPortlet.xml configuration file correctly. <BR />Using sakai.home: " + sakaiHome + "<BR />Using CATALINA_BASE: " + catalinaBase + "<BR />Using CATALINA_HOME: " + catalinaHome + "<br />" + e; } launch = launch + LaunchEndpoint; String userId = null; String siteTitle = null; String siteId = "012345"; userId = UserDirectoryService.getCurrentUser().getDisplayId(); if (userId == null || userId == "") { userId = "fake_user"; } if (siteTitle == null) siteTitle = "Non-Course Page"; String org_id = "mediasite"; String role = "Learner"; if (securityService != null && securityService.isSuperUser()) { role = "Instructor,Administrator,urn:lti:instrole:ims/lis/Administrator,urn:lti:sysrole:ims/lis/Administrator"; } else if (siteService != null && siteService.allowUpdateSite(siteId)) { role = "Instructor"; } // launch the LTI if (launch == null) { System.out.println("Node not configured as an LTI Launch - need ltiurl property"); message += "<br/>Node not configured as an LTI Launch - need ltiurl property: " + key + " appPath " + appPath; } else { Properties postProp = new Properties(); postProp.setProperty("lti_version", "LTI-1p0"); postProp.setProperty("lti_message_type", "basic-lti-launch-request"); postProp.setProperty("ext_content_intended_use", "embed"); postProp.setProperty("ext_content_return_types", "sakai"); if (newpage != null) { postProp.setProperty("custom_mediasite_newpageoverride", newpage); } postProp.setProperty("launch_presentation_return_url", ""); postProp.setProperty("tool_consumer_instance_guid", org_id); postProp.setProperty("tool_consumer_instance_description", "sakai"); postProp.setProperty("tool_consumer_info_product_family_code", "sakai"); postProp.setProperty("user_id", userId); postProp.setProperty("resource_link_id", "Test_String"); postProp.setProperty("roles", role); postProp.setProperty("context_id", siteId); postProp.setProperty("context_title", siteTitle); postProp.setProperty("context_label", siteTitle); // Must even include the Submit button in the signed material postProp.setProperty("ext_basiclti_submit", "Continue"); // Just to make sure we give BasicLTI a chance to remove // properties it will refuse to send postProp = BasicLTIUtil.cleanupProperties(postProp); OAuthMessage oam = new OAuthMessage("POST", launch, postProp.entrySet()); OAuthConsumer cons = new OAuthConsumer(null, key, secret, null); OAuthAccessor acc = new OAuthAccessor(cons); System.out.println("OAM=" + oam + "\n"); try { System.out.println("BM=" + OAuthSignatureMethod.getBaseString(oam) + "\n"); } catch (Exception e) { System.out.println("Yikes"); } try { oam.addRequiredParameters(acc); System.out.println("BM2=" + OAuthSignatureMethod.getBaseString(oam) + "\n"); } catch (Exception e) { System.out.println("Yikes"); } System.out.println("OAM=" + oam + "\n"); List<Map.Entry<String, String>> params = null; // Get the signed parameters try { params = oam.getParameters(); } catch (IOException e) { message += "<br/>ERROR: " + e; } // Convert to Properties Properties nextProp = new Properties(); for (Map.Entry<String, String> e : params) { nextProp.setProperty(e.getKey(), e.getValue()); } String postData = BasicLTIUtil.postLaunchHTML(nextProp, launch, false); //System.out.println(postData); if (message.equals("Mediasite content is loading...")) { message = postData; } } return message; }
From source file:org.searsia.engine.Resource.java
private SearchResult xpathSearch(String url, String page, boolean debug) throws IOException, XPathExpressionException { Document document;/*from ww w . ja va 2s .co m*/ if (this.mimeType != null && this.mimeType.equals("application/json")) { document = parseDocumentJSON(page); } else if (this.mimeType != null && this.mimeType.equals("application/x-javascript")) { document = parseDocumentJavascript(page); } else if (this.mimeType != null && this.mimeType.equals("application/xml")) { document = parseDocumentXML(page); } else { document = parseDocumentHTML(page, url); } if (document == null) { throw new IOException("Error parsing document. Wrong mimetype?"); } SearchResult result = new SearchResult(); if (debug) { result.setXmlOut(DOMBuilder.DOM2String(document)); } XPathFactory xFactory = XPathFactory.newInstance(); XPath xpath = xFactory.newXPath(); NodeList xmlNodeList = (NodeList) xpath.evaluate(itemXpath, document, XPathConstants.NODESET); for (int i = 0; i < xmlNodeList.getLength() && i < 30; i++) { Node item = xmlNodeList.item(i); result.addHit(extractHit(item)); } return result; }
From source file:org.socraticgrid.xmlCommon.XpathHelper.java
public static Node performXpathQuery(String sourceXml, String xpathQuery, NamespaceContext namespaceContext) throws XPathExpressionException { javax.xml.xpath.XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance(); javax.xml.xpath.XPath xpath = factory.newXPath(); if (namespaceContext != null) { xpath.setNamespaceContext(namespaceContext); }/*from ww w . j a v a2s .c o m*/ InputSource inputSource = new InputSource(new ByteArrayInputStream(sourceXml.getBytes())); log.debug("perform xpath query (query='" + xpathQuery + "'"); Node result = null; if (XmlUtfHelper.isUtf16(sourceXml)) { try { result = (Node) xpath.evaluate(xpathQuery, inputSource, XPathConstants.NODE); } catch (Exception ex) { // Exception may be due to the encoding of the message being incorrect. // retry using UTF-8 log.warn("failed to perform xpath query - retrying with UTF-8"); sourceXml = XmlUtfHelper.convertToUtf8(sourceXml); result = performXpathQuery(sourceXml, xpathQuery, namespaceContext); } } else { result = (Node) xpath.evaluate(xpathQuery, inputSource, XPathConstants.NODE); } log.debug("xpath query complete [result?=" + result + "]"); return result; }
From source file:org.socraticgrid.xmlCommon.XpathHelper.java
public static Node performXpathQuery(Element sourceElement, String xpathQuery, NamespaceContext namespaceContext) throws XPathExpressionException { javax.xml.xpath.XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance(); javax.xml.xpath.XPath xpath = factory.newXPath(); if (namespaceContext != null) { xpath.setNamespaceContext(namespaceContext); }/*w w w . j a va2 s . c om*/ log.debug("About to perform xpath query (query='" + xpathQuery + "'"); Node result = (Node) xpath.evaluate(xpathQuery, sourceElement, XPathConstants.NODE); return result; }
From source file:org.sonar.api.utils.XpathParser.java
public void parse(String xml) { try {//from w w w . j a va 2 s .c o m xml = fixUnicodeChar(xml); doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); XPathFactory factory = XPathFactory.newInstance(); xpath = factory.newXPath(); } catch (SAXException e) { throw new XmlParserException("can not parse xml : " + xml, e); } catch (IOException e) { throw new XmlParserException("can not parse xml : " + xml, e); } }