View Javadoc
1   /*
2    * Copyright 2009 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *     
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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  
21  import static java.util.Objects.requireNonNull;
22  import static org.openehealth.ipf.commons.xml.XmlUtils.rootElementName;
23  import static org.openehealth.ipf.commons.xml.XmlUtils.source;
24  
25  /**
26   * XSD- and Schematron-based validator for HL7 v3 messages.
27   * @author Dmytro Rud
28   */
29  public class CombinedXmlValidator implements Validator<String, CombinedXmlValidationProfile> {
30  
31      private static final XsdValidator XSD_VALIDATOR = new XsdValidator(CombinedXmlValidator.class.getClassLoader());
32      private static final SchematronValidator SCHEMATRON_VALIDATOR = new SchematronValidator();
33  
34  
35      public void validate(String message, CombinedXmlValidationProfile profile) throws ValidationException {
36          requireNonNull(profile, "validation profile must be not null");
37          // check whether the root element name is valid
38          String rootElementName = rootElementName(requireNonNull(message, "message must be not null"));
39          if (! profile.isValidRootElement(rootElementName)) {
40              throw new ValidationException("Invalid root element '" + rootElementName + "'");
41          }
42  
43          // XSD validation
44          String xsdPath = profile.getXsdPath(rootElementName);
45          if (xsdPath != null) {
46              XSD_VALIDATOR.validate(source(message), xsdPath);
47          }
48  
49          // Schematron validation
50          String schematronPath = profile.getSchematronPath(rootElementName);
51          if (schematronPath != null) {
52              SchematronProfile schematronProfile = new SchematronProfile(
53                      schematronPath,
54                      profile.getCustomSchematronParameters(rootElementName));
55              SCHEMATRON_VALIDATOR.validate(source(message), schematronProfile);
56          }
57      }
58  }