javax.xml.xpath.XPathFactory Java Examples
The following examples show how to use
javax.xml.xpath.XPathFactory.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BeerXMLReader.java From SB_Elsinore_Server with MIT License | 6 votes |
public final ArrayList<String> getListOfRecipes() { ArrayList<String> nameList = new ArrayList<>(); XPath xp; try { xp = XPathFactory.newInstance().newXPath(); NodeList recipeList = (NodeList) xp.evaluate( "/RECIPES/RECIPE", recipeDocument, XPathConstants.NODESET); if (recipeList.getLength() == 0) { LaunchControl.setMessage("No Recipes found in file"); return null; } for (int i = 0; i < recipeList.getLength(); i++) { Node recipeNode = recipeList.item(i); String recipeName = (String) xp.evaluate("NAME/text()", recipeNode, XPathConstants.STRING); nameList.add(recipeName); } } catch (XPathException xpe) { BrewServer.LOG.warning("Couldn't run XPATH: " + xpe.getMessage()); return null; } return nameList; }
Example #2
Source File: Ciena5162DeviceDescription.java From onos with Apache License 2.0 | 6 votes |
@Override public DeviceDescription discoverDeviceDetails() { DeviceId deviceId = handler().data().deviceId(); NetconfController controller = checkNotNull(handler().get(NetconfController.class)); NetconfSession session = controller.getDevicesMap().get(handler().data().deviceId()).getSession(); try { Node systemInfo = TEMPLATE_MANAGER.doRequest(session, "systemInfo"); Node softwareVersion = TEMPLATE_MANAGER.doRequest(session, "softwareVersion"); XPath xp = XPathFactory.newInstance().newXPath(); String mac = xp.evaluate("components/component/properties/property/state/value/text()", systemInfo) .toUpperCase(); return new DefaultDeviceDescription(deviceId.uri(), Device.Type.SWITCH, xp.evaluate("components/component/state/mfg-name/text()", systemInfo), xp.evaluate("components/component/state/name/text()", systemInfo), xp.evaluate("software-state/running-package/package-version/text()", softwareVersion), xp.evaluate("components/component/state/serial-no/text()", systemInfo), new ChassisId(Long.valueOf(mac, 16))); } catch (XPathExpressionException | NetconfException ne) { log.error("failed to query system info from device {}", handler().data().deviceId(), ne); } return new DefaultDeviceDescription(deviceId.uri(), Device.Type.SWITCH, "Ciena", "5162", "Unknown", "Unknown", new ChassisId()); }
Example #3
Source File: IDLReader.java From cougar with Apache License 2.0 | 6 votes |
/** * Cycle through the target Node and remove any operations not defined in the extensions document. */ private void removeUndefinedOperations(Node target, Node extensions) throws Exception { final XPathFactory factory = XPathFactory.newInstance(); final NodeList nodes = (NodeList) factory.newXPath().evaluate("//operation", target, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { final Node targetNode = nodes.item(i); String nameBasedXpath = DomUtils.getNameBasedXPath(targetNode, true); log.debug("Checking operation: " + nameBasedXpath); final NodeList targetNodes = (NodeList) factory.newXPath().evaluate(nameBasedXpath, extensions, XPathConstants.NODESET); if (targetNodes.getLength() == 0) { // This operation is not defined in the extensions doc log.debug("Ignoring IDL defined operation: " + getAttribute(targetNode, "name")); targetNode.getParentNode().removeChild(targetNode); } } }
Example #4
Source File: Ciena5170DeviceDescription.java From onos with Apache License 2.0 | 6 votes |
@Override public DeviceDescription discoverDeviceDetails() { DeviceId deviceId = handler().data().deviceId(); NetconfController controller = checkNotNull(handler().get(NetconfController.class)); NetconfSession session = controller.getDevicesMap().get(handler().data().deviceId()).getSession(); try { Node systemInfo = TEMPLATE_MANAGER.doRequest(session, "systemInfo"); Node chassisMac = TEMPLATE_MANAGER.doRequest(session, "chassis-mac"); Node softwareVersion = TEMPLATE_MANAGER.doRequest(session, "softwareVersion"); XPath xp = XPathFactory.newInstance().newXPath(); String mac = xp.evaluate("lldp-global-operational/chassis-id/text()", chassisMac).toUpperCase(); return new DefaultDeviceDescription(deviceId.uri(), Device.Type.SWITCH, "Ciena", xp.evaluate("components/component/name/text()", systemInfo), xp.evaluate("software-state/running-package/package-version/text()", softwareVersion), mac, new ChassisId(Long.valueOf(mac, 16))); } catch (XPathExpressionException | NetconfException ne) { log.error("failed to query system info from device {} : {}", handler().data().deviceId(), ne.getMessage(), ne); } return new DefaultDeviceDescription(deviceId.uri(), Device.Type.SWITCH, "Ciena", "5170", "Unknown", "Unknown", new ChassisId()); }
Example #5
Source File: Tool.java From smartcheck with GNU General Public License v3.0 | 6 votes |
/** * * @param sourceLanguage source language * @return directory analysis * @throws Exception exception */ private DirectoryAnalysis makeDirectoryAnalysis( final SourceLanguage sourceLanguage ) throws Exception { return new DirectoryAnalysisDefault( this.source, p -> p.toString().endsWith(sourceLanguage.fileExtension()), new TreeFactoryDefault( DocumentBuilderFactory .newInstance() .newDocumentBuilder(), sourceLanguage ), new RulesCached( new RulesXml( this.rules.apply(sourceLanguage), XPathFactory.newInstance().newXPath(), Throwable::printStackTrace ) ) ); }
Example #6
Source File: VerifyTestSuite.java From teamengine with Apache License 2.0 | 6 votes |
@Test public void runNumParityTestSuite() throws Exception { this.kvpTestParam = "input=4"; URL ctlScript = getClass().getResource("/tebase/scripts/num-parity.ctl"); File ctlFile = new File(ctlScript.toURI()); this.setupOpts.addSource(ctlFile); QName startingTest = new QName(EX_NS, "num-parity-main", "ex"); this.runOpts.setTestName(startingTest.toString()); this.runOpts.addParam(this.kvpTestParam); File indexFile = new File(this.sessionDir, "index.xml"); Index mainIndex = Generator.generateXsl(this.setupOpts); mainIndex.persist(indexFile); File resourcesDir = new File(getClass().getResource("/").toURI()); TEClassLoader teLoader = new TEClassLoader(resourcesDir); Engine engine = new Engine(mainIndex, this.setupOpts.getSourcesName(), teLoader); TECore core = new TECore(engine, mainIndex, this.runOpts); core.execute(); Document testLog = docBuilder.parse(new File(this.sessionDir, "log.xml")); XPath xpath = XPathFactory.newInstance().newXPath(); String result = xpath.evaluate("/log/endtest/@result", testLog); assertEquals("Unexpected verdict.", VERDICT_PASS, Integer.parseInt(result)); }
Example #7
Source File: CrossGatewayRetrieveTest.java From openxds with Apache License 2.0 | 6 votes |
private NodeList getNodeCount(OMElement response, String type)throws ParserConfigurationException, IOException, SAXException, XPathExpressionException{ DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(false); // never forget this! DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(new StringInputStream(response.toString())); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = null; if (type.equalsIgnoreCase("ExtrinsicObject")) expr = xpath.compile("//AdhocQueryResponse/RegistryObjectList/ExtrinsicObject"); if (type.equalsIgnoreCase("ObjectRef")) expr = xpath.compile("//AdhocQueryResponse/RegistryObjectList/ObjectRef"); Object res = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) res; return nodes; }
Example #8
Source File: SubsystemParsingTestCase.java From keycloak with Apache License 2.0 | 6 votes |
private void buildSubsystemXml(final Element element, final String expression) throws IOException { if (element != null) { try { // locate the element and insert the node XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(this.document, XPathConstants.NODESET); nodeList.item(0).appendChild(element); // transform again to XML TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(this.document), new StreamResult(writer)); this.subsystemXml = writer.getBuffer().toString(); } catch(TransformerException | XPathExpressionException e) { throw new IOException(e); } } else { this.subsystemXml = this.subsystemTemplate; } }
Example #9
Source File: XmlFactory.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * Returns properly configured (e.g. security features) factory * - securityProcessing == is set based on security processing property, default is true */ public static XPathFactory createXPathFactory(boolean disableSecureProcessing) throws IllegalStateException { try { XPathFactory factory = XPathFactory.newInstance(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "XPathFactory instance: {0}", factory); } factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing)); return factory; } catch (XPathFactoryConfigurationException ex) { LOGGER.log(Level.SEVERE, null, ex); throw new IllegalStateException( ex); } catch (AbstractMethodError er) { LOGGER.log(Level.SEVERE, null, er); throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er); } }
Example #10
Source File: XmlSignature.java From cstc with GNU General Public License v3.0 | 6 votes |
protected void validateIdAttributes(Document doc) throws Exception { String idAttribute = new String(idIdentifier.getText()); if( idAttribute == null || idAttribute.isEmpty() ) { return; } XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("descendant-or-self::*/@" + idAttribute); NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); if(nodeList != null && nodeList.getLength() > 0) { for(int j = 0; j < nodeList.getLength(); j++) { Attr attr = (Attr)nodeList.item(j); ((Element)attr.getOwnerElement()).setIdAttributeNode(attr,true); } } }
Example #11
Source File: BaseOjbConfigurer.java From rice with Educational Community License v2.0 | 6 votes |
protected InputStream preprocessConnectionMetadata(InputStream inputStream) throws Exception { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(inputStream)); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList connectionDescriptors = (NodeList)xpath.evaluate("/descriptor-repository/jdbc-connection-descriptor", document, XPathConstants.NODESET); for (int index = 0; index < connectionDescriptors.getLength(); index++) { Element descriptor = (Element)connectionDescriptors.item(index); String currentPlatform = descriptor.getAttribute("platform"); if (StringUtils.isBlank(currentPlatform)) { String ojbPlatform = ConfigContext.getCurrentContextConfig().getProperty(Config.OJB_PLATFORM); if (StringUtils.isEmpty(ojbPlatform)) { throw new ConfigurationException("Could not configure OJB, the '" + Config.OJB_PLATFORM + "' configuration property was not set."); } LOG.info("Setting OJB connection descriptor database platform to '" + ojbPlatform + "'"); descriptor.setAttribute("platform", ojbPlatform); } } Transformer transformer = TransformerFactory.newInstance().newTransformer(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); transformer.transform(new DOMSource(document), new StreamResult(new BufferedOutputStream(baos))); return new BufferedInputStream(new ByteArrayInputStream(baos.toByteArray())); }
Example #12
Source File: WSDL11SOAPOperationExtractor.java From carbon-apimgt with Apache License 2.0 | 6 votes |
private Node findFirstElementByName(String name, Document doc) { XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); try { XPathExpression expr = xpath.compile("//*[@name='" + name + "']"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; if (nodes == null || nodes.getLength() < 1) { return null; } return nodes.item(0); } catch (XPathExpressionException e) { log.error("Error occurred while finding element " + name + "in given document", e); return null; } }
Example #13
Source File: ModuleBundle.java From wandora with GNU General Public License v3.0 | 6 votes |
@Override public Collection<Module> parseXMLConfigElement(Node doc, String source) { try{ ArrayList<Module> ret=new ArrayList<Module>(); XPath xpath=XPathFactory.newInstance().newXPath(); NodeList nl=(NodeList)xpath.evaluate("//bundleName",doc,XPathConstants.NODESET); if(nl.getLength()>0){ Element e2=(Element)nl.item(0); String s=e2.getTextContent().trim(); if(s.length()>0) setBundleName(s); } return super.parseXMLConfigElement(doc, source); }catch(Exception ex){ if(log!=null) log.error("Error reading options file", ex); return null; } }
Example #14
Source File: DictionaryParser.java From artio with Apache License 2.0 | 6 votes |
public DictionaryParser(final boolean allowDuplicates) { this.allowDuplicates = allowDuplicates; try { documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final XPath xPath = XPathFactory.newInstance().newXPath(); findField = xPath.compile(FIELD_EXPR); findMessage = xPath.compile(MESSAGE_EXPR); findComponent = xPath.compile(COMPONENT_EXPR); findHeader = xPath.compile(HEADER_EXPR); findTrailer = xPath.compile(TRAILER_EXPR); } catch (final ParserConfigurationException | XPathExpressionException ex) { throw new RuntimeException(ex); } }
Example #15
Source File: AndroidManifestPlainTextReader.java From android-classyshark with Apache License 2.0 | 6 votes |
public List<String> getServices() { List<String> list = new ArrayList<>(); try { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); XPathExpression expr = xpath.compile("/manifest/application/service"); NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node serviceNode = nodes.item(i); Node actionName = serviceNode.getAttributes().getNamedItem("name"); list.add(actionName.getTextContent()); } } catch (XPathExpressionException e) { e.printStackTrace(); } return list; }
Example #16
Source File: XPathCondition.java From development with Apache License 2.0 | 6 votes |
public boolean eval() throws BuildException { if (nullOrEmpty(fileName)) { throw new BuildException("No file set"); } File file = new File(fileName); if (!file.exists() || file.isDirectory()) { throw new BuildException( "The specified file does not exist or is a directory"); } if (nullOrEmpty(path)) { throw new BuildException("No XPath expression set"); } XPath xpath = XPathFactory.newInstance().newXPath(); InputSource inputSource = new InputSource(fileName); Boolean result = Boolean.FALSE; try { result = (Boolean) xpath.evaluate(path, inputSource, XPathConstants.BOOLEAN); } catch (XPathExpressionException e) { throw new BuildException("XPath expression fails", e); } return result.booleanValue(); }
Example #17
Source File: XMLUtils.java From teamengine with Apache License 2.0 | 6 votes |
/** * Get first node on a Document doc, give a xpath Expression * * @param doc * @param xPathExpression * @return a Node or null if not found */ public static Node getFirstNode(Document doc, String xPathExpression) { try { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr; expr = xpath.compile(xPathExpression); NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); return nl.item(0); } catch (XPathExpressionException e) { e.printStackTrace(); } return null; }
Example #18
Source File: JmsSubscription.java From cxf with Apache License 2.0 | 6 votes |
protected boolean doFilter(Element content) { if (contentFilter != null) { if (!contentFilter.getDialect().equals(XPATH1_URI)) { throw new IllegalStateException("Unsupported dialect: " + contentFilter.getDialect()); } try { XPathFactory xpfactory = XPathFactory.newInstance(); try { xpfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); } catch (Throwable t) { //possibly old version, though doesn't really matter as content is already parsed as an Element } XPath xpath = xpfactory.newXPath(); XPathExpression exp = xpath.compile(contentFilter.getContent().get(0).toString()); Boolean ret = (Boolean) exp.evaluate(content, XPathConstants.BOOLEAN); return ret.booleanValue(); } catch (XPathExpressionException e) { LOGGER.log(Level.WARNING, "Could not filter notification", e); } return false; } return true; }
Example #19
Source File: XmlUtil.java From cerberus-source with GNU General Public License v3.0 | 6 votes |
/** * Evaluates the given xpath against the given document and produces string * which satisfy the xpath expression. * * @param document the document to search against the given xpath * @param xpath the xpath expression * @return a string which satisfy the xpath expression against the given * document. * @throws XmlUtilException if an error occurred */ public static String evaluateString(Document document, String xpath) throws XmlUtilException { if (document == null || xpath == null) { throw new XmlUtilException("Unable to evaluate null document or xpath"); } XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpathObject = xpathFactory.newXPath(); xpathObject.setNamespaceContext(new UniversalNamespaceCache(document)); String result = null; try { XPathExpression expr = xpathObject.compile(xpath); result = (String) expr.evaluate(document, XPathConstants.STRING); } catch (XPathExpressionException xpee) { throw new XmlUtilException(xpee); } if (result == null) { throw new XmlUtilException("Evaluation caused a null result"); } return result; }
Example #20
Source File: XMLUtil.java From sagacity-sqltoy with Apache License 2.0 | 5 votes |
/** * @todo 获取qName对应的内容 * @param xmlFile * @param xmlQuery * @param qName * @return * @throws Exception */ public static Object getXPathContent(File xmlFile, String xmlQuery, QName qName) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); XPathFactory pathFactory = XPathFactory.newInstance(); XPath xpath = pathFactory.newXPath(); XPathExpression pathExpression = xpath.compile(xmlQuery); return pathExpression.evaluate(doc, qName); }
Example #21
Source File: PluginConfigXmlIT.java From ci.maven with Apache License 2.0 | 5 votes |
@Test public void testXmlElements() throws Exception { File in = new File(CONFIG_XML); FileInputStream input = new FileInputStream(in); // get input XML Document DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance(); inputBuilderFactory.setIgnoringComments(true); inputBuilderFactory.setCoalescing(true); inputBuilderFactory.setIgnoringElementContentWhitespace(true); inputBuilderFactory.setValidating(false); DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder(); Document inputDoc=inputBuilder.parse(input); // parse input XML Document XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "/liberty-plugin-config/installAppPackages/text()"; String value = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING); assertEquals("Value of <installAppPackages/> ==>", "dependencies", value); expression = "/liberty-plugin-config/projectType/text()"; value = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING); assertEquals("Value of <projectType/> ==>", "liberty-assembly", value); expression = "/liberty-plugin-config/aggregatorParentId/text()"; value = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING); assertEquals("Value of <aggregatorParentId/> ==>", "ear-project-it", value); expression = "/liberty-plugin-config/aggregatorParentBasedir/text()"; value = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING); File parentProj = new File(".."); assertEquals("Value of <aggregatorParentBasedir/> ==>", parentProj.getCanonicalPath(), value); }
Example #22
Source File: Test.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
public static void testXPath() throws Exception { //String html = Utils.httpGET("http://www.google.ru/search?q=site::http://endurancerobots.com/+робот"); //System.out.println(html); Bot bot = Bot.createInstance(); Http http = bot.awareness().getSense(Http.class); Element element = http.parseURL(new URL("http://ab-w.net/HTML5/html5_em.php")); System.out.println(element.getTextContent()); XPathFactory factory = XPathFactory.newInstance(); XPath path = factory.newXPath(); Object node = path.evaluate("//*/p[5]/em/text()", element, XPathConstants.NODE); System.out.println(((Text)node).getTextContent()); System.out.println("курсивный"); }
Example #23
Source File: XmlXPathExists.java From butterfly with MIT License | 5 votes |
private XPathExpression checkXPathCompile(String expression) throws TransformationDefinitionException{ XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); XPathExpression expr = null; try { expr = xpath.compile(expression); } catch (XPathExpressionException e) { throw new TransformationDefinitionException("XPath expression '" + expression + "' didn't compile correctly.", e); } return expr; }
Example #24
Source File: SOAPResponseValidator.java From gatf with Apache License 2.0 | 5 votes |
protected int getResponseMappedCount(String expression, Object nodeLst) throws Exception { expression = expression.replaceAll("\\.", "\\/"); if(expression.length()>1 && expression.charAt(0)!='/') expression = "/" + expression; Node envelope = getNodeByNameCaseInsensitive(((Document)nodeLst).getFirstChild(), "envelope"); Node body = getNodeByNameCaseInsensitive(envelope, "body"); Node requestBody = getNextElement(body); Node returnBody = getNextElement(requestBody); if(expression.equals("")) expression = SOAPResponseValidator.createXPathExpression(expression, envelope, body, requestBody) + "*"; else expression = SOAPResponseValidator.createXPathExpression(expression, envelope, body, requestBody, returnBody); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList xmlNodeList = (NodeList) xPath.compile(expression).evaluate((Document)nodeLst, XPathConstants.NODESET); Assert.assertTrue("Workflow soap variable " + expression +" is null", xmlNodeList!=null && xmlNodeList.getLength()>0); String xmlValue = XMLResponseValidator.getXMLNodeValue(xmlNodeList.item(0)); Assert.assertNotNull("Workflow soap variable " + expression +" is null", xmlValue); int responseCount = -1; try { responseCount = Integer.valueOf(xmlValue); } catch (Exception e) { throw new AssertionError("Invalid responseMappedCount variable defined, " + "derived value should be number - "+expression); } return responseCount; }
Example #25
Source File: CienaWaveserverAiDeviceDescriptionTest.java From onos with Apache License 2.0 | 5 votes |
@Test public void testDiscoverPortStatistics() { Collection<PortStatistics> result = new ArrayList<>(); Collection<PortStatistics> expectResult = getExpectedPortsStatistics(); try { XPath xp = XPathFactory.newInstance().newXPath(); String tx = "current-bin/statistics/interface-counts/tx/"; String rx = "current-bin/statistics/interface-counts/rx/"; Node node = doRequest("/response/discoverPortStatistics.xml", "/rpc-reply/data"); NodeList nodeList = (NodeList) xp.evaluate("waveserver-pm/ethernet-performance-instances", node, XPathConstants.NODESET); Node nodeListItem; int count = nodeList.getLength(); for (int i = 0; i < count; ++i) { nodeListItem = nodeList.item(i); result.add(DefaultPortStatistics.builder() .setDeviceId(mockDeviceId) .setPort(PortNumber.portNumber(portIdConvert( xp.evaluate("instance-name/text()", nodeListItem)))) .setBytesReceived(Long.parseLong(xp.evaluate(rx + "bytes/value/text()", nodeListItem))) .setPacketsReceived(Long.parseLong( xp.evaluate(rx + "packets/value/text()", nodeListItem))) .setBytesSent(Long.parseLong(xp.evaluate(tx + "bytes/value/text()", nodeListItem))) .setPacketsSent(Long.parseLong(xp.evaluate(tx + "packets/value/text()", nodeListItem))) .build()); } } catch (XPathExpressionException e) { e.printStackTrace(); } // TODO: the builder causes this test to fail // assertEquals(expectResult, result); }
Example #26
Source File: ProcessDiagramLayoutFactory.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
protected Map<String, DiagramNode> fixFlowNodePositionsIfModelFromAdonis(Document bpmnModel, Map<String, DiagramNode> elementBoundsFromBpmnDi) { if (isExportedFromAdonis50(bpmnModel)) { Map<String, DiagramNode> mapOfFixedBounds = new HashMap<String, DiagramNode>(); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); xPath.setNamespaceContext(new Bpmn20NamespaceContext()); for (Entry<String, DiagramNode> entry : elementBoundsFromBpmnDi.entrySet()) { String elementId = entry.getKey(); DiagramNode elementBounds = entry.getValue(); String expression = "local-name(//bpmn:*[@id = '" + elementId + "'])"; try { XPathExpression xPathExpression = xPath.compile(expression); String elementLocalName = xPathExpression.evaluate(bpmnModel); if (!"participant".equals(elementLocalName) && !"lane".equals(elementLocalName) && !"textAnnotation".equals(elementLocalName) && !"group".equals(elementLocalName)) { elementBounds.setX(elementBounds.getX() - elementBounds.getWidth() / 2); elementBounds.setY(elementBounds.getY() - elementBounds.getHeight() / 2); } } catch (XPathExpressionException e) { throw new ActivitiException("Error while evaluating the following XPath expression on a BPMN XML document: '" + expression + "'.", e); } mapOfFixedBounds.put(elementId, elementBounds); } return mapOfFixedBounds; } else { return elementBoundsFromBpmnDi; } }
Example #27
Source File: XPathExFuncTest.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
void evaluate(boolean enableExt) throws XPathFactoryConfigurationException, XPathExpressionException { Document document = getDocument(); XPathFactory xPathFactory = XPathFactory.newInstance(); /** * Use of the extension function 'http://exslt.org/strings:tokenize' is * not allowed when the secure processing feature is set to true. * Attempt to use the new property to enable extension function */ if (enableExt) { boolean isExtensionSupported = enableExtensionFunction(xPathFactory); } xPathFactory.setXPathFunctionResolver(new MyXPathFunctionResolver()); if (System.getSecurityManager() == null) { xPathFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); } XPath xPath = xPathFactory.newXPath(); xPath.setNamespaceContext(new MyNamespaceContext()); String xPathResult = xPath.evaluate(XPATH_EXPRESSION, document); System.out.println( "XPath result (enableExtensionFunction == " + enableExt + ") = \"" + xPathResult + "\""); }
Example #28
Source File: XML.java From scava with Eclipse Public License 2.0 | 5 votes |
private void init(String text) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //if html if (text.indexOf("<html")>-1 ||text.indexOf("<HTML")>-1 ){ //Logger.getLogger(this.getClass().getName()).warning("The text to be parsed seems to be in html format...html is not xml"); //Logger.getLogger(this.getClass().getName()).warning("Sanitizing html..."); //replace any entity text=text.replaceAll(" ","_");text=text.replaceAll("ú",""); text=text.replaceAll("&","_AND_SYMBOL_"); //remove w3c DTDs since they are slow int index=text.indexOf("<head");if(index==-1) index=text.indexOf("<HEAD"); text="<html>"+text.substring(index); //Actually remove all the head tag text=removeHead(text); //solve img tags not closed text=sanitizeTag("img",text); text=sanitizeTag("input",text); } DocumentBuilder db = dbf.newDocumentBuilder(); InputStream is=new ByteArrayInputStream(text.getBytes("UTF-8")); doc = db.parse(is); doc.getDocumentElement().normalize(); XPathFactory xFactory = XPathFactory.newInstance(); xpath = xFactory.newXPath(); }
Example #29
Source File: MigrationSiteBuilder.java From geoportal-server-harvester with Apache License 2.0 | 5 votes |
private String getProfileId(String protocol) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(protocol))); XPath xPath = XPathFactory.newInstance().newXPath(); return (String)xPath.evaluate("/protocol[@type='CSW']/profile", doc, XPathConstants.STRING); }
Example #30
Source File: ConfigTransformerTest.java From nifi-minifi with Apache License 2.0 | 5 votes |
@Before public void setup() throws ParserConfigurationException { documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); document = documentBuilder.newDocument(); config = document.createElement("config"); xPathFactory = XPathFactory.newInstance(); }