Example usage for javax.xml.xpath XPath evaluate

List of usage examples for javax.xml.xpath XPath evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPath evaluate.

Prototype

public Object evaluate(String expression, InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate an XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:org.ala.harvester.FlickrHarvester.java

private boolean isDocExtractionSuccessful(org.w3c.dom.Document resDom) throws Exception {

    if (resDom == null) {
        return false;
    }/*from  www. j a  v  a  2 s.co  m*/

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

    // <rsp stat="fail">
    // <err code="[error-code]" msg="[error-message]" />
    // </rsp>

    String xPathToStatus = "/rsp/@stat";

    String statusString = null;
    try {
        statusString = (String) xpath.evaluate(xPathToStatus, resDom, XPathConstants.STRING);
    } catch (XPathExpressionException getStatusStringErr) {
        String errMsg = "Failed to obtain Flickr REST response's status string.";
        logger.error(errMsg);
        throw new Exception(errMsg, getStatusStringErr);
    }
    logger.debug("Response status: " + statusString);
    if ("ok".equals(statusString)) {
        return true;
    } else {
        logger.error("Error response status: " + statusString);
    }

    // Status is false.
    String flickrErrCode = null;
    String flickrErrMsg = null;
    try {
        flickrErrCode = (String) xpath.evaluate("/rsp/err/@code", resDom, XPathConstants.STRING);
        flickrErrMsg = (String) xpath.evaluate("/rsp/err/@msg", resDom, XPathConstants.STRING);
    } catch (XPathExpressionException getErrDetailsErr) {
        String errMsg = "Failed to obtain Flickr REST response's error code and message.";
        logger.error(errMsg);
        throw new Exception(errMsg, getErrDetailsErr);
    }

    String errMsg = "Flickr REST response returned error.  Code: " + flickrErrCode + " " + "Message: " + "`"
            + flickrErrMsg + "`" + "\n";
    logger.error(errMsg);

    return false;
}

From source file:com.esri.gpt.server.openls.provider.services.route.DetermineRouteProvider.java

/**
 * Handles an XML based request (normally HTTP POST).
 * //from   www.  j  a  va2s .  c  o m
 * @param context
 *            the operation context
 * @param root
 *            the root node
 * @param xpath
 *            an XPath to enable queries (properly configured with name
 *            spaces)
 * @throws Exception
 */
public void handleXML(OperationContext context, Node root, XPath xpath) throws Exception {

    // initialize
    LOGGER.finer("Handling xls:DetermineRouteProvider request XML...");
    String locator = "xls:DetermineRouteRequest";

    // service and version are parsed by the parent RequestHandler
    Node ndReq = (Node) xpath.evaluate(locator, root, XPathConstants.NODE);
    if (ndReq != null) {
        parseRequest(context, ndReq, xpath);
    }
    // TODO requestId
    try {
        executeRequest(context);
    } catch (Throwable e) {
        e.printStackTrace();
    }
    generateResponse(context);
}

From source file:com.eucalyptus.imaging.backend.ImagingTaskStateManager.java

private List<String> getPartsHeadUrl(final String manifest) throws Exception {
    final XPath xpath = XPathFactory.newInstance().newXPath();
    final DocumentBuilder builder = XMLParser.getDocBuilder();
    final Document inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes()));

    final List<String> parts = Lists.newArrayList();
    final NodeList nodes = (NodeList) xpath.evaluate(ImportImageManifest.INSTANCE.getPartsPath() + "/head-url",
            inputSource, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        parts.add(nodes.item(i).getTextContent());
    }//from w ww. ja v  a2s  .com
    return parts;
}

From source file:com.esri.gpt.server.csw.provider3.GetRecordsProvider.java

/**
 * Builds an ogc:Filter node from HTTP GET parameters.
 * @param namespace the namespace parameter values
 * @param constraintFilter the constraint parameter value
 * @throws Exception if a processing exception occurs
 *//*  w  ww .  ja v a  2 s.co  m*/
