Example usage for javax.xml.xpath XPathConstants NODESET

List of usage examples for javax.xml.xpath XPathConstants NODESET

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODESET.

Prototype

QName NODESET

To view the source code for javax.xml.xpath XPathConstants NODESET.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Maps to Java org.w3c.dom.NodeList .

Usage

From source file:com.eviware.soapui.testondemand.TestOnDemandCaller.java

@NonNull
public List<Location> getLocations() throws Exception {
    Document responseDocument = makeCall(LOCATIONS_URI, generateLocationsRequestXML());
    NodeList locationNodes = (NodeList) xpath.evaluate(LOCATION_XPATH_EXPRESSION, responseDocument,
            XPathConstants.NODESET);

    List<Location> locations = new ArrayList<Location>();
    for (int i = 0; i < locationNodes.getLength(); i++) {
        Node locationNode = locationNodes.item(i);
        String name = (String) xpath.evaluate(LOCATION_NAME_XPATH_EXPRESSION, locationNode,
                XPathConstants.STRING);
        String code = (String) xpath.evaluate(LOCATION_CODE_XPATH_EXPRESSION, locationNode,
                XPathConstants.STRING);
        String unformattedServerIPAddresses = (String) xpath
                .evaluate(LOCATION_SERVER_IP_ADDRESSES_XPATH_EXPRESSION, locationNode, XPathConstants.STRING);

        String[] serverIPAddresses = new String[0];
        if (!unformattedServerIPAddresses.isEmpty()) {
            serverIPAddresses = unformattedServerIPAddresses.split(SERVER_IP_ADDRESSES_DELIMETER);
        }//from  ww w.j a v  a 2  s . com

        locations.add(new Location(code, name, serverIPAddresses));
    }

    return locations;
}

From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java

/**
 * Parses the response received by making call to REST API.
 * It parses and gets the total no. roles and their instances.
 * /*from  ww w .j a  v  a2  s.  c  om*/
 * @param roleInfo
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 * @throws ParseException
 */
private void parseRoleInfo(StringBuffer roleInfo) throws ParserConfigurationException, SAXException,
        IOException, XPathExpressionException, ParseException {
    DocumentBuilder docBuilder = null;
    Document doc = null;
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setIgnoringElementContentWhitespace(true);
    docBuilder = docBuilderFactory.newDocumentBuilder();
    doc = docBuilder.parse(new InputSource(new StringReader(roleInfo.toString())));

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    NodeList roleList = (NodeList) xPath.evaluate("/Deployment/RoleList/Role/RoleName", doc,
            XPathConstants.NODESET);
    //get all the roles
    String roleName = null;
    List<String> listRoleNames = new ArrayList<String>();
    for (int i = 0; i < roleList.getLength(); i++) {
        Element element = (Element) roleList.item(i);
        roleName = element.getTextContent();
        RoleEntity roleEntity = roleDao.findByRoleName(roleName);
        if (roleEntity == null) {
            roleEntity = new RoleEntity();
            roleEntity.setName(roleName);
            roleDao.add(roleEntity);
        }
        listRoleNames.add(roleName);
    }

    xPathFactory = XPathFactory.newInstance();
    xPath = xPathFactory.newXPath();
    RoleInstancesEntity roleInstancesEntity = null;
    RoleInstancesId roleInstancesId = null;
    for (String name : listRoleNames) {
        roleList = (NodeList) xPath.evaluate(
                "/Deployment/RoleInstanceList/RoleInstance[RoleName='" + name + "']", doc,
                XPathConstants.NODESET);
        //get no. of instances for WorkerRole
        int noOfInstances = roleList.getLength();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        String date = dateFormat.format(calendar.getTime());
        roleInstancesId = new RoleInstancesId(dateFormat.parse(date), name);
        roleInstancesEntity = new RoleInstancesEntity(roleInstancesId, noOfInstances, "UPDATE");
        roleInstancesDao.add(roleInstancesEntity);
    }

}

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>.
 *//*w w  w  .  j a v a2s .  co m*/
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:de.bayern.gdi.services.CatalogService.java

/**
 * Constructor./* w ww . j ava  2s  .  co  m*/
 *
 * @param url      URL
 * @param userName Username
 * @param password Password
 * @throws URISyntaxException if URL is wrong
 * @throws IOException if something in IO is wrong
 */
