Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:org.intellij.xquery.runner.rt.vendor.exist.ExistRunnerApp.java

private String getEvaluationResult(String response)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
        TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);//  w  ww  .j  a v a 2s  . co  m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(response)));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/result/value/text()");
    String textValue = expr.evaluate(doc);
    if (!"".equals(textValue))
        return textValue;
    expr = xpath.compile("/result/text()");
    String resultingXmlAsText = expr.evaluate(doc);
    if (!"".equals(resultingXmlAsText.trim()))
        return resultingXmlAsText;
    expr = xpath.compile("/result/child::*");
    Element node = (Element) expr.evaluate(doc, NODE);
    if (node != null) {
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            String nodeName = attribute.getNodeName();
            String nodeValue = attribute.getNodeValue();
            if (XMLNS.equals(nodeName) && SERIALIZED_NAMESPACE.equals(nodeValue)) {
                node.removeAttribute(XMLNS);
            }
        }
        return prettyPrint(node, builder.getDOMImplementation());
    } else {
        return response;
    }
}

From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

/**
   When user preferences are stored in the database for changes made to
   an incorporated node the node id can not be used because it does not
   represent a row in the up_layout_struct table for the user. The plfid
   must be used. Null will never be returned unless the layout or
   processing has really been screwed up. This is because changes made to
   the user prefs calls UserPrefsHandler which generates a shadow node in
   the db and sets the plfid of that node into the corresponding node in
   the PLF prior to the call to update the user prefs in the db.
 *//*from  w  w  w  . ja  v a2  s .c  o m*/
private String getPlfId(Document PLF, String incdId) {
    Element element = null;
    try {
        final XPathFactory fac = XPathFactory.newInstance();
        final XPath xp = fac.newXPath();
        element = (Element) xp.evaluate("//*[@ID = '" + incdId + "']", PLF, XPathConstants.NODE);
    } catch (final XPathExpressionException xpee) {
        throw new RuntimeException(xpee);
    }
    if (element == null) {
        this.log.warn("The specified folderId was not found in the user's PLF:  " + incdId);
        return null;
    }
    final Attr attr = element.getAttributeNode(Constants.ATT_PLF_ID);
    if (attr == null) {
        return null;
    }
    return attr.getValue();
}

From source file:org.jasig.portal.layout.dlm.remoting.UpdatePreferencesServlet.java

/**
 * Subscribe a user to a pre-formatted tab (pulled DLM fragment).
 * //from  w  w w . j  a  v a 2  s.  c o  m
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.POST, params = "action=subscribeToTab")
public ModelAndView subscribeToTab(HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    IUserInstance ui = userInstanceManager.getUserInstance(request);
    IPerson per = getPerson(ui, response);

    UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager();
    IUserLayoutManager ulm = upm.getUserLayoutManager();

    // Get the fragment owner's name from the request and construct 
    // an IPerson object representing that user
    String fragmentOwnerName = request.getParameter("sourceID");
    if (StringUtils.isBlank(fragmentOwnerName)) {
        log.warn("Attempted to subscribe to tab with null owner ID");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
    RestrictedPerson fragmentOwner = PersonFactory.createRestrictedPerson();
    fragmentOwner.setUserName(fragmentOwnerName);

    // Mark the currently-authenticated user as subscribed to this fragment.
    // If an inactivated fragment registration already exists, update it
    // as an active subscription.  Otherwise, create a new fragment
    // subscription.
    IUserFragmentSubscription userFragmentInfo = userFragmentInfoDao.getUserFragmentInfo(per, fragmentOwner);
    if (userFragmentInfo == null) {
        userFragmentInfo = userFragmentInfoDao.createUserFragmentInfo(per, fragmentOwner);
    } else {
        userFragmentInfo.setActive(true);
        userFragmentInfoDao.updateUserFragmentInfo(userFragmentInfo);
    }

    try {
        // reload user layout and stylesheet to incorporate new DLM fragment
        ulm.loadUserLayout(true);

        // get the target node this new tab should be moved after
        String destinationId = request.getParameter("elementID");

        // get the user layout for the currently-authenticated user
        int uid = userIdentityStore.getPortalUID(fragmentOwner, false);
        final DistributedUserLayout userLayout = userLayoutStore.getUserLayout(per, upm.getUserProfile());
        Document layoutDocument = userLayout.getLayout();

        // attempt to find the new subscribed tab in the layout so we can
        // move it
        StringBuilder expression = new StringBuilder("//folder[@type='root']/folder[starts-with(@ID,'")
                .append(Constants.FRAGMENT_ID_USER_PREFIX).append(uid).append("')]");
        XPathFactory fac = XPathFactory.newInstance();
        XPath xpath = fac.newXPath();
        NodeList nodes = (NodeList) xpath.evaluate(expression.toString(), layoutDocument,
                XPathConstants.NODESET);
        String sourceId = nodes.item(0).getAttributes().getNamedItem("ID").getTextContent();
        ulm.moveNode(sourceId, ulm.getParentId(destinationId), destinationId);

        ulm.saveUserLayout();

        return new ModelAndView("jsonView", Collections.singletonMap("tabId", sourceId));

    } catch (Exception e) {
        log.warn("Error subscribing to fragment owned by " + fragmentOwnerName, e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

}

From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java

/**
 * Gets a {@link NodeList} of {@link Node}s that contain information about the web
 * modules in the EAR./*from   ww  w  .j ava  2  s  . com*/
 * 
 * @param descriptorDom The EAR descriptor.
 * @return A NodeList of web module nodes.
 */
