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:ch.dbs.actions.bestellung.EZBJOP.java

/**
 * This class uses the official EZB/ZDB API from
 * http://services.dnb.de/fize-service/gvr/full.xml.
 *///from   w ww.j  a v  a2s  . c om
public EZBForm read(final String content) {

    final EZBForm ezbform = new EZBForm();

    try {

        if (content != null) {

            final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
            final DocumentBuilder builder = domFactory.newDocumentBuilder();
            final Document doc = builder.parse(new InputSource(new StringReader(content)));

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

            // references electronic data
            //            final XPathExpression exprRefE = xpath.compile("//ElectronicData/References/Reference");
            //            final NodeList resultListRefE = (NodeList) exprRefE.evaluate(doc, XPathConstants.NODESET);
            //
            //            for (int i = 0; i < resultListRefE.getLength(); i++) {
            //                final Node firstResultNode = resultListRefE.item(i);
            //                final Element result = (Element) firstResultNode;
            //
            //                final EZBReference ref = new EZBReference();
            //
            //                // EZB URLs
            //                final String url = getValue(result.getElementsByTagName("URL"));
            //                ref.setUrl(url);
            //
            //                // Label for URLs
            //                final String label = getValue(result.getElementsByTagName("Label"));
            //                ref.setLabel(label);
            //
            //                ezbform.getReferencesonline().add(ref);
            //            }

            // electronic data
            final XPathExpression exprE = xpath.compile("//ElectronicData/ResultList/Result");
            final NodeList resultListE = (NodeList) exprE.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < resultListE.getLength(); i++) {
                final Node firstResultNode = resultListE.item(i);
                final Element result = (Element) firstResultNode;

                final EZBDataOnline online = new EZBDataOnline();

                // state
                online.setState(Integer.valueOf(result.getAttribute("state")));
                // 0 free accessible
                if (online.getState() == JOPState.FREE.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.free");
                    // 1 partially free accesible
                } else if (online.getState() == JOPState.FREE_PARTIALLY.getValue()) {
                    online.setAmpel("green");
                    online.setComment("availresult.partially_free");
                    // 2 licensed ; 3 partially licensed
                } else if (online.getState() == JOPState.LICENSED.getValue()
                        || online.getState() == JOPState.LICENSED_PARTIALLY.getValue()) {
                    online.setAmpel("yellow");
                    online.setComment("availresult.abonniert");
                    // journal not online for periode
                } else if (online.getState() == JOPState.OUTSIDE_PERIOD.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.timeperiode");
                    // not indexed
                } else if (online.getState() == JOPState.NO_HITS.getValue()) {
                    online.setAmpel("red");
                    online.setComment("availresult.nohits");
                } else {
                    online.setAmpel("red");
                    online.setComment("availresult.not_licensed");
                }

                // title
                String title = getValue(result.getElementsByTagName("Title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    online.setTitle(Jsoup.parse(title).text());
                }

                online.setUrl(getValue(result.getElementsByTagName("AccessURL")));
                online.setLevel(getValue(result.getElementsByTagName("AccessLevel")));
                online.setReadme(getValue(result.getElementsByTagName("ReadmeURL")));
                // National licenses etc.
                online.setAdditional(getValue(result.getElementsByTagName("Additional")));

                ezbform.getOnline().add(online);
            }

            // Title not found
            if (resultListE.getLength() == 0) {
                final EZBDataOnline online = new EZBDataOnline();
                online.setAmpel("red");
                online.setComment("availresult.nohits");
                online.setState(JOPState.NO_HITS.getValue());

                ezbform.getOnline().add(online);
            }

            // references print data
            final XPathExpression exprRefP = xpath.compile("//PrintData/References/Reference");
            final NodeList resultListRefP = (NodeList) exprRefP.evaluate(doc, XPathConstants.NODESET);

            final EZBReference ref = new EZBReference();

            for (int i = 0; i < resultListRefP.getLength(); i++) {
                final Node firstResultNode = resultListRefP.item(i);
                final Element result = (Element) firstResultNode;

                // EZB URLs
                ref.setUrl(getValue(result.getElementsByTagName("URL")));

                // Label for URLs
                //                final String label = getValue(result.getElementsByTagName("Label"));
                ref.setLabel("availresult.link_title_print");

                ezbform.getReferencesprint().add(ref);
            }

            // print data
            final XPathExpression exprP = xpath.compile("//PrintData/ResultList/Result");
            final NodeList resultListP = (NodeList) exprP.evaluate(doc, XPathConstants.NODESET);

            for (int i = 0; i < resultListP.getLength(); i++) {
                final Node firstResultNode = resultListP.item(i);
                final Element result = (Element) firstResultNode;

                final EZBDataPrint print = new EZBDataPrint();

                // state
                print.setState(Integer.valueOf(result.getAttribute("state")));

                // title
                String title = getValue(result.getElementsByTagName("Title"));
                if (title != null) {
                    title = Jsoup.clean(title, Whitelist.none());
                    print.setTitle(Jsoup.parse(title).text());
                }

                print.setLocation(getValue(result.getElementsByTagName("Location")));
                print.setCallnr(getValue(result.getElementsByTagName("Signature")));
                print.setCoverage(getValue(result.getElementsByTagName("Period")));

                // set previous extracted URL and label
                print.setInfo(ref);

                // in stock ; partially in stock
                if (print.getState() == JOPState.LICENSED.getValue()
                        || print.getState() == JOPState.LICENSED_PARTIALLY.getValue()) {
                    print.setAmpel("yellow");
                    print.setComment("availresult.print");
                    // only return if existing in Print
                    ezbform.getPrint().add(print);
                }
            }
        }

    } catch (final XPathExpressionException e) {
        LOG.error(e.toString());
    } catch (final SAXParseException e) {
        LOG.error(e.toString());
    } catch (final SAXException e) {
        LOG.error(e.toString());
    } catch (final IOException e) {
        LOG.error(e.toString());
    } catch (final ParserConfigurationException e) {
        LOG.error(e.toString());
    } catch (final Exception e) {
        LOG.error(e.toString());
    }

    return ezbform;
}

