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.kuali.mobility.maps.service.LocationServiceImpl.java

private List<Location> buildLocationsByCampusCodeFromXml(String groupCode, String xml) {
    List<Location> locations = new ArrayList<Location>();
    MapsGroup mapsGroup = this.getMapsGroupByCode(groupCode);
    if (mapsGroup != null) {
        if (!"".equals(xml)) {
            XPathFactory factory = XPathFactory.newInstance();
            XPath xPath = factory.newXPath();
            DocumentBuilderFactory dbf;
            try {
                dbf = DocumentBuilderFactory.newInstance();
                Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
                //Get all markers from XML
                NodeList nodes = (NodeList) xPath.evaluate("/markers/marker", doc, XPathConstants.NODESET);
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    if (node != null) {
                        NamedNodeMap nodeMap = node.getAttributes();
                        Location loc = new Location();
                        //                     loc.setCampus(campusCode);
                        // Code should be updated to assign an MIU-specific code
                        if (isNotNullNotEmptyAttribute(nodeMap, "miu")) {
                            loc.setCode(nodeMap.getNamedItem("miu").getNodeValue());
                        }//from w  ww.ja  va 2  s  . c om
                        if (isNotNullNotEmptyAttribute(nodeMap, "scd")) {
                            loc.setShortCode(nodeMap.getNamedItem("scd").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "cd")) {
                            loc.setBuildingCode(nodeMap.getNamedItem("cd").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "nm")) {
                            loc.setName(nodeMap.getNamedItem("nm").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "snm")) {
                            loc.setShortName(nodeMap.getNamedItem("snm").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "cty")) {
                            loc.setCity(nodeMap.getNamedItem("cty").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "sta")) {
                            loc.setState(nodeMap.getNamedItem("sta").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "str")) {
                            loc.setStreet(nodeMap.getNamedItem("str").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "zip")) {
                            loc.setZip(nodeMap.getNamedItem("zip").getNodeValue());
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "active")) {
                            Boolean active = new Boolean(nodeMap.getNamedItem("active").getNodeValue());
                            loc.setActive(active);
                        } else {
                            loc.setActive(true);
                        }
                        if (isNotNullNotEmptyAttribute(nodeMap, "override")) {
                            Boolean override = new Boolean(nodeMap.getNamedItem("override").getNodeValue());
                            loc.setOverride(override);
                        } else {
                            loc.setOverride(false);
                        }

                        try {
                            loc.setLatitude(new Double(nodeMap.getNamedItem("lat").getNodeValue()));
                        } catch (Exception e) {
                        }
                        try {
                            loc.setLongitude(new Double(nodeMap.getNamedItem("lng").getNodeValue()));
                        } catch (Exception e) {
                        }

                        Set<MapsGroup> mapsGroups = new HashSet<MapsGroup>();
                        try {
                            if (isNotNullNotEmptyAttribute(nodeMap, "grp")) {
                                MapsGroup mapsGroupForThisLocation = this
                                        .getMapsGroupByCode(nodeMap.getNamedItem("grp").getNodeValue());
                                if (mapsGroupForThisLocation != null) {
                                    mapsGroups.add(mapsGroupForThisLocation);
                                } else {
                                    //                              LOG.info("Location " + loc.getName() + " (" + loc.getShortName() + ") assigned to default group because group " + nodeMap.getNamedItem("grp").getNodeValue() + " does not exist.");
                                    mapsGroups.add(mapsGroup);
                                }
                            } else {
                                mapsGroups.add(mapsGroup);
                            }
                        } catch (Exception e) {
                        }
                        loc.setMapsGroups(mapsGroups);
                        locations.add(loc);
                    }
                }
            } catch (Exception e) {
                //               LOG.info("Error loading data to group code: " + groupCode);
            }
        }
    } else {
        //         LOG.info("Error loading data to group code due to missing group: " + groupCode);
    }
    return locations;
}

From source file:dk.statsbiblioteket.doms.central.CentralWebserviceImpl.java

