View Javadoc

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     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     public Terser(Message message) {
122     	if (message == null) {
123     		throw new NullPointerException("Message may not be null");
124     	}
125         finder = new SegmentFinder(message);
126     }
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         if (segment == null) {
141             throw new NullPointerException("segment may not be null");
142         }
143         if (rep < 0) {
144             throw new IllegalArgumentException("rep must not be negative");
145         }
146         if (component < 1) {
147             throw new IllegalArgumentException(
148                     "component must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
149         }
150         if (subcomponent < 1) {
151             throw new IllegalArgumentException(
152                     "subcomponent must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
153         }
154 
155         Primitive prim = getPrimitive(segment, field, rep, component, subcomponent);
156         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         if (segment == null) {
173             throw new NullPointerException("segment may not be null");
174         }
175         if (rep < 0) {
176             throw new IllegalArgumentException("rep must not be negative");
177         }
178         if (component < 1) {
179             throw new IllegalArgumentException(
180                     "component must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
181         }
182         if (subcomponent < 1) {
183             throw new IllegalArgumentException(
184                     "subcomponent must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
185         }
186 
187         Primitive prim = getPrimitive(segment, field, rep, component, subcomponent);
188         prim.setValue(value);
189     }
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         Type type = segment.getField(field, rep);
197         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         if (type == null) {
213             throw new NullPointerException("type may not be null");
214         }
215         if (component < 1) {
216             throw new IllegalArgumentException(
217                     "component must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
218         }
219         if (subcomponent < 1) {
220             throw new IllegalArgumentException(
221                     "subcomponent must not be 1 or more (note that this parameter is 1-indexed, not 0-indexed)");
222         }
223 
224         Type comp = getComponent(type, component);
225         if (type instanceof Varies && comp instanceof GenericPrimitive && subcomponent > 1) {
226             try {
227                 final Varies varies = (Varies) type;
228                 final GenericComposite comp2 = new GenericComposite(type.getMessage());
229                 varies.setData(comp2);
230                 comp = getComponent(type, component);
231             } catch (final DataTypeException de) {
232                 final String message = "Unexpected exception copying data to generic composite. This is probably a bug within HAPI. "
233                         + de.getMessage();
234                 log.error(message, de);
235                 throw new Error(message);
236             }
237         }
238         final Type sub = getComponent(comp, subcomponent);
239         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         if (type instanceof Primitive) {
248             return (Primitive) type;
249         }
250         if (type instanceof Composite) {
251             try {
252                 return getPrimitive(((Composite) type).getComponent(0));
253             } catch (HL7Exception e) {
254                 throw new RuntimeException("Internal error: HL7Exception thrown on Composite.getComponent(0).");
255             }
256         }
257         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         if (type instanceof Primitive && comp == 1) {
269             return type;
270         }
271         if (type instanceof Composite) {
272             if (comp <= numStandardComponents(type) || type instanceof GenericComposite) {
273                 try {
274                     return ((Composite) type).getComponent(comp - 1);
275                 } catch (DataTypeException e) {
276                     throw new RuntimeException(
277                             "Internal error: HL7Exception thrown on getComponent(x) where x < # standard components.",
278                             e);
279                 }
280             }
281         }
282         if (Varies.class.isAssignableFrom(type.getClass())) {
283             Varies v = (Varies) type;
284             try {
285                 if (comp > 1 && GenericPrimitive.class.isAssignableFrom(v.getData().getClass()))
286                     v.setData(new GenericComposite(v.getMessage()));
287             } catch (DataTypeException e) {
288                 throw new RuntimeException("Unexpected exception copying data to generic composite: " + e.getMessage(),
289                         e);
290             }
291 
292             return getComponent(v.getData(), comp);
293         }
294 
295         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         StringTokenizer tok = new StringTokenizer(spec, "-", false);
314         Segment segment = getSegment(tok.nextToken());
315 
316         int[] ind = getIndices(spec);
317         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         Segment seg = null;
329 
330         if (segSpec.startsWith("/")) {
331             getFinder().reset();
332         }
333 
334         StringTokenizer tok = new StringTokenizer(segSpec, "/", false);
335         SegmentFinder finder = getFinder();
336         while (tok.hasMoreTokens()) {
337             String pathSpec = tok.nextToken();
338             Terser.PathSpec ps = parsePathSpec(pathSpec);
339             ps.isGroup = tok.hasMoreTokens();
340             if (ps.isGroup) {
341                 Group g = ps.find ?
342                         finder.findGroup(ps.pattern, ps.rep) :
343                         finder.getGroup(ps.pattern, ps.rep);
344                 finder = new SegmentFinder(g);
345             } else {
346                 seg = ps.find ?
347                         finder.findSegment(ps.pattern, ps.rep) :
348                         finder.getSegment(ps.pattern, ps.rep);
349             }
350         }
351 
352         return seg;
353     }
354 
355     /** Gets path information from a path spec. */
356     private PathSpec parsePathSpec(String spec) throws HL7Exception {
357         PathSpec ps = new PathSpec();
358 
359         if (spec.startsWith(".")) {
360             ps.find = true;
361             spec = spec.substring(1);
362         } else {
363             ps.find = false;
364         }
365 
366         if (spec.length() == 0) {
367             throw new HL7Exception("Invalid path (some path element is either empty or contains only a dot)");
368         }
369         StringTokenizer tok = new StringTokenizer(spec, "()", false);
370         ps.pattern = tok.nextToken();
371         if (tok.hasMoreTokens()) {
372             String repString = tok.nextToken();
373             try {
374                 ps.rep = Integer.parseInt(repString);
375             } catch (NumberFormatException e) {
376                 throw new HL7Exception(repString + " is not a valid rep #");
377             }
378         } else {
379             ps.rep = 0;
380         }
381         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         StringTokenizer tok = new StringTokenizer(spec, "-", false);
394         tok.nextToken(); // skip over segment
395         if (!tok.hasMoreTokens())
396             throw new HL7Exception("Must specify field in spec " + spec);
397         try {
398             StringTokenizer fieldSpec = new StringTokenizer(tok.nextToken(), "()", false);
399             int fieldNum = Integer.parseInt(fieldSpec.nextToken());
400             int fieldRep = fieldSpec.hasMoreTokens() ?
401                     Integer.parseInt(fieldSpec.nextToken()) : 0;
402             int component = tok.hasMoreTokens() ?
403                     Integer.parseInt(tok.nextToken()) : 1;
404             int subcomponent = tok.hasMoreTokens() ?
405                     Integer.parseInt(tok.nextToken()) : 1;
406             return new int[] { fieldNum, fieldRep, component, subcomponent };
407         } catch (NumberFormatException e) {
408             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         StringTokenizer tok = new StringTokenizer(spec, "-", false);
422         Segment segment = getSegment(tok.nextToken());
423 
424         int[] ind = getIndices(spec);
425         log.trace("Setting {} seg: {} ind: {} {} {} {}", new Object[] { spec, segment.getName(), ind[0], ind[1],
426                 ind[2], ind[3] });
427         set(segment, ind[0], ind[1], ind[2], ind[3], value);
428     }
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         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             return 1;
445         }
446         Type comp = getComponent(type, component);
447         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         if (!(t instanceof Varies)) {
459             return numStandardComponents(t) + t.getExtraComponents().numComponents();
460         }
461         return numComponents(((Varies) t).getData());
462     }
463 
464     private static int numStandardComponents(Type t) {
465         if (t instanceof Composite) {
466             return ((Composite) t).getComponents().length;
467         }
468         if (t instanceof Varies) {
469             return numStandardComponents(((Varies) t).getData());
470         }
471         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         return finder;
483     }
484 
485     /** Struct for information about a step in a segment path. */
486     private class PathSpec {
487         public String pattern;
488         public boolean isGroup;
489         public boolean find;
490         public int rep;
491     }
492 }