From source file:org.dasein.cloud.azure.Azure.java

public @Nullable String getStorageEndpoint() throws CloudException, InternalException {
    if (storageEndpoint == null) {
        ProviderContext ctx = getContext();

        if (ctx == null) {
            throw new AzureConfigException("No configuration was set for this request");
        }/*from  www .  jav a2s .  c  o  m*/
        AzureMethod method = new AzureMethod(this);

        Document xml = method.getAsXML(ctx.getAccountNumber(), "/services/storageservices");

        if (xml == null) {
            throw new CloudException("Unable to identify the blob endpoint");
        }
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        try {
            XPathExpression expr = xpath
                    .compile("(/StorageServices/StorageService/StorageServiceProperties[GeoPrimaryRegion='"
                            + ctx.getRegionId() + "']/Endpoints/Endpoint[contains(.,'.blob.')])[1]");
            storageEndpoint = expr.evaluate(xml).trim();
        } catch (XPathExpressionException e) {
            throw new CloudException("Invalid blob endpoint search expression");
        }

        if (storageEndpoint == null || storageEndpoint.isEmpty())
            storageEndpoint = null;
    }
    return storageEndpoint;
}

From source file:org.dasein.cloud.azure.Azure.java

public @Nullable String getStorageService() throws CloudException, InternalException {
    if (storageService == null) {
        ProviderContext ctx = getContext();

        if (ctx == null) {
            throw new AzureConfigException("No configuration was set for this request");
        }/*from  w w  w .j a v  a2s . co  m*/
        AzureMethod method = new AzureMethod(this);

        Document xml = method.getAsXML(ctx.getAccountNumber(), "/services/storageservices");

        if (xml == null) {
            throw new CloudException("Unable to identify the storage service");
        }
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();

        try {
            XPathExpression expr = xpath
                    .compile("(/StorageServices/StorageService/StorageServiceProperties[GeoPrimaryRegion='"
                            + ctx.getRegionId() + "']/../ServiceName)[1]");
            storageService = expr.evaluate(xml).trim();
        } catch (XPathExpressionException e) {
            throw new CloudException(
                    "Failed to find storage service in the current region: " + ctx.getRegionId());
        }

        if (storageService == null || storageService.isEmpty())
            storageService = null;
    }
    return storageService;
}

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

private int getResultNumber(Document currentResDom) throws Exception {
    int resultNum = 0;

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

    String xPathToResultNum = "/response/numMatches/text()";

    resultNum = Integer// ww w.  ja  v a2s  .c om
            .valueOf((String) xpath.evaluate(xPathToResultNum, currentResDom, XPathConstants.STRING));

    return resultNum;
}

From source file:com.hygenics.parser.ManualReplacement.java

