Example usage for javax.xml.xpath XPathExpression evaluate

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.bedework.notifier.outbound.email.EmailAdaptor.java

private List<TemplateResult> applyTemplates(final Action action) throws NoteException {
    final Note note = action.getNote();
    final NotificationType nt = note.getNotification();
    final EmailSubscription sub = EmailSubscription.rewrap(action.getSub());

    List<TemplateResult> results = new ArrayList<TemplateResult>();
    try {//from  w w w  .  java2 s  .c  o  m
        String prefix = nt.getParsed().getDocumentElement().getPrefix();

        if (prefix == null) {
            prefix = "default";
        }

        final String abstractPath = Util.buildPath(false, Note.DeliveryMethod.email.toString(), "/", prefix,
                "/", nt.getNotification().getElementName().getLocalPart());

        File templateDir = new File(Util.buildPath(false, globalConfig.getTemplatesPath(), "/", abstractPath));
        if (templateDir.isDirectory()) {

            Map<String, Object> root = new HashMap<String, Object>();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(nt.toXml(true))));
            Element el = doc.getDocumentElement();
            NodeModel.simplify(el);
            NodeModel.useJaxenXPathSupport();
            root.put("notification", el);

            HashSet<String> recipients = new HashSet<String>();
            for (String email : sub.getEmails()) {
                recipients.add(MAILTO + email);
            }
            root.put("recipients", recipients);

            if (globalConfig.getCardDAVHost() != null && globalConfig.getCardDAVPort() != 0
                    && globalConfig.getCardDAVContextPath() != null) {
                HashMap<String, Object> vcards = new HashMap<String, Object>();
                BasicHttpClient client;
                try {
                    ArrayList<Header> hdrs = new ArrayList<Header>();
                    BasicHeader h = new BasicHeader(HEADER_ACCEPT, globalConfig.getVCardContentType());
                    hdrs.add(h);

                    client = new BasicHttpClient(globalConfig.getCardDAVHost(), globalConfig.getCardDAVPort(),
                            null, 15 * 1000);

                    XPathExpression exp = xPath.compile("//*[local-name() = 'href']");
                    NodeList nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);

                    HashSet<String> vcardLookups = new HashSet<String>();
                    for (int i = 0; i < nl.getLength(); i++) {
                        Node n = nl.item(i);
                        String text = n.getTextContent();

                        text = pMailto.matcher(text).replaceFirst(MAILTO);
                        if (text.startsWith(MAILTO)
                                || text.startsWith(globalConfig.getCardDAVPrincipalsPath())) {
                            vcardLookups.add(text);
                        }
                    }

                    // Get vCards for recipients too. They may not be referenced in the notification.
                    vcardLookups.addAll(recipients);

                    for (String lookup : vcardLookups) {
                        String path = Util.buildPath(false,
                                globalConfig.getCardDAVContextPath() + "/" + lookup.replace(':', '/'));

                        final InputStream is = client.get(path + VCARD_SUFFIX, "application/text", hdrs);
                        if (is != null) {
                            ObjectMapper om = new ObjectMapper();
                            @SuppressWarnings("unchecked")
                            ArrayList<Object> hm = om.readValue(is, ArrayList.class);
                            vcards.put(lookup, hm);
                        }
                    }
                    root.put("vcards", vcards);
                } catch (final Throwable t) {
                    error(t);
                }
            }

            if (nt.getNotification() instanceof ResourceChangeType) {
                ResourceChangeType chg = (ResourceChangeType) nt.getNotification();
                BedeworkConnectorConfig cfg = ((BedeworkConnector) action.getConn()).getConnectorConfig();
                BasicHttpClient cl = getClient(cfg);
                List<Header> hdrs = getHeaders(cfg, new BedeworkSubscription(action.getSub()));

                String href = null;
                if (chg.getCreated() != null) {
                    href = chg.getCreated().getHref();
                } else if (chg.getDeleted() != null) {
                    href = chg.getDeleted().getHref();
                } else if (chg.getUpdated() != null && chg.getUpdated().size() > 0) {
                    href = chg.getUpdated().get(0).getHref();
                }

                if (href != null) {
                    if (chg.getDeleted() == null) {
                        // We only have an event for the templates on a create or update, not on delete.
                        ObjectMapper om = new ObjectMapper();
                        final InputStream is = cl.get(cfg.getSystemUrl() + href, null, hdrs);
                        JsonNode a = om.readValue(is, JsonNode.class);

                        // Check for a recurrence ID on this notification.
                        XPathExpression exp = xPath.compile("//*[local-name() = 'recurrenceid']/text()");
                        String rid = exp.evaluate(doc);
                        if (rid != null && !rid.isEmpty()) {
                            Calendar rcal = Calendar.getInstance();
                            recurIdFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                            rcal.setTime(recurIdFormat.parse(rid));

                            // Find the matching recurrence ID in the JSON, and make that the only vevent object.
                            Calendar c = Calendar.getInstance();
                            ArrayNode vevents = (ArrayNode) a.get(2);
                            for (JsonNode vevent : vevents) {
                                if (vevent.size() > 1 && vevent.get(1).size() > 1) {
                                    JsonNode n = vevent.get(1).get(0);
                                    if (n.get(0).asText().equals("recurrence-id")) {
                                        if (n.get(1).size() > 0 && n.get(1).get("tzid") != null) {
                                            jsonIdFormatTZ.setTimeZone(
                                                    TimeZone.getTimeZone(n.get(1).get("tzid").asText()));
                                            c.setTime(jsonIdFormatTZ.parse(n.get(3).asText()));
                                        } else {
                                            jsonIdFormatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
                                            c.setTime(jsonIdFormatUTC.parse(n.get(3).asText()));
                                        }
                                        if (rcal.compareTo(c) == 0) {
                                            vevents.removeAll();
                                            vevents.add(vevent);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        root.put("vevent", (ArrayList<Object>) om.convertValue(a, ArrayList.class));
                    }

                    // TODO: Provide some calendar information to the templates. This is currently the publisher's
                    // calendar, but needs to be fixed to be the subscriber's calendar.
                    String chref = href.substring(0, href.lastIndexOf("/"));
                    hdrs.add(new BasicHeader(HEADER_DEPTH, "0"));
                    int rc = cl.sendRequest("PROPFIND", cfg.getSystemUrl() + chref, hdrs, "text/xml",
                            CALENDAR_PROPFIND.length(), CALENDAR_PROPFIND.getBytes());
                    if (rc == HttpServletResponse.SC_OK || rc == SC_MULTISTATUS) {
                        Document d = builder.parse(new InputSource(cl.getResponseBodyAsStream()));
                        HashMap<String, String> hm = new HashMap<String, String>();
                        XPathExpression exp = xPath.compile("//*[local-name() = 'href']/text()");
                        hm.put("href", exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'displayname']/text()");
                        hm.put("name", (String) exp.evaluate(d));
                        exp = xPath.compile("//*[local-name() = 'calendar-description']/text()");
                        hm.put("description", (String) exp.evaluate(d));
                        root.put("calendar", hm);
                    }
                }
            }

            if (note.getExtraValues() != null) {
                root.putAll(note.getExtraValues());
            }

            DefaultObjectWrapper wrapper = new DefaultObjectWrapperBuilder(
                    Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS).build();
            root.put("timezone", (TemplateHashModel) wrapper.getStaticModels().get("java.util.TimeZone"));

            // Sort files so the user can control the order of content types/body parts of the email by template file name.
            File[] templates = templateDir.listFiles(templateFilter);
            Arrays.sort(templates);
            for (File f : templates) {
                Template template = fmConfig.getTemplate(Util.buildPath(false, abstractPath, "/", f.getName()));
                Writer out = new StringWriter();
                Environment env = template.createProcessingEnvironment(root, out);
                env.process();

                TemplateResult r = new TemplateResult(f.getName(), out.toString(), env);
                if (!r.getBooleanVariable("skip")) {
                    results.add(new TemplateResult(f.getName(), out.toString(), env));
                }
            }
        }
    } catch (final Throwable t) {
        throw new NoteException(t);
    }
    return results;
}

From source file:betullam.xmlmodifier.XMLmodifier.java

private boolean checkCondition(String condStructureType, String condMdName, String condMdValue, Document xmlDoc)
        throws XPathExpressionException {
    String textContent;/* w  w  w.  ja va  2s. c  om*/

    // Get the IDs for the requestet structure type, e. g. for "Monograph", "JournalVolume", etc.
    List<String> dmdIDs = getDMDIDs(condStructureType, xmlDoc);

    // Loop over the structure types and check if the metadata and it's value matches the requestet metadata and value.
    // E. g.: Only change a file if "TitleDocMain" (=condMdName) of a "Monograph" (=condMdValue) has the value "Title of the Monograph" (=condMdValue)
    for (String dmdID : dmdIDs) {

        // If we do not check for the value of the "name" attribute, we always have a match, so return true
        if (condMdName.equals("null")) {
            return true;
        } else {
            String xPathString = "//dmdSec[@ID=\"" + dmdID + "\"]//goobi/metadata[@name=\"" + condMdName
                    + "\"]";
            XPathFactory xPathFactory = XPathFactory.newInstance();
            XPath xPath = xPathFactory.newXPath();
            XPathExpression xPathExpr = xPath.compile(xPathString);
            NodeList nodeList = (NodeList) xPathExpr.evaluate(xmlDoc, XPathConstants.NODESET);

            // Check if there is at least 1 element with the given value (condMdName)
            if (nodeList.getLength() > 0) {
                if (condMdValue.equals("null")) { // If we do not check for the value of the element, we always have a match, so return true
                    return true;
                } else {
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        Element xmlElement = (Element) nodeList.item(i);
                        textContent = xmlElement.getTextContent();
                        if (textContent.equals(condMdValue)) {
                            // Return true immediatly if the condition is met, because there could be other values for a duplicate metadata, which could return false.
                            return true;
                        }
                    }
                }
            }
        }
    }
    return false;
}

From source file:eu.interedition.collatex.tools.CollationPipe.java

public static void start(CommandLine commandLine) throws Exception {
    List<SimpleWitness> witnesses = null;
    Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT;
    Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS;
    Comparator<Token> comparator = new EqualityTokenComparator();
    CollationAlgorithm collationAlgorithm = null;
    boolean joined = true;

    final String[] witnessSpecs = commandLine.getArgs();
    final InputStream[] inputStreams = new InputStream[witnessSpecs.length];
    for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) {
        try {/*from  ww  w . j a  v  a  2s  .c o  m*/
            inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]);
        } catch (MalformedURLException urlEx) {
            throw new ParseException("Invalid resource: " + witnessSpecs[wc]);
        }
    }

    if (inputStreams.length < 1) {
        throw new ParseException("No input resource(s) given");
    } else if (inputStreams.length < 2) {
        try (InputStream inputStream = inputStreams[0]) {
            final SimpleCollation collation = JsonProcessor.read(inputStream);
            witnesses = collation.getWitnesses();
            collationAlgorithm = collation.getAlgorithm();
            joined = collation.isJoined();
        }
    }

    final String script = commandLine.getOptionValue("s");
    try {
        final PluginScript pluginScript = (script == null
                ? PluginScript.read("<internal>", new StringReader(""))
                : PluginScript.read(argumentToInput(script)));

        tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer);
        normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer);
        comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator);
    } catch (IOException e) {
        throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage());
    }

    switch (commandLine.getOptionValue("a", "").toLowerCase()) {
    case "needleman-wunsch":
        collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator);
        break;
    case "medite":
        collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR);
        break;
    case "gst":
        collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2);
        break;
    default:
        collationAlgorithm = Optional.ofNullable(collationAlgorithm)
                .orElse(CollationAlgorithmFactory.dekker(comparator));
        break;
    }

    if (witnesses == null) {
        final Charset inputCharset = Charset
                .forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name()));
        final boolean xmlMode = commandLine.hasOption("xml");
        final XPathExpression tokenXPath = XPathFactory.newInstance().newXPath()
                .compile(commandLine.getOptionValue("xp", "//text()"));

        witnesses = new ArrayList<>(inputStreams.length);
        for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) {
            try (InputStream stream = inputStreams[wc]) {
                final String sigil = "w" + (wc + 1);
                if (!xmlMode) {
                    final BufferedReader reader = new BufferedReader(
                            new InputStreamReader(stream, inputCharset));
                    final StringWriter writer = new StringWriter();
                    final char[] buf = new char[1024];
                    while (reader.read(buf) != -1) {
                        writer.write(buf);
                    }
                    witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer));
                } else {
                    final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
                            .newDocumentBuilder();
                    final Document document = documentBuilder.parse(stream);
                    document.normalizeDocument();

                    final SimpleWitness witness = new SimpleWitness(sigil);
                    final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document,
                            XPathConstants.NODESET);
                    final List<Token> tokens = new ArrayList<>(tokenNodes.getLength());
                    for (int nc = 0; nc < tokenNodes.getLength(); nc++) {
                        final String tokenText = tokenNodes.item(nc).getTextContent();
                        tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText)));
                    }
                    witness.setTokens(tokens);
                    witnesses.add(witness);
                }
            }
        }
    }

    final VariantGraph variantGraph = new VariantGraph();
    collationAlgorithm.collate(variantGraph, witnesses);

    if (joined && !commandLine.hasOption("t")) {
        VariantGraph.JOIN.apply(variantGraph);
    }

    final String output = commandLine.getOptionValue("o", "-");
    final Charset outputCharset = Charset
            .forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name()));
    final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase();

    try (PrintWriter out = argumentToOutput(output, outputCharset)) {
        final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph);
        if ("csv".equals(outputFormat)) {
            serializer.toCsv(out);
        } else if ("dot".equals(outputFormat)) {
            serializer.toDot(out);
        } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) {
            XMLStreamWriter xml = null;
            try {
                xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
                xml.writeStartDocument(outputCharset.name(), "1.0");
                if ("graphml".equals(outputFormat)) {
                    serializer.toGraphML(xml);
                } else {
                    serializer.toTEI(xml);
                }
                xml.writeEndDocument();
            } catch (XMLStreamException e) {
                throw new IOException(e);
            } finally {
                if (xml != null) {
                    try {
                        xml.close();
                    } catch (XMLStreamException e) {
                        // ignored
                    }
                }
            }
        } else {
            JsonProcessor.write(variantGraph, out);
        }
    }
}

