Java Code Examples for javax.xml.xpath.XPathFactory

The following examples show how to use javax.xml.xpath.XPathFactory. These examples are extracted from open source projects. 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 Project: cxf   Source File: JmsSubscription.java    License: Apache License 2.0 6 votes vote down vote up
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 2
Source Project: development   Source File: XPathCondition.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: SB_Elsinore_Server   Source File: BeerXMLReader.java    License: MIT License 6 votes vote down vote up
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 4
Source Project: cstc   Source File: XmlSignature.java    License: GNU General Public License v3.0 6 votes vote down vote up
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 5
Source Project: openjdk-8   Source File: XmlFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 6
Source Project: onos   Source File: Ciena5170DeviceDescription.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: onos   Source File: Ciena5162DeviceDescription.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: cougar   Source File: IDLReader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 9
Source Project: rice   Source File: BaseOjbConfigurer.java    License: Educational Community License v2.0 6 votes vote down vote up
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 10
Source Project: keycloak   Source File: SubsystemParsingTestCase.java    License: Apache License 2.0 6 votes vote down vote up
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 11
Source Project: smartcheck   Source File: Tool.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * @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 12
Source Project: teamengine   Source File: VerifyTestSuite.java    License: Apache License 2.0 6 votes vote down vote up
@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 13
Source Project: openxds   Source File: CrossGatewayRetrieveTest.java    License: Apache License 2.0 6 votes vote down vote up
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 14
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 15
Source Project: wandora   Source File: ModuleBundle.java    License: GNU General Public License v3.0 6 votes vote down vote up
@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 16
Source Project: artio   Source File: DictionaryParser.java    License: Apache License 2.0 6 votes vote down vote up
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 17
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 18
Source Project: teamengine   Source File: XMLUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 19
Source Project: cerberus-source   Source File: XmlUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 Project: MeituanLintDemo   Source File: XMLMergeUtil.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 21
Source Project: proarc   Source File: MetsElementVisitor.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 22
Source Project: hottub   Source File: XmlUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 23
Source Project: spring-analysis-note   Source File: XpathExpectationsHelper.java    License: MIT License 5 votes vote down vote up
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);
}
 
Example 24
Source Project: SI   Source File: TR069KeyExtractor.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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;
}
 
Example 25
Source Project: scava   Source File: XML.java    License: Eclipse Public License 2.0 5 votes vote down vote up
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();
}
 
Example 26
Source Project: onos   Source File: CienaWaveserverAiDeviceDescription.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 27
Source Project: sailfish-core   Source File: ServiceMarshalManager.java    License: Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 28
Source Project: openjdk-jdk9   Source File: XPathExFuncTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
boolean enableExtensionFunction(XPathFactory factory) {
    boolean isSupported = true;
    try {
        factory.setFeature(ENABLE_EXTENSION_FUNCTIONS, true);
    } catch (XPathFactoryConfigurationException ex) {
        isSupported = false;
    }
    return isSupported;
}
 
Example 29
Source Project: JavaTutorial   Source File: XPathDemo.java    License: Apache License 2.0 5 votes vote down vote up
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());
    }
}
 
Example 30
Source Project: BotLibre   Source File: Http.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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;
	}
}