Coverage Report - ca.uhn.hl7v2.parser.OldPipeParser
 
Classes in this File Line Coverage Branch Coverage Complexity
OldPipeParser
45%
140/311
39%
70/176
4.613
OldPipeParser$1
100%
4/4
100%
2/2
4.613
OldPipeParser$2
100%
4/4
N/A
4.613
OldPipeParser$MessageStructure
100%
4/4
N/A
4.613
 
 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 "PipeParser.java".  Description:
 10  
  * "An implementation of Parser that supports traditionally encoded (i.e"
 11  
  *
 12  
  * The Initial Developer of the Original Code is University Health Network. Copyright (C)
 13  
  * 2001.  All Rights Reserved.
 14  
  *
 15  
  * Contributor(s): Kenneth Beaton.
 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  
  */
 27  
 
 28  
 package ca.uhn.hl7v2.parser;
 29  
 
 30  
 import java.util.ArrayList;
 31  
 import java.util.List;
 32  
 import java.util.StringTokenizer;
 33  
 
 34  
 import org.slf4j.Logger;
 35  
 import org.slf4j.LoggerFactory;
 36  
 
 37  
 import ca.uhn.hl7v2.ErrorCode;
 38  
 import ca.uhn.hl7v2.HL7Exception;
 39  
 import ca.uhn.hl7v2.Version;
 40  
 import ca.uhn.hl7v2.model.Group;
 41  
 import ca.uhn.hl7v2.model.Message;
 42  
 import ca.uhn.hl7v2.model.Primitive;
 43  
 import ca.uhn.hl7v2.model.Segment;
 44  
 import ca.uhn.hl7v2.model.Structure;
 45  
 import ca.uhn.hl7v2.model.Type;
 46  
 import ca.uhn.hl7v2.util.FilterIterator;
 47  
 import ca.uhn.hl7v2.util.MessageIterator;
 48  
 import ca.uhn.hl7v2.util.Terser;
 49  
 
 50  
 /**
 51  
  * This is a legacy implementation of the PipeParser and should not be used
 52  
  * for new projects.
 53  
  *
 54  
  * In version 1.0 of HAPI, a behaviour was corrected where unexpected segments
 55  
  * would be placed at the tail end of the first segment group encountered. Any
 56  
  * legacy code which still depends on previous behaviour can use this
 57  
  * implementation.
 58  
  *
 59  
  * @author Bryan Tripp (bryan_tripp@sourceforge.net)
 60  
  * @deprecated
 61  
  */
 62  100
 class OldPipeParser extends Parser {
 63  
     
 64  5
     private static final Logger log = LoggerFactory.getLogger(OldPipeParser.class);
 65  
     
 66  
     private final static String segDelim = "\r"; //see section 2.8 of spec
 67  
     
 68  
     /** Creates a new PipeParser */
 69  0
     public OldPipeParser() {
 70  0
     }
 71  
 
 72  
     /** 
 73  
      * Creates a new PipeParser 
 74  
      *  
 75  
      * @param theFactory custom factory to use for model class lookup 
 76  
      */
 77  
     public OldPipeParser(ModelClassFactory theFactory) {
 78  5
             super(theFactory);
 79  5
     }
 80  
     
 81  
     /**
 82  
      * Returns a String representing the encoding of the given message, if
 83  
      * the encoding is recognized.  For example if the given message appears
 84  
      * to be encoded using HL7 2.x XML rules then "XML" would be returned.
 85  
      * If the encoding is not recognized then null is returned.  That this
 86  
      * method returns a specific encoding does not guarantee that the
 87  
      * message is correctly encoded (e.g. well formed XML) - just that
 88  
      * it is not encoded using any other encoding than the one returned.
 89  
      */
 90  
     public String getEncoding(String message) {
 91  5
         String encoding = null;
 92  
         
 93  
         //quit if the string is too short
 94  5
         if (message.length() < 4)
 95  0
             return null;
 96  
         
 97  
         //see if it looks like this message is | encoded ...
 98  5
         boolean ok = true;
 99  
         
 100  
         //string should start with "MSH"
 101  5
         if (!message.startsWith("MSH"))
 102  0
             return null;
 103  
         
 104  
         //4th character of each segment should be field delimiter
 105  5
         char fourthChar = message.charAt(3);
 106  5
         StringTokenizer st = new StringTokenizer(message, String.valueOf(segDelim), false);
 107  35
         while (st.hasMoreTokens()) {
 108  30
             String x = st.nextToken();
 109  30
             if (x.length() > 0) {
 110  30
                 if (Character.isWhitespace(x.charAt(0)))
 111  0
                     x = stripLeadingWhitespace(x);
 112  30
                 if (x.length() >= 4 && x.charAt(3) != fourthChar)
 113  0
                     return null;
 114  
             }
 115  30
         }
 116  
         
 117  
         //should be at least 11 field delimiters (because MSH-12 is required)
 118  5
         int nextFieldDelimLoc = 0;
 119  60
         for (int i = 0; i < 11; i++) {
 120  55
             nextFieldDelimLoc = message.indexOf(fourthChar, nextFieldDelimLoc + 1);
 121  55
             if (nextFieldDelimLoc < 0)
 122  0
                 return null;
 123  
         }
 124  
         
 125  5
         if (ok)
 126  5
             encoding = "VB";
 127  
         
 128  5
         return encoding;
 129  
     }
 130  
     
 131  
     /**
 132  
      * @return the preferred encoding of this Parser
 133  
      */
 134  
     public String getDefaultEncoding() {
 135  0
         return "VB";
 136  
     }
 137  
     
 138  
     /**
 139  
      * Returns true if and only if the given encoding is supported
 140  
      * by this Parser.
 141  
      */
 142  
     public boolean supportsEncoding(String encoding) {
 143  5
         boolean supports = false;
 144  5
         if (encoding != null && encoding.equals("VB"))
 145  5
             supports = true;
 146  5
         return supports;
 147  
     }
 148  
     
 149  
     /**
 150  
      * @deprecated this method should not be public 
 151  
      * @param message
 152  
      * @return
 153  
      * @throws HL7Exception
 154  
      * @throws EncodingNotSupportedException
 155  
      */
 156  
     public String getMessageStructure(String message) throws HL7Exception, EncodingNotSupportedException {
 157  0
         return getStructure(message).messageStructure;
 158  
     }
 159  
     
 160  
     /**
 161  
      * @returns the message structure from MSH-9-3
 162  
      */
 163  
     private MessageStructure getStructure(String message) throws HL7Exception, EncodingNotSupportedException {
 164  5
         EncodingCharacters ec = getEncodingChars(message);
 165  5
         String messageStructure = null;
 166  5
         boolean explicityDefined = true;
 167  
         String wholeFieldNine;
 168  
         try {
 169  10
             String[] fields = split(message.substring(0, Math.max(message.indexOf(segDelim), message.length())),
 170  5
                 String.valueOf(ec.getFieldSeparator()));
 171  5
             wholeFieldNine = fields[8];
 172  
             
 173  
             //message structure is component 3 but we'll accept a composite of 1 and 2 if there is no component 3 ...
 174  
             //      if component 1 is ACK, then the structure is ACK regardless of component 2
 175  5
             String[] comps = split(wholeFieldNine, String.valueOf(ec.getComponentSeparator()));
 176  5
             if (comps.length >= 3) {
 177  0
                 messageStructure = comps[2];
 178  5
             } else if (comps.length > 0 && comps[0] != null && comps[0].equals("ACK")) {
 179  0
                 messageStructure = "ACK";
 180  5
             } else if (comps.length == 2) {
 181  5
                 explicityDefined = false;
 182  5
                 messageStructure = comps[0] + "_" + comps[1];
 183  
             }
 184  
             /*else if (comps.length == 1 && comps[0] != null && comps[0].equals("ACK")) {
 185  
                 messageStructure = "ACK"; //it's common for people to only populate component 1 in an ACK msg
 186  
             }*/
 187  
             else {
 188  0
                 StringBuffer buf = new StringBuffer("Can't determine message structure from MSH-9: ");
 189  0
                 buf.append(wholeFieldNine);
 190  0
                 if (comps.length < 3) {
 191  0
                     buf.append(" HINT: there are only ");
 192  0
                     buf.append(comps.length);
 193  0
                     buf.append(" of 3 components present");
 194  
                 }
 195  0
                 throw new HL7Exception(buf.toString(), ErrorCode.UNSUPPORTED_MESSAGE_TYPE);
 196  
             }            
 197  
         }
 198  0
         catch (IndexOutOfBoundsException e) {
 199  0
             throw new HL7Exception(
 200  0
             "Can't find message structure (MSH-9-3): " + e.getMessage(),
 201  
             ErrorCode.UNSUPPORTED_MESSAGE_TYPE);
 202  5
         }
 203  
         
 204  5
         return new MessageStructure(messageStructure, explicityDefined);
 205  
     }
 206  
     
 207  
     /**
 208  
      * Returns object that contains the field separator and encoding characters
 209  
      * for this message.
 210  
      */
 211  
     private static EncodingCharacters getEncodingChars(String message) {
 212  35
         return new EncodingCharacters(message.charAt(3), message.substring(4, 8));
 213  
     }
 214  
     
 215  
     /**
 216  
      * Parses a message string and returns the corresponding Message
 217  
      * object.  Unexpected segments added at the end of their group.  
 218  
      *
 219  
      * @throws HL7Exception if the message is not correctly formatted.
 220  
      * @throws EncodingNotSupportedException if the message encoded
 221  
      *      is not supported by this parser.
 222  
      */
 223  
     protected Message doParse(String message, String version) throws HL7Exception, EncodingNotSupportedException {
 224  
         
 225  
         //try to instantiate a message object of the right class
 226  5
         MessageStructure structure = getStructure(message);
 227  5
         Message m = instantiateMessage(structure.messageStructure, version, structure.explicitlyDefined);
 228  
 
 229  5
         parse(m, message);
 230  
 
 231  5
         return m;
 232  
     }
 233  
     
 234  
     /**
 235  
      * Parses a segment string and populates the given Segment object.  Unexpected fields are
 236  
      * added as Varies' at the end of the segment.  
 237  
      *
 238  
      * @throws HL7Exception if the given string does not contain the
 239  
      *      given segment or if the string is not encoded properly
 240  
      */
 241  
     public void parse(Segment destination, String segment, EncodingCharacters encodingChars) throws HL7Exception {
 242  30
         int fieldOffset = 0;
 243  30
         if (isDelimDefSegment(destination.getName())) {
 244  5
             fieldOffset = 1;
 245  
             //set field 1 to fourth character of string
 246  5
             Terser.set(destination, 1, 0, 1, 1, String.valueOf(encodingChars.getFieldSeparator()));
 247  
         }
 248  
         
 249  30
         String[] fields = split(segment, String.valueOf(encodingChars.getFieldSeparator()));
 250  
         //destination.setName(fields[0]);
 251  510
         for (int i = 1; i < fields.length; i++) {
 252  480
             String[] reps = split(fields[i], String.valueOf(encodingChars.getRepetitionSeparator()));
 253  480
             log.debug("{} reps delimited by: {}", reps.length, encodingChars.getRepetitionSeparator());                
 254  
             
 255  
             //MSH-2 will get split incorrectly so we have to fudge it ...
 256  480
             boolean isMSH2 = isDelimDefSegment(destination.getName()) && i+fieldOffset == 2;
 257  480
             if (isMSH2) {  
 258  5
                 reps = new String[1];
 259  5
                 reps[0] = fields[i];
 260  
             }
 261  
             
 262  720
             for (int j = 0; j < reps.length; j++) {
 263  
                 try {
 264  240
                     StringBuffer statusMessage = new StringBuffer("Parsing field ");
 265  240
                     statusMessage.append(i+fieldOffset);
 266  240
                     statusMessage.append(" repetition ");
 267  240
                     statusMessage.append(j);
 268  240
                     log.debug(statusMessage.toString());
 269  
                     //parse(destination.getField(i + fieldOffset, j), reps[j], encodingChars, false);
 270  
 
 271  240
                     Type field = destination.getField(i + fieldOffset, j);
 272  240
                     if (isMSH2) {
 273  5
                         Terser.getPrimitive(field, 1, 1).setValue(reps[j]);
 274  
                     } else {
 275  235
                         parse(field, reps[j], encodingChars);
 276  
                     }
 277  
                 }
 278  0
                 catch (HL7Exception e) {
 279  
                     //set the field location and throw again ...
 280  0
                     e.setFieldPosition(i);
 281  0
                     e.setSegmentRepetition(MessageIterator.getIndex(destination.getParent(), destination).rep);
 282  0
                     e.setSegmentName(destination.getName());
 283  0
                     throw e;
 284  240
                 }
 285  
             }
 286  
         }
 287  
         
 288  
         //set data type of OBX-5
 289  30
         if (destination.getClass().getName().indexOf("OBX") >= 0) {
 290  0
             FixFieldDataType.fixOBX5(destination, getFactory(), getHapiContext().getParserConfiguration());
 291  
         }
 292  
         
 293  30
     }
 294  
     
 295  
     /** 
 296  
      * @return true if the segment is MSH, FHS, or BHS.  These need special treatment 
 297  
      *  because they define delimiters.
 298  
      * @param theSegmentName
 299  
      */
 300  
     private static boolean isDelimDefSegment(String theSegmentName) {
 301  510
         boolean is = false;
 302  510
         if (theSegmentName.equals("MSH") 
 303  425
             || theSegmentName.equals("FHS") 
 304  425
             || theSegmentName.equals("BHS")) 
 305  
         {
 306  85
             is = true;
 307  
         }
 308  510
         return is;
 309  
     }
 310  
     
 311  
     /**
 312  
      * Fills a field with values from an unparsed string representing the field.  
 313  
      * @param destinationField the field Type
 314  
      * @param data the field string (including all components and subcomponents; not including field delimiters)
 315  
      * @param encodingCharacters the encoding characters used in the message
 316  
      */
 317  
     public void parse(Type destinationField, String data, EncodingCharacters encodingCharacters) throws HL7Exception {
 318  235
         String[] components = split(data, String.valueOf(encodingCharacters.getComponentSeparator()));
 319  580
         for (int i = 0; i < components.length; i++) {
 320  345
             String[] subcomponents = split(components[i], String.valueOf(encodingCharacters.getSubcomponentSeparator()));
 321  675
             for (int j = 0; j < subcomponents.length; j++) {
 322  330
                 String val = subcomponents[j];
 323  330
                 if (val != null) {
 324  330
                     val = Escape.unescape(val, encodingCharacters);
 325  
                 }
 326  330
                 Terser.getPrimitive(destinationField, i+1, j+1).setValue(val);                
 327  
             }
 328  
         }
 329  235
     }
 330  
     
 331  
     /**
 332  
      * Splits the given composite string into an array of components using the given
 333  
      * delimiter.
 334  
      */
 335  
     public static String[] split(String composite, String delim) {
 336  1115
         List<String> components = new ArrayList<String>();
 337  
         
 338  
         //defend against evil nulls
 339  1115
         if (composite == null)
 340  265
             composite = "";
 341  1115
         if (delim == null)
 342  0
             delim = "";
 343  
         
 344  1115
         StringTokenizer tok = new StringTokenizer(composite, delim, true);
 345  1115
         boolean previousTokenWasDelim = true;
 346  3910
         while (tok.hasMoreTokens()) {
 347  2795
             String thisTok = tok.nextToken();
 348  2795
             if (thisTok.equals(delim)) {
 349  1255
                 if (previousTokenWasDelim)
 350  525
                     components.add(null);
 351  1255
                 previousTokenWasDelim = true;
 352  
             }
 353  
             else {
 354  1540
                 components.add(thisTok);
 355  1540
                 previousTokenWasDelim = false;
 356  
             }
 357  2795
         }
 358  
         
 359  1115
         return components.toArray(new String[components.size()]);
 360  
     }
 361  
     
 362  
     /**
 363  
      * Encodes the given Type, using the given encoding characters. 
 364  
      * It is assumed that the Type represents a complete field rather than a component.
 365  
      */
 366  
     public static String encode(Type source, EncodingCharacters encodingChars) {
 367  0
         StringBuffer field = new StringBuffer();
 368  0
         for (int i = 1; i <= Terser.numComponents(source); i++) {
 369  0
             StringBuffer comp = new StringBuffer();
 370  0
             for (int j = 1; j <= Terser.numSubComponents(source, i); j++) {
 371  0
                 Primitive p = Terser.getPrimitive(source, i, j);
 372  0
                 comp.append(encodePrimitive(p, encodingChars));
 373  0
                 comp.append(encodingChars.getSubcomponentSeparator());
 374  
             }
 375  0
             field.append(stripExtraDelimiters(comp.toString(), encodingChars.getSubcomponentSeparator()));
 376  0
             field.append(encodingChars.getComponentSeparator());
 377  
         }
 378  0
         return stripExtraDelimiters(field.toString(), encodingChars.getComponentSeparator());
 379  
         //return encode(source, encodingChars, false);
 380  
     }
 381  
     
 382  
     private static String encodePrimitive(Primitive p, EncodingCharacters encodingChars) {
 383  0
         String val = ((Primitive) p).getValue();
 384  0
         if (val == null) {
 385  0
             val = "";
 386  
         } else {
 387  0
             val = Escape.escape(val, encodingChars);
 388  
         }
 389  0
         return val;
 390  
     }
 391  
     
 392  
     /**
 393  
      * Removes unecessary delimiters from the end of a field or segment.
 394  
      * This seems to be more convenient than checking to see if they are needed
 395  
      * while we are building the encoded string.
 396  
      */
 397  
     private static String stripExtraDelimiters(String in, char delim) {
 398  0
         char[] chars = in.toCharArray();
 399  
         
 400  
         //search from back end for first occurance of non-delimiter ...
 401  0
         int c = chars.length - 1;
 402  0
         boolean found = false;
 403  0
         while (c >= 0 && !found) {
 404  0
             if (chars[c--] != delim)
 405  0
                 found = true;
 406  
         }
 407  
         
 408  0
         String ret = "";
 409  0
         if (found)
 410  0
             ret = String.valueOf(chars, 0, c + 2);
 411  0
         return ret;
 412  
     }
 413  
     
 414  
     /**
 415  
      * Formats a Message object into an HL7 message string using the given
 416  
      * encoding.
 417  
      * @throws HL7Exception if the data fields in the message do not permit encoding
 418  
      *      (e.g. required fields are null)
 419  
      * @throws EncodingNotSupportedException if the requested encoding is not
 420  
      *      supported by this parser.
 421  
      */
 422  
     protected String doEncode(Message source, String encoding) throws HL7Exception, EncodingNotSupportedException {
 423  0
         if (!this.supportsEncoding(encoding))
 424  0
             throw new EncodingNotSupportedException("This parser does not support the " + encoding + " encoding");
 425  
         
 426  0
         return encode(source);
 427  
     }
 428  
     
 429  
     /**
 430  
      * Formats a Message object into an HL7 message string using this parser's
 431  
      * default encoding ("VB").
 432  
      * @throws HL7Exception if the data fields in the message do not permit encoding
 433  
      *      (e.g. required fields are null)
 434  
      */
 435  
     protected String doEncode(Message source) throws HL7Exception {
 436  
         //get encoding characters ...
 437  0
         Segment msh = (Segment) source.get("MSH");
 438  0
         String fieldSepString = Terser.get(msh, 1, 0, 1, 1);
 439  
         
 440  0
         if (fieldSepString == null) 
 441  0
             throw new HL7Exception("Can't encode message: MSH-1 (field separator) is missing");
 442  
         
 443  0
         char fieldSep = '|';
 444  0
         if (fieldSepString != null && fieldSepString.length() > 0)
 445  0
             fieldSep = fieldSepString.charAt(0);
 446  
         
 447  0
         String encCharString = Terser.get(msh, 2, 0, 1, 1);
 448  
         
 449  0
         if (encCharString == null) 
 450  0
             throw new HL7Exception("Can't encode message: MSH-2 (encoding characters) is missing");
 451  
                 
 452  0
         if (encCharString.length() != 4)
 453  0
             throw new HL7Exception(
 454  
             "Encoding characters '" + encCharString + "' invalid -- must be 4 characters",
 455  
             ErrorCode.DATA_TYPE_ERROR);
 456  0
         EncodingCharacters en = new EncodingCharacters(fieldSep, encCharString);
 457  
         
 458  
         //pass down to group encoding method which will operate recursively on children ...
 459  0
         return encode((Group) source, en);
 460  
     }
 461  
     
 462  
     /**
 463  
      * Returns given group serialized as a pipe-encoded string - this method is called
 464  
      * by encode(Message source, String encoding).
 465  
      */
 466  
     public static String encode(Group source, EncodingCharacters encodingChars) throws HL7Exception {
 467  0
         StringBuffer result = new StringBuffer();
 468  
         
 469  0
         String[] names = source.getNames();
 470  0
         for (int i = 0; i < names.length; i++) {
 471  0
             Structure[] reps = source.getAll(names[i]);
 472  0
             for (int rep = 0; rep < reps.length; rep++) {
 473  0
                 if (reps[rep] instanceof Group) {
 474  0
                     result.append(encode((Group) reps[rep], encodingChars));
 475  
                 }
 476  
                 else {
 477  0
                     String segString = encode((Segment) reps[rep], encodingChars);
 478  0
                     if (segString.length() >= 4) {
 479  0
                         result.append(segString);
 480  0
                         result.append('\r');
 481  
                     }
 482  
                 }
 483  
             }
 484  
         }
 485  0
         return result.toString();
 486  
     }
 487  
     
 488  
     public static String encode(Segment source, EncodingCharacters encodingChars) {
 489  0
         StringBuffer result = new StringBuffer();
 490  0
         result.append(source.getName());
 491  0
         result.append(encodingChars.getFieldSeparator());
 492  
         
 493  
         //start at field 2 for MSH segment because field 1 is the field delimiter
 494  0
         int startAt = 1;
 495  0
         if (isDelimDefSegment(source.getName()))
 496  0
             startAt = 2;
 497  
         
 498  
         //loop through fields; for every field delimit any repetitions and add field delimiter after ...
 499  0
         int numFields = source.numFields();
 500  0
         for (int i = startAt; i <= numFields; i++) {
 501  
             try {
 502  0
                 Type[] reps = source.getField(i);
 503  0
                 for (int j = 0; j < reps.length; j++) {
 504  0
                     String fieldText = encode(reps[j], encodingChars);
 505  
                     //if this is MSH-2, then it shouldn't be escaped, so unescape it again
 506  0
                     if (isDelimDefSegment(source.getName()) && i == 2)
 507  0
                         fieldText = Escape.unescape(fieldText, encodingChars);
 508  0
                     result.append(fieldText);
 509  0
                     if (j < reps.length - 1)
 510  0
                         result.append(encodingChars.getRepetitionSeparator());
 511  
                 }
 512  
             }
 513  0
             catch (HL7Exception e) {
 514  0
                 log.error("Error while encoding segment: ", e);
 515  0
             }
 516  0
             result.append(encodingChars.getFieldSeparator());
 517  
         }
 518  
         
 519  
         //strip trailing delimiters ...
 520  0
         return stripExtraDelimiters(result.toString(), encodingChars.getFieldSeparator());
 521  
     }
 522  
     
 523  
     /**
 524  
      * Removes leading whitespace from the given string.  This method was created to deal with frequent
 525  
      * problems parsing messages that have been hand-written in windows.  The intuitive way to delimit
 526  
      * segments is to hit <ENTER> at the end of each segment, but this creates both a carriage return
 527  
      * and a line feed, so to the parser, the first character of the next segment is the line feed.
 528  
      */
 529  
     public static String stripLeadingWhitespace(String in) {
 530  0
         StringBuffer out = new StringBuffer();
 531  0
         char[] chars = in.toCharArray();
 532  0
         int c = 0;
 533  0
         while (c < chars.length) {
 534  0
             if (!Character.isWhitespace(chars[c]))
 535  0
                 break;
 536  0
             c++;
 537  
         }
 538  0
         for (int i = c; i < chars.length; i++) {
 539  0
             out.append(chars[i]);
 540  
         }
 541  0
         return out.toString();
 542  
     }
 543  
     
 544  
     /**
 545  
      * <p>Returns a minimal amount of data from a message string, including only the
 546  
      * data needed to send a response to the remote system.  This includes the
 547  
      * following fields:
 548  
      * <ul><li>field separator</li>
 549  
      * <li>encoding characters</li>
 550  
      * <li>processing ID</li>
 551  
      * <li>message control ID</li></ul>
 552  
      * This method is intended for use when there is an error parsing a message,
 553  
      * (so the Message object is unavailable) but an error message must be sent
 554  
      * back to the remote system including some of the information in the inbound
 555  
      * message.  This method parses only that required information, hopefully
 556  
      * avoiding the condition that caused the original error.  The other
 557  
      * fields in the returned MSH segment are empty.</p>
 558  
      */
 559  
     public Segment getCriticalResponseData(String message) throws HL7Exception {
 560  
         //try to get MSH segment
 561  0
         int locStartMSH = message.indexOf("MSH");
 562  0
         if (locStartMSH < 0)
 563  0
             throw new HL7Exception(
 564  
             "Couldn't find MSH segment in message: " + message,
 565  
             ErrorCode.SEGMENT_SEQUENCE_ERROR);
 566  0
         int locEndMSH = message.indexOf('\r', locStartMSH + 1);
 567  0
         if (locEndMSH < 0)
 568  0
             locEndMSH = message.length();
 569  0
         String mshString = message.substring(locStartMSH, locEndMSH);
 570  
         
 571  
         //find out what the field separator is
 572  0
         char fieldSep = mshString.charAt(3);
 573  
         
 574  
         //get field array
 575  0
         String[] fields = split(mshString, String.valueOf(fieldSep));
 576  
         
 577  0
         Segment msh = null;
 578  
         try {
 579  
             //parse required fields
 580  0
             String encChars = fields[1];
 581  0
             char compSep = encChars.charAt(0);
 582  0
             String messControlID = fields[9];
 583  0
             String[] procIDComps = split(fields[10], String.valueOf(compSep));
 584  
             
 585  
             //fill MSH segment
 586  0
             String version = Version.lowestAvailableVersion().getVersion(); //default
 587  
             try {
 588  0
                 version = this.getVersion(message);
 589  
             }
 590  0
             catch (Exception e) { /* use the default */
 591  0
             }
 592  
             
 593  0
             msh = Parser.makeControlMSH(version, getFactory());
 594  0
             Terser.set(msh, 1, 0, 1, 1, String.valueOf(fieldSep));
 595  0
             Terser.set(msh, 2, 0, 1, 1, encChars);
 596  0
             Terser.set(msh, 10, 0, 1, 1, messControlID);
 597  0
             Terser.set(msh, 11, 0, 1, 1, procIDComps[0]);
 598  0
             Terser.set(msh, 12, 0, 1, 1, version);
 599  
             
 600  
             }
 601  0
         catch (Exception e) {
 602  0
             throw new HL7Exception(
 603  
             "Can't parse critical fields from MSH segment ("
 604  0
             + e.getClass().getName()
 605  
             + ": "
 606  0
             + e.getMessage()
 607  
             + "): "
 608  
             + mshString,
 609  
             ErrorCode.REQUIRED_FIELD_MISSING, e);
 610  0
         }
 611  
         
 612  0
         return msh;
 613  
     }
 614  
     
 615  
     /**
 616  
      * For response messages, returns the value of MSA-2 (the message ID of the message
 617  
      * sent by the sending system).  This value may be needed prior to main message parsing,
 618  
      * so that (particularly in a multi-threaded scenario) the message can be routed to
 619  
      * the thread that sent the request.  We need this information first so that any
 620  
      * parse exceptions are thrown to the correct thread.
 621  
      * Returns null if MSA-2 can not be found (e.g. if the message is not a
 622  
      * response message).
 623  
      */
 624  
     public String getAckID(String message) {
 625  0
         String ackID = null;
 626  0
         int startMSA = message.indexOf("\rMSA");
 627  0
         if (startMSA >= 0) {
 628  0
             int startFieldOne = startMSA + 5;
 629  0
             char fieldDelim = message.charAt(startFieldOne - 1);
 630  0
             int start = message.indexOf(fieldDelim, startFieldOne) + 1;
 631  0
             int end = message.indexOf(fieldDelim, start);
 632  0
             int segEnd = message.indexOf(String.valueOf(segDelim), start);
 633  0
             if (segEnd > start && segEnd < end)
 634  0
                 end = segEnd;
 635  
             
 636  
             //if there is no field delim after MSH-2, need to go to end of message, but not including end seg delim if it exists
 637  0
             if (end < 0) {
 638  0
                 if (message.charAt(message.length() - 1) == '\r') {
 639  0
                     end = message.length() - 1;
 640  
                 }
 641  
                 else {
 642  0
                     end = message.length();
 643  
                 }
 644  
             }
 645  0
             if (start > 0 && end > start) {
 646  0
                 ackID = message.substring(start, end);
 647  
             }
 648  
         }
 649  0
         log.debug("ACK ID: {}", ackID);
 650  0
         return ackID;
 651  
     }
 652  
     
 653  
     /**
 654  
      * Returns the version ID (MSH-12) from the given message, without fully parsing the message.
 655  
      * The version is needed prior to parsing in order to determine the message class
 656  
      * into which the text of the message should be parsed.
 657  
      * @throws HL7Exception if the version field can not be found.
 658  
      */
 659  
     public String getVersion(String message) throws HL7Exception {
 660  5
         int startMSH = message.indexOf("MSH");
 661  5
         int endMSH = message.indexOf(OldPipeParser.segDelim, startMSH);
 662  5
         if (endMSH < 0)
 663  0
             endMSH = message.length();
 664  5
         String msh = message.substring(startMSH, endMSH);
 665  5
         String fieldSep = null;
 666  5
         if (msh.length() > 3) {
 667  5
             fieldSep = String.valueOf(msh.charAt(3));
 668  
         }
 669  
         else {
 670  0
             throw new HL7Exception("Can't find field separator in MSH: " + msh, ErrorCode.UNSUPPORTED_VERSION_ID);
 671  
         }
 672  
         
 673  5
         String[] fields = split(msh, fieldSep);
 674  
         
 675  5
         String compSep = null;
 676  5
         if (fields.length >= 2 && fields[1] != null && fields[1].length() == 4) {
 677  5
             compSep = String.valueOf(fields[1].charAt(0)); //get component separator as 1st encoding char
 678  
         } 
 679  
         else {
 680  0
             throw new HL7Exception("Invalid or incomplete encoding characters - MSH-2 is " + fields[1],  
 681  
                     ErrorCode.REQUIRED_FIELD_MISSING);
 682  
         }
 683  
         
 684  5
         String version = null;
 685  5
         if (fields.length >= 12) {
 686  5
                 String[] comp = split(fields[11], compSep);
 687  5
                 if (comp.length >= 1) {
 688  5
                         version = comp[0];
 689  
                 } else {
 690  0
                         throw new HL7Exception("Can't find version ID - MSH.12 is " + fields[11],
 691  
                                         ErrorCode.REQUIRED_FIELD_MISSING);
 692  
                 }
 693  5
         }
 694  
         else {
 695  0
             throw new HL7Exception(
 696  
                             "Can't find version ID - MSH has only " + fields.length + " fields.",
 697  
                             ErrorCode.REQUIRED_FIELD_MISSING);
 698  
         }
 699  5
         return version;
 700  
     }
 701  
 
 702  
     /**
 703  
      * {@inheritDoc }
 704  
      */
 705  
     public String doEncode(Segment structure, EncodingCharacters encodingCharacters) throws HL7Exception {
 706  0
         return encode(structure, encodingCharacters);
 707  
     }
 708  
 
 709  
     /**
 710  
      * {@inheritDoc }
 711  
      */
 712  
     public String doEncode(Type type, EncodingCharacters encodingCharacters) throws HL7Exception {
 713  0
         return encode(type, encodingCharacters);
 714  
     }
 715  
 
 716  
     /**
 717  
      * Throws unsupported operation exception
 718  
      *
 719  
      * @throws UnsupportedOperationException
 720  
      */
 721  
     @Override
 722  
         protected Message doParseForSpecificPackage(String theMessage, String theVersion, String thePackageName) throws HL7Exception, EncodingNotSupportedException {
 723  0
         throw new UnsupportedOperationException("Not supported yet.");
 724  
         }
 725  
     
 726  
     public void parse(Message message, String string) throws HL7Exception {
 727  5
         MessageIterator messageIter = new MessageIterator(message, "MSH", true);
 728  5
         FilterIterator.Predicate<Structure> segmentsOnly = new FilterIterator.Predicate<Structure>() {
 729  
             public boolean evaluate(Structure obj) {
 730  130
                 if (Segment.class.isAssignableFrom(obj.getClass())) {
 731  100
                     return true;
 732  
                 } else {
 733  30
                     return false;
 734  
                 }
 735  
             }
 736  
         };
 737  5
         FilterIterator<Structure> segmentIter = new FilterIterator<Structure>(messageIter, segmentsOnly);
 738  
 
 739  5
         String[] segments = split(string, segDelim);
 740  
 
 741  5
         char delim = '|';
 742  35
         for (int i = 0; i < segments.length; i++) {
 743  
 
 744  
             //get rid of any leading whitespace characters ...
 745  30
             if (segments[i] != null && segments[i].length() > 0 && Character.isWhitespace(segments[i].charAt(0)))
 746  0
                 segments[i] = stripLeadingWhitespace(segments[i]);
 747  
 
 748  
             //sometimes people put extra segment delimiters at end of msg ...
 749  30
             if (segments[i] != null && segments[i].length() >= 3) {
 750  
                 final String name;
 751  30
                 if (i == 0) {
 752  5
                     name = segments[i].substring(0, 3);
 753  5
                     delim = segments[i].charAt(3);
 754  
                 } else {
 755  25
                     if (segments[i].indexOf(delim) >= 0 ) {
 756  25
                         name = segments[i].substring(0, segments[i].indexOf(delim));
 757  
                       } else {
 758  0
                         name = segments[i];
 759  
                       }
 760  
                  }
 761  
 
 762  30
                 log.debug("Parsing segment {}", name);
 763  
 
 764  30
                 messageIter.setDirection(name);
 765  30
                 FilterIterator.Predicate<Structure> byDirection = new FilterIterator.Predicate<Structure>() {
 766  
                     public boolean evaluate(Structure obj) {
 767  100
                         Structure s = (Structure) obj;
 768  100
                         log.debug("PipeParser iterating message in direction {} at {} ", name, s.getName());
 769  100
                         return s.getName().matches(name + "\\d*");
 770  
                     }
 771  
                 };
 772  30
                 FilterIterator<Structure> dirIter = new FilterIterator<Structure>(segmentIter, byDirection);
 773  30
                 if (dirIter.hasNext()) {
 774  30
                     parse((Segment) dirIter.next(), segments[i], getEncodingChars(string));
 775  
                 }
 776  
             }
 777  
         }
 778  5
     }
 779  
 
 780  
     
 781  
     /**
 782  
      * A struct for holding a message class string and a boolean indicating whether it 
 783  
      * was defined explicitly.  
 784  
      */
 785  
     private static class MessageStructure {
 786  
         public String messageStructure;
 787  
         public boolean explicitlyDefined;
 788  
         
 789  5
         public MessageStructure(String theMessageStructure, boolean isExplicitlyDefined) {
 790  5
             messageStructure = theMessageStructure;
 791  5
             explicitlyDefined = isExplicitlyDefined;
 792  5
         }
 793  
     }
 794  
     
 795  
 }