protected Node buildFilterNode(String[] namespace, String constraintFilter) throws Exception {

    // TODO GetRecordsDomBuilder had a different pattern??

    // parse namespaces
    // pattern: namespace=xmlns(ogc=http://www.opengis.net/ogc),xmlns(gml=http://www.opengis.net/gml)...
    StringBuilder nsBuffer = new StringBuilder();
    boolean hasCswUri = false;
    boolean hasCswPfx = false;
    String cswPfx = "";

    List<String[]> parseNamespace = parseNamespace(namespace);
    for (String[] ns : parseNamespace) {
        String nsUri = ns[0];
        String nsPfx = ns[1];
        if (nsUri.equals(CswNamespaces.CSW_30.URI_CSW())) {
            hasCswUri = true;
            if (!nsPfx.isEmpty()) {
                hasCswPfx = true;
                cswPfx = nsPfx;
            }
        }
        if (nsPfx.isEmpty()) {
            nsBuffer.append(" xmlns=\"").append(nsUri).append("\"");
        } else {
            nsBuffer.append(" xmlns:").append(nsPfx).append("=\"").append(nsUri).append("\"");
        }
    }

    // use ogc as the default namespace if no namespace parameter was supplied
    if (nsBuffer.length() == 0) {
        nsBuffer.append(" xmlns=\"http://www.opengis.net/ogc\"");
    }

    // build the constraint XML
    StringBuilder sbXml = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    if (hasCswUri && hasCswPfx) {
        cswPfx = cswPfx + ":";
    } else if (hasCswUri) {
        cswPfx = "";
    } else {
        cswPfx = "csw:";
        nsBuffer.append(" xmlns:csw=\"http://www.opengis.net/cat/csw/3.0\"");
    }
    sbXml.append("\r\n<").append(cswPfx).append("Constraint");
    if (nsBuffer.length() > 0) {
        sbXml.append(" ").append(nsBuffer);
    }
    sbXml.append(">");
    sbXml.append("\r\n").append(constraintFilter);
    sbXml.append("\r\n</").append(cswPfx).append("Constraint>");

    // make the dom, find the ogc:Filter node
    try {
        Document dom = DomUtil.makeDomFromString(sbXml.toString(), true);
        CswNamespaces ns = CswNamespaces.CSW_30;
        XPath xpath = XPathFactory.newInstance().newXPath();
        xpath.setNamespaceContext(ns.makeNamespaceContext());

        Node ndFilter = null;
        Node ndConstraint = (Node) xpath.evaluate("csw:Constraint", dom, XPathConstants.NODE);
        if (ndConstraint != null) {
            ndFilter = (Node) xpath.evaluate("ogc:Filter", ndConstraint, XPathConstants.NODE);
            ;
        }
        if (ndFilter == null) {
            String msg = "The supplied constraint was not a valid ogc:Filter.";
            throw new OwsException(OwsException.OWSCODE_NoApplicableCode, "constraint", msg);
        } else {
            return ndFilter;
        }

    } catch (SAXException e) {
        String msg = "The supplied namespace/constraint pairs were not well-formed xml: ";
        msg += " " + e.toString();
        throw new OwsException(OwsException.OWSCODE_NoApplicableCode, "constraint", msg);
    }

}

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

/**
 * This method takes the ER response and converts the Java objects to the Merge Response XML.
 * /*from   www .  ja  v a  2  s  .  c  o  m*/
 * @param entityContainerNode
 * @param results
 * @param recordLimit
 * @param attributeParametersNode
 * @return
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 * @throws TransformerException
 */
