Example usage for javax.xml.xpath XPathFactory newInstance

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

Introduction

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

Prototype

public static XPathFactory newInstance() 

Source Link

Document

Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.

This method is functionally equivalent to:

 newInstance(DEFAULT_OBJECT_MODEL_URI) 

Since the implementation for the W3C DOM is always available, this method will never fail.

Usage

From source file:com.mirth.connect.plugins.datatypes.hl7v2.HL7v2AutoResponder.java

private Response generateACK(Status status, String hl7Message,
        HL7v2ResponseGenerationProperties hl7v2Properties) throws Exception {
    boolean errorOnly = false;
    boolean always = false;
    boolean successOnly = false;

    hl7Message = hl7Message.trim();/*w w  w  .  ja v  a2 s  . c  om*/
    boolean isXML = StringUtils.isNotBlank(hl7Message) && hl7Message.charAt(0) == '<';

    String ACK = null;
    String statusMessage = null;
    String error = null;

    try {
        if (serializationProperties.isConvertLineBreaks() && !isXML) {
            hl7Message = StringUtil.convertLineBreaks(hl7Message, serializationSegmentDelimiter);
        }

        // Check if we have to look at MSH15     
        if (hl7v2Properties.isMsh15ACKAccept()) {
            // MSH15 Dictionary:
            // AL: Always
            // NE: Never
            // ER: Error / Reject condition
            // SU: Successful completion only

            String msh15 = "";

            // Check if the message is ER7 or XML
            if (isXML) { // XML form
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression msh15Query = xpath.compile("//MSH.15/text()");
                DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = domFactory.newDocumentBuilder();
                Reader reader = new CharArrayReader(hl7Message.toCharArray());
                Document doc = builder.parse(new InputSource(reader));
                msh15 = msh15Query.evaluate(doc);
            } else { // ER7
                char fieldDelim = hl7Message.charAt(3); // Usually |
                char componentDelim = hl7Message.charAt(4); // Usually ^

                Pattern fieldPattern = Pattern.compile(Pattern.quote(String.valueOf(fieldDelim)));
                Pattern componentPattern = Pattern.compile(Pattern.quote(String.valueOf(componentDelim)));

                String mshString = StringUtils.split(hl7Message, serializationSegmentDelimiter)[0];
                String[] mshFields = fieldPattern.split(mshString);

                if (mshFields.length > 14) {
                    msh15 = componentPattern.split(mshFields[14])[0]; // MSH.15.1
                }
            }

            if (msh15 != null && !msh15.equals("")) {
                if (msh15.equalsIgnoreCase("AL")) {
                    always = true;
                } else if (msh15.equalsIgnoreCase("NE")) {
                    logger.debug("MSH15 is NE, Skipping ACK");
                    return null;
                } else if (msh15.equalsIgnoreCase("ER")) {
                    errorOnly = true;
                } else if (msh15.equalsIgnoreCase("SU")) {
                    successOnly = true;
                }
            }
        }

        String ackCode = "AA";
        String ackMessage = "";
        boolean nack = false;

        if (status == Status.ERROR) {
            if (successOnly) {
                // we only send an ACK on success
                return null;
            }
            ackCode = hl7v2Properties.getErrorACKCode();
            ackMessage = hl7v2Properties.getErrorACKMessage();
            nack = true;
        } else if (status == Status.FILTERED) {
            if (successOnly) {
                return null;
            }
            ackCode = hl7v2Properties.getRejectedACKCode();
            ackMessage = hl7v2Properties.getRejectedACKMessage();
            nack = true;
        } else {
            if (errorOnly) {
                return null;
            }
            ackCode = hl7v2Properties.getSuccessfulACKCode();
            ackMessage = hl7v2Properties.getSuccessfulACKMessage();
        }

        ACK = HL7v2ACKGenerator.generateAckResponse(hl7Message, isXML, ackCode, ackMessage,
                generationProperties.getDateFormat(), new String(), deserializationSegmentDelimiter);
        statusMessage = "HL7v2 " + (nack ? "N" : "") + "ACK successfully generated.";
        logger.debug("HL7v2 " + (nack ? "N" : "") + "ACK successfully generated: " + ACK);
    } catch (Exception e) {
        logger.warn("Error generating HL7v2 ACK.", e);
        throw new Exception("Error generating HL7v2 ACK.", e);
    }

    return new Response(status, ACK, statusMessage, error);
}

From source file:it.jnrpe.plugin.tomcat.TomcatDataProvider.java