@Override
public SearchResultList findObjects(@WebParam(name = "query", targetNamespace = "") String query,
        @WebParam(name = "offset", targetNamespace = "") int offset,
        @WebParam(name = "pageSize", targetNamespace = "") int pageSize) throws MethodFailedException {
    try {/*from   w w w . ja  v a 2 s. c om*/
        log.trace("Entering findObjects with param query=" + query + ", offset=" + offset + ", pageSize="
                + pageSize);

        JSONObject jsonQuery = new JSONObject();
        jsonQuery.put("search.document.resultfields", "recordID, domsshortrecord");
        jsonQuery.put("search.document.query", query);
        jsonQuery.put("search.document.startindex", offset);
        jsonQuery.put("search.document.maxrecords", pageSize);

        SearchWS summaSearch = getSearchWSService();
        String searchResultString = summaSearch.directJSON(jsonQuery.toString());

        Document searchResultDOM = DOM.stringToDOM(searchResultString);
        XPath xPath = XPathFactory.newInstance().newXPath();

        NodeList nodeList = (NodeList) xPath.evaluate("//responsecollection/response/documentresult/record",
                searchResultDOM.getDocumentElement(), XPathConstants.NODESET);

        java.lang.Long hitCount = java.lang.Long
                .parseLong((String) (xPath.evaluate("//responsecollection/response/documentresult/@hitCount",
                        searchResultDOM.getDocumentElement(), XPathConstants.STRING)));

        SearchResultList searchResultList = new SearchResultList();
        searchResultList.setHitCount(hitCount);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            SearchResult searchResult = new SearchResult();

            Node shortRecordNode = (Node) xPath.evaluate("field[@name='domsshortrecord']", node,
                    XPathConstants.NODE);

            if (shortRecordNode != null) {
                Node shortRecord = DOM.stringToDOM(shortRecordNode.getTextContent()).getDocumentElement();
                String pid = xPath.evaluate("pid", shortRecord);
                String title = xPath.evaluate("title", shortRecord);
                searchResult.setPid(pid);
                if (title != null && !title.equals("")) {
                    searchResult.setTitle(title);
                } else {
                    searchResult.setTitle(pid);
                }
                searchResult.setType(xPath.evaluate("type", shortRecord));
                searchResult.setSource(xPath.evaluate("source", shortRecord));
                searchResult.setTime(xPath.evaluate("time", shortRecord));
                searchResult.setDescription(xPath.evaluate("description", shortRecord));
                searchResult.setState(xPath.evaluate("state", shortRecord));

                try {
                    searchResult.setCreatedDate(DatatypeConverter
                            .parseDateTime(xPath.evaluate("createdDate", shortRecord)).getTimeInMillis());
                } catch (IllegalArgumentException ignored) {
                }
                try {
                    searchResult.setModifiedDate(DatatypeConverter
                            .parseDateTime(xPath.evaluate("modifiedDate", shortRecord)).getTimeInMillis());
                } catch (IllegalArgumentException ignored) {
                }
            } else {
                String pid = xPath.evaluate("field[@name='recordID']/text()", node);
                pid = pid.substring(pid.indexOf(':') + 1);
                searchResult.setPid(pid);
                searchResult.setTitle(pid);
                searchResult.setDescription("");
                searchResult.setSource("");
                searchResult.setState("");
                searchResult.setTime("");
                searchResult.setType("");
            }

            searchResultList.getSearchResult().add(searchResult);
        }

        return searchResultList;

    } catch (XPathExpressionException e) {
        log.warn("Failed to execute method", e);
        throw new MethodFailedException("Method failed to execute", "Method failed to execute", e);
    } catch (Exception e) {
        log.warn("Caught Unknown Exception", e);
        throw new MethodFailedException("Server error", "Server error", e);
    }
}

From source file:org.dataconservancy.dcs.integration.main.ManualDepositIT.java

/**
 * Ensure that the <code>href</code> attribute values for &lt;collection&gt;s are valid URLs.
 *///from   w w w.j a v a  2s  .  c om
