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.jasig.springframework.security.portlet.authentication.PortletXmlMappableAttributesRetriever.java
/** * Loads the portlet.xml file using the configured <tt>ResourceLoader</tt> and * parses the role-name elements from it, using these as the set of <tt>mappableAttributes</tt>. *///from ww w.j a v a 2s .c om public void afterPropertiesSet() throws Exception { Resource portletXml = resourceLoader.getResource("/WEB-INF/portlet.xml"); Document doc = getDocument(portletXml.getInputStream()); final XPathExpression roleNamesExpression; if (portletConfig == null) { final XPathFactory xPathFactory = XPathFactory.newInstance(); final XPath xPath = xPathFactory.newXPath(); roleNamesExpression = xPath.compile("/portlet-app/portlet/security-role-ref/role-name"); } else { final XPathFactory xPathFactory = XPathFactory.newInstance(); xPathFactory.setXPathVariableResolver(new XPathVariableResolver() { @Override public Object resolveVariable(QName variableName) { if ("portletName".equals(variableName.getLocalPart())) { return portletConfig.getPortletName(); } return null; } }); final XPath xPath = xPathFactory.newXPath(); roleNamesExpression = xPath .compile("/portlet-app/portlet[portlet-name=$portletName]/security-role-ref/role-name"); } final NodeList securityRoles = (NodeList) roleNamesExpression.evaluate(doc, XPathConstants.NODESET); final Set<String> roleNames = new HashSet<String>(); for (int i = 0; i < securityRoles.getLength(); i++) { Element secRoleElt = (Element) securityRoles.item(i); String roleName = secRoleElt.getTextContent().trim(); roleNames.add(roleName); logger.info("Retrieved role-name '" + roleName + "' from portlet.xml"); } if (roleNames.isEmpty()) { logger.info("No security-role-ref elements found in " + portletXml + (portletConfig == null ? "" : " for portlet " + portletConfig.getPortletName())); } mappableAttributes = Collections.unmodifiableSet(roleNames); }
From source file:dk.statsbiblioteket.doms.iprolemapper.webservice.IPRangesConfigReader.java
/** * This method produces an <code>IPRangeRoles</code> instance from the * information stored in the <code>Node</code> specified by * <code>ipRangeNode</code>. * //from w w w . j a v a2 s.com * @param ipRangeNode * a <code>Document Node</code> containing information about an * IP range and its associated roles. * @return an <code>IPRangeRoles</code> instance created from the * information contained in <code>ipRangeNode</code>. * @throws XPathExpressionException * if any errors are encountered while reading range roles from * <code>ipRangeNode</code>. * @throws UnknownHostException * if the begin or end address of <code>ipRangeNode</code> is * either an unknown host name or an illegal IP address. * @throws IllegalArgumentException * if the begin address and end address of the range is not of * the same type. I.e. if they are not both IPv4 or IPv6 * addresses, or if <code>beginAddress</code> is higher/after * <code>endAddress</code>. */ private IPRangeRoles produceIPRangeInstance(Node ipRangeNode) throws XPathExpressionException, IllegalArgumentException, UnknownHostException { if (log.isTraceEnabled()) { String ipRangeNodeXMLString = "Malformed XML"; try { ipRangeNodeXMLString = DOM.domToString(ipRangeNode); } catch (TransformerException transformerException) { // Just ignore for now and log. The code will break later... } log.trace("produceIPRangeInstance(): Called with XML node: " + ipRangeNodeXMLString); } final NamedNodeMap attributes = ipRangeNode.getAttributes(); final String beginAddress = attributes.getNamedItem("begin").getNodeValue(); final String endAddress = attributes.getNamedItem("end").getNodeValue(); final XPathFactory xPathFactory = XPathFactory.newInstance(); final XPath xPath = xPathFactory.newXPath(); final NodeList ipRangeRoleNodes = (NodeList) xPath.evaluate("role", ipRangeNode, XPathConstants.NODESET); final List<String> ipRangeRoles = new LinkedList<String>(); for (int nodeIdx = 0; nodeIdx < ipRangeRoleNodes.getLength(); nodeIdx++) { ipRangeRoles.add(ipRangeRoleNodes.item(nodeIdx).getTextContent().trim()); } final IPRangeRoles rangeRoles = new IPRangeRoles(InetAddress.getByName(beginAddress), InetAddress.getByName(endAddress), ipRangeRoles); if (log.isTraceEnabled()) { log.trace("produceIPRangeInstance(): Returning IPRangeRoles " + "instance: " + rangeRoles); } return rangeRoles; }
From source file:com.codspire.mojo.artifactlookup.ProcessResponse.java
/** * //ww w . j ava 2s.c om * @param document * @param xPathfactory * @param targetXpath * @return */ private String getXpathValue(Document document, XPathFactory xPathfactory, String targetXpath) { XPath xpath = xPathfactory.newXPath(); String xpathValue = null; try { xpathValue = xpath.compile(targetXpath).evaluate(document, XPathConstants.STRING).toString(); } catch (XPathExpressionException e) { log.error(e); } return xpathValue; }
From source file:it.acubelab.batframework.systemPlugins.AIDAAnnotator.java
private String getConfigValue(String setting, String name, Document doc) throws XPathExpressionException { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression userExpr = xpath .compile("aida/setting[@name=\"" + setting + "\"]/param[@name=\"" + name + "\"]/@value"); return userExpr.evaluate(doc); }
From source file:eu.scape_project.resource.planmanagement.Plans.java
private PlanData createDeploymentPlanData(InputStream src) throws IOException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder;/*from w ww . ja v a 2 s.c o m*/ PlanData.Builder data = new PlanData.Builder(); try { builder = factory.newDocumentBuilder(); Document doc = builder.parse(src); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); data.title(xpath.compile("/plans/plan/properties/@name").evaluate(doc)); data.description(xpath.compile("/plans/plan/properties/description").evaluate(doc)); data.lifecycleState(new PlanLifecycleState( eu.scape_project.model.plan.PlanLifecycleState.PlanState.ENABLED, "Initial deployment")); return data.build(); } catch (ParserConfigurationException | SAXException | XPathExpressionException e) { throw new IOException(e); } }
From source file:com.webwoz.wizard.server.components.MTinMicrosoft.java
public String translate(String inputText, String srcLang, String trgLang) { // initialize connection // adapt proxies and settings to fit your server environment initializeConnection("www-proxy.cs.tcd.ie", 8080); String translation = null;/*w w w . j a v a 2 s .c om*/ String query = inputText; String MICROSOFT_TRANSLATION_BASE_URL = "http://api.microsofttranslator.com/V2/Http.svc/Translate?"; String appID = "226846CE16BC2542B7916B05CE9284CF4075B843"; try { // encode text query = URLEncoder.encode(query, "UTF-8"); // exchange + for space query = query.replace("+", "%20"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } String requestURL = MICROSOFT_TRANSLATION_BASE_URL + "appid=" + appID + "&from=" + srcLang + "&to=" + trgLang + "&text=" + query; HttpGet getRequest = new HttpGet(requestURL); try { HttpResponse response = httpClient.execute(getRequest); HttpEntity responseEntity = response.getEntity(); InputStream inputStream = responseEntity.getContent(); Document myDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); translation = (String) xPath.evaluate("/string", myDocument, XPathConstants.STRING); inputStream.close(); translation = translation.trim(); // if the original string did not have a dot at the end, then // remove the dot that Microsoft Translator sometimes places at the // end!! (not so sure it still happens anyway!) if (!inputText.endsWith(".") && (translation.endsWith("."))) { translation = translation.substring(0, translation.length() - 1); } setUttText(translation); } catch (Exception ex) { ex.printStackTrace(); translation = ex.toString(); } shutDownConnection(); return translation; }
From source file:org.fedoracommons.funapi.pmh.AbstractPmhResolver.java
private XPath getXPath() { XPathFactory xpFactory = XPathFactory.newInstance(); XPath xpath = xpFactory.newXPath(); if (nsCtx == null) { nsCtx = new NamespaceContextImpl(); nsCtx.addNamespace("oai", "http://www.openarchives.org/OAI/2.0/"); nsCtx.addNamespace("oai_dc", "http://www.openarchives.org/OAI/2.0/oai_dc/"); nsCtx.addNamespace("dc", "http://purl.org/dc/elements/1.1/"); }//from w w w . j a v a2s . c o m xpath.setNamespaceContext(nsCtx); return xpath; }
From source file:edu.sabanciuniv.sentilab.sare.controllers.aspect.AspectLexiconFactory.java
protected AspectLexiconFactory addXmlAspect(AspectLexicon lexicon, Node aspectNode) throws XPathExpressionException { Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon"); Validate.notNull(aspectNode, CannedMessages.NULL_ARGUMENT, "node"); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); // if the node is called "lexicon" then we're at the root, so we won't need to add an aspect and its expressions. AspectLexicon aspect = lexicon;/*from w w w . jav a 2s . c o m*/ if (!"aspect-lexicon".equalsIgnoreCase(aspectNode.getLocalName())) { String title = Validate.notEmpty( (String) xpath.compile("./@title").evaluate(aspectNode, XPathConstants.STRING), CannedMessages.EMPTY_ARGUMENT, "./aspect/@title"); ; // fetch or create aspect. aspect = lexicon.findAspect(title); if (aspect == null) { aspect = lexicon.addAspect(title); } // get all expressions or keywords, whatever they're called. NodeList expressionNodes = (NodeList) xpath.compile("./expressions/expression").evaluate(aspectNode, XPathConstants.NODESET); if (expressionNodes == null || expressionNodes.getLength() == 0) { expressionNodes = (NodeList) xpath.compile("./keywords/keyword").evaluate(aspectNode, XPathConstants.NODESET); } // add each of them if they don't exist. if (expressionNodes != null) { for (int index = 0; index < expressionNodes.getLength(); index++) { String expression = expressionNodes.item(index).getTextContent().trim(); if (!aspect.hasExpression(expression)) { aspect.addExpression(expression); } } } } // get all sub-aspects and add them recursively. NodeList subAspectNodes = (NodeList) xpath.compile("./aspects/aspect").evaluate(aspectNode, XPathConstants.NODESET); if (subAspectNodes != null) { for (int index = 0; index < subAspectNodes.getLength(); index++) { this.addXmlAspect(aspect, subAspectNodes.item(index)); } } return this; }
From source file:it.jnrpe.plugin.tomcat.TomcatDataProvider.java
private void parseConnectorsThreadData() 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(); NodeList connectorsNodeList = (NodeList) xpath.compile("//status/connector") .evaluate(doc.getDocumentElement(), XPathConstants.NODESET); for (int i = 0; i < connectorsNodeList.getLength(); i++) { Node connector = connectorsNodeList.item(i); NodeList connectorChildren = connector.getChildNodes(); final String connectorName = connector.getAttributes().getNamedItem("name").getNodeValue(); for (int j = 0; j < connectorChildren.getLength(); j++) { Node node = connectorChildren.item(j); if (node.getNodeName().equalsIgnoreCase("threadInfo")) { NamedNodeMap atts = node.getAttributes(); long maxThreads = Long.parseLong(atts.getNamedItem("maxThreads").getNodeValue()); long currentThreadsBusy = Long .parseLong(atts.getNamedItem("currentThreadsBusy").getNodeValue()); long currentThreadCount = Long .parseLong(atts.getNamedItem("currentThreadCount").getNodeValue()); connectorThreadData.put(connectorName, new ThreadData(connectorName, currentThreadCount, currentThreadsBusy, maxThreads)); }/*from w w w. java 2 s . c o m*/ } } }
From source file:com.persistent.cloudninja.service.impl.RunningInstancesJSONDataServiceImpl.java
/** * Parse the response from deployment monitoring and get role name, instance name and instance status. * @param response The XML response of deployment monitoring task. * @return List of InstanceHealthRoleInstanceEntity * @throws ParserConfigurationException/*w ww. j a va2 s.co m*/ * @throws SAXException * @throws IOException * @throws XPathExpressionException */ private List<InstanceHealthRoleInstanceEntity> parseResponse(StringBuffer response) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilder documentBuilder = null; Document document = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setIgnoringElementContentWhitespace(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.parse(new InputSource(new StringReader(response.toString()))); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); NodeList roleNameList = (NodeList) xPath.evaluate("/Deployment/RoleInstanceList/RoleInstance/RoleName", document, XPathConstants.NODESET); NodeList instanceNameList = (NodeList) xPath.evaluate( "/Deployment/RoleInstanceList/RoleInstance/InstanceName", document, XPathConstants.NODESET); NodeList instanceStatusList = (NodeList) xPath.evaluate( "/Deployment/RoleInstanceList/RoleInstance/InstanceStatus", document, XPathConstants.NODESET); List<InstanceHealthRoleInstanceEntity> list = new ArrayList<InstanceHealthRoleInstanceEntity>(); for (int index = 0; index < roleNameList.getLength(); index++) { Element roleElement = (Element) roleNameList.item(index); Element instanceElement = (Element) instanceNameList.item(index); Element statusElement = (Element) instanceStatusList.item(index); InstanceHealthRoleInstanceEntity roleInstanceEntity = new InstanceHealthRoleInstanceEntity(); roleInstanceEntity.setRoleName(roleElement.getTextContent()); roleInstanceEntity.setInstanceName(instanceElement.getTextContent()); roleInstanceEntity.setInstanceStatus(statusElement.getTextContent()); list.add(roleInstanceEntity); } return list; }