private Document createResponseMessage(Node entityContainerNode, EntityResolutionResults results,
        Node attributeParametersNode, int recordLimit) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    Document resultDocument = dbf.newDocumentBuilder().newDocument();

    Element entityMergeResultMessageElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityMergeResultMessage");
    resultDocument.appendChild(entityMergeResultMessageElement);

    Element entityContainerElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityContainer");
    entityMergeResultMessageElement.appendChild(entityContainerElement);

    NodeList inputEntityNodes = (NodeList) xpath.evaluate("er-ext:Entity", entityContainerNode,
            XPathConstants.NODESET);
    Collection<Element> inputEntityElements = null;
    if (attributeParametersNode == null) {
        inputEntityElements = new ArrayList<Element>();
    } else {
        inputEntityElements = TreeMultiset
                .create(new EntityElementComparator((Element) attributeParametersNode));
        //inputEntityElements = new ArrayList<Element>();
    }

    for (int i = 0; i < inputEntityNodes.getLength(); i++) {
        inputEntityElements.add((Element) inputEntityNodes.item(i));
    }

    if (attributeParametersNode == null) {
        LOG.warn("Attribute Parameters element was null, so records will not be sorted");
    }
    //Collections.sort((List<Element>) inputEntityElements, new EntityElementComparator((Element) attributeParametersNode));

    if (inputEntityElements.size() != inputEntityNodes.getLength()) {
        LOG.error("Lost elements in ER output sorting.  Input count=" + inputEntityNodes.getLength()
                + ", output count=" + inputEntityElements.size());
    }

    for (Element e : inputEntityElements) {
        Node clone = resultDocument.adoptNode(e.cloneNode(true));
        resultDocument.renameNode(clone, EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                e.getLocalName());
        entityContainerElement.appendChild(clone);
    }

    Element mergedRecordsElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "MergedRecords");
    entityMergeResultMessageElement.appendChild(mergedRecordsElement);

    if (results != null) {

        List<RecordWrapper> records = results.getRecords();

        // Loop through RecordWrappers to extract info to create merged records
        for (RecordWrapper record : records) {
            LOG.debug("  !#!#!#!# Record 1, id=" + record.getExternalId() + ", externals="
                    + record.getRelatedIds());

            // Create Merged Record Container
            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            // Create Original Record Reference for 'first record'
            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", record.getExternalId());
            mergedRecordElement.appendChild(originalRecordRefElement);

            // Loop through and add any related records
            for (String relatedRecordId : record.getRelatedIds()) {
                originalRecordRefElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
                originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                        "ref", relatedRecordId);
                mergedRecordElement.appendChild(originalRecordRefElement);
            }

            // Create Merge Quality Element
            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            Set<AttributeStatistics> stats = results.getStatisticsForRecord(record.getExternalId());
            for (AttributeStatistics stat : stats) {
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(stat.getAttributeName());
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode(String.valueOf(stat.getAverageStringDistance()));
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument
                        .createTextNode(String.valueOf(stat.getStandardDeviationStringDistance()));
                sdElement.appendChild(contentNode);

            }
        }

    } else {

        for (Element e : inputEntityElements) {

            String id = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "id");

            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", id);
            mergedRecordElement.appendChild(originalRecordRefElement);

            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            XPath xp = XPathFactory.newInstance().newXPath();
            xp.setNamespaceContext(new EntityResolutionNamespaceContext());
            NodeList attributeParameterNodes = (NodeList) xp.evaluate("er-ext:AttributeParameter",
                    attributeParametersNode, XPathConstants.NODESET);
            for (int i = 0; i < attributeParameterNodes.getLength(); i++) {
                String attributeName = xp.evaluate("er-ext:AttributeXPath", attributeParametersNode);
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(attributeName);
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode("0.0");
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument.createTextNode("0.0");
                sdElement.appendChild(contentNode);
            }

        }

    }

    Element recordLimitExceededElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "RecordLimitExceededIndicator");
    recordLimitExceededElement.setTextContent(new Boolean(results == null).toString());
    entityMergeResultMessageElement.appendChild(recordLimitExceededElement);

    return resultDocument;

}

From source file:com.amalto.core.util.Util.java

