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