javax.xml.xpath.XPathFactoryConfigurationException#javax.xml.xpath.XPathFactory源码实例Demo

下面列出了javax.xml.xpath.XPathFactoryConfigurationException#javax.xml.xpath.XPathFactory 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cxf   文件: JmsSubscription.java
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;
}
 
源代码2 项目: development   文件: XPathCondition.java
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();
}
 
源代码3 项目: SB_Elsinore_Server   文件: BeerXMLReader.java
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;
}
 
源代码4 项目: cstc   文件: XmlSignature.java
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);
    }
  }
}
 
源代码5 项目: openjdk-8   文件: XmlFactory.java
/**
 * 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);
    }
}
 
源代码6 项目: onos   文件: Ciena5170DeviceDescription.java
@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());
}
 
源代码7 项目: onos   文件: Ciena5162DeviceDescription.java
@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());
}
 
源代码8 项目: cougar   文件: IDLReader.java
/**
 * 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);
        }
    }
}
 
源代码9 项目: rice   文件: BaseOjbConfigurer.java
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()));
}
 
源代码10 项目: keycloak   文件: SubsystemParsingTestCase.java
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;
    }
}
 
源代码11 项目: smartcheck   文件: Tool.java
/**
 *
 * @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
                    )
            )
    );
}
 
源代码12 项目: teamengine   文件: VerifyTestSuite.java
@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));
}
 
源代码13 项目: openxds   文件: CrossGatewayRetrieveTest.java
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;
}
 
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;
    }
}
 
源代码15 项目: wandora   文件: ModuleBundle.java
@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;
    }
}
 
源代码16 项目: artio   文件: DictionaryParser.java
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);
    }
}
 
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;
}
 
源代码18 项目: teamengine   文件: XMLUtils.java
/**
 * 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;
}
 
源代码19 项目: cerberus-source   文件: XmlUtil.java
/**
 * 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;
}
 
源代码20 项目: MeituanLintDemo   文件: XMLMergeUtil.java
public static void merge(OutputStream outputStream, String expression,
                             InputStream... inputStreams) throws Exception {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();
    XPathExpression compiledExpression = xpath
            .compile(expression);
    Document doc = merge(compiledExpression, inputStreams);

    print(doc, outputStream);

    for (InputStream inputStream : inputStreams) {
        IOUtils.closeQuietly(inputStream);
    }
    IOUtils.closeQuietly(outputStream);
}
 
源代码21 项目: proarc   文件: MetsElementVisitor.java
private Node createNode(JAXBElement jaxb, JAXBContext jc, String expression) throws  Exception{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.newDocument();
    Marshaller marshaller = jc.createMarshaller();
    marshaller.marshal(jaxb, document);
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node node = (Node) xpath.compile(expression).evaluate(document, XPathConstants.NODE);
    return node;
}
 
源代码22 项目: hottub   文件: XmlUtil.java
public static XPathFactory newXPathFactory(boolean secureXmlProcessingEnabled) {
    XPathFactory factory = XPathFactory.newInstance();
    try {
        factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isXMLSecurityDisabled(secureXmlProcessingEnabled));
    } catch (XPathFactoryConfigurationException e) {
        LOGGER.log(Level.WARNING, "Factory [{0}] doesn't support secure xml processing!", new Object[] { factory.getClass().getName() } );
    }
    return factory;
}
 
private static XPathExpression compileXpathExpression(String expression,
		@Nullable Map<String, String> namespaces) throws XPathExpressionException {

	SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
	namespaceContext.setBindings(namespaces != null ? namespaces : Collections.emptyMap());
	XPath xpath = XPathFactory.newInstance().newXPath();
	xpath.setNamespaceContext(namespaceContext);
	return xpath.compile(expression);
}
 
源代码24 项目: SI   文件: TR069KeyExtractor.java
public JSONObject parametersToJSON(String xml){
	JSONObject result = new JSONObject();
	
	try{
		InputSource is = new InputSource(new StringReader(xml));
		Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
		XPath  xpath = XPathFactory.newInstance().newXPath();
		
		String expression = "//ParameterList/ParameterValueStruct";
		//NodeList cols = (NodeList) xpath.compile(expression).evaluate(document, XPathConstants.NODESET);
		NodeList cols = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
		
		expression = "//*/EventCode";
		String command = xpath.compile(expression).evaluate(document);
		////System.out.println("Command................"+command);
		
		result.put("command", command);
		
		for( int idx=1; idx<=cols.getLength(); idx++ ){
			
			expression = "//ParameterList/ParameterValueStruct["+idx+"]/Name";
			String name = xpath.compile(expression).evaluate(document);
			////System.out.println("Name................"+name);

			expression = "//ParameterList/ParameterValueStruct["+idx+"]/Value";
			String value = xpath.compile(expression).evaluate(document);
			////System.out.println("Value................"+value);
			
			//System.out.println("["+idx+"] name : " + name + " / value : " + value);
			if(!name.equals("")){
				result.put(name, value);
			}
		}
		
	} catch(Exception e){}
	
	return result;
}
 
