1 package net.sf.mavenhist.extractor;
2
3 import javax.xml.transform.TransformerException;
4
5 import org.apache.xpath.XPathAPI;
6 import org.w3c.dom.Document;
7 import org.w3c.dom.NodeList;
8
9 /**
10 * Used to validate the xml file with a test xpath that has to return a value.
11 */
12 public abstract class AbstractValidatingXMLValueExtractor extends AbstractXMLValueExtractor {
13
14 /**
15 * Implementation that checks first the validity of the xml file with the xpath given from the
16 * method <code>getValidityTestXPath</code>. If the check was successful the method <code>
17 * extractValidatedDocument</code> is called.
18 * {@inheritDoc}
19 */
20 public final MultiMetric[] extract(Document document) throws ExtractionException {
21 try {
22 if (isDocumentValid(document, getValidityTestXPath())) {
23 return extractValidatedDocument(document);
24 } else {
25 throw new ExtractionException(
26 "The given document was not valid to extract data: " + document.getLocalName(), null);
27 }
28 } catch (TransformerException e) {
29 throw new ExtractionException("Unable to validate document: " + document.getLocalName(), e);
30 }
31 }
32
33 /**
34 * Extracts muliple values from one result document.
35 * @param document to parse for the values.
36 * @return Array of metrics with the differentiated locations and values.
37 * @throws TransformerException the XML-Queries failed.
38 */
39 protected abstract MultiMetric[] extractValidatedDocument(Document document)
40 throws TransformerException;
41
42 /**
43 * Tests that the document is valid at all. When the given xpath returns at minimum 1 node the
44 * XML is taken as valid.
45 * @param document to search inside.
46 * @param xpath to check the document with.
47 * @return validity of the document.
48 * @throws TransformerException selection with xpath was not successful.
49 */
50 protected boolean isDocumentValid(Document document, String xpath) throws TransformerException {
51 NodeList nodeList = XPathAPI.selectNodeList(document, xpath);
52 return (nodeList.getLength() > 0);
53 }
54
55 /**
56 * The given xml-file will be tested with this xpath to be sure that the result will be valid.
57 * It is necessairy that the xpath query has a result to mark the XML as okay.
58 * @return XPath to check validity of the given file.
59 */
60 protected abstract String getValidityTestXPath();
61 }