protected NodeList getWebModules(Document descriptorDom) {
    final XPathFactory xpathFactory = XPathFactory.newInstance();
    final XPath xpath = xpathFactory.newXPath();

    final XPathExpression xpathExpr;
    try {
        xpathExpr = xpath.compile(WEB_MODULE_XPATH);
    } catch (XPathExpressionException xpee) {
        throw new RuntimeException("Failed to compile XPathExpression from '" + WEB_MODULE_XPATH + "'", xpee);
    }

    try {
        final NodeList nodes = (NodeList) xpathExpr.evaluate(descriptorDom, XPathConstants.NODESET);

        if (this.getLogger().isDebugEnabled()) {
            this.getLogger()
                    .debug("Found " + nodes.getLength() + " '" + WEB_MODULE_XPATH + "' nodes in descriptor.");
        }

        return nodes;
    } catch (XPathExpressionException xpee) {
        throw new RuntimeException("Failed to evaluate XPathExpression='" + xpathExpr + "'", xpee);
    }
}

From source file:org.jboss.as.jdr.util.XMLSanitizer.java

public XMLSanitizer(String pattern, VirtualFileFilter filter) throws Exception {
    this.filter = filter;
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    expression = xpath.compile(pattern);

    DocumentBuilderFactory DBfactory = DocumentBuilderFactory.newInstance();
    DBfactory.setNamespaceAware(true);/*w  w  w .  jav  a  2 s.  co m*/
    builder = DBfactory.newDocumentBuilder();
    builder.setErrorHandler(null);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformer = transformerFactory.newTransformer();

}

From source file:org.jboss.as.test.integration.management.cli.ModuleTestCase.java