源代码25 项目: scava   文件: XML.java
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("&nbsp;","_");text=text.replaceAll("&uacute;","");
       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();
}
 
源代码26 项目: onos   文件: CienaWaveserverAiDeviceDescription.java
@Override
public List<PortDescription> discoverPortDetails() {
    log.info("Adding ports for Waveserver Ai device");
    List<PortDescription> ports = new ArrayList<>();

    Device device = getDevice(handler().data().deviceId());
    NetconfSession session = getNetconfSession();

    try {
        XPath xp = XPathFactory.newInstance().newXPath();
        Node nodeListItem;

        Node node = TEMPLATE_MANAGER.doRequest(session, "discoverPortDetails");
        NodeList nodeList = (NodeList) xp.evaluate("waveserver-ports/ports", node, XPathConstants.NODESET);
        int count = nodeList.getLength();
        for (int i = 0; i < count; ++i) {
            nodeListItem = nodeList.item(i);
            DefaultAnnotations annotationPort = DefaultAnnotations.builder()
                    .set(AnnotationKeys.PORT_NAME, xp.evaluate("port-id/text()", nodeListItem))
                    .set(AnnotationKeys.PROTOCOL, xp.evaluate("id/type/text()", nodeListItem))
                    .build();
            String port = xp.evaluate("port-id/text()", nodeListItem);
            ports.add(DefaultPortDescription.builder()
                      .withPortNumber(PortNumber.portNumber(
                              portIdConvert(port), port))
                      .isEnabled(portStateConvert(
                              xp.evaluate("state/operational-state/text()", nodeListItem)))
                      .portSpeed(portSpeedToLong(xp.evaluate("id/speed/text()", nodeListItem)))
                      .type(Port.Type.PACKET)
                      .annotations(annotationPort)
                      .build());
        }
    } catch (NetconfException | XPathExpressionException e) {
        log.error("Unable to retrieve port information for device {}, {}", device.chassisId(), e);
    }
    return ImmutableList.copyOf(ports);
}
 
源代码27 项目: sailfish-core   文件: ServiceMarshalManager.java
public ServiceMarshalManager(IStaticServiceManager staticServiceManager, IDictionaryManager dictionaryManager) {
    this.staticServiceManager = staticServiceManager;
    this.dictionaryManager = dictionaryManager;

	try {
           domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
           typeExpression = XPathFactory.newInstance().newXPath().compile("serviceDescription/type");
       } catch(ParserConfigurationException | XPathExpressionException e) {
           throw new EPSCommonException(e);
	}
}
 
源代码28 项目: openjdk-jdk9   文件: XPathExFuncTest.java
boolean enableExtensionFunction(XPathFactory factory) {
    boolean isSupported = true;
    try {
        factory.setFeature(ENABLE_EXTENSION_FUNCTIONS, true);
    } catch (XPathFactoryConfigurationException ex) {
        isSupported = false;
    }
    return isSupported;
}
 
源代码29 项目: JavaTutorial   文件: XPathDemo.java
public static void main(String[] args) throws XPathExpressionException {
    InputSource ins = new InputSource(XPathDemo.class.getResourceAsStream("/cn/aofeng/demo/xml/BookStore.xml"));
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    NodeList result = (NodeList) xpath.evaluate("//title[@lang='de']", ins, XPathConstants.NODESET);
    for (int i = 0; i < result.getLength(); i++) {
        Node node = result.item(i);
        StringBuilder buffer = new StringBuilder()
            .append("NodeName=").append(node.getNodeName()).append(", ")
            .append("NodeValue=").append(node.getNodeValue()).append(", ")
            .append("Text=").append(node.getTextContent());
        System.out.println(buffer.toString());
    }
}
 
源代码30 项目: BotLibre   文件: Http.java
/**
 * Post the HTML forms params and return the HTML data from the URL.
 */
public Vertex postHTML(String url, Vertex paramsObject, String xpath, Map<String, String> headers, Network network) {
	log("POST HTML", Level.INFO, url, xpath);
	try {
		Map<String, String> data = convertToMap(paramsObject);
		log("POST params", Level.FINE, data);
		String html = Utils.httpPOST(url, data, headers);
		InputStream stream = new ByteArrayInputStream(html.getBytes("utf-8"));
		StringReader reader = convertToXHTML(stream);
		Element element = parseXHTML(reader);
		if (element == null) {
			return null;
		}
		XPathFactory factory = XPathFactory.newInstance();
		XPath path = factory.newXPath();
		Object node = path.evaluate(xpath, element, XPathConstants.NODE);
		if (node instanceof Element) {
			return convertElement((Element)node, network);
		} else if (node instanceof Attr) {
			return network.createVertex(((Attr)node).getValue());
		} else if (node instanceof org.w3c.dom.Text) {
			return network.createVertex(((org.w3c.dom.Text)node).getTextContent());
		}
		return null;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}