private static String[] getTextNodes(Node contextNode, String xPath, final Node namespaceNode)
        throws TransformerException {
    String[] results;//from  w w  w  . j  ava2s. c  o m
    // test for hard-coded values
    if (xPath.startsWith("\"") && xPath.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
        return new String[] { xPath.substring(1, xPath.length() - 1) };
    }
    // test for incomplete path (elements missing /text())
    if (!xPath.matches(".*@[^/\\]]+")) { // attribute
        if (!xPath.endsWith(")")) { // function
            xPath += "/text()";
        }
    }
    try {
        XPath path = XPathFactory.newInstance().newXPath();
        path.setNamespaceContext(new NamespaceContext() {

            @Override
            public String getNamespaceURI(String s) {
                return namespaceNode.getNamespaceURI();
            }

            @Override
            public String getPrefix(String s) {
                return namespaceNode.getPrefix();
            }

            @Override
            public Iterator getPrefixes(String s) {
                return Collections.singleton(namespaceNode.getPrefix()).iterator();
            }
        });
        NodeList xo = (NodeList) path.evaluate(xPath, contextNode, XPathConstants.NODESET);
        results = new String[xo.getLength()];
        for (int i = 0; i < xo.getLength(); i++) {
            results[i] = xo.item(i).getTextContent();
        }
    } catch (Exception e) {
        String err = "Unable to get the text node(s) of " + xPath + ": " + e.getClass().getName() + ": "
                + e.getLocalizedMessage();
        throw new TransformerException(err);
    }
    return results;

}

From source file:be.fgov.kszbcss.rhq.websphere.component.server.WebSphereServerDiscoveryComponent.java

public Set<DiscoveredResourceDetails> discoverResources(ResourceDiscoveryContext<ResourceComponent<?>> context)
        throws InvalidPluginConfigurationException, Exception {
    Set<DiscoveredResourceDetails> result = new HashSet<DiscoveredResourceDetails>();
    for (ProcessScanResult process : context.getAutoDiscoveredProcesses()) {
        ProcessInfo processInfo = process.getProcessInfo();
        String[] commandLine = processInfo.getCommandLine();
        if (log.isDebugEnabled()) {
            log.debug("Examining process " + processInfo.getPid());
            log.debug("Command line: " + Arrays.asList(commandLine));
        }//from   ww  w.  ja v a  2 s.  com
        int appOptionIndex = -1; // The index of the -application option
        for (int i = 0; i < commandLine.length; i++) {
            if (commandLine[i].equals("-application")) {
                appOptionIndex = i;
                break;
            }
        }
        if (appOptionIndex == -1) {
            log.debug("No -application option found");
            continue;
        }
        if (commandLine.length - appOptionIndex != 7) {
            if (log.isDebugEnabled()) {
                log.debug("Unexpected number of arguments (" + (commandLine.length - appOptionIndex)
                        + ") after -application");
            }
            continue;
        }
        if (!commandLine[appOptionIndex + 1].equals("com.ibm.ws.bootstrap.WSLauncher")) {
            log.debug("Expected com.ibm.ws.bootstrap.WSLauncher after -application");
            continue;
        }
        if (!commandLine[appOptionIndex + 2].equals("com.ibm.ws.runtime.WsServer")) {
            if (log.isDebugEnabled()) {
                log.debug("Process doesn't appear to be a WebSphere server process; main class is "
                        + commandLine[appOptionIndex + 2]);
            }
            continue;
        }
        File repository = new File(commandLine[appOptionIndex + 3]);
        String cell = commandLine[appOptionIndex + 4];
        String node = commandLine[appOptionIndex + 5];
        String processName = commandLine[appOptionIndex + 6];
        if (processName.equals("nodeagent")) {
            log.debug("Process appears to be a node agent");
            continue;
        }
        if (processName.equals("dmgr")) {
            log.debug("Process appears to be a deployment manager");
            continue;
        }
        log.info("Discovered WebSphere application server process " + cell + "/" + node + "/" + processName);
        if (!repository.exists()) {
            log.error("Configuration repository " + repository + " doesn't exist");
            continue;
        }
        if (!repository.canRead()) {
            log.error("Configuration repository " + repository + " not readable");
            continue;
        }

        // Parse the serverindex.xml file for the node
        File serverIndexFile = new File(repository, "cells" + File.separator + cell + File.separator + "nodes"
                + File.separator + node + File.separator + "serverindex.xml");
        if (log.isDebugEnabled()) {
            log.debug("Attempting to read " + serverIndexFile);
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document serverIndex;
        try {
            serverIndex = builder.parse(serverIndexFile);
        } catch (Exception ex) {
            log.error("Unable to parse " + serverIndexFile, ex);
            continue;
        }

        // Extract the port number
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
        nsContext.setPrefix("serverindex",
                "http://www.ibm.com/websphere/appserver/schemas/5.0/serverindex.xmi");
        xpath.setNamespaceContext(nsContext);
        int port = -1;
        String protocol = null;
        for (PortSpec portSpec : portSpecs) {
            if (log.isDebugEnabled()) {
                log.debug("Attempting to extract " + portSpec.getEndPointName());
            }
            String portString = (String) xpath.evaluate("/serverindex:ServerIndex/serverEntries[@serverName='"
                    + processName + "']/specialEndpoints[@endPointName='" + portSpec.getEndPointName()
                    + "']/endPoint/@port", serverIndex, XPathConstants.STRING);
            if (portString == null || portString.length() == 0) {
                log.debug(portSpec.getEndPointName() + " not found");
                continue;
            }
            int candidatePort;
            try {
                candidatePort = Integer.parseInt(portString);
            } catch (NumberFormatException ex) {
                log.warn("Found non numerical port number in " + serverIndexFile);
                continue;
            }
            if (log.isDebugEnabled()) {
                log.debug("Port is " + candidatePort);
            }
            if (candidatePort != 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Using " + portSpec.getEndPointName() + "=" + candidatePort + ", protocol "
                            + portSpec.getProtocol());
                }
                port = candidatePort;
                protocol = portSpec.getProtocol();
                break;
            }
        }
        if (port == -1) {
            log.error("Unable to locate usable port in " + serverIndexFile);
            continue;
        }

        // Check if this is a managed server by looking for WebSphere instances of type NODE_AGENT
        boolean unmanaged = ((NodeList) xpath.evaluate(
                "/serverindex:ServerIndex/serverEntries[@serverType='NODE_AGENT']", serverIndex,
                XPathConstants.NODESET)).getLength() == 0;

        Configuration conf = new Configuration();
        conf.put(new PropertySimple("host", "localhost"));
        conf.put(new PropertySimple("port", port));
        conf.put(new PropertySimple("protocol", protocol));
        conf.put(new PropertySimple("loggingProvider", "none")); // TODO: autodetect XM4WAS
        conf.put(new PropertySimple("childJmxServerName", "JVM"));
        conf.put(new PropertySimple("unmanaged", unmanaged));
        result.add(new DiscoveredResourceDetails(context.getResourceType(),
                cell + "/" + node + "/" + processName, processName, null,
                processName + " (cell " + cell + ", node " + node + ")", conf, processInfo));
    }
    return result;
}

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