@Test
public void testServiceDocCollectionUrls() throws IOException, XPathExpressionException {
    final HttpGet req = new HttpGet(serviceDocUrl);
    final HttpResponse resp = client.execute(req);
    assertEquals("Unable to retrieve atompub service document " + serviceDocUrl, 200,
            resp.getStatusLine().getStatusCode());

    final XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            if ("app".equals(prefix) || prefix == null || "".equals(prefix)) {
                return ATOM_NS;
            }
            throw new RuntimeException("Unknown xmlns prefix: '" + prefix + "'");
        }

        @Override
        public String getPrefix(String nsUri) {
            if (ATOM_NS.equals(nsUri)) {
                return "app";
            }
            throw new RuntimeException("Unknown xmlns uri '" + nsUri + "'");
        }

        @Override
        public Iterator<String> getPrefixes(String s) {
            ArrayList<String> prefixes = new ArrayList<String>();
            prefixes.add("app");
            return prefixes.iterator();
        }
    });

    final String xpathExpression = "//app:collection/@href";
    final NodeList collectionHrefs = (NodeList) xpath.evaluate(xpathExpression,
            new InputSource(resp.getEntity().getContent()), XPathConstants.NODESET);

    assertTrue(
            "No atompub collections found in service document " + serviceDocUrl + " (xpath search '"
                    + xpathExpression + "' yielded no results.",
            collectionHrefs != null && collectionHrefs.getLength() > 0);

    for (int i = 0; i < collectionHrefs.getLength(); i++) {
        final String collectionUrl = collectionHrefs.item(i).getNodeValue();
        assertNotNull("atompub collection url was null.", collectionUrl);
        assertTrue("atompub collection url was the empty string.", collectionUrl.trim().length() > 0);
        new URL(collectionUrl);
        assertTrue("Expected atompub collection url to start with " + serviceDocUrl + " (collection url was: "
                + collectionUrl, collectionUrl.startsWith(serviceDocUrl));
    }
}

From source file:net.firejack.platform.api.content.ContentServiceTest.java

