View Javadoc
1   /*
2    * Copyright 2017 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.modules.hl7.validation;
17  
18  import ca.uhn.hl7v2.HL7Exception;
19  import ca.uhn.hl7v2.HapiContext;
20  import ca.uhn.hl7v2.Severity;
21  import ca.uhn.hl7v2.model.Message;
22  import ca.uhn.hl7v2.validation.impl.SimpleValidationExceptionHandler;
23  import org.openehealth.ipf.commons.core.modules.api.ValidationException;
24  
25  public class Validator {
26  
27      /**
28       * Validates an HL7v2 message.
29       *
30       * @param msg     message to be validated.
31       * @param context optional HAPI Context referencing validation rules.
32       *                When <code>null</code> then the message's own context will be used instead.
33       */
34      public static void validate(Message msg, HapiContext context) {
35          HapiContext ctx = context == null ? msg.getParser().getHapiContext() : context;
36  
37          // We could also write an exception handler on top of SimpleValidationExceptionHandler that
38          // encapsulates the behavior below, but that may restrict custom validation...
39          SimpleValidationExceptionHandler handler = new SimpleValidationExceptionHandler(ctx);
40          handler.setMinimumSeverityToCollect(Severity.ERROR);
41          try {
42              if (ctx.<Boolean>getMessageValidator().validate(msg, handler)) {
43                  throw new ValidationException("Message validation failed", handler.getExceptions());
44              }
45          } catch (HL7Exception hl7Exception) {
46              throw new ValidationException("Message validation failed", hl7Exception);
47          }
48      }
49  
50  }