private void parseConnectorsThreadData() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(tomcatXML));

    Document doc = builder.parse(is);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();

    NodeList connectorsNodeList = (NodeList) xpath.compile("//status/connector")
            .evaluate(doc.getDocumentElement(), XPathConstants.NODESET);

    for (int i = 0; i < connectorsNodeList.getLength(); i++) {
        Node connector = connectorsNodeList.item(i);
        NodeList connectorChildren = connector.getChildNodes();

        final String connectorName = connector.getAttributes().getNamedItem("name").getNodeValue();
        for (int j = 0; j < connectorChildren.getLength(); j++) {
            Node node = connectorChildren.item(j);
            if (node.getNodeName().equalsIgnoreCase("threadInfo")) {

                NamedNodeMap atts = node.getAttributes();

                long maxThreads = Long.parseLong(atts.getNamedItem("maxThreads").getNodeValue());
                long currentThreadsBusy = Long
                        .parseLong(atts.getNamedItem("currentThreadsBusy").getNodeValue());
                long currentThreadCount = Long
                        .parseLong(atts.getNamedItem("currentThreadCount").getNodeValue());

                connectorThreadData.put(connectorName,
                        new ThreadData(connectorName, currentThreadCount, currentThreadsBusy, maxThreads));
            }/*from  w  w  w. j  av a 2s  .co  m*/
        }
    }
}

From source file:org.opencastproject.remotetest.util.WorkflowUtils.java

/**
 * Parses the workflow instance represented by <code>xml</code> and extracts the workflow state.
 * /*w  w w.  ja  v  a2 s.  co  m*/
 * @param xml
 *          the workflow instance
 * @return the workflow state
 * @throws Exception
 *           if parsing fails
 */
public static String getWorkflowState(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8"));
    return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE))
            .getAttribute("state");
}

From source file:org.opencastproject.remotetest.server.perf.ConcurrentWorkflowTest.java

protected String getWorkflowInstanceStatus(String xml) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from   w  ww  . ja va  2s .  c  o  m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8"));
    return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE))
            .getAttribute("state");
}

From source file:com.provenance.cloudprovenance.policyhandler.ws.support.PolicyRequestProcessor.java

public String getIdforPolicyMatch(String responseContent, String xpathToDocumentId)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
        XPathFactoryConfigurationException {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from   w  ww  .  j ava2s .c om*/
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource is = new InputSource(new StringReader(responseContent));
    Document doc = builder.parse(is);

    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xpath = xPathFactory.newXPath();
    xpath.setNamespaceContext(cProvMapper);

    XPathExpression xPathExpr;
    xPathExpr = xpath.compile(xpathToDocumentId);

    logger.debug("XpathExpression to match: " + xpathToDocumentId);
    logger.debug("Document to match is: " + responseContent);

    return (String) xPathExpr.evaluate(doc, XPathConstants.STRING);
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Test
public void testPerformEntityResolutionWithDetermFactors() throws Exception {
    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    InputStream attributeParametersStream = getClass()
            .getResourceAsStream("/xml/TestAttributeParametersWithDeterm.xml");
    entityResolutionMessageHandler.setAttributeParametersStream(attributeParametersStream);
    testRequestMessageInputStream = getClass()
            .getResourceAsStream("/xml/EntityMergeRequestMessageForDeterm.xml");
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);/*from   w  w  w  .j  a va2  s. c  o  m*/
    assertNotNull(entityContainerNode);
    Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            null);

    resultDocument.normalizeDocument();
    // LOG.info(converter.toString(resultDocument));
    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    assertEquals(2, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(2, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:OriginalRecordReference", resultDocument,
            XPathConstants.NODESET);
    assertEquals(2, entityNodes.getLength());
    for (int i = 0; i < entityNodes.getLength(); i++) {
        Element e = (Element) entityNodes.item(i);
        String entityIdRef = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref");
        assertNotNull(entityIdRef);
        assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + entityIdRef + "']", resultDocument,
                XPathConstants.NODE));
    }
}

From source file:au.csiro.casda.sodalint.ValidateCapabilities.java

/**
 * One or more of the sync and async SODA endpoints should be listed in the capabilities document.
 * /* ww  w.jav  a  2  s .  c  om*/
 * @param reporter
 *            validation message destination
 * @param document
 *            The capabilities XML document
 * @param sodaService
 *            The service being tested.
 * @throws XPathExpressionException
 *             If ther eis acoding error in the xpath expression.
 */
