1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.openehealth.ipf.commons.xml;
17
18 import org.openehealth.ipf.commons.core.modules.api.ValidationException;
19 import org.openehealth.ipf.commons.core.modules.api.Validator;
20 import org.openehealth.ipf.commons.xml.svrl.DiagnosticReference;
21 import org.openehealth.ipf.commons.xml.svrl.FailedAssert;
22 import org.openehealth.ipf.commons.xml.svrl.SchematronOutput;
23
24 import javax.xml.transform.Source;
25 import java.util.ArrayList;
26 import java.util.List;
27
28
29
30
31
32
33
34
35
36
37
38 public class SchematronValidator implements Validator<Source, SchematronProfile> {
39
40 private final SchematronTransmogrifier<SchematronOutput> schematronTransmogrifier =
41 new SchematronTransmogrifier<>(SchematronOutput.class);
42
43 public void validate(Source message, SchematronProfile profile) {
44 SchematronOutput svrl = schematronTransmogrifier.zap(message, profile);
45 List<ValidationException> exceptions = new ArrayList<>();
46 svrl.getActivePatternAndFiredRuleAndFailedAssert().stream()
47 .filter(o -> o instanceof FailedAssert)
48 .forEach(o -> {
49 FailedAssert failedAssert = (FailedAssert) o;
50 exceptions.add(new ValidationException(message(failedAssert)));
51 });
52 if (!exceptions.isEmpty()) {
53 throw new SchematronValidationException(exceptions, svrl);
54 }
55 }
56
57 private static String message(FailedAssert failedAssert) {
58 StringBuilder sb = new StringBuilder()
59 .append("Validation error at ")
60 .append(failedAssert.getLocation())
61 .append(" : ")
62 .append(failedAssert.getText());
63
64 if (!failedAssert.getDiagnosticReference().isEmpty()) {
65 sb.append("\nDetail:");
66 for (DiagnosticReference diagnosticReference : failedAssert.getDiagnosticReference()) {
67 sb.append('\n').append(diagnosticReference.getText());
68 }
69 }
70
71 return sb.toString();
72 }
73
74 }