From source file:betullam.xmlmodifier.XMLmodifier.java

private Set<File> getFilesForInsertion(String condStructureElements, String mdDirectory) {
    Set<File> filesForInsertion = new HashSet<File>();
    List<String> lstStructureElements = Arrays.asList(condStructureElements.split("\\s*,\\s*"));
    // Iterate over all files in the given directory and it's subdirectories. Works with "FileUtils" in Apache "commons-io" library.

    //for (File mdFile : FileUtils.listFiles(new File(mdDirectory), new WildcardFileFilter(new String[]{"meta.xml", "meta_anchor.xml"}, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE)) {
    for (File mdFile : FileUtils.listFiles(new File(mdDirectory),
            new WildcardFileFilter("*.xml", IOCase.INSENSITIVE), TrueFileFilter.INSTANCE)) {
        // DOM Parser:
        String filePath = mdFile.getAbsolutePath();
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        Document xmlDoc = null;//from  w  ww .j  ava  2 s. c o m
        try {
            documentBuilder = documentFactory.newDocumentBuilder();
            xmlDoc = documentBuilder.parse(filePath);

            // Only get files with a structure element that is listed in condStructureElements
            for (String structureElement : lstStructureElements) {

                String xPathString = "/mets/structMap[@TYPE='LOGICAL']//div[@TYPE='" + structureElement + "']";
                XPathFactory xPathFactory = XPathFactory.newInstance();
                XPath xPath = xPathFactory.newXPath();
                XPathExpression xPathExpr = xPath.compile(xPathString);
                NodeList nodeList = (NodeList) xPathExpr.evaluate(xmlDoc, XPathConstants.NODESET);

                if (nodeList.getLength() > 0) {
                    filesForInsertion.add(mdFile);
                } else {
                }
            }

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

}

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Get references for a given article// w w w .  j a  v a  2s  . co  m
 * @param doc article xml
 * @return references
 */
public ArrayList<CitationReference> getReferences(Document doc) {
    ArrayList<CitationReference> list = new ArrayList<CitationReference>();

    if (doc == null) {
        return list;
    }

    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile("//back/ref-list[title='References']/ref");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList refList = (NodeList) result;

        if (refList.getLength() == 0) {
            expr = xpath.compile("//back/ref-list/ref");
            result = expr.evaluate(doc, XPathConstants.NODESET);
            refList = (NodeList) result;
        }

        XPathExpression typeExpr = xpath.compile("//citation | //nlm-citation");
        XPathExpression titleExpr = xpath.compile("//article-title");
        XPathExpression authorsExpr = xpath.compile("//person-group[@person-group-type='author']/name");
        XPathExpression journalExpr = xpath.compile("//source");
        XPathExpression volumeExpr = xpath.compile("//volume");
        XPathExpression numberExpr = xpath.compile("//label");
        XPathExpression fPageExpr = xpath.compile("//fpage");
        XPathExpression lPageExpr = xpath.compile("//lpage");
        XPathExpression yearExpr = xpath.compile("//year");
        XPathExpression publisherExpr = xpath.compile("//publisher-name");

        for (int i = 0; i < refList.getLength(); i++) {

            Node refNode = refList.item(i);
            CitationReference citation = new CitationReference();

            DocumentFragment df = doc.createDocumentFragment();
            df.appendChild(refNode);

            // citation type
            Object resultObj = typeExpr.evaluate(df, XPathConstants.NODE);
            Node resultNode = (Node) resultObj;
            if (resultNode != null) {
                NamedNodeMap nnm = resultNode.getAttributes();
                Node nnmNode = nnm.getNamedItem("citation-type");
                // some old articles do not have this attribute
                if (nnmNode != null) {
                    citation.setCitationType(nnmNode.getTextContent());
                }
            }

            // title
            resultObj = titleExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setTitle(resultNode.getTextContent());
            }

            // authors
            resultObj = authorsExpr.evaluate(df, XPathConstants.NODESET);
            NodeList resultNodeList = (NodeList) resultObj;
            ArrayList<String> authors = new ArrayList<String>();
            for (int j = 0; j < resultNodeList.getLength(); j++) {
                Node nameNode = resultNodeList.item(j);
                NodeList namePartList = nameNode.getChildNodes();
                String surName = "";
                String givenName = "";
                for (int k = 0; k < namePartList.getLength(); k++) {
                    Node namePartNode = namePartList.item(k);
                    if (namePartNode.getNodeName().equals("surname")) {
                        surName = namePartNode.getTextContent();
                    } else if (namePartNode.getNodeName().equals("given-names")) {
                        givenName = namePartNode.getTextContent();
                    }
                }
                authors.add(givenName + " " + surName);
            }

            citation.setAuthors(authors);

            // journal title
            resultObj = journalExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setJournalTitle(resultNode.getTextContent());
            }

            // volume
            resultObj = volumeExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setVolume(resultNode.getTextContent());
            }

            // citation number
            resultObj = numberExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setNumber(resultNode.getTextContent());
            }

            // citation pages
            String firstPage = null;
            String lastPage = null;
            resultObj = fPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                firstPage = resultNode.getTextContent();
            }

            resultObj = lPageExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                lastPage = resultNode.getTextContent();
            }

            if (firstPage != null) {
                if (lastPage != null) {
                    citation.setPages(firstPage + "-" + lastPage);
                } else {
                    citation.setPages(firstPage);
                }
            }

            // citation year
            resultObj = yearExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setYear(resultNode.getTextContent());
            }

            // citation publisher
            resultObj = publisherExpr.evaluate(df, XPathConstants.NODE);
            resultNode = (Node) resultObj;
            if (resultNode != null) {
                citation.setPublisher(resultNode.getTextContent());
            }

            list.add(citation);
        }

    } catch (Exception e) {
        log.error("Error occurred while gathering the citation references.", e);
    }

    return list;

}

