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 "Terser.java".  Description:
010 * "Wraps a message to provide access to fields using a more terse syntax."
011 *
012 * The Initial Developer of the Original Code is University Health Network. Copyright (C)
013 * 2002.  All Rights Reserved.
014 *
015 * Contributor(s): Ryan W. Gross (General Electric Corporation - Healthcare IT).
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.util;
029
030import ca.uhn.hl7v2.model.*;
031import ca.uhn.hl7v2.HL7Exception;
032import java.util.StringTokenizer;
033
034import org.slf4j.Logger;
035import org.slf4j.LoggerFactory;
036
037/**
038 * <p>
039 * Wraps a message to provide access to fields using a terse location specification syntax. For
040 * example:
041 * </p>
042 * <p>
043 * <code>terser.set("MSH-9-3", "ADT_A01");</code> <br>
044 * can be used instead of <br>
045 * <code>message.getMSH().getMessageType().getMessageStructure().setValue("ADT_A01"); </code>
046 * </p>
047 * <p>
048 * The syntax of a location spec is as follows:
049 * </p>
050 * <p>
051 * location_spec:
052 * <code>segment_path_spec "-" field ["(" rep ")"] ["-" component ["-" subcomponent]] </code>
053 * </p>
054 * <p>
055 * ... where rep, field, component, and subcomponent are integers (representing, respectively, the
056 * field repetition (starting at 0), and the field number, component number, and subcomponent
057 * numbers (starting at 1). Omitting the rep is equivalent to specifying 0; omitting the component
058 * or subcomponent is equivalent to specifying 1.
059 * </p>
060 * <p>
061 * The syntax for the segment_path_spec is as follows:
062 * </p>
063 * <p>
064 * segment_path_spec: </code> ["/"] (group_spec ["(" rep ")"] "/")* segment_spec ["(" rep
065 * ")"]</code>
066 * </p>
067 * <p>
068 * ... where rep has the same meaning as for fields.
069 * </p>
070 * <p>
071 * A leading "/" indicates that navigation to the
072 * location begins at the root of the message; omitting this indicates that navigation begins at
073 * the current location of the underlying SegmentFinder (see getFinder() -- this allows manual
074 * navigation if desired). The syntax for group_spec is:
075 * </p>
076 * <p>
077 * group_spec: <code>["."] group_name_pattern</code>
078 * </p>
079 * <p>
080 * Here, a . indicates that the group should be searched for (using a SegmentFinder) starting at the
081 * current location in the message. The wildcards "*" and "?" represent any number of arbitrary
082 * characters, and a single arbitrary character, respectively. For example, "M*" and "?S?" match
083 * MSH. The first group with a name that matches the given group_name_pattern will be matched.
084 * </p>
085 * <p>
086 * The segment_spec is analogous to the group_spec.
087 * </p>
088 * <p>
089 * As another example, the following subcomponent in an SIU_S12 message:
090 * <p>
091 * <p>
092 * <code>msg.getSIU_S12_RGSAISNTEAIGNTEAILNTEAIPNTE(1).getSIU_S12_AIGNTE().getAIG().getResourceGroup(1).getIdentifier();</code>
093 * </p>
094 * </p> ... is referenced by all of the following location_spec: </p>
095 * <p>
096 * <code>/SIU_S12_RGSAISNTEAIGNTEAILNTEAIPNTE(1)/SIU_S12_AIGNTE/AIG-5(1)-1 <br>
097 * /*AIG*(1)/SIU_S12_AIGNTE/AIG-5(1)-1 <br>
098 * /*AIG*(1)/.AIG-5(1) <code>
099 * </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 */
112public 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}