private void checkModuleXml(String slotName, File modulesPath, boolean checkResources,
        boolean checkAbsoluteResources, boolean checkProperties, boolean checkDependencies,
        boolean checkMainClass) throws Exception {
    File testModuleRoot = new File(modulesPath, MODULE_NAME.replace('.', File.separatorChar));
    File slot = new File(testModuleRoot, slotName);
    File moduleXml = new File(slot, "module.xml");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(moduleXml);

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

    // check resource-root
    XPathExpression pathAttrExpr = xpath.compile("/module/resources/resource-root/@path");
    NodeList nl = (NodeList) pathAttrExpr.evaluate(doc, XPathConstants.NODESET);
    List<String> paths = new ArrayList<>(2);
    for (int i = 0; i < nl.getLength(); i++) {
        paths.add(nl.item(i).getNodeValue());
    }// w  ww  .  j  a  v  a  2s  .  c  o m
    if (checkResources && checkAbsoluteResources) {
        assertTrue("module.xml should contain two resource-root elements", nl.getLength() == 2);
        assertTrue("module.xml should contain resource-root element with atrribute path=\"Dummy.jar\"",
                paths.contains("Dummy.jar"));
        assertTrue("module.xml should contain resource-root element with atrribute path=\""
                + jarFile2.getCanonicalPath() + "\"", paths.contains(jarFile2.getCanonicalPath()));
    } else if (checkResources && !checkAbsoluteResources) {
        assertTrue("module.xml should contain one resource-root elements", nl.getLength() == 1);
        assertTrue("module.xml should contain resource-root element with atrribute path=\"Dummy.jar\"",
                paths.contains("Dummy.jar"));
    } else if (!checkResources && checkAbsoluteResources) {
        assertTrue("module.xml should contain one resource-root elements", nl.getLength() == 1);
        assertTrue("module.xml should contain resource-root element with atrribute path=\""
                + jarFile2.getCanonicalPath() + "\"", paths.contains(jarFile2.getCanonicalPath()));
    }

    // check properties
    XPathExpression propertiesExpr = xpath.compile("/module/properties/property");
    nl = (NodeList) propertiesExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkProperties) {
        assertTrue("module.xml should contain one property but it has " + nl.getLength() + " properties",
                nl.getLength() == 1);
        NamedNodeMap attributes = nl.item(0).getAttributes();
        String name = attributes.getNamedItem("name").getNodeValue();
        String value = attributes.getNamedItem("value").getNodeValue();
        assertTrue("module.xml should contain property bat=man", name.equals("bat") && value.equals("man"));
    } else {
        assertTrue("module.xml shouldn't contain any properties but it has " + nl.getLength() + " properties",
                nl.getLength() == 0);
    }

    // check dependencies
    XPathExpression dependenciesNameAttrExpr = xpath.compile("/module/dependencies/module/@name");
    nl = (NodeList) dependenciesNameAttrExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkDependencies) {
        assertTrue("module.xml should contain two resource-root elements", nl.getLength() == 2);
        assertTrue("module.xml should contain module element with atrribute name=\"org.jboss.logging\"",
                nl.item(0).getNodeValue().equals("org.jboss.logging"));
        assertTrue("module.xml should contain module element with atrribute name=\"org.jboss.logmanager\"",
                nl.item(1).getNodeValue().equals("org.jboss.logmanager"));
    } else {
        assertTrue(
                "module.xml shouldn't contain any dependencies but it has " + nl.getLength() + " dependencies",
                nl.getLength() == 0);
    }

    XPathExpression exportDependenciesNameAttrExpr = xpath.compile("/module/dependencies/module/@export");
    nl = (NodeList) exportDependenciesNameAttrExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkDependencies) {
        assertTrue("module.xml should contain one resource-root elements", nl.getLength() == 1);
        assertTrue("module.xml should contain module element with atrribute export=true",
                nl.item(0).getNodeValue().equals("true"));
    } else {
        assertTrue(
                "module.xml shouldn't contain any dependencies but it has " + nl.getLength() + " dependencies",
                nl.getLength() == 0);
    }

    // check main class
    XPathExpression mainClassNameAttrExpr = xpath.compile("/module/main-class/@name");
    nl = (NodeList) mainClassNameAttrExpr.evaluate(doc, XPathConstants.NODESET);
    if (checkMainClass) {
        assertTrue("module.xml should contain main-class element", nl.getLength() == 1);
        assertTrue("module.xml should contain main-class element with atrribute name=\"org.jboss.Test\"",
                nl.item(0).getNodeValue().equals("org.jboss.Test"));
    } else {
        assertTrue("module.xml shouldn't contain main-class element", nl.getLength() == 0);
    }

}

From source file:org.jboss.on.common.jbossas.JmxInvokerServiceConfiguration.java