From source file:betullam.xmlmodifier.XMLmodifier.java

private List<Node> getElementsToModify(String mdName, String mdValue, Document xmlDoc)
        throws XPathExpressionException {
    List<Node> nodeArrayList = new ArrayList<Node>();

    if (!mdName.equals("null")) {
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();
        XPathExpression xPathExpr = xPath.compile("//goobi/metadata[@name=\"" + mdName + "\"]");
        NodeList nodeList = (NodeList) xPathExpr.evaluate(xmlDoc, XPathConstants.NODESET);
        if (mdValue.equals("null")) {
            for (int n = 0; n < nodeList.getLength(); n++) {
                nodeArrayList.add(nodeList.item(n));
            }//from w  w  w  .ja va 2 s  .co m
        } else {
            for (int n = 0; n < nodeList.getLength(); n++) {
                Element xmlElement = (Element) nodeList.item(n);
                String textContent = xmlElement.getTextContent();
                if (textContent.equals(mdValue)) {
                    nodeArrayList.add(nodeList.item(n));
                }
            }
        }
    }

    return nodeArrayList;
}

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Get the author affiliations for a given article
 * @param doc article xml/* w  ww. j  a v  a 2s .  c o  m*/
 * @param doc article xml
 * @return author affiliations
 */
public ArrayList<AuthorExtra> getAuthorAffiliations(Document doc) {

    ArrayList<AuthorExtra> list = new ArrayList<AuthorExtra>();
    Map<String, String> affiliateMap = new HashMap<String, String>();

    if (doc == null) {
        return list;
    }

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

        XPathExpression affiliationListExpr = xpath.compile("//aff");
        XPathExpression affiliationAddrExpr = xpath.compile("//addr-line");

        NodeList affiliationNodeList = (NodeList) affiliationListExpr.evaluate(doc, XPathConstants.NODESET);

        // Map all affiliation id's to their affiliation strings
        for (int i = 0; i < affiliationNodeList.getLength(); i++) {
            Node node = affiliationNodeList.item(i);
            // Not all <aff>'s have the 'id' attribute.
            String id = (node.getAttributes().getNamedItem("id") == null) ? ""
                    : node.getAttributes().getNamedItem("id").getTextContent();
            // Not all <aff> id's are affiliations.
            if (id.startsWith("aff")) {
                DocumentFragment df = doc.createDocumentFragment();
                df.appendChild(node);
                String address = ((Node) affiliationAddrExpr.evaluate(df, XPathConstants.NODE))
                        .getTextContent();
                affiliateMap.put(id, address);
            }
        }

        XPathExpression authorExpr = xpath.compile("//contrib-group/contrib[@contrib-type='author']");
        XPathExpression surNameExpr = xpath.compile("//name/surname");
        XPathExpression givenNameExpr = xpath.compile("//name/given-names");
        XPathExpression affExpr = xpath.compile("//xref[@ref-type='aff']");

        NodeList authorList = (NodeList) authorExpr.evaluate(doc, XPathConstants.NODESET);

        for (int i = 0; i < authorList.getLength(); i++) {
            Node cnode = authorList.item(i);
            DocumentFragment df = doc.createDocumentFragment();
            df.appendChild(cnode);
            Node sNode = (Node) surNameExpr.evaluate(df, XPathConstants.NODE);
            Node gNode = (Node) givenNameExpr.evaluate(df, XPathConstants.NODE);

            // Either surname or givenName can be blank
            String surname = (sNode == null) ? "" : sNode.getTextContent();
            String givenName = (gNode == null) ? "" : gNode.getTextContent();
            // If both are null then don't bother to add
            if ((sNode != null) || (gNode != null)) {
                NodeList affList = (NodeList) affExpr.evaluate(df, XPathConstants.NODESET);
                ArrayList<String> affiliations = new ArrayList<String>();

                // Build a list of affiliations for this author
                for (int j = 0; j < affList.getLength(); j++) {
                    Node anode = affList.item(j);
                    String affId = anode.getAttributes().getNamedItem("rid").getTextContent();
                    affiliations.add(affiliateMap.get(affId));
                }

                AuthorExtra authorEx = new AuthorExtra();
                authorEx.setAuthorName(surname, givenName);
                authorEx.setAffiliations(affiliations);
                list.add(authorEx);
            }
        }
    } catch (Exception e) {
        log.error("Error occurred while gathering the author affiliations.", e);
    }

    return list;
}

