1
|
package eu.dnetlib.data.resultSet.cleaner;
|
2
|
|
3
|
import java.io.StringReader;
|
4
|
import java.util.ArrayList;
|
5
|
import java.util.List;
|
6
|
import java.util.Map;
|
7
|
|
8
|
import org.apache.commons.logging.Log;
|
9
|
import org.apache.commons.logging.LogFactory;
|
10
|
import org.dom4j.Document;
|
11
|
import org.dom4j.Element;
|
12
|
import org.dom4j.Namespace;
|
13
|
import org.dom4j.QName;
|
14
|
import org.dom4j.io.SAXReader;
|
15
|
|
16
|
import com.google.common.base.Function;
|
17
|
import com.google.common.collect.Lists;
|
18
|
|
19
|
public class Cleaner implements Function<String, String> {
|
20
|
|
21
|
private static final Log log = LogFactory.getLog(Cleaner.class);
|
22
|
|
23
|
private List<XPathCleaningRule> xpathRules = Lists.newArrayList();
|
24
|
|
25
|
public Cleaner(final List<XPathCleaningRule> xpathRules) {
|
26
|
this.xpathRules = xpathRules;
|
27
|
}
|
28
|
|
29
|
@Override
|
30
|
public String apply(final String text) {
|
31
|
|
32
|
try {
|
33
|
final List<Map<String, String>> errors = new ArrayList<Map<String, String>>();
|
34
|
final Document doc = new SAXReader().read(new StringReader(text));
|
35
|
for (final XPathCleaningRule r : xpathRules) {
|
36
|
errors.addAll(r.applyXpathRule(doc));
|
37
|
}
|
38
|
if (errors.size() > 0) {
|
39
|
markAsInvalid(doc, errors);
|
40
|
}
|
41
|
return doc.asXML();
|
42
|
} catch (final Exception e) {
|
43
|
log.error("Error evaluating rule", e);
|
44
|
}
|
45
|
return "";
|
46
|
}
|
47
|
|
48
|
private void markAsInvalid(final Document doc, final List<Map<String, String>> errors) {
|
49
|
final Element element = (Element) doc.selectSingleNode("//*[local-name()='header']");
|
50
|
if (element != null) {
|
51
|
final Element inv = element.addElement(new QName("invalid", new Namespace("dri", "http://www.driver-repository.eu/namespace/dri")));
|
52
|
for (final Map<String, String> e : errors) {
|
53
|
final Element err = inv.addElement(new QName("error", new Namespace("dri", "http://www.driver-repository.eu/namespace/dri")));
|
54
|
for (final Map.Entry<String, String> entry : e.entrySet()) {
|
55
|
err.addAttribute(entry.getKey(), entry.getValue());
|
56
|
}
|
57
|
}
|
58
|
inv.addAttribute("value", "true");
|
59
|
}
|
60
|
}
|
61
|
}
|