001/**
002The contents of this file are subject to the Mozilla Public License Version 1.1 
003(the "License"); you may not use this file except in compliance with the License. 
004You may obtain a copy of the License at http://www.mozilla.org/MPL/ 
005Software distributed under the License is distributed on an "AS IS" basis, 
006WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the 
007specific language governing rights and limitations under the License. 
008
009The Original Code is "MessageValidator.java".  Description: 
010"Validates parsed message against MessageRules that are enabled according to runtime 
011 configuration information."
012 
013The Initial Developer of the Original Code is University Health Network. Copyright (C) 
0142002.  All Rights Reserved. 
015
016Contributor(s): ______________________________________. 
017
018Alternatively, the contents of this file may be used under the terms of the 
019GNU General Public License (the "GPL"), in which case the provisions of the GPL are 
020applicable instead of those above.  If you wish to allow use of your version of this 
021file only under the terms of the GPL and not to allow others to use your version 
022of this file under the MPL, indicate your decision by deleting  the provisions above 
023and replace  them with the notice and other provisions required by the GPL License.  
024If you do not delete the provisions above, a recipient may use your version of 
025this file under either the MPL or the GPL. 
026*/
027
028package ca.uhn.hl7v2.validation;
029
030import org.slf4j.Logger;
031import org.slf4j.LoggerFactory;
032
033import ca.uhn.hl7v2.HL7Exception;
034import ca.uhn.hl7v2.model.Message;
035import ca.uhn.hl7v2.util.Terser;
036
037/**
038 * Validation utilities for parsed and encoded messages.  
039 *  
040 * @author Bryan Tripp
041 */
042public class MessageValidator {
043
044    private static final MessageRule[] EMPTY_MESSAGE_RULES_ARRAY = new MessageRule[0];
045    private static final EncodingRule[] EMPTY_ENCODING_RULES_ARRAY = new EncodingRule[0];
046        private static final Logger ourLog = LoggerFactory.getLogger(MessageValidator.class);
047    
048    private ValidationContext myContext;
049    private boolean failOnError;
050
051    /**
052     * @param theContext context that determines which validation rules apply 
053     * @param theFailOnErrorFlag
054     */
055    public MessageValidator(ValidationContext theContext, boolean theFailOnErrorFlag) {
056        myContext = theContext;
057        failOnError = theFailOnErrorFlag;
058    }
059    
060    /**
061     * @param message a parsed message to validate (note that MSH-9-1 and MSH-9-2 must be valued)
062     * @return true if the message is OK
063     * @throws HL7Exception if there is at least one error and this validator is set to fail on errors
064     */
065    public boolean validate(Message message) throws HL7Exception {
066        if (message == null) {
067                throw new NullPointerException("Message may not be null");
068        }
069        
070        Terser t = new Terser(message);
071        
072        MessageRule[] rules = EMPTY_MESSAGE_RULES_ARRAY;
073        if (myContext != null) {
074                rules = myContext.getMessageRules(message.getVersion(), t.get("MSH-9-1"), t.get("MSH-9-2"));
075        }
076        
077        ValidationException toThrow = null;
078        boolean result = true;
079        for (int i = 0; i < rules.length; i++) {
080            ValidationException[] ex = rules[i].test(message);
081            for (int j = 0; j < ex.length; j++) {
082                result = false;
083                ourLog.error("Invalid message", ex[j]);
084                if (failOnError && toThrow == null) {
085                    toThrow = ex[j];
086                }
087            }
088        }
089        
090        if (toThrow != null) {
091            throw new HL7Exception("Invalid message", toThrow);
092        }
093        
094        return result;
095    }
096    
097    /**
098     * @param message an ER7 or XML encoded message to validate 
099     * @param isXML true if XML, false if ER7
100     * @param version HL7 version (e.g. "2.2") to which the message belongs
101     * @return true if the message is OK
102     * @throws HL7Exception if there is at least one error and this validator is set to fail on errors
103     */
104    public boolean validate(String message, boolean isXML, String version) throws HL7Exception {
105        
106        EncodingRule[] rules = EMPTY_ENCODING_RULES_ARRAY;
107        if (myContext != null) {
108                rules = myContext.getEncodingRules(version, isXML ? "XML" : "ER7");
109        }
110        
111        ValidationException toThrow = null;
112        boolean result = true;
113        for (int i = 0; i < rules.length; i++) {
114            ValidationException[] ex = rules[i].test(message);
115            for (int j = 0; j < ex.length; j++) {
116                result = false;
117                ourLog.error("Invalid message", ex[j]);
118                if (failOnError && toThrow == null) {
119                    toThrow = ex[j];
120                }
121            }
122        }
123        
124        if (toThrow != null) {
125            throw new HL7Exception("Invalid message", toThrow);
126        }
127
128        return result;
129    }
130}