@Test
public void exportImportCollectionTest() {
    Folder folder = createFolder(domain.getId());

    Collection collection = new Collection();
    collection.setName(time + "-collection");
    collection.setParentId(folder.getId());
    collection.setType("COLLECTION");
    collection.setDescription("Some Description");

    ServiceResponse<RegistryNodeTree> response2 = OPFEngine.ContentService.createCollection(collection);
    Assert.assertTrue("Collection should be created.", response2.isSuccess());

    RegistryNodeTree registryNodeTree2 = response2.getItem();
    Assert.assertNotNull("Should not be null.", registryNodeTree2);
    collection.setId(registryNodeTree2.getId());

    ServiceResponse<FileInfo> response3 = OPFEngine.ContentService
            .exportCollectionArchiveFile(collection.getId());
    FileInfo fileInfo = response3.getItem();
    Assert.assertNotNull("Should not be null.", fileInfo);

    File contentArchive;//from w  w w.java2s  .c  om
    try {
        File tempDir = FileUtils.getTempDirectory();
        contentArchive = FileUtils.create(tempDir, "content.zip");
        InputStream stream = fileInfo.getStream();
        FileUtils.writeToFile(contentArchive, stream);
        IOUtils.closeQuietly(stream);

        ArchiveUtils.unZIP(contentArchive, tempDir);

        File contentXml = FileUtils.create(tempDir, "content.xml");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document document = factory.newDocumentBuilder().parse(contentXml);
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();
        Object evaluate = xpath.evaluate("/content/collection", document, XPathConstants.NODE);
        String collectionName = (String) xpath.evaluate("@name", evaluate, XPathConstants.STRING);
        Assert.assertEquals("Exported collection should be equal name.", collection.getName(), collectionName);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    ServiceResponse response4 = OPFEngine.ContentService.deleteCollection(collection.getId());
    Assert.assertTrue("Collection should be deleted.", response4.isSuccess());

    try {
        InputStream contentStream = FileUtils.openInputStream(contentArchive);
        ServiceResponse<FileInfo> response5 = OPFEngine.ContentService
                .importCollectionArchiveFile(contentStream);
        Assert.assertTrue("Import should be completed.", response5.isSuccess());
        IOUtils.closeQuietly(contentStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    ServiceResponse<Collection> response6 = OPFEngine.ContentService
            .readCollectionsByLikeLookup(folder.getLookup());
    Assert.assertTrue("Collections should be retrieved.", response6.isSuccess());

    Collection collection2 = response6.getItem();
    Assert.assertNotNull("Should not be null.", collection2);
    Assert.assertEquals("Should be the same name.", collection.getName(), collection2.getName());

    deleteFolder(folder);
}

From source file:es.itecban.deployment.executionmanager.gui.swf.service.CommonCreationManager.java

/**
 * //w w w .jav  a 2  s.c  o  m
 * @param context
 * @throws Exception
 */
public List<InstalledUnit> getInstalledUnits(RequestContext context, DeploymentGroup[] deploymentGroupArray,
        DeploymentTargetType environment) throws Exception {

    logger.fine("Getting the already installed units");
    // Get the selected unit
    String unitName = (String) context.getFlowScope().get(Constants.FLOW_SELECTED_UNIT_NAME);
    List<InstalledUnit> installedUnitList = new ArrayList<InstalledUnit>();
    // Getting the xml object
    String envXML = this.getEnvironmentXML(environment);

    InputStream is = null;
    try {
        is = new ByteArrayInputStream(envXML.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Get Xpath instance
    XPath xpath = XPathFactory.newInstance().newXPath();
    String expression = "";
    NodeList nodeSet = null;
    for (DeploymentGroup deploymentGroup : deploymentGroupArray) {
        List<DeploymentUnit> unitList = deploymentGroup.getUnits();
        for (DeploymentUnit unit : unitList) {
            // Asking with XPath to get the version of an specific unit
            expression = "//unit[name[text()='" + unit.getName() + "']]/version";
            try {
                is = new ByteArrayInputStream(envXML.getBytes());
                nodeSet = (NodeList) xpath.evaluate(expression, new InputSource(is), XPathConstants.NODESET);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String[] versionArray = new String[nodeSet.getLength()];
            for (int i = 0; i < nodeSet.getLength(); i++) {
                Element element = (Element) nodeSet.item(i);
                versionArray[i] = (String) element.getTextContent();
            }
            // if is an updating or deletion, the unit must exist in any
            // container
            if (versionArray.length == 0 && unit.getName().equals(unitName)
                    && ((context.getFlowScope().get(Constants.FLOW_OPERATION_FLOW))
                            .equals(Constants.FLOW_OPERATION_UPDATE)
                            || (context.getFlowScope().get(Constants.FLOW_OPERATION_FLOW))
                                    .equals(Constants.FLOW_OPERATION_DELETE))) {
                if ((context.getFlowScope().get(Constants.FLOW_OPERATION_FLOW))
                        .equals(Constants.FLOW_OPERATION_UPDATE)) {
                    String[] args = { unit.getName() + "_" + unit.getVersion(), "'UPDATE OPERATION'" };
                    ErrorUtils.createMessageError(context, "running.error.noSuitableContaierForUpdate", args);
                } else {
                    String[] args = { unit.getName() + "_" + unit.getVersion(), "'DELETE OPERATION'" };
                    ErrorUtils.createMessageError(context, "running.error.noSuitableContaierForUpdate", args);
                }

                throw new Exception();
            }

            // We have an array with the name of the containers where the
            // unit is in any version. Search with exact version has each
            // container
            for (String version : versionArray) {
                expression = "//nodeContainer[runtimeUnits/unit/name[text()='" + unit.getName()
                        + "'] and runtimeUnits/unit/version[text()='" + version + "']]/name";
                try {
                    is = new ByteArrayInputStream(envXML.getBytes());
                    nodeSet = (NodeList) xpath.evaluate(expression, new InputSource(is),
                            XPathConstants.NODESET);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                String[] containerArray = new String[nodeSet.getLength()];
                for (int i = 0; i < nodeSet.getLength(); i++) {
                    Element element = (Element) nodeSet.item(i);
                    containerArray[i] = (String) element.getTextContent();
                }
                if (containerArray.length > 0) {
                    InstalledUnit installedUnit = new InstalledUnit(unit.getName(), version, containerArray);
                    installedUnitList.add(installedUnit);
                }
            }
        }
    }
    return installedUnitList;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.validation.ClinicalXmlValidator.java

/**
 * This methods takes a W3C Document as well as an XPath expression suffix (the last part of an element's name)
 * and will retrieve the 3 date fields under the following XPath expressions:
 * <p/>/*from   ww w. ja  v a  2 s.c  o  m*/
 * "DAYOF" + suffix
 * "MONTHOF" + suffix
 * "YEAROF" + suffix
 * <p/>
 * It will then proceed to validate the date retrieved and return the result of this validation.
 *
 * @param document
 * @param xpath
 * @param xpathExpressionSuffix
 * @param context
 * @param dateNameToValueMap a Map to store the dates that need to be compared later
 * @param datePrecision a map to hold date precisions
 * @return <code>true</code> if the date retrieved is valid, <code>false</code> otherwise.
 * @throws XPathExpressionException
 */
private boolean checkDateForXPath(final Document document, final XPath xpath,
        final String xpathExpressionSuffix, final QcContext context, final Map<String, Date> dateNameToValueMap,
        final Map<String, String> datePrecision) throws XPathExpressionException, UnexpectedInput {

    boolean result = true;

    final NodeList yearOfNodes = (NodeList) xpath.evaluate(
            getXPathExpressionIgnoringNamespace(yearOfPrefix, xpathExpressionSuffix), document,
            XPathConstants.NODESET);
    final NodeList monthOfNodes = (NodeList) xpath.evaluate(
            getXPathExpressionIgnoringNamespace(monthOfPrefix, xpathExpressionSuffix), document,
            XPathConstants.NODESET);
    final NodeList dayOfNodes = (NodeList) xpath.evaluate(
            getXPathExpressionIgnoringNamespace(dayOfPrefix, xpathExpressionSuffix), document,
            XPathConstants.NODESET);

    //Need to make sure that yearOfNodes.getLength() == monthOfNodes.getLength() == dayOfNodes.getLength()
    //
    //Anything different should never happen, as the number of nodes found in for the 3 instances should always be the same
    //if the XML file respects the 'intgen.org_TCGA_ver1_17.xsd' schema
    if (yearOfNodes.getLength() != monthOfNodes.getLength()) {

        final String throwableMsg = "The number of nodes named '"
                + getXPathExpressionIgnoringNamespace(yearOfPrefix, xpathExpressionSuffix) + "' (Found "
                + yearOfNodes.getLength() + ")" + " is different from the number of nodes named '"
                + getXPathExpressionIgnoringNamespace(monthOfPrefix, xpathExpressionSuffix) + "' (Found "
                + monthOfNodes.getLength() + ")";

        throw new UnexpectedInput(throwableMsg);
    }

    if (yearOfNodes.getLength() != dayOfNodes.getLength()) {

        final String throwableMsg = "The number of nodes named '"
                + getXPathExpressionIgnoringNamespace(yearOfPrefix, xpathExpressionSuffix) + "' (Found "
                + yearOfNodes.getLength() + ")" + " is different from the number of nodes named '"
                + getXPathExpressionIgnoringNamespace(dayOfPrefix, xpathExpressionSuffix) + "' (Found "
                + dayOfNodes.getLength() + ")";

        throw new UnexpectedInput(throwableMsg);
    }

    //Getting the YEAROF, MONTHOF and DAYOF values for each Nodes
    String yearValue = null, monthValue = null, dayValue = null;
    for (int nodeIndex = 0; result == true && nodeIndex < yearOfNodes.getLength(); nodeIndex++) {

        //We can use the same index safely because XPath always returns nodes in document order
        //(See http://www.w3.org/TR/xpath/#dt-document-order)
        yearValue = yearOfNodes.item(nodeIndex).getTextContent().trim();
        monthValue = monthOfNodes.item(nodeIndex).getTextContent().trim();
        dayValue = dayOfNodes.item(nodeIndex).getTextContent().trim();

        //Update result
        result = validateDate(xpathExpressionSuffix, yearValue, monthValue, dayValue, context,
                dateNameToValueMap, datePrecision);
    }

    return result;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.validation.ClinicalXmlValidator.java

/**
 * Return <code>true</code> if there is a valid patient barcode contained in the given filename and if it matches the patient barcode in the file content,
 * <code>false</code> otherwise.
 *
 * Note: the patient barcode is valid if it has the expected format. It is not checked against actual values in the database.
 *
 * @param filename the filename to validate
 * @param document the document to parse
 * @param xpath <code>XPath</code> for XML parsing without namespace awareness
 * @param context the context/* w w w .  ja  v a  2  s.c  om*/
 * @return <code>true</code> if there is a valid patient barcode contained in the given filename and if it matches the patient barcode in the file content,
 * <code>false</code> otherwise.
 */
private Boolean checkPatientBarcode(final String filename, final Document document, final XPath xpath,
        final QcContext context) throws XPathExpressionException {

    Boolean result = true;

    final String patientBarcodeFromFilename = qcLiveBarcodeAndUUIDValidator.getPatientBarcode(filename);

    if (patientBarcodeFromFilename != null) {

        final NodeList patientBarcodeNodes = (NodeList) xpath.evaluate(PATIENT_BARCODE_XPATH_EXPRESSION,
                document, XPathConstants.NODESET);

        if (patientBarcodeNodes != null && patientBarcodeNodes.getLength() > 0) {

            if (patientBarcodeNodes.getLength() == 1) {

                final String patientBarcodeFromFileContent = patientBarcodeNodes.item(0).getTextContent();

                if (!patientBarcodeFromFileContent.equals(patientBarcodeFromFilename)) { // Patient barcodes don't match

                    result = false;
                    context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR,
                            filename,
                            new StringBuilder("The file '").append(filename).append("' has a patient barcode [")
                                    .append(patientBarcodeFromFileContent)
                                    .append("] that does not match the patient barcode found in the filename [")
                                    .append(patientBarcodeFromFilename).append("].")));
                }

            } else { // More than 1 patient barcode in XML
                //This shouldn't happen as long as the XSD requires that element to be unique, but this check is here in case that requirement is removed
                result = false;
                context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR, filename,
                        new StringBuilder("The file '").append(filename)
                                .append("' has more than one patient barcode element.")));
            }

        } else { // No patient barcode in XML
            //This shouldn't happen as long as the XSD requires that element, but this check is here in case that requirement is removed
            result = false;
            context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR, filename,
                    new StringBuilder("The file '").append(filename)
                            .append("' does not have any patient barcode element.")));
        }

    } else { // No patient barcode in filename

        result = false;
        context.addError(MessageFormat.format(MessagePropertyType.XML_FILE_PROCESSING_ERROR, filename,
                new StringBuilder("The filename '").append(filename)
                        .append("' does not contain a patient barcode.")));
    }

    return result;
}

From source file:jef.tools.XMLUtils.java

/**
 * XPATH/*w  w  w .ja  va  2 s  . co  m*/
 * 
 * @param startPoint
 *            
 * @param expr
 *            xpath?
 * @return xpath
 * @throws XPathExpressionException
 */
public static Node selectNode(Object startPoint, String expr) throws XPathExpressionException {
    XPath xpath = xp.newXPath();
    return (Node) xpath.evaluate(expr, startPoint, XPathConstants.NODE);
}

From source file:jef.tools.XMLUtils.java

/**
 * XPATH/*from w  ww. j a v  a  2 s .com*/
 * 
 * @param startPoint
 *            
 * @param expr
 *            xpath?
 * @return ?xpath
 * @throws XPathExpressionException
 */
public static NodeList selectNodes(Object startPoint, String expr) throws XPathExpressionException {
    XPath xpath = xp.newXPath();
    return (NodeList) xpath.evaluate(expr, startPoint, XPathConstants.NODESET);
}

From source file:com.esri.gpt.server.openls.provider.services.geocode.GeocodeProvider.java

/**
 * Handles an XML based request (normally HTTP POST).
 * //from ww w  .j ava 2 s  .co 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
 *             if a processing exception occurs
 */
public void handleXML(OperationContext context, Node root, XPath xpath) throws Exception {

    // initialize
    LOGGER.finer("Handling Geocode request XML...");
    GeocodeParams tOptions = context.getRequestOptions().getGeocodeOptions();
    ServiceProperties svcProps = context.getServiceProperties();
    ParseHelper pHelper = new ParseHelper();
    ValidationHelper vHelper = new ValidationHelper();
    String locator;
    String[] parsed;
    ISupportedValues supported;

    // service and version are parsed by the parent RequestHandler

    // output format
    locator = "@outputFormat";
    parsed = pHelper.getParameterValues(root, xpath, locator);
    supported = svcProps.getSupportedValues(XlsConstants.Parameter_OutputFormat);
    context.getOperationResponse().setOutputFormat(vHelper.validateValue(supported, locator, parsed, false));

    // request ID
    locator = "@requestId";
    parsed = pHelper.getParameterValues(root, xpath, locator);
    tOptions.setRequestId(vHelper.validateValue(locator, parsed, false));

    GeocodeParams reqParams = new GeocodeParams();
    locator = "xls:GeocodeRequest";
    Node ndReq = (Node) xpath.evaluate(locator, root, XPathConstants.NODE);
    if (ndReq != null) {
        parseRequest(reqParams, ndReq, xpath);
    }

    try {
        context.getRequestOptions().getGeocodeOptions().setgAddrList(executeRequest(context, reqParams));

    } catch (Throwable e) {
        e.printStackTrace();
    }
    generateResponse(context);
}