001/** 002 * The 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. 004 * You may obtain a copy of the License at http://www.mozilla.org/MPL/ 005 * Software distributed under the License is distributed on an "AS IS" basis, 006 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the 007 * specific language governing rights and limitations under the License. 008 * 009 * The Original Code is "PipeParser.java". Description: 010 * "An implementation of Parser that supports traditionally encoded (i.e" 011 * 012 * The Initial Developer of the Original Code is University Health Network. Copyright (C) 013 * 2001. All Rights Reserved. 014 * 015 * Contributor(s): Kenneth Beaton. 016 * 017 * Alternatively, the contents of this file may be used under the terms of the 018 * GNU General Public License (the "GPL"), in which case the provisions of the GPL are 019 * applicable instead of those above. If you wish to allow use of your version of this 020 * file only under the terms of the GPL and not to allow others to use your version 021 * of this file under the MPL, indicate your decision by deleting the provisions above 022 * and replace them with the notice and other provisions required by the GPL License. 023 * If you do not delete the provisions above, a recipient may use your version of 024 * this file under either the MPL or the GPL. 025 * 026 */ 027 028package ca.uhn.hl7v2.parser; 029 030import java.util.ArrayList; 031import java.util.Arrays; 032import java.util.HashMap; 033import java.util.List; 034import java.util.Map; 035import java.util.Set; 036import java.util.StringTokenizer; 037 038import ca.uhn.hl7v2.validation.ValidationContext; 039import org.slf4j.Logger; 040import org.slf4j.LoggerFactory; 041 042import ca.uhn.hl7v2.DefaultHapiContext; 043import ca.uhn.hl7v2.ErrorCode; 044import ca.uhn.hl7v2.HL7Exception; 045import ca.uhn.hl7v2.HapiContext; 046import ca.uhn.hl7v2.Version; 047import ca.uhn.hl7v2.model.AbstractSuperMessage; 048import ca.uhn.hl7v2.model.DoNotCacheStructure; 049import ca.uhn.hl7v2.model.Group; 050import ca.uhn.hl7v2.model.Message; 051import ca.uhn.hl7v2.model.Primitive; 052import ca.uhn.hl7v2.model.Segment; 053import ca.uhn.hl7v2.model.Structure; 054import ca.uhn.hl7v2.model.SuperStructure; 055import ca.uhn.hl7v2.model.Type; 056import ca.uhn.hl7v2.model.Varies; 057import ca.uhn.hl7v2.util.ReflectionUtil; 058import ca.uhn.hl7v2.util.Terser; 059import ca.uhn.hl7v2.validation.impl.NoValidation; 060import ca.uhn.hl7v2.validation.impl.ValidationContextFactory; 061 062/** 063 * An implementation of Parser that supports traditionally encoded (ie delimited 064 * with characters like |, ^, and ~) HL7 messages. Unexpected segments and 065 * fields are parsed into generic elements that are added to the message. 066 * 067 * @see ParserConfiguration for configuration options which may affect parser encoding and decoding behaviour 068 * @author Bryan Tripp (bryan_tripp@sourceforge.net) 069 */ 070public class PipeParser extends Parser { 071 072 private static final Logger log = LoggerFactory.getLogger(PipeParser.class); 073 074 /** 075 * The HL7 ER7 segment delimiter (see section 2.8 of spec) 076 */ 077 final static String SEGMENT_DELIMITER = "\r"; 078 079 private final HashMap<Class<? extends Message>, HashMap<String, StructureDefinition>> myStructureDefinitions = new HashMap<>(); 080 081 /** 082 * System property key. If value is "true", legacy mode will default to true 083 * 084 * @see #isLegacyMode() 085 * @deprecated This will be removed in HAPI 3.0 086 */ 087 public static final String DEFAULT_LEGACY_MODE_PROPERTY = "ca.uhn.hl7v2.parser.PipeParser.default_legacy_mode"; 088 089 private Boolean myLegacyMode = null; 090 091 public PipeParser() { 092 super(); 093 } 094 095 /** 096 * @param context 097 * the context containing all configuration items to be used 098 */ 099 public PipeParser(HapiContext context) { 100 super(context); 101 } 102 103 /** 104 * Creates a new PipeParser 105 * 106 * @param theFactory 107 * custom factory to use for model class lookup 108 */ 109 public PipeParser(ModelClassFactory theFactory) { 110 super(theFactory); 111 } 112 113 @Override 114 public void setValidationContext(ValidationContext context) { 115 super.setValidationContext(context); 116 } 117 118 /** 119 * Returns a String representing the encoding of the given message, if the 120 * encoding is recognized. For example if the given message appears to be 121 * encoded using HL7 2.x XML rules then "XML" would be returned. If the 122 * encoding is not recognized then null is returned. That this method 123 * returns a specific encoding does not guarantee that the message is 124 * correctly encoded (e.g. well formed XML) - just that it is not encoded 125 * using any other encoding than the one returned. 126 */ 127 public String getEncoding(String message) { 128 return EncodingDetector.isEr7Encoded(message) ? getDefaultEncoding() : null; 129 } 130 131 /** 132 * @return the preferred encoding of this Parser 133 */ 134 public String getDefaultEncoding() { 135 return "VB"; 136 } 137 138 /** 139 * @deprecated this method should not be public 140 * @param message HL7 message 141 * @return message structure 142 * @throws HL7Exception 143 */ 144 public String getMessageStructure(String message) throws HL7Exception { 145 return getStructure(message).messageStructure; 146 } 147 148 /** 149 * @return the message structure from MSH-9-3 150 */ 151 private MessageStructure getStructure(String message) throws HL7Exception { 152 EncodingCharacters ec = getEncodingChars(message); 153 String messageStructure; 154 boolean explicityDefined = true; 155 String wholeFieldNine; 156 try { 157 String[] fields = split(message.substring(0, Math.max(message.indexOf(SEGMENT_DELIMITER), message.length())), String.valueOf(ec.getFieldSeparator())); 158 wholeFieldNine = fields[8]; 159 160 // message structure is component 3 but we'll accept a composite of 161 // 1 and 2 if there is no component 3 ... 162 // if component 1 is ACK, then the structure is ACK regardless of 163 // component 2 164 String[] comps = split(wholeFieldNine, String.valueOf(ec.getComponentSeparator())); 165 if (comps.length >= 3) { 166 messageStructure = comps[2]; 167 } else if (comps.length > 0 && comps[0] != null && comps[0].equals("ACK")) { 168 messageStructure = "ACK"; 169 } else if (comps.length == 2) { 170 explicityDefined = false; 171 messageStructure = comps[0] + "_" + comps[1]; 172 } 173 /* 174 * else if (comps.length == 1 && comps[0] != null && 175 * comps[0].equals("ACK")) { messageStructure = "ACK"; //it's common 176 * for people to only populate component 1 in an ACK msg } 177 */ 178 else { 179 String buf = "Can't determine message structure from MSH-9: " + wholeFieldNine + 180 " HINT: there are only " + 181 comps.length + 182 " of 3 components present"; 183 throw new HL7Exception(buf, ErrorCode.UNSUPPORTED_MESSAGE_TYPE); 184 } 185 } catch (IndexOutOfBoundsException e) { 186 throw new HL7Exception("Can't find message structure (MSH-9-3): " + e.getMessage(), ErrorCode.UNSUPPORTED_MESSAGE_TYPE); 187 } 188 189 return new MessageStructure(messageStructure, explicityDefined); 190 } 191 192 /** 193 * Returns object that contains the field separator and encoding characters 194 * for this message. 195 * 196 * There's an additional character starting with v2.7 (truncation), but we will 197 * accept it in messages of any version. 198 * 199 * @throws HL7Exception 200 */ 201 private static EncodingCharacters getEncodingChars(String message) throws HL7Exception { 202 if (message.length() < 9) { 203 throw new HL7Exception("Invalid message content: \"" + message + "\""); 204 } 205 return new EncodingCharacters(message.charAt(3), message.substring(4, 9)); 206 } 207 208 /** 209 * Parses a message string and returns the corresponding Message object. 210 * Unexpected segments added at the end of their group. 211 * 212 * @throws HL7Exception 213 * if the message is not correctly formatted. 214 * @throws EncodingNotSupportedException 215 * if the message encoded is not supported by this parser. 216 */ 217 protected Message doParse(String message, String version) throws HL7Exception { 218 219 // try to instantiate a message object of the right class 220 MessageStructure structure = getStructure(message); 221 Message m = instantiateMessage(structure.messageStructure, version, structure.explicitlyDefined); 222 m.setParser(this); 223 parse(m, message); 224 return m; 225 } 226 227 /** 228 * {@inheritDoc} 229 */ 230 protected Message doParseForSpecificPackage(String message, String version, String packageName) throws HL7Exception { 231 232 // try to instantiate a message object of the right class 233 MessageStructure structure = getStructure(message); 234 Message m = instantiateMessageInASpecificPackage(structure.messageStructure, version, structure.explicitlyDefined, packageName); 235 236 parse(m, message); 237 238 return m; 239 } 240 241 /** 242 * Generates (or returns the cached value of) the message 243 */ 244 private IStructureDefinition getStructureDefinition(Message theMessage) throws HL7Exception { 245 246 Class<? extends Message> clazz = theMessage.getClass(); 247 HashMap<String, StructureDefinition> definitions = myStructureDefinitions.get(clazz); 248 249 StructureDefinition retVal; 250 if (definitions != null) { 251 retVal = definitions.get(theMessage.getName()); 252 if (retVal != null) { 253 return retVal; 254 } 255 } 256 257 if (theMessage instanceof SuperStructure) { 258 Set<String> appliesTo = ((SuperStructure) theMessage).getStructuresWhichChildAppliesTo("MSH"); 259 if (!appliesTo.contains(theMessage.getName())) { 260 throw new HL7Exception("Superstructure " + theMessage.getClass().getSimpleName() + " does not apply to message " + theMessage.getName() + ", can not parse."); 261 } 262 } 263 264 if (clazz.isAnnotationPresent(DoNotCacheStructure.class)) { 265 Holder<StructureDefinition> previousLeaf = new Holder<>(); 266 retVal = createStructureDefinition(theMessage, previousLeaf, theMessage.getName()); 267 } else { 268 Message message = ReflectionUtil.instantiateMessage(clazz, getFactory()); 269 Holder<StructureDefinition> previousLeaf = new Holder<>(); 270 retVal = createStructureDefinition(message, previousLeaf, theMessage.getName()); 271 272 if (!myStructureDefinitions.containsKey(clazz)) { 273 myStructureDefinitions.put(clazz, new HashMap<>()); 274 } 275 myStructureDefinitions.get(clazz).put(theMessage.getName(), retVal); 276 } 277 278 return retVal; 279 } 280 281 private StructureDefinition createStructureDefinition(Structure theStructure, Holder<StructureDefinition> thePreviousLeaf, String theStructureName) throws HL7Exception { 282 283 StructureDefinition retVal = new StructureDefinition(); 284 retVal.setName(theStructure.getName()); 285 286 if (theStructure instanceof Group) { 287 retVal.setSegment(false); 288 Group group = (Group) theStructure; 289 int index = 0; 290 List<String> childNames = Arrays.asList(group.getNames()); 291 292 /* 293 * For SuperStructures, which can hold more than one type of structure, 294 * we only actually bring in the child names that are actually a part 295 * of the structure we are trying to parse 296 */ 297 if (theStructure instanceof SuperStructure) { 298 String struct = theStructureName; 299 Map<String, String> evtMap = new DefaultModelClassFactory().getEventMapForVersion(Version.versionOf(theStructure.getMessage().getVersion())); 300 if (evtMap.containsKey(struct)) { 301 struct = evtMap.get(struct); 302 } 303 childNames = ((SuperStructure) theStructure).getChildNamesForStructure(struct); 304 } 305 306 for (String nextName : childNames) { 307 Structure nextChild = group.get(nextName); 308 StructureDefinition structureDefinition = createStructureDefinition(nextChild, thePreviousLeaf, theStructureName); 309 structureDefinition.setNameAsItAppearsInParent(nextName); 310 structureDefinition.setRepeating(group.isRepeating(nextName)); 311 structureDefinition.setRequired(group.isRequired(nextName)); 312 structureDefinition.setChoiceElement(group.isChoiceElement(nextName)); 313 structureDefinition.setPosition(index++); 314 structureDefinition.setParent(retVal); 315 retVal.addChild(structureDefinition); 316 } 317 } else { 318 if (thePreviousLeaf.getObject() != null) { 319 thePreviousLeaf.getObject().setNextLeaf(retVal); 320 } 321 thePreviousLeaf.setObject(retVal); 322 retVal.setSegment(true); 323 } 324 325 return retVal; 326 } 327 328 /** 329 * Parses a segment string and populates the given Segment object. 330 * Unexpected fields are added as Varies' at the end of the segment. 331 * 332 * @param destination segment to parse the segment string into 333 * @param segment encoded segment 334 * @param encodingChars encoding characters to be used 335 * @throws HL7Exception 336 * if the given string does not contain the given segment or if 337 * the string is not encoded properly 338 */ 339 public void parse(Segment destination, String segment, EncodingCharacters encodingChars) throws HL7Exception { 340 parse(destination, segment, encodingChars, 0); 341 } 342 343 /** 344 * Parses a segment string and populates the given Segment object. 345 * Unexpected fields are added as Varies' at the end of the segment. 346 * 347 * @param destination segment to parse the segment string into 348 * @param segment encoded segment 349 * @param encodingChars encoding characters to be used 350 * @param theRepetition the repetition number of this segment within its group 351 * @throws HL7Exception 352 * if the given string does not contain the given segment or if 353 * the string is not encoded properly 354 */ 355 public void parse(Segment destination, String segment, EncodingCharacters encodingChars, int theRepetition) throws HL7Exception { 356 int fieldOffset = 0; 357 if (isDelimDefSegment(destination.getName())) { 358 fieldOffset = 1; 359 // set field 1 to fourth character of string 360 Terser.set(destination, 1, 0, 1, 1, String.valueOf(encodingChars.getFieldSeparator())); 361 } 362 363 String[] fields = split(segment, String.valueOf(encodingChars.getFieldSeparator())); 364 // destination.setName(fields[0]); 365 for (int i = 1; i < fields.length; i++) { 366 String[] reps = split(fields[i], String.valueOf(encodingChars.getRepetitionSeparator())); 367 368 // MSH-2 will get split incorrectly so we have to fudge it ... 369 boolean isMSH2 = isDelimDefSegment(destination.getName()) && i + fieldOffset == 2; 370 if (isMSH2) { 371 reps = new String[1]; 372 reps[0] = fields[i]; 373 } 374 375 for (int j = 0; j < reps.length; j++) { 376 try { 377 log.trace("Parsing field {} repetition {}", i + fieldOffset, j); 378 Type field = destination.getField(i + fieldOffset, j); 379 if (isMSH2) { 380 Terser.getPrimitive(field, 1, 1).setValue(reps[j]); 381 } else { 382 parse(field, reps[j], encodingChars); 383 } 384 } catch (HL7Exception e) { 385 // set the field location and throw again ... 386 e.setFieldPosition(i); 387 if (theRepetition > 1) { 388 e.setSegmentRepetition(theRepetition); 389 } 390 e.setSegmentName(destination.getName()); 391 throw e; 392 } 393 } 394 } 395 396 // set data type of OBX-5 397 if (destination.getClass().getName().contains("OBX")) { 398 FixFieldDataType.fixOBX5(destination, getFactory(), getHapiContext().getParserConfiguration()); 399 } 400 // set data type of MFE-4 401 if (destination.getClass().getName().contains("MFE") && 402 Version.versionOf(destination.getMessage().getVersion()).isGreaterThan(Version.V23)) { 403 FixFieldDataType.fixMFE4(destination, getFactory(), getHapiContext().getParserConfiguration()); 404 } 405 406 } 407 408 /** 409 * @return true if the segment is MSH, FHS, or BHS. These need special 410 * treatment because they define delimiters. 411 * @param theSegmentName 412 * segment name 413 */ 414 private static boolean isDelimDefSegment(String theSegmentName) { 415 boolean is = false; 416 if (theSegmentName.equals("MSH") || theSegmentName.equals("FHS") || theSegmentName.equals("BHS")) { 417 is = true; 418 } 419 return is; 420 } 421 422 /** 423 * Fills a field with values from an unparsed string representing the field. 424 * 425 * @param destinationField 426 * the field Type 427 * @param data 428 * the field string (including all components and subcomponents; 429 * not including field delimiters) 430 * @param encodingCharacters 431 * the encoding characters used in the message 432 */ 433 @Override 434 public void parse(Type destinationField, String data, EncodingCharacters encodingCharacters) throws HL7Exception { 435 String[] components = split(data, String.valueOf(encodingCharacters.getComponentSeparator())); 436 for (int i = 0; i < components.length; i++) { 437 String[] subcomponents = split(components[i], String.valueOf(encodingCharacters.getSubcomponentSeparator())); 438 for (int j = 0; j < subcomponents.length; j++) { 439 String val = subcomponents[j]; 440 if (val != null) { 441 val = getParserConfiguration().getEscaping().unescape(val, encodingCharacters); 442 } 443 Terser.getPrimitive(destinationField, i + 1, j + 1).setValue(val); 444 } 445 } 446 } 447 448 /** 449 * Splits the given composite string into an array of components using the 450 * given delimiter. 451 * 452 * @param composite encoded composite string 453 * @param delim delimiter to split upon 454 * @return split string 455 */ 456 public static String[] split(String composite, String delim) { 457 ArrayList<String> components = new ArrayList<>(); 458 459 // defend against evil nulls 460 if (composite == null) 461 composite = ""; 462 if (delim == null) 463 delim = ""; 464 465 StringTokenizer tok = new StringTokenizer(composite, delim, true); 466 boolean previousTokenWasDelim = true; 467 while (tok.hasMoreTokens()) { 468 String thisTok = tok.nextToken(); 469 if (thisTok.equals(delim)) { 470 if (previousTokenWasDelim) 471 components.add(null); 472 previousTokenWasDelim = true; 473 } else { 474 components.add(thisTok); 475 previousTokenWasDelim = false; 476 } 477 } 478 479 String[] ret = new String[components.size()]; 480 for (int i = 0; i < components.size(); i++) { 481 ret[i] = components.get(i); 482 } 483 484 return ret; 485 } 486 487 /** 488 * {@inheritDoc } 489 */ 490 @Override 491 public String doEncode(Segment structure, EncodingCharacters encodingCharacters) { 492 return encode(structure, encodingCharacters, getParserConfiguration(), null); 493 } 494 495 /** 496 * {@inheritDoc } 497 */ 498 @Override 499 public String doEncode(Type type, EncodingCharacters encodingCharacters) { 500 return encode(type, encodingCharacters, getParserConfiguration(), null); 501 } 502 503 /** 504 * Encodes the given Type, using the given encoding characters. It is 505 * assumed that the Type represents a complete field rather than a 506 * component. 507 * 508 * @param source type to be encoded 509 * @param encodingChars encoding characters to be used 510 * @return encoded type 511 */ 512 public static String encode(Type source, EncodingCharacters encodingChars) { 513 return encode(source, encodingChars, source.getMessage().getParser().getParserConfiguration(), null); 514 } 515 516 private static String encode(Type source, EncodingCharacters encodingChars, ParserConfiguration parserConfig, String currentTerserPath) { 517 if (source instanceof Varies) { 518 Varies varies = (Varies) source; 519 if (varies.getData() != null) { 520 source = varies.getData(); 521 } 522 } 523 524 StringBuilder field = new StringBuilder(); 525 for (int i = 1; i <= Terser.numComponents(source); i++) { 526 StringBuilder comp = new StringBuilder(); 527 for (int j = 1; j <= Terser.numSubComponents(source, i); j++) { 528 Primitive p = Terser.getPrimitive(source, i, j); 529 comp.append(encodePrimitive(p, parserConfig.getEscaping(), encodingChars)); 530 comp.append(encodingChars.getSubcomponentSeparator()); 531 } 532 field.append(stripExtraDelimiters(comp.toString(), encodingChars.getSubcomponentSeparator())); 533 field.append(encodingChars.getComponentSeparator()); 534 } 535 536 int forceUpToFieldNum = 0; 537 if (parserConfig != null && currentTerserPath != null) { 538 for (String nextPath : parserConfig.getForcedEncode()) { 539 if (nextPath.startsWith(currentTerserPath + "-") && nextPath.length() > currentTerserPath.length()) { 540 int endOfFieldDef = nextPath.indexOf('-', currentTerserPath.length()); 541 if (endOfFieldDef == -1) { 542 forceUpToFieldNum = 0; 543 break; 544 } 545 String fieldNumString = nextPath.substring(endOfFieldDef + 1); 546 if (fieldNumString.length() > 0) { 547 forceUpToFieldNum = Math.max(forceUpToFieldNum, Integer.parseInt(fieldNumString)); 548 } 549 } 550 } 551 } 552 553 char componentSeparator = encodingChars.getComponentSeparator(); 554 String retVal = stripExtraDelimiters(field.toString(), componentSeparator); 555 556 while (forceUpToFieldNum > 0 && (countInstancesOf(retVal, componentSeparator) + 1) < forceUpToFieldNum) { 557 retVal = retVal + componentSeparator; 558 } 559 560 return retVal; 561 } 562 563 private static String encodePrimitive(Primitive p, Escaping escaping, EncodingCharacters encodingChars) { 564 String val = (p).getValue(); 565 if (val == null) { 566 val = ""; 567 } else { 568 val = escaping.escape(val, encodingChars); 569 } 570 return val; 571 } 572 573 /** 574 * Removes unecessary delimiters from the end of a field or segment. This 575 * seems to be more convenient than checking to see if they are needed while 576 * we are building the encoded string. 577 */ 578 private static String stripExtraDelimiters(String in, char delim) { 579 char[] chars = in.toCharArray(); 580 581 // search from back end for first occurance of non-delimiter ... 582 int c = chars.length - 1; 583 boolean found = false; 584 while (c >= 0 && !found) { 585 if (chars[c--] != delim) 586 found = true; 587 } 588 589 String ret = ""; 590 if (found) 591 ret = String.valueOf(chars, 0, c + 2); 592 return ret; 593 } 594 595 /** 596 * Formats a Message object into an HL7 message string using the given 597 * encoding. 598 * 599 * @throws HL7Exception 600 * if the data fields in the message do not permit encoding 601 * (e.g. required fields are null) 602 * @throws EncodingNotSupportedException 603 * if the requested encoding is not supported by this parser. 604 */ 605 protected String doEncode(Message source, String encoding) throws HL7Exception { 606 if (!this.supportsEncoding(encoding)) 607 throw new EncodingNotSupportedException("This parser does not support the " + encoding + " encoding"); 608 609 return encode(source); 610 } 611 612 /** 613 * Formats a Message object into an HL7 message string using this parser's 614 * default encoding ("VB"). 615 * 616 * @throws HL7Exception 617 * if the data fields in the message do not permit encoding 618 * (e.g. required fields are null) 619 */ 620 protected String doEncode(Message source) throws HL7Exception { 621 // get encoding characters ... 622 Segment msh = (Segment) source.get("MSH"); 623 String fieldSepString = Terser.get(msh, 1, 0, 1, 1); 624 625 if (fieldSepString == null) 626 throw new HL7Exception("Can't encode message: MSH-1 (field separator) is missing"); 627 628 char fieldSep = '|'; 629 if (fieldSepString.length() > 0) fieldSep = fieldSepString.charAt(0); 630 631 EncodingCharacters en = getValidEncodingCharacters(fieldSep, msh); 632 633 // pass down to group encoding method which will operate recursively on 634 // children ... 635 return encode(source, en, getParserConfiguration(), ""); 636 } 637 638 private EncodingCharacters getValidEncodingCharacters(char fieldSep, Segment msh) throws HL7Exception { 639 String encCharString = Terser.get(msh, 2, 0, 1, 1); 640 641 if (encCharString == null) { 642 throw new HL7Exception("Can't encode message: MSH-2 (encoding characters) is missing"); 643 } 644 645 if (Version.V27.isGreaterThan(Version.versionOf(msh.getMessage().getVersion())) && encCharString.length() != 4) { 646 throw new HL7Exception("Encoding characters (MSH-2) value '" + encCharString + "' invalid -- must be 4 characters", ErrorCode.DATA_TYPE_ERROR); 647 } else if (encCharString.length() != 4 && encCharString.length() != 5) { 648 throw new HL7Exception("Encoding characters (MSH-2) value '" + encCharString + "' invalid -- must be 4 or 5 characters", ErrorCode.DATA_TYPE_ERROR); 649 } 650 651 return new EncodingCharacters(fieldSep, encCharString); 652 } 653 654 /** 655 * Returns given group serialized as a pipe-encoded string - this method is 656 * called by encode(Message source, String encoding). 657 * 658 * @param source group to be encoded 659 * @param encodingChars encoding characters to be used 660 * @throws HL7Exception if an error occurred while encoding 661 * @return encoded group 662 */ 663 public static String encode(Group source, EncodingCharacters encodingChars) throws HL7Exception { 664 return encode(source, encodingChars, source.getMessage().getParser().getParserConfiguration(), ""); 665 } 666 667 /** 668 * Returns given group serialized as a pipe-encoded string - this method is 669 * called by encode(Message source, String encoding). 670 */ 671 private static String encode(Group source, EncodingCharacters encodingChars, ParserConfiguration parserConfiguration, String currentTerserPath) throws HL7Exception { 672 StringBuilder result = new StringBuilder(); 673 674 String[] names = source.getNames(); 675 676 String firstMandatorySegmentName = null; 677 boolean haveEncounteredMandatorySegment = false; 678 boolean haveEncounteredContent = false; 679 boolean haveHadMandatorySegment = false; 680 boolean haveHadSegmentBeforeMandatorySegment = false; 681 682 for (String nextName : names) { 683 684 // source.get(nextName, 0); 685 Structure[] reps = source.getAll(nextName); 686 boolean nextNameIsRequired = source.isRequired(nextName); 687 688 boolean havePreviouslyEncounteredMandatorySegment = haveEncounteredMandatorySegment; 689 haveEncounteredMandatorySegment |= nextNameIsRequired; 690 if (nextNameIsRequired && !haveHadMandatorySegment) { 691 if (!source.isGroup(nextName)) { 692 firstMandatorySegmentName = nextName; 693 } 694 } 695 696 String nextTerserPath = currentTerserPath.length() > 0 ? currentTerserPath + "/" + nextName : nextName; 697 698 // Add all reps of the next segment/group 699 for (Structure rep : reps) { 700 701 if (rep instanceof Group) { 702 703 String encodedGroup = encode((Group) rep, encodingChars, parserConfiguration, nextTerserPath); 704 result.append(encodedGroup); 705 706 if (encodedGroup.length() > 0) { 707 if (!haveHadMandatorySegment && !haveEncounteredMandatorySegment) { 708 haveHadSegmentBeforeMandatorySegment = true; 709 } 710 if (nextNameIsRequired && !haveHadMandatorySegment && !havePreviouslyEncounteredMandatorySegment) { 711 haveHadMandatorySegment = true; 712 } 713 haveEncounteredContent = true; 714 } 715 716 } else { 717 718 // Check if we are configured to force the encoding of this 719 // segment 720 boolean encodeEmptySegments = parserConfiguration.determineForcedEncodeIncludesTerserPath(nextTerserPath); 721 String segString = encode((Segment) rep, encodingChars, parserConfiguration, nextTerserPath); 722 if (segString.length() >= 4 || encodeEmptySegments) { 723 result.append(segString); 724 725 if (segString.length() == 3) { 726 result.append(encodingChars.getFieldSeparator()); 727 } 728 729 result.append(SEGMENT_DELIMITER); 730 731 haveEncounteredContent = true; 732 733 if (nextNameIsRequired) { 734 haveHadMandatorySegment = true; 735 } 736 737 if (!haveHadMandatorySegment && !haveEncounteredMandatorySegment) { 738 haveHadSegmentBeforeMandatorySegment = true; 739 } 740 741 } 742 743 } 744 745 } 746 747 } 748 749 if (firstMandatorySegmentName != null && !haveHadMandatorySegment && !haveHadSegmentBeforeMandatorySegment && haveEncounteredContent && parserConfiguration.isEncodeEmptyMandatorySegments()) { 750 return firstMandatorySegmentName.substring(0, 3) + encodingChars.getFieldSeparator() + SEGMENT_DELIMITER + result; 751 } else { 752 return result.toString(); 753 } 754 } 755 756 /** 757 * Convenience factory method which returns an instance that has a new 758 * {@link DefaultHapiContext} initialized with a {@link NoValidation 759 * NoValidation validation context}. 760 * 761 * @return PipeParser with disabled validation 762 */ 763 public static PipeParser getInstanceWithNoValidation() { 764 HapiContext context = new DefaultHapiContext(); 765 context.setValidationContext(ValidationContextFactory.noValidation()); 766 return new PipeParser(context); 767 } 768 769 /** 770 * Returns given segment serialized as a pipe-encoded string. 771 * 772 * @param source segment to be encoded 773 * @param encodingChars encoding characters to be used 774 * @return encoded group 775 */ 776 public static String encode(Segment source, EncodingCharacters encodingChars) { 777 return encode(source, encodingChars, source.getMessage().getParser().getParserConfiguration(), null); 778 } 779 780 private static String encode(Segment source, EncodingCharacters encodingChars, ParserConfiguration parserConfig, String currentTerserPath) { 781 StringBuilder result = new StringBuilder(); 782 result.append(source.getName()); 783 result.append(encodingChars.getFieldSeparator()); 784 785 // start at field 2 for MSH segment because field 1 is the field 786 // delimiter 787 int startAt = 1; 788 if (isDelimDefSegment(source.getName())) 789 startAt = 2; 790 791 // loop through fields; for every field delimit any repetitions and add 792 // field delimiter after ... 793 int numFields = source.numFields(); 794 795 int forceUpToFieldNum = 0; 796 if (parserConfig != null && currentTerserPath != null) { 797 forceUpToFieldNum = parserConfig.determineForcedFieldNumForTerserPath(currentTerserPath); 798 } 799 numFields = Math.max(numFields, forceUpToFieldNum); 800 801 for (int i = startAt; i <= numFields; i++) { 802 803 String nextFieldTerserPath = currentTerserPath + "-" + i; 804 if (parserConfig != null && currentTerserPath != null) { 805 for (String nextPath : parserConfig.getForcedEncode()) { 806 if (nextPath.startsWith(nextFieldTerserPath + "-")) { 807 try { 808 source.getField(i, 0); 809 } catch (HL7Exception e) { 810 log.error("Error while encoding segment: ", e); 811 } 812 } 813 } 814 } 815 816 try { 817 Type[] reps = source.getField(i); 818 for (int j = 0; j < reps.length; j++) { 819 String fieldText = encode(reps[j], encodingChars, parserConfig, nextFieldTerserPath); 820 // if this is MSH-2, then it shouldn't be escaped, so 821 // unescape it again 822 if (isDelimDefSegment(source.getName()) && i == 2) 823 fieldText = parserConfig.getEscaping().unescape(fieldText, encodingChars); 824 result.append(fieldText); 825 if (j < reps.length - 1) 826 result.append(encodingChars.getRepetitionSeparator()); 827 } 828 } catch (HL7Exception e) { 829 log.error("Error while encoding segment: ", e); 830 } 831 result.append(encodingChars.getFieldSeparator()); 832 } 833 834 // strip trailing delimiters ... 835 char fieldSeparator = encodingChars.getFieldSeparator(); 836 String retVal = stripExtraDelimiters(result.toString(), fieldSeparator); 837 838 int offset = isDelimDefSegment(source.getName()) ? 1 : 0; 839 while (forceUpToFieldNum > 0 && (countInstancesOf(retVal, fieldSeparator) + offset) < forceUpToFieldNum) { 840 retVal = retVal + fieldSeparator; 841 } 842 843 return retVal; 844 } 845 846 private static int countInstancesOf(String theString, char theCharToSearchFor) { 847 int retVal = 0; 848 for (int i = 0; i < theString.length(); i++) { 849 if (theString.charAt(i) == theCharToSearchFor) { 850 retVal++; 851 } 852 } 853 return retVal; 854 } 855 856 /** 857 * Removes leading whitespace from the given string. This method was created 858 * to deal with frequent problems parsing messages that have been 859 * hand-written in windows. The intuitive way to delimit segments is to hit 860 * <ENTER> at the end of each segment, but this creates both a carriage 861 * return and a line feed, so to the parser, the first character of the next 862 * segment is the line feed. 863 * 864 * @param in input string 865 * @return string with leading whitespaces removed 866 */ 867 public static String stripLeadingWhitespace(String in) { 868 StringBuilder out = new StringBuilder(); 869 char[] chars = in.toCharArray(); 870 int c = 0; 871 while (c < chars.length) { 872 if (!Character.isWhitespace(chars[c])) 873 break; 874 c++; 875 } 876 for (int i = c; i < chars.length; i++) { 877 out.append(chars[i]); 878 } 879 return out.toString(); 880 } 881 882 /** 883 * <p> 884 * Returns a minimal amount of data from a message string, including only 885 * the data needed to send a response to the remote system. This includes 886 * the following fields: 887 * <ul> 888 * <li>field separator</li> 889 * <li>encoding characters</li> 890 * <li>processing ID</li> 891 * <li>message control ID</li> 892 * </ul> 893 * This method is intended for use when there is an error parsing a message, 894 * (so the Message object is unavailable) but an error message must be sent 895 * back to the remote system including some of the information in the 896 * inbound message. This method parses only that required information, 897 * hopefully avoiding the condition that caused the original error. The 898 * other fields in the returned MSH segment are empty. 899 * </p> 900 */ 901 public Segment getCriticalResponseData(String message) throws HL7Exception { 902 // try to get MSH segment 903 int locStartMSH = message.indexOf("MSH"); 904 if (locStartMSH < 0) 905 throw new HL7Exception("Couldn't find MSH segment in message: " + message, ErrorCode.SEGMENT_SEQUENCE_ERROR); 906 int locEndMSH = message.indexOf('\r', locStartMSH + 1); 907 if (locEndMSH < 0) 908 locEndMSH = message.length(); 909 String mshString = message.substring(locStartMSH, locEndMSH); 910 911 // find out what the field separator is 912 char fieldSep = mshString.charAt(3); 913 914 // get field array 915 String[] fields = split(mshString, String.valueOf(fieldSep)); 916 917 try { 918 // parse required fields 919 String encChars = fields[1]; 920 char compSep = encChars.charAt(0); 921 String messControlID = fields[9]; 922 String[] procIDComps = split(fields[10], String.valueOf(compSep)); 923 924 // fill MSH segment 925 String version = null; 926 try { 927 version = getVersion(message); 928 } catch (Exception e) { /* use the default */ 929 } 930 931 if (version == null) { 932 Version availableVersion = Version.highestAvailableVersionOrDefault(); 933 version = availableVersion.getVersion(); 934 } 935 936 Segment msh = Parser.makeControlMSH(version, getFactory()); 937 Terser.set(msh, 1, 0, 1, 1, String.valueOf(fieldSep)); 938 Terser.set(msh, 2, 0, 1, 1, encChars); 939 Terser.set(msh, 10, 0, 1, 1, messControlID); 940 Terser.set(msh, 11, 0, 1, 1, procIDComps[0]); 941 Terser.set(msh, 12, 0, 1, 1, version); 942 return msh; 943 944 } catch (Exception e) { 945 throw new HL7Exception("Can't parse critical fields from MSH segment (" + e.getClass().getName() + ": " + e.getMessage() + "): " + mshString, ErrorCode.REQUIRED_FIELD_MISSING, e); 946 } 947 948 } 949 950 /** 951 * For response messages, returns the value of MSA-2 (the message ID of the 952 * message sent by the sending system). This value may be needed prior to 953 * main message parsing, so that (particularly in a multi-threaded scenario) 954 * the message can be routed to the thread that sent the request. We need 955 * this information first so that any parse exceptions are thrown to the 956 * correct thread. Returns null if MSA-2 can not be found (e.g. if the 957 * message is not a response message). 958 */ 959 public String getAckID(String message) { 960 String ackID = null; 961 int startMSA = message.indexOf("\rMSA"); 962 if (startMSA >= 0) { 963 int startFieldOne = startMSA + 5; 964 char fieldDelim = message.charAt(startFieldOne - 1); 965 int start = message.indexOf(fieldDelim, startFieldOne) + 1; 966 int end = message.indexOf(fieldDelim, start); 967 int segEnd = message.indexOf(SEGMENT_DELIMITER, start); 968 if (segEnd > start && segEnd < end) 969 end = segEnd; 970 971 // if there is no field delim after MSH-2, need to go to end of 972 // message, but not including end seg delim if it exists 973 if (end < 0) { 974 if (message.charAt(message.length() - 1) == '\r') { 975 end = message.length() - 1; 976 } else { 977 end = message.length(); 978 } 979 } 980 if (start > 0 && end > start) { 981 ackID = message.substring(start, end); 982 } 983 } 984 log.trace("ACK ID: {}", ackID); 985 return ackID; 986 } 987 988 /** 989 * Defaults to <code>false</code> 990 * 991 * @see #isLegacyMode() 992 * @deprecated This will be removed in HAPI 3.0 993 */ 994 public void setLegacyMode(boolean legacyMode) { 995 this.myLegacyMode = legacyMode; 996 } 997 998 /** 999 * {@inheritDoc } 1000 */ 1001 @Override 1002 public String encode(Message source) throws HL7Exception { 1003 if (myLegacyMode != null && myLegacyMode) { 1004 1005 @SuppressWarnings("deprecation") 1006 OldPipeParser oldPipeParser = new OldPipeParser(getFactory()); 1007 1008 return oldPipeParser.encode(source); 1009 } 1010 return super.encode(source); 1011 } 1012 1013 /** 1014 * {@inheritDoc } 1015 */ 1016 @Override 1017 public Message parse(String message) throws HL7Exception { 1018 if (myLegacyMode != null && myLegacyMode) { 1019 1020 @SuppressWarnings("deprecation") 1021 OldPipeParser oldPipeParser = new OldPipeParser(getFactory()); 1022 1023 return oldPipeParser.parse(message); 1024 } 1025 return super.parse(message); 1026 } 1027 1028 /** 1029 * <p> 1030 * Returns <code>true</code> if legacy mode is on. 1031 * </p> 1032 * <p> 1033 * Prior to release 1.0, when an unexpected segment was encountered in a 1034 * message, HAPI would recurse to the deepest nesting in the last group it 1035 * encountered after the current position in the message, and deposit the 1036 * segment there. This could lead to unusual behaviour where all segments 1037 * afterward would not be in an expected spot within the message. 1038 * </p> 1039 * <p> 1040 * This should normally be set to false, but any code written before the 1041 * release of HAPI 1.0 which depended on this behaviour might need legacy 1042 * mode to be set to true. 1043 * </p> 1044 * <p> 1045 * Defaults to <code>false</code>. Note that this method only overrides 1046 * behaviour of the {@link #parse(java.lang.String)} and 1047 * {@link #encode(ca.uhn.hl7v2.model.Message) } methods 1048 * </p> 1049 * 1050 * @deprecated This will be removed in HAPI 3.0 1051 */ 1052 public boolean isLegacyMode() { 1053 if (myLegacyMode == null) 1054 return (Boolean.parseBoolean(System.getProperty(DEFAULT_LEGACY_MODE_PROPERTY))); 1055 return this.myLegacyMode; 1056 } 1057 1058 /** 1059 * Returns the version ID (MSH-12) from the given message, without fully 1060 * parsing the message. The version is needed prior to parsing in order to 1061 * determine the message class into which the text of the message should be 1062 * parsed. 1063 * 1064 * @throws HL7Exception 1065 * if the version field can not be found. 1066 */ 1067 public String getVersion(String message) throws HL7Exception { 1068 int startMSH = message.indexOf("MSH"); 1069 int endMSH = message.indexOf(PipeParser.SEGMENT_DELIMITER, startMSH); 1070 if (endMSH < 0) 1071 endMSH = message.length(); 1072 String msh = message.substring(startMSH, endMSH); 1073 String fieldSep; 1074 if (msh.length() > 3) { 1075 fieldSep = String.valueOf(msh.charAt(3)); 1076 } else { 1077 throw new HL7Exception("Can't find field separator in MSH: " + msh, ErrorCode.UNSUPPORTED_VERSION_ID); 1078 } 1079 1080 String[] fields = split(msh, fieldSep); 1081 1082 String compSep; 1083 if (fields.length >= 2 && fields[1] != null && (fields[1].length() == 4 || fields[1].length() == 5)) { 1084 compSep = String.valueOf(fields[1].charAt(0)); // get component separator as 1st encoding char 1085 } else { 1086 throw new HL7Exception("Invalid or incomplete encoding characters - MSH-2 is " + fields[1], ErrorCode.REQUIRED_FIELD_MISSING); 1087 } 1088 1089 String version; 1090 if (fields.length >= 12) { 1091 String[] comp = split(fields[11], compSep); 1092 if (comp.length >= 1) { 1093 version = comp[0]; 1094 } else { 1095 throw new HL7Exception("Can't find version ID - MSH.12 is " + fields[11], ErrorCode.REQUIRED_FIELD_MISSING); 1096 } 1097 } else if (getParserConfiguration().isAllowUnknownVersions()) { 1098 return Version.highestAvailableVersionOrDefault().getVersion(); 1099 } else { 1100 throw new HL7Exception("Can't find version ID - MSH has only " + fields.length + " fields.", ErrorCode.REQUIRED_FIELD_MISSING); 1101 } 1102 return version; 1103 } 1104 1105 @Override 1106 public void parse(Message message, String string) throws HL7Exception { 1107 if (message instanceof AbstractSuperMessage && message.getName() == null) { 1108 String structure = getStructure(string).messageStructure; 1109 ((AbstractSuperMessage) message).setName(structure); 1110 } 1111 1112 message.setParser(this); 1113 1114 IStructureDefinition structureDef = getStructureDefinition(message); 1115 MessageIterator messageIter = new MessageIterator(message, structureDef, "MSH", true); 1116 1117 String[] segments = split(string, SEGMENT_DELIMITER); 1118 1119 if (segments.length == 0) { 1120 throw new HL7Exception("Invalid message content: \"" + string + "\""); 1121 } 1122 1123 if (segments[0] == null || segments[0].length() < 4) { 1124 throw new HL7Exception("Invalid message content: \"" + string + "\""); 1125 } 1126 1127 char delim = '|'; 1128 String prevName = null; 1129 int repNum = 1; 1130 for (int i = 0; i < segments.length; i++) { 1131 1132 // get rid of any leading whitespace characters ... 1133 if (segments[i] != null && segments[i].length() > 0 && Character.isWhitespace(segments[i].charAt(0))) 1134 segments[i] = stripLeadingWhitespace(segments[i]); 1135 1136 // sometimes people put extra segment delimiters at end of msg ... 1137 if (segments[i] != null && segments[i].length() >= 3) { 1138 1139 final String name; 1140 if (i == 0) { 1141 if (segments[i].length() < 4) { 1142 throw new HL7Exception("Invalid message content: \"" + string + "\""); 1143 } 1144 name = segments[i].substring(0, 3); 1145 delim = segments[i].charAt(3); 1146 } else { 1147 if (segments[i].indexOf(delim) >= 0) { 1148 name = segments[i].substring(0, segments[i].indexOf(delim)); 1149 } else { 1150 name = segments[i]; 1151 } 1152 } 1153 1154 log.trace("Parsing segment {}", name); 1155 1156 if (name.equals(prevName)) { 1157 repNum++; 1158 } else { 1159 repNum = 1; 1160 prevName = name; 1161 } 1162 1163 messageIter.setDirection(name); 1164 1165 try { 1166 if (messageIter.hasNext()) { 1167 Segment next = (Segment) messageIter.next(); 1168 parse(next, segments[i], getEncodingChars(string), repNum); 1169 } 1170 } catch (Error e) { 1171 if (e.getCause() instanceof HL7Exception) { 1172 throw (HL7Exception)e.getCause(); 1173 } 1174 throw e; 1175 } 1176 } 1177 } 1178 1179 applySuperStructureName(message); 1180 } 1181 1182 /** 1183 * A struct for holding a message class string and a boolean indicating 1184 * whether it was defined explicitly. 1185 */ 1186 private static class MessageStructure { 1187 public final String messageStructure; 1188 public final boolean explicitlyDefined; 1189 1190 public MessageStructure(String theMessageStructure, boolean isExplicitlyDefined) { 1191 messageStructure = theMessageStructure; 1192 explicitlyDefined = isExplicitlyDefined; 1193 } 1194 } 1195 1196 private static class Holder<T> { 1197 private T myObject; 1198 1199 public T getObject() { 1200 return myObject; 1201 } 1202 1203 public void setObject(T theObject) { 1204 myObject = theObject; 1205 } 1206 } 1207 1208}