From source file:betullam.xmlmodifier.XMLmodifier.java

private List<String> getDMDIDs(String structureType, Document xmlDoc) throws XPathExpressionException {
    List<String> lstDMDIDs = new ArrayList<String>();
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    XPathExpression xPathExpr = xPath
            .compile("//structMap[@TYPE=\"LOGICAL\"]//div[@DMDID][@TYPE=\"" + structureType + "\"]");
    NodeList nodeList = (NodeList) xPathExpr.evaluate(xmlDoc, XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); i++) {
        Element xmlElement = (Element) nodeList.item(i);
        String dmdId = xmlElement.getAttribute("DMDID");
        //System.out.println(dmdId + " = " + xmlElement.getAttribute("TYPE"));
        lstDMDIDs.add(dmdId);/*from   w ww  .j  a va2  s. c o m*/
    }
    return lstDMDIDs;
}

From source file:com.meltmedia.cadmium.servlets.guice.CadmiumListener.java

public String getVHostName(ServletContext context) {
    String jbossWebXml = context.getRealPath("/WEB-INF/jboss-web.xml");
    try {/*  ww  w  .j  av  a  2  s . c o m*/
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); // never forget this!
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(jbossWebXml);

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

        XPathExpression expr = xpath.compile("/jboss-web/virtual-host/text()");

        NodeList result = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

        if (result.getLength() > 0) {
            return result.item(0).getNodeValue();
        }

    } catch (Exception e) {
        log.warn("Failed to read/parse file.", e);
    }
    return WarUtils.getWarName(context);
}

