Coverage Report - ca.uhn.hl7v2.util.Terser
 
Classes in this File Line Coverage Branch Coverage Complexity
Terser
80%
112/140
83%
70/84
5.875
Terser$1
N/A
N/A
5.875
Terser$PathSpec
100%
1/1
N/A
5.875
 
 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 "Terser.java".  Description:
 10  
  * "Wraps a message to provide access to fields using a more terse syntax."
 11  
  *
 12  
  * The Initial Developer of the Original Code is University Health Network. Copyright (C)
 13  
  * 2002.  All Rights Reserved.
 14  
  *
 15  
  * Contributor(s): Ryan W. Gross (General Electric Corporation - Healthcare IT).
 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.util;
 29  
 
 30  
 import ca.uhn.hl7v2.model.*;
 31  
 import ca.uhn.hl7v2.HL7Exception;
 32  
 import java.util.StringTokenizer;
 33  
 
 34  
 import org.slf4j.Logger;
 35  
 import org.slf4j.LoggerFactory;
 36  
 
 37  
 /**
 38  
  * <p>
 39  
  * Wraps a message to provide access to fields using a terse location specification syntax. For
 40  
  * example:
 41  
  * </p>
 42  
  * <p>
 43  
  * <code>terser.set("MSH-9-3", "ADT_A01");</code> <br>
 44  
  * can be used instead of <br>
 45  
  * <code>message.getMSH().getMessageType().getMessageStructure().setValue("ADT_A01"); </code>
 46  
  * </p>
 47  
  * <p>
 48  
  * The syntax of a location spec is as follows:
 49  
  * </p>
 50  
  * <p>
 51  
  * location_spec:
 52  
  * <code>segment_path_spec "-" field ["(" rep ")"] ["-" component ["-" subcomponent]] </code>
 53  
  * </p>
 54  
  * <p>
 55  
  * ... where rep, field, component, and subcomponent are integers (representing, respectively, the
 56  
  * field repetition (starting at 0), and the field number, component number, and subcomponent
 57  
  * numbers (starting at 1). Omitting the rep is equivalent to specifying 0; omitting the component
 58  
  * or subcomponent is equivalent to specifying 1.
 59  
  * </p>
 60  
  * <p>
 61  
  * The syntax for the segment_path_spec is as follows:
 62  
  * </p>
 63  
  * <p>
 64  
  * segment_path_spec: </code> ["/"] (group_spec ["(" rep ")"] "/")* segment_spec ["(" rep
 65  
  * ")"]</code>
 66  
  * </p>
 67  
  * <p>
 68  
  * ... where rep has the same meaning as for fields.
 69  
  * </p>
 70  
  * <p>
 71  
  * A leading "/" indicates that navigation to the
 72  
  * location begins at the root of the message; omitting this indicates that navigation begins at
 73  
  * the current location of the underlying SegmentFinder (see getFinder() -- this allows manual
 74  
  * navigation if desired). The syntax for group_spec is:
 75  
  * </p>
 76  
  * <p>
 77  
  * group_spec: <code>["."] group_name_pattern</code>
 78  
  * </p>
 79  
  * <p>
 80  
  * Here, a . indicates that the group should be searched for (using a SegmentFinder) starting at the
 81  
  * current location in the message. The wildcards "*" and "?" represent any number of arbitrary
 82  
  * characters, and a single arbitrary character, respectively. For example, "M*" and "?S?" match
 83  
  * MSH. The first group with a name that matches the given group_name_pattern will be matched.
 84  
  * </p>
 85  
  * <p>
 86  
  * The segment_spec is analogous to the group_spec.
 87  
  * </p>
 88  
  * <p>
 89  
  * As another example, the following subcomponent in an SIU_S12 message:
 90  
  * <p>
 91  
  * <p>
 92  
  * <code>msg.getSIU_S12_RGSAISNTEAIGNTEAILNTEAIPNTE(1).getSIU_S12_AIGNTE().getAIG().getResourceGroup(1).getIdentifier();</code>
 93  
  * </p>
 94  
  * </p> ... is referenced by all of the following location_spec: </p>
 95  
  * <p>
 96  
  * <code>/SIU_S12_RGSAISNTEAIGNTEAILNTEAIPNTE(1)/SIU_S12_AIGNTE/AIG-5(1)-1 <br>
 97  
  * /*AIG*(1)/SIU_S12_AIGNTE/AIG-5(1)-1 <br>
 98  
  * /*AIG*(1)/.AIG-5(1) <code>
 99  
  * </p>
 100  
  * <p>
 101  
  * The search function only iterates through rep 0 of each group. Thus if rep 0 of the first group
 102  
  * in this example was desired instead of rep 1, the following syntax would also work (since there
 103  
  * is only one AIG segment position in SUI_S12):
 104  
  * </p>
 105  
  * <p>
 106  
  * <code>/.AIG-5(1)</code>
 107  
  * </p>
 108  
  * 
 109  
  * @author Bryan Tripp
 110  
  * @author Ryan W. Gross (General Electric Corporation - Healthcare IT).
 111  
  */
 112  
 public class Terser {
 113  
 
 114  
     private SegmentFinder finder;
 115  1
     private static Logger log = LoggerFactory.getLogger(Terser.class);
 116  
 
 117  
     /** Creates a new instance of Terser
 118  
      *
 119  
      * @param message message for which the Terser is created
 120  
      */
 121  1643
     public Terser(Message message) {
 122  1643
             if (message == null) {
 123  1
                     throw new NullPointerException("Message may not be null");
 124  
             }
 125  1642
         finder = new SegmentFinder(message);
 126  1642
     }
 127  
 
 128  
     /**
 129  
      * Returns the string value of the Primitive at the given location.
 130  
      * 
 131  
      * @param segment the segment from which to get the primitive
 132  
      * @param field the field number (indexed from 1)
 133  
      * @param rep the field repetition (indexed from 0)
 134  
      * @param component the component number (indexed from 1, use 1 for primitive field)
 135  
      * @param subcomponent the subcomponent number (indexed from 1, use 1 for primitive component)
 136  
      * @return string value of the Primitive at the given location
 137  
      * @throws HL7Exception if the primitive could not be obtained
 138  
      */
 139  
     public static String get(Segment segment, int field, int rep, int component, int subcomponent) throws HL7Exception {
 140  5732
         if (segment == null) {
 141  0
             throw new NullPointerException("segment may not be null");
 142  
         }
 143  5732
         if (rep < 0) {
 144  0
             throw new IllegalArgumentException("rep must not be negative");
 145  
         }
 146  5732
         if (component < 1) {
 147  0
             throw new IllegalArgumentException(
 148  
                     "component must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
 149  
         }
 150  5732
         if (subcomponent < 1) {
 151  0
             throw new IllegalArgumentException(
 152  
                     "subcomponent must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
 153  
         }
 154  
 
 155  5732
         Primitive prim = getPrimitive(segment, field, rep, component, subcomponent);
 156  5732
         return prim.getValue();
 157  
     }
 158  
 
 159  
     /**
 160  
      * Sets the string value of the Primitive at the given location.
 161  
      * 
 162  
      * @param segment the segment from which to get the primitive
 163  
      * @param field the field number (indexed from 1)
 164  
      * @param rep the field repetition (indexed from 0)
 165  
      * @param component the component number (indexed from 1, use 1 for primitive field)
 166  
      * @param subcomponent the subcomponent number (indexed from 1, use 1 for primitive component)
 167  
      * @param value value to be set
 168  
      * @throws HL7Exception if the value could not be set
 169  
      */
 170  
     public static void set(Segment segment, int field, int rep, int component, int subcomponent, String value)
 171  
             throws HL7Exception {
 172  3819
         if (segment == null) {
 173  0
             throw new NullPointerException("segment may not be null");
 174  
         }
 175  3819
         if (rep < 0) {
 176  0
             throw new IllegalArgumentException("rep must not be negative");
 177  
         }
 178  3819
         if (component < 1) {
 179  0
             throw new IllegalArgumentException(
 180  
                     "component must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
 181  
         }
 182  3819
         if (subcomponent < 1) {
 183  0
             throw new IllegalArgumentException(
 184  
                     "subcomponent must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
 185  
         }
 186  
 
 187  3819
         Primitive prim = getPrimitive(segment, field, rep, component, subcomponent);
 188  3819
         prim.setValue(value);
 189  3819
     }
 190  
 
 191  
     /**
 192  
      * Returns the Primitive object at the given location.
 193  
      */
 194  
     private static Primitive getPrimitive(Segment segment, int field, int rep, int component, int subcomponent)
 195  
             throws HL7Exception {
 196  9551
         Type type = segment.getField(field, rep);
 197  9551
         return getPrimitive(type, component, subcomponent);
 198  
     }
 199  
 
 200  
     /**
 201  
      * Returns the Primitive object at the given location in the given field. It is intended that
 202  
      * the given type be at the field level, although extra components will be added blindly if, for
 203  
      * example, you provide a primitive subcomponent instead and specify component or subcomponent >
 204  
      * 1
 205  
      * 
 206  
      * @param type the type from which to get the primitive
 207  
      * @param component the component number (indexed from 1, use 1 for primitive field)
 208  
      * @param subcomponent the subcomponent number (indexed from 1, use 1 for primitive component)
 209  
      * @return the Primitive object at the given location
 210  
      */
 211  
     public static Primitive getPrimitive(final Type type, final int component, final int subcomponent) {
 212  66576
         if (type == null) {
 213  0
             throw new NullPointerException("type may not be null");
 214  
         }
 215  66576
         if (component < 1) {
 216  0
             throw new IllegalArgumentException(
 217  
                     "component must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
 218  
         }
 219  66576
         if (subcomponent < 1) {
 220  0
             throw new IllegalArgumentException(
 221  
                     "subcomponent must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
 222  
         }
 223  
 
 224  66576
         Type comp = getComponent(type, component);
 225  66576
         if (type instanceof Varies && comp instanceof GenericPrimitive && subcomponent > 1) {
 226  
             try {
 227  10
                 final Varies varies = (Varies) type;
 228  10
                 final GenericComposite comp2 = new GenericComposite(type.getMessage());
 229  10
                 varies.setData(comp2);
 230  10
                 comp = getComponent(type, component);
 231  0
             } catch (final DataTypeException de) {
 232  0
                 final String message = "Unexpected exception copying data to generic composite. This is probably a bug within HAPI. "
 233  
                         + de.getMessage();
 234  0
                 log.error(message, de);
 235  0
                 throw new Error(message);
 236  10
             }
 237  
         }
 238  66576
         final Type sub = getComponent(comp, subcomponent);
 239  66576
         return getPrimitive(sub);
 240  
     }
 241  
 
 242  
     /**
 243  
      * Attempts to extract a Primitive from the given type. If it's a composite, drills down through
 244  
      * first components until a primitive is reached.
 245  
      */
 246  
     private static Primitive getPrimitive(Type type) {
 247  67478
         if (type instanceof Primitive) {
 248  66576
             return (Primitive) type;
 249  
         }
 250  902
         if (type instanceof Composite) {
 251  
             try {
 252  774
                 return getPrimitive(((Composite) type).getComponent(0));
 253  0
             } catch (HL7Exception e) {
 254  0
                 throw new RuntimeException("Internal error: HL7Exception thrown on Composite.getComponent(0).");
 255  
             }
 256  
         }
 257  128
         return getPrimitive(((Varies) type).getData());
 258  
     }
 259  
 
 260  
     /**
 261  
      * Returns the component (or sub-component, as the case may be) at the given index. If it does
 262  
      * not exist, it is added as an "extra component". If comp > 1 is requested from a Varies with
 263  
      * GenericPrimitive data, the data is set to GenericComposite (this avoids the creation of a
 264  
      * chain of ExtraComponents on GenericPrimitives). Components are numbered from 1.
 265  
      */
 266  
     private static Type getComponent(Type type, int comp) {
 267  
 
 268  192164
         if (type instanceof Primitive && comp == 1) {
 269  60243
             return type;
 270  
         }
 271  131921
         if (type instanceof Composite) {
 272  130285
             if (comp <= numStandardComponents(type) || type instanceof GenericComposite) {
 273  
                 try {
 274  130203
                     return ((Composite) type).getComponent(comp - 1);
 275  0
                 } catch (DataTypeException e) {
 276  0
                     throw new RuntimeException(
 277  
                             "Internal error: HL7Exception thrown on getComponent(x) where x < # standard components.",
 278  
                             e);
 279  
                 }
 280  
             }
 281  
         }
 282  1718
         if (Varies.class.isAssignableFrom(type.getClass())) {
 283  1412
             Varies v = (Varies) type;
 284  
             try {
 285  1412
                 if (comp > 1 && GenericPrimitive.class.isAssignableFrom(v.getData().getClass()))
 286  105
                     v.setData(new GenericComposite(v.getMessage()));
 287  0
             } catch (DataTypeException e) {
 288  0
                 throw new RuntimeException("Unexpected exception copying data to generic composite: " + e.getMessage(),
 289  
                         e);
 290  1412
             }
 291  
 
 292  1412
             return getComponent(v.getData(), comp);
 293  
         }
 294  
 
 295  306
         return type.getExtraComponents().getComponent(comp - numStandardComponents(type) - 1);
 296  
     }
 297  
 
 298  
     /**
 299  
      * <p>
 300  
      * Gets the string value of the field specified. See the class docs for syntax of the location
 301  
      * spec.
 302  
      * </p>
 303  
      * <p>
 304  
      * If a repetition is omitted for a repeating segment or field, the first rep is used. If the
 305  
      * component or subcomponent is not specified for a composite field, the first component is used
 306  
      * (this allows one to write code that will work with later versions of the HL7 standard).
 307  
      *
 308  
      * @param spec field specification
 309  
      * @return string value of the specified field
 310  
      * @throws HL7Exception if the primitive could not be obtained
 311  
      */
 312  
     public String get(String spec) throws HL7Exception {
 313  3271
         StringTokenizer tok = new StringTokenizer(spec, "-", false);
 314  3271
         Segment segment = getSegment(tok.nextToken());
 315  
 
 316  3269
         int[] ind = getIndices(spec);
 317  3269
         return get(segment, ind[0], ind[1], ind[2], ind[3]);
 318  
     }
 319  
 
 320  
     /**
 321  
      * Returns the segment specified in the given segment_path_spec.
 322  
      *
 323  
      * @param segSpec segment specification
 324  
      * @return the segment specified
 325  
      * @throws HL7Exception if the segment could not be obtained
 326  
      */
 327  
     public Segment getSegment(String segSpec) throws HL7Exception {
 328  3297
         Segment seg = null;
 329  
 
 330  3297
         if (segSpec.startsWith("/")) {
 331  1140
             getFinder().reset();
 332  
         }
 333  
 
 334  3297
         StringTokenizer tok = new StringTokenizer(segSpec, "/", false);
 335  3297
         SegmentFinder finder = getFinder();
 336  6712
         while (tok.hasMoreTokens()) {
 337  3417
             String pathSpec = tok.nextToken();
 338  3417
             Terser.PathSpec ps = parsePathSpec(pathSpec);
 339  3417
             ps.isGroup = tok.hasMoreTokens();
 340  3417
             if (ps.isGroup) {
 341  120
                 Group g = ps.find ?
 342  
                         finder.findGroup(ps.pattern, ps.rep) :
 343  
                         finder.getGroup(ps.pattern, ps.rep);
 344  120
                 finder = new SegmentFinder(g);
 345  120
             } else {
 346  3297
                 seg = ps.find ?
 347  
                         finder.findSegment(ps.pattern, ps.rep) :
 348  
                         finder.getSegment(ps.pattern, ps.rep);
 349  
             }
 350  3415
         }
 351  
 
 352  3295
         return seg;
 353  
     }
 354  
 
 355  
     /** Gets path information from a path spec. */
 356  
     private PathSpec parsePathSpec(String spec) throws HL7Exception {
 357  3417
         PathSpec ps = new PathSpec();
 358  
 
 359  3417
         if (spec.startsWith(".")) {
 360  265
             ps.find = true;
 361  265
             spec = spec.substring(1);
 362  
         } else {
 363  3152
             ps.find = false;
 364  
         }
 365  
 
 366  3417
         if (spec.length() == 0) {
 367  0
             throw new HL7Exception("Invalid path (some path element is either empty or contains only a dot)");
 368  
         }
 369  3417
         StringTokenizer tok = new StringTokenizer(spec, "()", false);
 370  3417
         ps.pattern = tok.nextToken();
 371  3417
         if (tok.hasMoreTokens()) {
 372  98
             String repString = tok.nextToken();
 373  
             try {
 374  98
                 ps.rep = Integer.parseInt(repString);
 375  0
             } catch (NumberFormatException e) {
 376  0
                 throw new HL7Exception(repString + " is not a valid rep #");
 377  98
             }
 378  98
         } else {
 379  3319
             ps.rep = 0;
 380  
         }
 381  3417
         return ps;
 382  
     }
 383  
 
 384  
     /**
 385  
      * Given a Terser path, returns an array containing field num, field rep, component, and
 386  
      * subcomponent.
 387  
      *
 388  
      * @param spec field specification
 389  
      * @return an array containing field num, field rep, component, and subcomponent
 390  
      * @throws HL7Exception if the field does not exist
 391  
      */
 392  
     public static int[] getIndices(String spec) throws HL7Exception {
 393  3421
         StringTokenizer tok = new StringTokenizer(spec, "-", false);
 394  3421
         tok.nextToken(); // skip over segment
 395  3421
         if (!tok.hasMoreTokens())
 396  0
             throw new HL7Exception("Must specify field in spec " + spec);
 397  
         try {
 398  3421
             StringTokenizer fieldSpec = new StringTokenizer(tok.nextToken(), "()", false);
 399  3421
             int fieldNum = Integer.parseInt(fieldSpec.nextToken());
 400  3421
             int fieldRep = fieldSpec.hasMoreTokens() ?
 401  
                     Integer.parseInt(fieldSpec.nextToken()) : 0;
 402  3421
             int component = tok.hasMoreTokens() ?
 403  
                     Integer.parseInt(tok.nextToken()) : 1;
 404  3421
             int subcomponent = tok.hasMoreTokens() ?
 405  
                     Integer.parseInt(tok.nextToken()) : 1;
 406  3421
             return new int[] { fieldNum, fieldRep, component, subcomponent };
 407  0
         } catch (NumberFormatException e) {
 408  0
             throw new HL7Exception("Invalid integer in spec " + spec);
 409  
         }
 410  
     }
 411  
 
 412  
 
 413  
     /**
 414  
      * Sets the string value of the field specified. See class docs for location spec syntax.
 415  
      *
 416  
      * @param spec primitive path specification
 417  
      * @param value value to be set
 418  
      * @throws HL7Exception if the primitive does not exist
 419  
      */
 420  
     public void set(String spec, String value) throws HL7Exception {
 421  24
         StringTokenizer tok = new StringTokenizer(spec, "-", false);
 422  24
         Segment segment = getSegment(tok.nextToken());
 423  
 
 424  24
         int[] ind = getIndices(spec);
 425  24
         log.trace("Setting {} seg: {} ind: {} {} {} {}", new Object[] { spec, segment.getName(), ind[0], ind[1],
 426  
                 ind[2], ind[3] });
 427  24
         set(segment, ind[0], ind[1], ind[2], ind[3], value);
 428  24
     }
 429  
 
 430  
     /**
 431  
      * Returns the number of sub-components in the specified component, i.e. the number of standard
 432  
      * sub-components (e.g. 6 for CE) plus any extra components that that have been added at
 433  
      * runtime.
 434  
      *
 435  
      * @param type composite type
 436  
      * @param component numbered from 1
 437  
      * @return number of sub-components in the specified component
 438  
      */
 439  
     public static int numSubComponents(Type type, int component) {
 440  64532
         if (component == 1 && Primitive.class.isAssignableFrom(type.getClass())) {
 441  
             // note that getComponent(primitive, 1) below returns the primitive
 442  
             // itself -- if we do numComponents on it, we'll end up with the
 443  
             // number of components in the field, not the number of subcomponents
 444  6942
             return 1;
 445  
         }
 446  57590
         Type comp = getComponent(type, component);
 447  57590
         return numComponents(comp);
 448  
     }
 449  
 
 450  
     /**
 451  
      * Returns the number of components in the given type, i.e. the number of standard components
 452  
      * (e.g. 6 for CE) plus any extra components that have been added at runtime.
 453  
      *
 454  
      * @param t composite type
 455  
      * @return the number of components in the given type
 456  
      */
 457  
     public static int numComponents(Type t) {
 458  91976
         if (!(t instanceof Varies)) {
 459  91413
             return numStandardComponents(t) + t.getExtraComponents().numComponents();
 460  
         }
 461  563
         return numComponents(((Varies) t).getData());
 462  
     }
 463  
 
 464  
     private static int numStandardComponents(Type t) {
 465  222004
         if (t instanceof Composite) {
 466  177805
             return ((Composite) t).getComponents().length;
 467  
         }
 468  44199
         if (t instanceof Varies) {
 469  0
             return numStandardComponents(((Varies) t).getData());
 470  
         }
 471  44199
         return 1;
 472  
     }
 473  
 
 474  
     /**
 475  
      * Returns the segment finder used by this Terser. Navigating the finder will influence the
 476  
      * behaviour of the Terser accordingly. Ie when the full path of the segment is not specified
 477  
      * the segment will be sought beginning at the current location of the finder.
 478  
      *
 479  
      * @return the segment finder used by this Terser
 480  
      */
 481  
     public SegmentFinder getFinder() {
 482  4437
         return finder;
 483  
     }
 484  
 
 485  
     /** Struct for information about a step in a segment path. */
 486  6834
     private class PathSpec {
 487  
         public String pattern;
 488  
         public boolean isGroup;
 489  
         public boolean find;
 490  
         public int rep;
 491  
     }
 492  
 }