1 package net.sf.mavenhist.extractor;
2
3 import javax.xml.transform.TransformerException;
4
5 import org.apache.commons.lang.StringUtils;
6 import org.apache.xpath.XPathAPI;
7 import org.apache.xpath.objects.XObject;
8 import org.w3c.dom.Document;
9
10 /**
11 * Default implementation for a <code>IValueExtractor</code>. Supports the easy usage of
12 * a XPath query.
13 */
14 public abstract class AbstractXPathValueExtractor extends AbstractValidatingXMLValueExtractor {
15
16 /**
17 * {@inheritDoc}
18 */
19 public final MultiMetric[] extractValidatedDocument(Document document)
20 throws TransformerException {
21 String version = getVersion(document);
22 String xpath = getXPath(version);
23
24 XObject xObject = XPathAPI.eval(document, xpath);
25 String string = xObject.str();
26 if (!StringUtils.isEmpty(string)) {
27 return new MultiMetric[] {new MultiMetric(null, string)};
28 }
29 return new MultiMetric[0];
30 }
31
32 /**
33 * Returns the XPath to get the required value of a specified XML version.
34 * @return XPath to get the required value.
35 */
36 protected abstract String getXPath(String version);
37
38 /**
39 * Returns the version of the underlying XML file. If nothing is defined <code>null<code> is returned.
40 * @return version of the underlying XML file or <code>null</code> if no version is provided.
41 *
42 * @throws TransformerException if version could not be found in the document
43 */
44 protected final String getVersion(Document document) throws TransformerException {
45 String xpath = getVersionXPath();
46 if (!StringUtils.isEmpty(xpath)) {
47 XObject xObject = XPathAPI.eval(document, xpath);
48
49 String result = xObject.str();
50 if (xObject.getType() == XObject.CLASS_NODESET) {
51 if (xObject.nodelist().getLength() > 0 && xObject.nodelist().item(0) != null) {
52 result = xObject.nodelist().item(0).getNodeValue();
53 }
54 }
55 return result;
56 }
57 return null;
58 }
59
60 /**
61 * Returns the XPath to get the version of the underlying XML file.
62 * @return XPath to get the version of the underlying XML file or <code>null</code> if no version is available.
63 */
64 protected String getVersionXPath() {
65 return null;
66 }
67 }