@Test
public void testCreateLargeRecordSet() throws Exception {
    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);
    Element entityContainerElement = (Element) xp.evaluate(
            "/merge:EntityMergeRequestMessage/merge:MergeParameters/er-ext:EntityContainer", testRequestMessage,
            XPathConstants.NODE);
    assertNotNull(entityContainerElement);
    Element entityElement = (Element) xp.evaluate("er-ext:Entity[1]", entityContainerElement,
            XPathConstants.NODE);
    assertNotNull(entityElement);/* ww w  . ja  va 2s .  co  m*/
    int entityCount = ((NodeList) xp.evaluate("er-ext:Entity", entityContainerElement, XPathConstants.NODESET))
            .getLength();
    int expectedInitialEntityCount = 6;
    assertEquals(expectedInitialEntityCount, entityCount);
    int recordIncrement = 500;
    for (int i = 0; i < recordIncrement; i++) {
        Element newEntityElement = (Element) entityElement.cloneNode(true);
        entityContainerElement.appendChild(newEntityElement);
    }
    entityCount = ((NodeList) xp.evaluate("er-ext:Entity", entityContainerElement, XPathConstants.NODESET))
            .getLength();
    assertEquals(expectedInitialEntityCount + recordIncrement, entityCount);

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);
    assertNotNull(entityContainerNode);

    NodeList entityNodeList = ((Element) entityContainerNode)
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "Entity");
    List<RecordWrapper> records = entityResolutionMessageHandler.createRecordsFromRequestMessage(entityNodeList,
            null);
    assertEquals(expectedInitialEntityCount + recordIncrement, records.size());
}

From source file:de.huberlin.wbi.hiway.am.galaxy.GalaxyApplicationMaster.java

