Coverage Report - ca.uhn.hl7v2.validation.impl.ConformanceProfileRule
 
Classes in this File Line Coverage Branch Coverage Complexity
ConformanceProfileRule
83%
55/66
83%
15/18
2.273
ConformanceProfileRule$1
100%
2/2
50%
1/2
2.273
 
 1  
 /**
 2  
 The contents of this file are subject to the Mozilla Public License Version 1.1 
 3  
 (the "License"); you may not use this file except in compliance with the License. 
 4  
 You may obtain a copy of the License at http://www.mozilla.org/MPL/ 
 5  
 Software distributed under the License is distributed on an "AS IS" basis, 
 6  
 WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the 
 7  
 specific language governing rights and limitations under the License. 
 8  
 
 9  
 The Original Code is "ConformanceProfileRule.java".  Description: 
 10  
 "A MessageRule that checks conformance to message profiles." 
 11  
 
 12  
 The Initial Developer of the Original Code is University Health Network. Copyright (C) 
 13  
 2005.  All Rights Reserved. 
 14  
 
 15  
 Contributor(s): ______________________________________. 
 16  
 
 17  
 Alternatively, the contents of this file may be used under the terms of the 
 18  
 GNU General Public License (the "GPL"), in which case the provisions of the GPL are 
 19  
 applicable instead of those above.  If you wish to allow use of your version of this 
 20  
 file only under the terms of the GPL and not to allow others to use your version 
 21  
 of this file under the MPL, indicate your decision by deleting  the provisions above 
 22  
 and replace  them with the notice and other provisions required by the GPL License.  
 23  
 If you do not delete the provisions above, a recipient may use your version of 
 24  
 this file under either the MPL or the GPL. 
 25  
 */
 26  
 package ca.uhn.hl7v2.validation.impl;
 27  
 
 28  
 import java.io.IOException;
 29  
 import java.util.ArrayList;
 30  
 import java.util.Arrays;
 31  
 import java.util.LinkedHashMap;
 32  
 import java.util.List;
 33  
 import java.util.Map;
 34  
 
 35  
 import org.slf4j.Logger;
 36  
 import org.slf4j.LoggerFactory;
 37  
 
 38  
 import ca.uhn.hl7v2.HL7Exception;
 39  
 import ca.uhn.hl7v2.HapiContext;
 40  
 import ca.uhn.hl7v2.conf.ProfileException;
 41  
 import ca.uhn.hl7v2.conf.check.Validator;
 42  
 import ca.uhn.hl7v2.conf.parser.ProfileParser;
 43  
 import ca.uhn.hl7v2.conf.spec.RuntimeProfile;
 44  
 import ca.uhn.hl7v2.conf.store.ProfileStore;
 45  
 import ca.uhn.hl7v2.model.Message;
 46  
 import ca.uhn.hl7v2.util.Terser;
 47  
 import ca.uhn.hl7v2.validation.ValidationException;
 48  
 
 49  
 /**
 50  
  * A MessageRule that checks conformance to message profiles. Messages can either be tested 
 51  
  * against the profiles they declare, or against a pre-defined profile. If you want both, 
 52  
  * use two <code>ConformanceProfileRule</code>s.  
 53  
  * 
 54  
  * @author Bryan Tripp
 55  
  * @version $Revision: 1.1 $ updated on $Date: 2007-02-19 02:24:40 $ by $Author: jamesagnew $
 56  
  */
 57  30
 @SuppressWarnings("serial")
 58  
 public class ConformanceProfileRule extends AbstractMessageRule {
 59  
 
 60  5
     private static final Logger log = LoggerFactory.getLogger(ConformanceProfileRule.class);
 61  5
     private static final ProfileParser PARSER = new ProfileParser(true);
 62  
     private String myProfileID;
 63  20
     private boolean enableCaching = true;
 64  
 
 65  5
     private static final LinkedHashMap<String, RuntimeProfile> PROFILE_CACHE = new LinkedHashMap<String, RuntimeProfile>(100, 0.75f, true) {
 66  
         @Override
 67  
         protected boolean removeEldestEntry(Map.Entry<String, RuntimeProfile> eldest) {
 68  5
             return size() > 100;
 69  
         }
 70  
     };
 71  
 
 72  
     /**
 73  
      * Creates an instance that tests messages against whatever profiles they declare in 
 74  
      * MSH-21. The ID declared in MSH-21 is evaluated in a way that the corresponding
 75  
      * profile file is expected to be BASEDIR/profiles/ID.xml.
 76  
      */
 77  
     public ConformanceProfileRule() {
 78  20
             super();
 79  20
             setDescription("Unknown segments found in message");
 80  20
             setSectionReference("HL7 2.5 section 2.12");
 81  20
     }
 82  
     
 83  
     /**
 84  
      * @param theProfileID the ID of a constant profile against which to test all messages
 85  
      *      (instead of the profiles they declare in MSH-21). The ID is evaluated in a way
 86  
      *      that the corresponding profile file is expected to be BASEDIR/profiles/ID.xml.
 87  
      */
 88  
     public ConformanceProfileRule(String theProfileID) {
 89  15
             this();
 90  15
         myProfileID = theProfileID;
 91  15
     }
 92  
     
 93  
 
 94  
     /** 
 95  
      * @see ca.uhn.hl7v2.validation.MessageRule#test(ca.uhn.hl7v2.model.Message)
 96  
      */
 97  
     public ValidationException[] apply(Message msg) {
 98  30
         List<ValidationException> problems = new ArrayList<ValidationException>();
 99  30
         String[] ids = {myProfileID};
 100  
         
 101  
         try {
 102  30
             if (myProfileID == null) {
 103  15
                 ids = getDeclaredProfileIDs(msg);
 104  
             }
 105  
             
 106  60
             for (String id : ids) {
 107  30
                 log.debug("Testing message against profile: {}", id);
 108  
                 try {
 109  30
                     ValidationException[] shortList = testAgainstProfile(msg, id);
 110  30
                     log.debug("{} non-conformances", shortList.length);
 111  30
                     problems.addAll(Arrays.asList(shortList));
 112  0
                 } catch (ProfileException e) {
 113  0
                     problems.add(new ValidationException("Can't validate against profile: " + e.getMessage(), e));
 114  30
                 }
 115  
             }            
 116  0
         } catch (HL7Exception e) {
 117  0
             problems.add(new ValidationException("Can't validate against profile: " + e.getMessage(), e));
 118  30
         }
 119  
         
 120  30
         return problems.toArray(new ValidationException[problems.size()]);
 121  
     }
 122  
     
 123  
     private String[] getDeclaredProfileIDs(Message theMessage) throws HL7Exception {
 124  15
         Terser t = new Terser(theMessage);
 125  15
         boolean noMore = false;
 126  15
         int c = 0;
 127  15
         List<String> declaredProfiles = new ArrayList<String>(8);
 128  45
         while (!noMore) {
 129  30
             String path = "MSH-21(" + c++ + ")";
 130  30
             String idRep = t.get(path);
 131  
             //FIXME fails if empty rep precedes full rep ... should add getAll() to Terser and use that
 132  30
             if (idRep == null || idRep.equals("")) {
 133  15
                 noMore = true;
 134  
             } else {
 135  15
                 declaredProfiles.add(idRep);
 136  
             }
 137  30
         }
 138  15
         return declaredProfiles.toArray(new String[declaredProfiles.size()]);
 139  
     }
 140  
 
 141  
     private synchronized RuntimeProfile getProfile(String profileString) throws ProfileException {
 142  30
         RuntimeProfile profile = PROFILE_CACHE.get(profileString);
 143  30
         if (profile == null) {
 144  5
             profile = PARSER.parse(profileString);
 145  5
             if (enableCaching) PROFILE_CACHE.put(profileString, profile);
 146  
         }
 147  30
         return profile;
 148  
     }
 149  
 
 150  
     private ValidationException[] testAgainstProfile(Message message, String id) throws ProfileException, HL7Exception {
 151  
         HL7Exception[] exceptions;
 152  30
         HapiContext context = message.getParser().getHapiContext();
 153  30
         Validator validator = context.getConformanceValidator();
 154  
         try {
 155  30
             ProfileStore profileStore = context.getProfileStore();
 156  30
             String profileString = profileStore.getProfile(id);
 157  30
             if (profileString != null) {
 158  30
                 RuntimeProfile profile = getProfile(profileString);
 159  30
                 exceptions = validator.validate(message, profile.getMessage());
 160  30
             } else {
 161  0
                 throw new ProfileException("Unable to find the profile " + id);
 162  
             }
 163  0
         } catch (IOException e) {
 164  0
             throw new ProfileException("Error retreiving profile " + id, e);
 165  30
         }
 166  
         
 167  30
         ValidationException[] result = new ValidationException[exceptions.length];
 168  265
         for (int i = 0; i < exceptions.length; i++) {
 169  235
             result[i] = ValidationException.fromHL7Exception(exceptions[i]);
 170  
         }
 171  30
         return result;
 172  
     }
 173  
     
 174  
 
 175  
     /** 
 176  
      * @see ca.uhn.hl7v2.validation.Rule#getDescription()
 177  
      */
 178  
     public String getDescription() {
 179  0
         return "expected conformance to declared or predefined message profiles";
 180  
     }
 181  
 
 182  
     /** 
 183  
      * @see ca.uhn.hl7v2.validation.Rule#getSectionReference()
 184  
      */
 185  
     public String getSectionReference() {
 186  0
         return "HL7 2.5 section 2.12";
 187  
     }
 188  
 
 189  
         public String getProfileID() {
 190  10
                 return myProfileID;
 191  
         }
 192  
 
 193  
     public void setEnableCaching(boolean enableCaching) {
 194  0
         this.enableCaching = enableCaching;
 195  0
     }
 196  
 }