private void parseDocument(Document doc) throws Exception {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    // Use a bunch of incremental XPath expressions rather than one big XPath expression,
    // so we can provide better log messages.
    Node invokerMBeanNode = (Node) xPath.evaluate(
            "//server/mbean[@name = 'jboss.jmx:type=adaptor,name=Invoker']", doc, XPathConstants.NODE);
    if (invokerMBeanNode == null) {
        // This is uncommon and therefore suspicious.
        log.warn("'jboss.jmx:type=adaptor,name=Invoker' mbean not found while parsing '" + this.source + "'.");
        return;// w  w  w  . j a v a 2s . c  om
    }
    Node invokeOperationNode = (Node) xPath.evaluate("xmbean/operation[name = 'invoke']", invokerMBeanNode,
            XPathConstants.NODE);
    if (invokeOperationNode == null) {
        // This is uncommon and therefore suspicious.
        log.warn("'invoke' operation not found for 'jboss.jmx:type=adaptor,name=Invoker' mbean while parsing '"
                + this.source + "'.");
        return;
    }
    Node interceptorsNode = (Node) xPath.evaluate("descriptors/interceptors", invokeOperationNode,
            XPathConstants.NODE);
    if (interceptorsNode == null) {
        log.debug(
                "No interceptors are defined for 'invoke' operation for 'jboss.jmx:type=adaptor,name=Invoker' mbean while parsing '"
                        + this.source + "'.");
        return;
    }
    Node authenticationInterceptorNode = (Node) xPath.evaluate(
            "interceptor[@code = 'org.jboss.jmx.connector.invoker.AuthenticationInterceptor']",
            interceptorsNode, XPathConstants.NODE);
    if (authenticationInterceptorNode == null) {
        // This is normal. It just means the authentication interceptor isn't enabled (typically it's commented out).
        return;
    }
    // e.g. "java:/jaas/jmx-console"
    String securityDomainJndiName;
    try {
        securityDomainJndiName = xPath.evaluate("@securityDomain", authenticationInterceptorNode);
    } catch (XPathExpressionException e) {
        throw new Exception(
                "'securityDomain' attribute not found on 'org.jboss.jmx.connector.invoker.AuthenticationInterceptor' interceptor while parsing '"
                        + this.source + "'.");
    }
    // e.g. "jmx-console"
    this.securityDomain = securityDomainJndiName.replaceFirst("^java:/jaas/", "");
}

From source file:org.jboss.qa.jcontainer.tomcat.TomcatContainer.java

protected void configureServer() {
    try {//  ww  w.  j  a v  a  2 s .co  m
        final File file = new File(configuration.getDirectory(), "conf" + File.separator + "server.xml");
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document doc = docBuilder.parse(file);

        final XPathFactory xPathfactory = XPathFactory.newInstance();
        final XPath xpath = xPathfactory.newXPath();
        final XPathExpression expr = xpath.compile("/Server/Service/Connector[@protocol='HTTP/1.1']");

        final Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
        node.getAttributes().getNamedItem("port").setNodeValue(Integer.toString(configuration.getHttpPort()));

        // Write the content into xml file
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        final Transformer transformer = transformerFactory.newTransformer();
        final DOMSource source = new DOMSource(doc);
        final StreamResult result = new StreamResult(file);
        transformer.transform(source, result);
    } catch (Exception e) {
        log.error("Ports was not configured", e);
    }
}

From source file:org.jboss.shrinkwrap.resolver.impl.maven.aether.ClasspathWorkspaceReader.java

private XPath getXPath() {
    if (xPath == null) {
        final XPathFactory factory = XPathFactory.newInstance();
        xPath = factory.newXPath();
    }/*from w w w  . j a  v  a  2 s . com*/
    return xPath;
}

From source file:org.jembi.rhea.orchestration.QueryPatientGetListOfOpenEMPIPersonIds.java

@Override
public Object onCall(MuleEventContext eventContext) throws Exception {
    MuleMessage msg = eventContext.getMessage();

    String openempiPeopleXml = (String) msg.getPayloadAsString();

    try {/* ww  w  .j  av  a  2 s . c om*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document document = dbf.newDocumentBuilder()
                .parse(new InputSource(new StringReader(openempiPeopleXml)));

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

        XPathExpression expression = xpath.compile("/people/person/personId");
        NodeList patientIdNodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);

        String idListStr = "";
        for (int i = 0; i < patientIdNodeList.getLength(); i++) {
            Node node = patientIdNodeList.item(i);
            String id = node.getTextContent();
            if (idListStr.isEmpty()) {
                //idListStr = id;
                idListStr = "personId=" + id;
            } else {
                //idListStr += "," + id;
                idListStr += "&personId=" + id;
            }
        }

        msg.setOutboundProperty("idList", idListStr);

    } catch (SAXParseException s) {
        throw new InvalidOpenEMPIResponseException("Empty or invalid response from OpenEMPI");
    }

    return msg;
}