/**
 * A (recursive) helper function for parsing the parameters of a tool from their XML specification
 * /*from   w  w  w. j  ava2 s. c  om*/
 * @param el
 *            the XML element from which to commence the parsing
 * @return the set of parameters under this element
 * @throws XPathExpressionException
 */
private Set<GalaxyParam> getParams(Element el, GalaxyTool tool) throws XPathExpressionException {
    Set<GalaxyParam> params = new HashSet<>();
    XPath xpath = XPathFactory.newInstance().newXPath();

    // there are three different types of parameters in Galaxy's tool descriptions: atomic parameters, conditionals and repeats
    NodeList paramNds = (NodeList) xpath.evaluate("param", el, XPathConstants.NODESET);
    NodeList conditionalNds = (NodeList) xpath.evaluate("conditional", el, XPathConstants.NODESET);
    NodeList repeatNds = (NodeList) xpath.evaluate("repeat", el, XPathConstants.NODESET);

    // (1) parse atomic parameters
    for (int i = 0; i < paramNds.getLength(); i++) {
        Element paramEl = (Element) paramNds.item(i);
        String name = paramEl.getAttribute("name");
        GalaxyParamValue param = new GalaxyParamValue(name);
        params.add(param);

        // (a) determine default values and mappings of values
        String type = paramEl.getAttribute("type");
        switch (type) {
        case "data":
            param.addMapping("", "{\"path\": \"\"}");
            tool.setPath(name);
            break;
        case "boolean":
            String trueValue = paramEl.getAttribute("truevalue");
            param.addMapping("True", trueValue);
            String falseValue = paramEl.getAttribute("falsevalue");
            param.addMapping("False", falseValue);
            break;
        case "select":
            param.addMapping("", "None");
            break;
        default:
        }

        // (b) resolve references to Galaxy data tables
        NodeList optionNds = (NodeList) xpath.evaluate("option", paramEl, XPathConstants.NODESET);
        NodeList optionsNds = (NodeList) xpath.evaluate("options", paramEl, XPathConstants.NODESET);
        for (int j = 0; j < optionNds.getLength() + optionsNds.getLength(); j++) {
            Element optionEl = j < optionNds.getLength() ? (Element) optionNds.item(j)
                    : (Element) optionsNds.item(j - optionNds.getLength());
            if (optionEl.hasAttribute("from_data_table")) {
                String tableName = optionEl.getAttribute("from_data_table");
                GalaxyDataTable galaxyDataTable = galaxyDataTables.get(tableName);
                for (String value : galaxyDataTable.getValues()) {
                    param.addMapping(value, galaxyDataTable.getContent(value));
                }
            }
        }
    }

    // (2) parse conditionals, which consist of a single condition parameter and several "when condition equals" parameters
    for (int i = 0; i < conditionalNds.getLength(); i++) {
        Element conditionalEl = (Element) conditionalNds.item(i);
        String name = conditionalEl.getAttribute("name");
        GalaxyConditional conditional = new GalaxyConditional(name);

        NodeList conditionNds = (NodeList) xpath.evaluate("param", conditionalEl, XPathConstants.NODESET);
        NodeList whenNds = (NodeList) xpath.evaluate("when", conditionalEl, XPathConstants.NODESET);
        if (conditionNds.getLength() == 0 || whenNds.getLength() == 0)
            continue;

        Element conditionEl = (Element) conditionNds.item(0);
        name = conditionEl.getAttribute("name");
        GalaxyParamValue condition = new GalaxyParamValue(name);
        conditional.setCondition(condition);

        for (int j = 0; j < whenNds.getLength(); j++) {
            Element whenEl = (Element) whenNds.item(j);
            String conditionValue = whenEl.getAttribute("value");
            conditional.setConditionalParams(conditionValue, getParams(whenEl, tool));
        }

        params.add(conditional);
    }

    // (3) parse repeats, which consist of a list of parameters
    for (int i = 0; i < repeatNds.getLength(); i++) {
        Element repeatEl = (Element) repeatNds.item(i);
        String name = repeatEl.getAttribute("name");
        GalaxyRepeat repeat = new GalaxyRepeat(name);
        params.add(repeat);

        repeat.setParams(getParams(repeatEl, tool));
    }

    return params;
}