From source file:com.photon.phresco.impl.DrupalApplicationProcessor.java

private void storeConfigObj(List<Configuration> configs, File featureManifestXmlFile, File featureSqlDir,
        String environmentName) throws PhrescoException {
    try {/*from www . ja va  2s  . c  o  m*/
        if (!featureManifestXmlFile.isFile()) {
            throw new PhrescoException("manifest file is not available");
        }

        // Document
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(featureManifestXmlFile);
        doc.getDocumentElement().normalize();

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

        for (Configuration configuration : configs) {
            Properties properties = configuration.getProperties();
            Enumeration em = properties.keys();
            while (em.hasMoreElements()) {
                String insertQuery = "";
                String insertFieldQuery = "";

                String deleteQuery = "";
                String deleteFieldQuery = "";

                String tableName = "";
                String variableName = "";
                String defaultValue = "";

                String constructedQuery = "";
                String key = (String) em.nextElement();
                Object object = properties.get(key);

                // get config object for this key
                String xPathQuery = CONFIG_XPATH + key + CONFIG_XPATH_END_TAG;
                XPathExpression xPathExpression = xPathInstance.compile(xPathQuery);
                //evalute the xpath query in the entire xml document and define the return type
                Object results = xPathExpression.evaluate(doc, XPathConstants.NODESET);
                NodeList nList = (NodeList) results;

                // config objects
                for (int i = 0; i < nList.getLength(); i++) {
                    Node nNode = nList.item(i);
                    // get config object values
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                        // getting child nodes to construct query
                        NodeList childNodes = nNode.getChildNodes();
                        for (int temp1 = 0; temp1 < childNodes.getLength(); temp1++) {
                            Node childNode = childNodes.item(temp1);
                            if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                                if (TABLE_NAME.equals(childNode.getNodeName())) {
                                    tableName = childNode.getTextContent();
                                    if (!VARIABLE_FIELD.equals(tableName)) {
                                        return;
                                    }
                                    deleteQuery = deleteQuery + DELETE_FROM + childNode.getTextContent() + WHERE
                                            + NAME_FIELD + EQUAL;
                                    insertQuery = insertQuery + INSERT_INTO + childNode.getTextContent()
                                            + VARIABLE_START_TAG + NAME_FIELD + SQL_VARIABLE_SEP + VALUE_FIELD
                                            + VARIABLE_END_TAG + VALUES_START_TAG;
                                } else if (VARIABLE_NAME.equals(childNode.getNodeName())) {
                                    variableName = childNode.getTextContent();
                                    deleteFieldQuery = SINGLE_QUOTE + childNode.getTextContent() + SINGLE_QUOTE
                                            + SEMI_COLON + LINE_BREAK;
                                } else if (CURRENT_VALUE.equals(childNode.getNodeName())) {
                                    childNode.setTextContent(object.toString());
                                }
                                defaultValue = object.toString();
                                insertFieldQuery = variableName + SQL_VALUE_SEP + defaultValue + VALUES_END_TAG;
                            }
                        }
                    }
                }

                constructedQuery = deleteQuery + deleteFieldQuery + insertQuery + insertFieldQuery;

                List<File> sqlFolders = getSqlFolders(featureSqlDir);
                for (File sqlFolder : sqlFolders) {
                    replaceSqlBlock(sqlFolder, CONFIGURATION + environmentName + DOT_SQL, key,
                            constructedQuery);
                }
            }
        }
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(doc), new StreamResult(featureManifestXmlFile.getPath()));
    } catch (Exception e) {
        throw new PhrescoException(e);
    }
}