private void transform() {
    log.info("Transforming");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    for (String fpath : fpaths) {
        log.info("FILE: " + fpath);
        try {//from  ww  w .  ja va  2  s .  c o  m
            // TRANSFORM
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File(fpath));
            Node root = doc.getFirstChild();
            XPathFactory xfactory = XPathFactory.newInstance();
            XPath xpath = xfactory.newXPath();
            String database = null;
            String path = "//transformation/connection";

            log.info("Removing");
            for (String dbname : remove) {
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + dbname.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                if (conn != null) {
                    root.removeChild(conn);
                }
            }

            log.info("Transforming");
            for (String key : databaseAttributes.keySet()) {
                database = key;
                log.info("XPATH:" + path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                XPathExpression xepr = xpath
                        .compile(path + "[descendant::name[contains(text(),'" + database.trim() + "')]]");
                Node conn = (Node) xepr.evaluate(doc, XPathConstants.NODE);

                if (conn != null) {
                    if (remove.contains(key)) {
                        root.removeChild(conn);
                    } else {
                        Map<String, String> attrs = databaseAttributes.get(database);
                        NodeList nl = conn.getChildNodes();
                        Set<String> keys = databaseAttributes.get(key).keySet();

                        for (int i = 0; i < nl.getLength(); i++) {
                            org.w3c.dom.Node n = nl.item(i);

                            if (keys.contains(n.getNodeName().trim())) {
                                n.setNodeValue(attrs.get(n.getNodeName()));
                            }
                        }
                    }
                }

                if (!this.log_to_table || (this.log_to_table && this.loggingTables != null)) {
                    log.info("Logging Manipulation");
                    log.info("PERFORMING LOGGING MANIPULATION: " + (!this.log_to_table) != null
                            ? "Removing Logging Data"
                            : "Adding Logging data");
                    String[] sections = new String[] { "trans-log-table", "perf-log-table", "channel-log-table",
                            "step-log-table", "metrics-log-table" };
                    for (String section : sections) {
                        log.info("Changing Settings for " + section);
                        xepr = xpath.compile("//" + section + "/field/enabled");
                        NodeList nodes = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET);
                        log.info("Nodes Found: " + Integer.toString(nodes.getLength()));
                        for (int i = 0; i < nodes.getLength(); i++) {
                            if (!this.log_to_table) {
                                nodes.item(i).setNodeValue("N");
                            } else {
                                nodes.item(i).setNodeValue("Y");
                            }
                        }

                        for (String nodeName : new String[] { "schema", "connection", "table",
                                "size_limit_lines", "interval", "timeout_days" }) {
                            if (!this.log_to_table) {
                                log.info("Changing Settings for Node: " + nodeName);
                                xepr = xpath.compile("//" + section + "/" + nodeName);
                                Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                                if (node != null) {
                                    if (!this.log_to_table) {
                                        node.setNodeValue(null);
                                    } else if (this.loggingTables.containsKey(section)
                                            && this.loggingTables.get(section).containsKey(nodeName)) {
                                        node.setNodeValue(this.loggingTables.get(section).get(nodeName));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // SET MAIN CONNECTION
            if (mainConnection != null) {
                XPathExpression xepr = xpath.compile(path);
                NodeList conns = (NodeList) xepr.evaluate(doc, XPathConstants.NODESET); // NodeSet is not a part of
                // org.w3c it is
                // actually a NodeList
                for (int i = 0; i < conns.getLength(); i++) {
                    if (!conns.item(i).hasChildNodes()) {// only connection
                        // elements
                        // without child
                        // nodes have
                        // text content
                        conns.item(i).setNodeValue(mainConnection);
                    }
                }
            }

            if (this.replacements != null) {
                for (String key : this.replacements.keySet()) {
                    XPathExpression xepr = xpath.compile(key);
                    Node node = (Node) xepr.evaluate(doc, XPathConstants.NODE);
                    if (node != null) {
                        for (String attrVal : this.replacements.get(key).keySet()) {
                            log.info("Replacing Information at " + key + "at " + attrVal);
                            log.info("Replacement Will Be: "
                                    + StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));

                            if (attrVal.toLowerCase().trim().equals("text")) {
                                node.setNodeValue(
                                        StringEscapeUtils.escapeXml11(this.replacements.get(key).get(attrVal)));
                                if (node.getNodeValue() == null) {
                                    node.setTextContent(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                }

                            } else {
                                NamedNodeMap nattrs = node.getAttributes();
                                Node n = nattrs.getNamedItem(attrVal);
                                if (n != null) {
                                    n.setNodeValue(StringEscapeUtils
                                            .escapeXml11(this.replacements.get(key).get(attrVal)));
                                } else {
                                    log.warn("Attribute Not Found " + attrVal);
                                }
                            }
                        }
                    } else {
                        log.warn("Node not found for " + key);
                    }
                }
            }

            // WRITE TO FILE
            log.info("Writing to File");
            TransformerFactory tfact = TransformerFactory.newInstance();
            Transformer transformer = tfact.newTransformer();
            DOMSource source = new DOMSource(doc);
            try (FileOutputStream stream = new FileOutputStream(new File(fpath))) {
                StreamResult result = new StreamResult(stream);
                transformer.transform(source, result);
                stream.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}

From source file:android.databinding.tool.store.LayoutFileParser.java

private File stripFileAndGetOriginal(File xml, String binderId)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    L.d("parsing resource file %s", xml.getAbsolutePath());
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(xml);
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    final XPathExpression commentElementExpr = xPath
            .compile("//comment()[starts-with(., \" From: file:\")][last()]");
    final NodeList commentElementNodes = (NodeList) commentElementExpr.evaluate(doc, XPathConstants.NODESET);
    L.d("comment element nodes count %s", commentElementNodes.getLength());
    if (commentElementNodes.getLength() == 0) {
        L.d("cannot find comment element to find the actual file");
        return null;
    }//from  w  w  w  .j a  va 2  s .  c  o m
    final Node first = commentElementNodes.item(0);
    String actualFilePath = first.getNodeValue().substring(" From:".length()).trim();
    L.d("actual file to parse: %s", actualFilePath);
    File actualFile = urlToFile(new java.net.URL(actualFilePath));
    if (!actualFile.canRead()) {
        L.d("cannot find original, skipping. %s", actualFile.getAbsolutePath());
        return null;
    }

    // now if file has any binding expressions, find and delete them
    // TODO we should rely on namespace to avoid parsing file twice
    boolean changed = isBindingLayout(doc, xPath);
    if (changed) {
        stripBindingTags(xml, binderId);
    }
    return actualFile;
}

From source file:com.rapid.core.Pages.java

public void loadpages(ServletContext servletContext)
        throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {

    // clear the pages
    _pages.clear();//  w ww. j a v a  2  s  . c o  m

    // force the pages to be resorted
    _sortedPageHeaders = null;

    // create a new map for caching page files by id's
    _pageHeaders = new HashMap<String, PageHeader>();

    // initiate pages folder 
    File pagesFolder = new File(_application.getConfigFolder(servletContext) + "/pages");

    // if the folder is there
    if (pagesFolder.exists()) {

        // these are not thread safe so can't be reused
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();

        // create objects for xml parsing          
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        // compile the xpath expressions
        XPathExpression xpathId = xpath.compile("/page/id");
        XPathExpression xpathName = xpath.compile("/page/name");
        XPathExpression xpathTitle = xpath.compile("/page/title");

        // loop the .page.xml files and add to the application
        for (File pageFile : pagesFolder.listFiles(_filenameFilter)) {

            // parse the xml file
            Document doc = docBuilder.parse(pageFile);

            // get the page id from the file
            String pageId = xpathId.evaluate(doc);
            // get the name
            String pageName = xpathName.evaluate(doc);
            // get the title
            String pageTitle = xpathTitle.evaluate(doc);

            // cache the page id against the file so we don't need to use the expensive parsing operation again
            _pageHeaders.put(pageId, new PageHeader(pageId, pageName, pageTitle, pageFile));

        }

    }

}

From source file:com.esri.geoportal.commons.csw.client.impl.Client.java

/**
 * Reads record from the stream//  ww w  . ja  va 2 s . c om
 *
 * @param contentStream content stream
 * @return list of records
 * @throws IOException if reading records fails
 * @throws TransformerConfigurationException if creating transformer fails
 * @throws TransformerException if creating transformer fails
 * @throws ParserConfigurationException if unable to create XML parser
 * @throws SAXException if unable to parse content
 * @throws XPathExpressionException if invalid XPath
 */
private List<IRecord> readRecords(InputStream contentStream)
        throws IOException, TransformerConfigurationException, TransformerException,
        ParserConfigurationException, SAXException, XPathExpressionException {
    ArrayList<IRecord> records = new ArrayList<>();

    // create transformer
    Templates template = TemplatesManager.getInstance().getTemplate(profile.getResponsexslt());
    Transformer transformer = template.newTransformer();

    // perform transformation
    StringWriter writer = new StringWriter();
    transformer.transform(new StreamSource(contentStream), new StreamResult(writer));

    LOG.trace(String.format("Received records:\n%s", writer.toString()));

    try (ByteArrayInputStream transformedContentStream = new ByteArrayInputStream(
            writer.toString().getBytes("UTF-8"))) {

        // create internal request DOM
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document resultDom = builder.parse(new InputSource(transformedContentStream));

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

        NodeList recordNodeList = (NodeList) xpath.evaluate("/Records/Record", resultDom,
                XPathConstants.NODESET);
        for (int i = 0; i < recordNodeList.getLength(); i++) {
            Node recordNode = recordNodeList.item(i);
            String id = (String) xpath.evaluate("ID", recordNode, XPathConstants.STRING);
            String strModifiedDate = (String) xpath.evaluate("ModifiedDate", recordNode, XPathConstants.STRING);
            Date modifedDate = parseIsoDate(strModifiedDate);
            IRecord record = new Record(id, modifedDate);
            records.add(record);
        }
    }

    return records;
}

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

/**
 * Process a single image, do the document mapping etc
 * // w w  w. j  a v  a2  s  . c o m
 * @param infosourceId
 * @param imageIndex
 * @param currentResDom
 * @throws Exception
 */
private void processSingleImage(int infosourceId, int imageIndex, Document currentResDom) throws Exception {

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    ParsedDocument pd = new ParsedDocument();

    String subject = MappingUtils.getSubject();

    String xPathToIdentifier = "//root/item[" + imageIndex + "]/url/text()";
    String xPathToScientificName = "//root/item[" + imageIndex + "]/scientificName/text()";
    String xPathToCommonName = "//root/item[" + imageIndex + "]/commonName/text()";
    String xPathToPhylum = "//root/item[" + imageIndex + "]/phylum/text()";
    String xPathToOrder = "//root/item[" + imageIndex + "]/order/text()";
    String xPathToGenus = "//root/item[" + imageIndex + "]/genus/text()";
    String xPathToSpecies = "//root/item[" + imageIndex + "]/species/text()";

    //        String xPathToImageUrl = "/response/object[" + imageIndex + "]/thumbUrl/text()";
    //        String xPathToLicense = "/response/object[" + imageIndex + "]/copyrightText/text()";
    //        String xPathToSpecificEpithet = "/response/object[" + imageIndex + "]/SpecificEpithet/text()";
    //        String xPathToCountry = "/response/object[" + imageIndex + "]/Country/text()";
    //        String xPathToLocality = "/response/object[" + imageIndex + "]/Locality/text()";

    String identifier = null;
    String scientificName = null;
    String phylum = null;
    String order = null;
    String genus = null;
    String commonName = null;
    String species = null;

    try {
        identifier = (String) xpath.evaluate(xPathToIdentifier, currentResDom, XPathConstants.STRING);
        scientificName = (String) xpath.evaluate(xPathToScientificName, currentResDom, XPathConstants.STRING);
        phylum = (String) xpath.evaluate(xPathToPhylum, currentResDom, XPathConstants.STRING);
        order = (String) xpath.evaluate(xPathToOrder, currentResDom, XPathConstants.STRING);
        genus = (String) xpath.evaluate(xPathToGenus, currentResDom, XPathConstants.STRING);
        commonName = (String) xpath.evaluate(xPathToCommonName, currentResDom, XPathConstants.STRING);
        species = (String) xpath.evaluate(xPathToSpecies, currentResDom, XPathConstants.STRING);

    } catch (XPathExpressionException getPageFragmentationError) {
        String errMsg = "Failed to obtain Detail Page Url";
        logger.error(errMsg);
        throw new Exception(errMsg, getPageFragmentationError);
    }

    //      System.out.println("Index: " + imageIndex);

    System.out.println(imageIndex + ", PHOTO URL:" + identifier);

    List<Triple<String, String, String>> triples = pd.getTriples();
    Map<String, String> dcs = pd.getDublinCore();

    pd.setGuid(identifier);
    pd.setContent(getContent(identifier));
    pd.setContentType(contentType);

    dcs.put(Predicates.DC_TITLE.toString(), scientificName);
    dcs.put(Predicates.DC_IDENTIFIER.toString(), identifier);
    //        dcs.put(Predicates.DC_LICENSE.toString(), "Creative Commons Attribution-Non Commercial 3.0 Australia License, http://creativecommons.org/licenses/by-nc/3.0/au/deed.en");
    //        dcs.put(Predicates.DC_CREATOR.toString(), license);
    dcs.put(Predicates.COUNTRY.toString(), "Australia");

    triples.add(new Triple(subject, Predicates.SCIENTIFIC_NAME.toString(), scientificName));
    triples.add(new Triple(subject, Predicates.PHYLUM.toString(), phylum));
    triples.add(new Triple(subject, Predicates.ORDER.toString(), order));
    triples.add(new Triple(subject, Predicates.GENUS.toString(), genus));
    triples.add(new Triple(subject, Predicates.SPECIES.toString(), species));
    triples.add(new Triple(subject, Predicates.COMMON_NAME.toString(), commonName));

    if (pd != null) {
        this.repository.storeDocument(infosourceId, pd);
        debugParsedDoc(pd);
    }

    String xpathToImageCount = "count(//root/item[" + imageIndex + "]/medium/media)";
    int imageCount = getCount(currentResDom, xpathToImageCount);

    System.out.println("item: " + imageIndex + ", counts: " + imageCount);

    for (int imgCounter = 1; imgCounter <= imageCount; imgCounter++) {
        String xPathToImageUrl = "//root/item[" + imageIndex + "]/medium/media[" + imgCounter
                + "]/filename/text()";
        String xPathToImageLicense = "//root/item[" + imageIndex + "]/medium/media[" + imgCounter
                + "]/rights/text()";
        String xPathToImageCreator = "//root/item[" + imageIndex + "]/medium/media[" + imgCounter
                + "]/acknowledgement/text()";
        String xPathToImageType = "//root/item[" + imageIndex + "]/medium/media[" + imgCounter
                + "]/type/text()";

        String imageUrl = null;
        String license = null;
        String creator = null;
        String type = null;

        try {
            imageUrl = (String) xpath.evaluate(xPathToImageUrl, currentResDom, XPathConstants.STRING);
            license = (String) xpath.evaluate(xPathToImageLicense, currentResDom, XPathConstants.STRING);
            creator = (String) xpath.evaluate(xPathToImageCreator, currentResDom, XPathConstants.STRING);
            type = (String) xpath.evaluate(xPathToImageType, currentResDom, XPathConstants.STRING);

        } catch (XPathExpressionException getPageFragmentationError) {
            String errMsg = "Failed to obtain Image details";
            logger.error(errMsg);
            throw new Exception(errMsg, getPageFragmentationError);
        }

        if (license != null && license.contains("CC BY") && imageUrl != null && !"".equals(imageUrl)
                && (type != null && (!type.contains("Thumb") && !type.contains("List")))) {
            ParsedDocument imageDoc = new ParsedDocument();
            System.out.println(type);
            imageDoc = MappingUtils.retrieveImageDocument(pd, imageUrl);

            if (imageDoc != null) {
                imageDoc.getDublinCore().put(Predicates.DC_LICENSE.toString(), license);
                if (creator != null && !"".equals(creator)) {
                    imageDoc.getDublinCore().put(Predicates.DC_CREATOR.toString(), creator);
                    imageDoc.getDublinCore().put(Predicates.DC_RIGHTS.toString(), creator);
                    debugParsedDoc(imageDoc);

                    this.repository.storeDocument(infosourceId, imageDoc);
                }
            }
        }

    }

}

From source file:org.apache.servicemix.wsn.jms.JmsSubscription.java

protected boolean doFilter(Element content) {
    if (contentFilter != null) {
        if (!contentFilter.getDialect().equals(XPATH1_URI)) {
            throw new IllegalStateException("Unsupported dialect: " + contentFilter.getDialect());
        }/*from w  w w  .jav a 2s .com*/
        try {
            XPathFactory xpfactory = XPathFactory.newInstance();
            XPath xpath = xpfactory.newXPath();
            XPathExpression exp = xpath.compile(contentFilter.getContent().get(0).toString());
            Boolean ret = (Boolean) exp.evaluate(content, XPathConstants.BOOLEAN);
            return ret.booleanValue();
        } catch (XPathExpressionException e) {
            log.warn("Could not filter notification", e);
        }
        return false;
    }
    return true;
}