public CatalogService(URL url, String userName, String password) throws URISyntaxException, IOException {
    this.catalogURL = url;
    this.userName = userName;
    this.password = password;
    this.context = new NamespaceContextMap("csw", CSW_NAMESPACE, "gmd", GMD_NAMESPACE, "ows", OWS_NAMESPACE,
            "srv", SRV_NAMESPACE, "gco", GCO_NAMESPACE);
    Document xml = XML.getDocument(this.catalogURL, this.userName, this.password);
    if (xml != null) {
        String getProviderExpr = "//ows:ServiceIdentification/ows:Title";
        Node providerNameNode = (Node) XML.xpath(xml, getProviderExpr, XPathConstants.NODE, context);
        this.providerName = providerNameNode.getTextContent();
        String getRecordsURLExpr = "//ows:OperationsMetadata" + "/ows:Operation[@name='GetRecords']"
                + "/ows:DCP" + "/ows:HTTP" + "/ows:Post";

        NodeList rL = (NodeList) XML.xpath(xml, getRecordsURLExpr, XPathConstants.NODESET, context);

        for (int i = 0; i < rL.getLength(); i++) {
            Node gruNode = rL.item(i);
            String getRecordsValueStr = (String) XML.xpath(gruNode, "ows:Constraint/ows:Value/text()",
                    XPathConstants.STRING, this.context);

            if (getRecordsValueStr == null || getRecordsValueStr.isEmpty()
                    || getRecordsValueStr.equals("XML")) {

                String getRecordsURLStr = (String) XML.xpath(gruNode, "@*[name()='xlink:href']",
                        XPathConstants.STRING, this.context);

                this.getRecordsURL = null;
                this.getRecordsURL = new URL(getRecordsURLStr);
                break;
            }
        }
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.common.informationflow.VisioInformationFlowTemplateParser.java

public void parseTemplate() {
    Document dom = parseXmlFile();

    XPath xPath = XPathFactory.newInstance().newXPath();
    String xPathFirstLevelApplicationNodesExpression = "/VisioDocument/Pages/Page[1]/"
            + APPLICATION_SHAPE_XPATH;// w ww.j av a  2s .c om
    parsedNodes = Maps.newHashMap();

    try {
        NodeList firstLevelApplicationNodes = (NodeList) xPath
                .evaluate(xPathFirstLevelApplicationNodesExpression, dom, XPathConstants.NODESET);
        for (int i = 0; i < firstLevelApplicationNodes.getLength(); i++) {
            Node node = firstLevelApplicationNodes.item(i);
            parseNodeAndAddToMap(node, null);
        }
    } catch (XPathExpressionException e) {
        LOGGER.error("XPath-error during parsing of template '" + templateFile.getName() + "'.", e);
        throw new IteraplanTechnicalException(IteraplanErrorMessages.INTERNAL_ERROR);
    }

}

From source file:de.dplatz.padersprinter.control.TripService.java

Optional<List<Leg>> parseLegs(Node node) {
    XPath xpath = XPathFactory.newInstance().newXPath();

    try {//from  w  w w.j a va2s  .co m
        NodeList legNodes = (NodeList) xpath.evaluate(".//table[contains(@class, 'legTable')]", node,
                XPathConstants.NODESET);

        final List<Leg> legs = new LinkedList<>();

        logger.debug("Number of legs indentified: " + legNodes.getLength());
        for (int i = 0; i < legNodes.getLength(); i++) {
            Optional<Leg> leg = parseLeg(legNodes.item(i), xpath);

            if (!leg.isPresent()) {
                logger.info("At least one leg could not be parsed. Ignoring trip.");
                return Optional.empty();
            }

            legs.add(leg.get());
        }
        return Optional.of(legs);
    } catch (Exception ex) {
        logger.log(Level.ERROR, null, ex);
        return Optional.empty();
    }
}

From source file:de.fzi.ALERT.actor.MessageObserver.ComplexEventObserver.JMSMessageParser.java

public Message XMLFileParse(String msgString) {

    Message message = new Message();

    try {//w ww .j  a va2s. c o  m

        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(new MyErrorHandler());

        InputStream in = new ByteArrayInputStream(msgString.getBytes("UTF-8"));
        org.w3c.dom.Document doc = builder.parse(in);

        XPath xpath = XPathFactory.newInstance().newXPath();
        // XPath Query for showing all nodes value
        javax.xml.xpath.XPathExpression expr = xpath.compile("//patternID/text()");

        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;
        Pattern pattern = new Pattern();
        if (nodes.getLength() > 0) {
            pattern = patternDAO.findById(nodes.item(0).getNodeValue());
        }
        if (pattern != null) {

            message.setPatternId(pattern);
            for (int i = 0; i < nodes.getLength(); i++) {
                System.out.println(nodes.item(i).getNodeValue());
            }

            javax.xml.xpath.XPathExpression expr1 = xpath.compile("//alertcomplex/*/text()");

            Object result1 = expr1.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes1 = (NodeList) result1;
            String content = "";
            if (nodes.getLength() > 0) {
                for (int i = 0; i < nodes1.getLength(); i++) {
                    System.out.println("modes " + nodes1.item(i).getParentNode().getNodeName());
                    System.out.println(nodes1.item(i).getNodeValue());
                    content += nodes1.item(i).getNodeValue();
                }
            }
            message.setSubject("complex event");
            message.setSummary("default summary");
            message.setContent(content);
            message.setMsgDate(new Date());
            message.setMsgID(1);
        } else {
            message.setContent("ERROR!");
        }
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        message.setContent("ERROR!");
        System.out.println(e.getMessage());
    }

    return message;

}

From source file:eu.impact_project.wsclient.HtmlServiceProvider.java

private NodeList applyXPath(Document doc, String xpathExpression, String namespace) {

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    if (!namespace.equals(NO_NAMESPACE))
        xpath.setNamespaceContext(new WSDLNamespaceContext());

    XPathExpression expr;/*  w w w .  j a va2s. co m*/

    Object result = null;
    try {
        expr = xpath.compile(xpathExpression);
        result = expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return (NodeList) result;

}

From source file:de.bitzeche.video.transcoding.zencoder.ZencoderClient.java

/**
 * Complete output IDs from response.//from   w ww. ja  v a  2 s  .  c o m
 * 
 * @param job
 * @param response
 */
private void completeJobInfo(ZencoderJob job, Document response) {
    try {
        NodeList outputs = (NodeList) xPath.evaluate("/api-response/job/outputs", response,
                XPathConstants.NODESET);
        if (job.getOutputs().size() == 1) {
            Integer id = findIdFromOutputNode(outputs.item(0));
            if (id != null) {
                job.getOutputs().get(0).setId(id);
            }
        } else {
            // try via labels
            Map<String, Integer> ids = new HashMap<String, Integer>();
            int outputSize = outputs.getLength();
            for (int i = 0; i < outputSize; i++) {
                String label = (String) xPath.evaluate("output/label", outputs.item(i), XPathConstants.STRING);
                if (label != null && !label.isEmpty()) {
                    int id = findIdFromOutputNode(outputs.item(i));
                    ids.put(label, new Integer(id));
                }
            }
            for (ZencoderOutput zcOutput : job.getOutputs()) {
                Integer foundId = ids.get(zcOutput.getLabel());
                if (foundId != null) {
                    zcOutput.setId(foundId);
                }
            }
        }

    } catch (XPathExpressionException e) {
        LOGGER.error("XPath threw Exception", e);
    }
}

From source file:com.wrightfully.sonar.plugins.dotnet.resharper.CustomSeverities.java

/**
 * Get the String nodes through the reader
 * @return list of string nodes// w w  w .j  av a2s.c o  m
 */
private NodeList getStringNodes(String propertyValue) {
    XPath xpath = createXPathForInspectCode();
    NodeList nodes = new EmptyNodeList();
    try {
        StringReader reader = new StringReader(propertyValue);
        InputSource source = new InputSource(reader);
        nodes = (NodeList) xpath.evaluate("//s:String", source, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        // There are two cases that can cause this error
        //1: invalid expression, which can't happen
        //2: invalid source, which can happen with an empty string
        LOG.debug("XPATH error (ignoring", e);
    }
    return nodes;
}