private void checkForSyncAsync(Reporter reporter, Document document, SodaService sodaService)
        throws XPathExpressionException {
    final String sodaStdIdPrefix = "ivo://ivoa.net/std/SODA";
    final String sodaStdIdSync = "ivo://ivoa.net/std/SODA#sync-1.0";
    final String sodaStdIdAsync = "ivo://ivoa.net/std/SODA#async-1.0";
    final String accessDataStdIdSync = "ivo://ivoa.net/std/AccessData#sync";
    final String accessDataStdIdAsync = "ivo://ivoa.net/std/AccessData#async";

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

    NodeList capNodeList = (NodeList) xpath.evaluate("capability", document.getDocumentElement(),
            XPathConstants.NODESET);
    boolean hasSoda = false;
    Node syncCapNode = null;
    Node asyncCapNode = null;

    for (int i = 0; i < capNodeList.getLength(); i++) {
        Node capNode = capNodeList.item(i);
        Node stdIdAttr = capNode.getAttributes().getNamedItem("standardID");

        if (stdIdAttr != null && StringUtils.isNotBlank(stdIdAttr.getNodeValue())) {
            String stdId = stdIdAttr.getNodeValue();
            if (stdId.startsWith(sodaStdIdPrefix)) {
                hasSoda = true;
            }
            if (stdId.equals(sodaStdIdSync)) {
                syncCapNode = capNode;
            } else if (stdId.equals(sodaStdIdAsync)) {
                asyncCapNode = capNode;
            } else if (stdId.equals(accessDataStdIdSync)) {
                reporter.report(SodaCode.E_CPEP, "SODA endpoint uses outdated AccessData id: " + stdId);
                syncCapNode = capNode;
            } else if (stdId.equals(accessDataStdIdAsync)) {
                reporter.report(SodaCode.E_CPEP, "SODA endpoint uses outdated AccessData id: " + stdId);
                asyncCapNode = capNode;
            }
        }
    }

    if (syncCapNode == null && asyncCapNode == null) {
        if (hasSoda) {
            reporter.report(SodaCode.E_CPEP,
                    "SODA endpoints found but they do not have v1.0 sync or async qualifiers");
        } else {
            reporter.report(SodaCode.E_CPEP, "SODA requires at least one of the sync and async endpoints");
        }
    }

    if (syncCapNode != null) {
        NodeList interfaces = (NodeList) xpath.evaluate("interface", syncCapNode, XPathConstants.NODESET);
        if (interfaces == null || interfaces.getLength() == 0) {
            reporter.report(SodaCode.E_CPIF, "SODA sync endpoint does not contain an interface");
        } else {
            sodaService.setSyncServiceNode(syncCapNode);
        }
    }
    if (asyncCapNode != null) {
        NodeList interfaces = (NodeList) xpath.evaluate("interface", asyncCapNode, XPathConstants.NODESET);
        if (interfaces == null || interfaces.getLength() == 0) {
            reporter.report(SodaCode.E_CPIF, "SODA async endpoint does not contain an interface");
        }
        sodaService.setAsyncServiceNode(asyncCapNode);
    }
}

From source file:com.comcast.magicwand.spells.web.iexplore.IePhoenixDriver.java

/**
 * {@inheritDoc}//from  www . j av a  2s  .c  o  m
 */
