64 lines
1.8 KiB
Java
64 lines
1.8 KiB
Java
package eu.dnetlib.data.mapping.cleaner;
|
|
|
|
import java.io.StringReader;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
import org.apache.commons.logging.Log;
|
|
import org.apache.commons.logging.LogFactory;
|
|
import org.dom4j.Document;
|
|
import org.dom4j.Element;
|
|
import org.dom4j.Namespace;
|
|
import org.dom4j.QName;
|
|
import org.dom4j.io.SAXReader;
|
|
|
|
import eu.dnetlib.data.mapping.RecordTransformer;
|
|
|
|
public class Cleaner extends RecordTransformer<String, String> {
|
|
|
|
private static final Log log = LogFactory.getLog(Cleaner.class);
|
|
|
|
private final List<VocabularyRule> rules = new ArrayList<>();
|
|
|
|
@Override
|
|
public String transform(final String source) {
|
|
|
|
try {
|
|
final List<Map<String, String>> errors = new ArrayList<>();
|
|
final Document doc = new SAXReader().read(new StringReader(source));
|
|
|
|
for (final VocabularyRule r : rules) {
|
|
errors.addAll(r.applyXpathRule(doc));
|
|
}
|
|
|
|
if (errors.size() > 0) {
|
|
markAsInvalid(doc, errors);
|
|
}
|
|
return doc.asXML();
|
|
} catch (final Exception e) {
|
|
log.error("Error evaluating rule", e);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private void markAsInvalid(final Document doc, final List<Map<String, String>> errors) {
|
|
final Element element = (Element) doc.selectSingleNode("//*[local-name()='header']");
|
|
if (element != null) {
|
|
final Element inv = element.addElement(new QName("invalid", new Namespace("dri", "http://www.driver-repository.eu/namespace/dri")));
|
|
for (final Map<String, String> e : errors) {
|
|
final Element err = inv.addElement(new QName("error", new Namespace("dri", "http://www.driver-repository.eu/namespace/dri")));
|
|
for (final Map.Entry<String, String> entry : e.entrySet()) {
|
|
err.addAttribute(entry.getKey(), entry.getValue());
|
|
}
|
|
}
|
|
inv.addAttribute("value", "true");
|
|
}
|
|
}
|
|
|
|
public List<VocabularyRule> getRules() {
|
|
return rules;
|
|
}
|
|
|
|
}
|