public boolean verify(PhoenixDriverIngredients i) {
    boolean rv = false;
    Map<String, Object> configs = i.getDriverConfigs();

    LOGGER.debug("[version_property, arch_property] = [{}, {}]", (String) configs.get(IE_DRIVER_VERSION_KEY),
            (String) configs.get(IE_DRIVER_ARCH_KEY));

    IePlatformSpecifics ips = this.createIePlatformSpecifics((String) configs.get(IE_DRIVER_VERSION_KEY),
            (String) configs.get(IE_DRIVER_ARCH_KEY));

    if (!ips.isValid()) {
        LOGGER.error("The IePlatformSpecifics retrieved are not valid.");
        return false;
    }

    try {
        XPath xpath = XPathFactory.newInstance().newXPath();

        String pwd = System.getProperty("user.dir");
        String version = ips.getVersion();
        String arch = ips.getArch();

        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(IE_XML_DRIVER_LISTING_URL);

        NodeList nodes = (NodeList) xpath.evaluate(IE_XML_DRIVER_LISTING_XPATH, doc, XPathConstants.NODESET);

        String highestVersion = null;
        String needle = version + "/IEDriverServer_" + arch + "_";

        for (int idx = 0; idx < nodes.getLength(); idx++) {
            Node n = nodes.item(idx);

            String text = n.getTextContent();

            if (text.startsWith(needle)) {
                text = text.substring(needle.length(), text.length());

                if (IePhoenixDriver.versionGreater(highestVersion, text)) {
                    highestVersion = text;
                }
            }
        }

        if (null != highestVersion) {
            highestVersion = FilenameUtils.removeExtension(highestVersion);

            URL url = new URL(String.format(IE_HTTP_DRIVER_PATH_FORMAT, version, arch, highestVersion));
            String zipName = String.format(IE_ZIP_FILE_FORMAT, arch, highestVersion);

            File ieSaveDir = new File(Paths.get(pwd, "target", "drivers", "iexplore", version).toString());

            LOGGER.debug("Will read from \"{}\"", url);
            File zipFile = new File(
                    Paths.get(pwd, "target", "drivers", "iexplore", version, zipName).toString());
            FileUtils.copyURLToFile(url, zipFile);

            extract(zipFile, ieSaveDir.getAbsolutePath());

            File exe = Paths.get(pwd, "target", "drivers", "iexplore", version, IE_EXE_FILE_NAME).toFile();

            if (exe.exists()) {
                exe.setExecutable(true);
                systemSetProperty("webdriver.ie.driver", exe.getAbsolutePath());
                this.webDriver = this.createDriver(i.getDriverCapabilities());
                rv = true;
            } else {
                LOGGER.error("Extracted zip archive did nto contain \"{}\".", IE_EXE_FILE_NAME);
            }
        } else {
            LOGGER.error("Unable to find any IE Drivers from [{}]", IE_XML_DRIVER_LISTING_XPATH);
        }
    } catch (ParserConfigurationException | SAXException | XPathExpressionException err) {
        throw new RuntimeException(err);
    } catch (IOException ioe) {
        LOGGER.error("IO failure: {}", ioe);
    }
    return rv;
}

From source file:com.wso2telco.identity.application.authentication.endpoint.util.TenantDataManager.java

private static void refreshActiveTenantDomainsList() {

    try {/*from   www  . j a  v  a  2  s .c o  m*/
        String url = "https://" + getPropertyValue(HOST) + ":" + getPropertyValue(PORT)
                + "/services/TenantMgtAdminService/retrieveTenants";

        String xmlString = getServiceResponse(url);

        if (xmlString != null && !"".equals(xmlString)) {

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

            InputSource inputSource = new InputSource(new StringReader(xmlString));
            String xPathExpression = "/*[local-name() = '" + RETRIEVE_TENANTS_RESPONSE + "']/*[local-name() = '"
                    + RETURN + "']";
            NodeList nodeList = (NodeList) xpath.evaluate(xPathExpression, inputSource, XPathConstants.NODESET);
            tenantDomainList = new ArrayList<String>();

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    NodeList tenantData = element.getChildNodes();
                    boolean activeChecked = false;
                    boolean domainChecked = false;
                    boolean isActive = false;
                    String tenantDomain = null;

                    for (int j = 0; j < tenantData.getLength(); j++) {

                        Node dataItem = tenantData.item(j);
                        String localName = dataItem.getLocalName();

                        if (ACTIVE.equals(localName)) {
                            activeChecked = true;
                            if ("true".equals(dataItem.getTextContent())) {
                                isActive = true;
                            }
                        }

                        if (TENANT_DOMAIN.equals(localName)) {
                            domainChecked = true;
                            tenantDomain = dataItem.getTextContent();
                        }

                        if (activeChecked && domainChecked) {
                            if (isActive) {
                                tenantDomainList.add(tenantDomain);
                            }
                            break;
                        }
                    }
                }
            }

            Collections.sort(tenantDomainList);
        }

    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Retrieving Active Tenant Domains Failed. Ignore this if there are no tenants : ", e);
        }
    }
}

From source file:eu.planets_project.tb.impl.services.EvaluationTestbedServiceTemplateImpl.java

/**
 * @param node a Node obtained by getAllEvalResultsRootNodes()
 * @return/* w ww  .  j  a v  a  2  s . c o  m*/
 * @throws XPathExpressionException
 */
public String getEvalResultName(Node node) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    String result = (String) xpath.evaluate(sXPathForBMGoalName, node, XPathConstants.STRING);
    return result;
}