001package ca.uhn.hl7v2.preparser;
002
003import java.util.ArrayList;
004import java.util.Iterator;
005import java.util.List;
006import java.util.Map;
007import java.util.Properties;
008import java.util.SortedMap;
009import java.util.StringTokenizer;
010import java.util.TreeMap;
011
012import ca.uhn.hl7v2.parser.EncodingCharacters;
013
014/*
015The point of this class (all static members, not instantiatable) is to take a
016traditionally-encoded HL7 message and add all it's contents to a Properties
017object, via the parseMessage() method.
018
019The key-value pairs added to the Properties argument have keys that represent a
020datum's location in the message.  (in the ZYX-1-2[0] style.  TODO: define
021exactly.)  See Datum, particularly the toString() of that class.
022Anyway, the Properties keys are those and the values are the tokens found.
023
024Note: we accept useless field repetition separators at the end of a 
025field repetition sequence.  i.e. |855-4545~555-3792~~~| , and interpret this
026as definining repetitions 0 and 1.  This might not be allowed.  (HL7 2.3.1
027section 2.10 explicitly allows this behaviour for fields / components /
028subcomponents, but the allowance is notably absent for repetitions.  TODO:
029nail down.)  We allow it anyway.
030
031Also, we accept things like |855-4545~~555-3792|, and interpret it as defining
032repetitions 0 and 2.  The spec would seem to disallow this too, but there's no
033harm.  :D  
034*/
035public class ER7 {
036        
037        private ER7() {}
038
039        /** characters that delimit segments.  for use with StringTokenizer.
040        We are forgiving: HL7 2.3.1 section 2.7 says that carriage return ('\r') is
041        the only segment delimiter.  TODO: check other versions. */ 
042        static final String segmentSeparators = "\r\n\f";
043
044        /** Parses message and dumps contents to props, with keys in the 
045        ZYX[a]-b[c]-d-e style.
046        */
047        public static boolean parseMessage(/*out*/ Properties props, 
048                /*in*/ List<DatumPath> msgMask, /*in*/ String message)
049        {
050                boolean ok = false;
051                if(message != null) {
052                        if(props == null)
053                                props = new Properties();
054
055                        StringTokenizer messageTokenizer 
056                                = new StringTokenizer(message, segmentSeparators);
057                        if(messageTokenizer.hasMoreTokens()) {
058                                String firstSegment = messageTokenizer.nextToken();
059                                EncodingCharacters encodingChars = new EncodingCharacters('0', "0000");
060                                if(parseMSHSegmentWhole(props, msgMask, encodingChars, firstSegment)) {
061                                        ok = true;
062                                        SortedMap<String, Integer> segmentId2nextRepIdx = new TreeMap<>();
063                                        segmentId2nextRepIdx.put("MSH", 1);
064                                                // in case we find another MSH segment, heh.
065                                        while(messageTokenizer.hasMoreTokens()) {
066                                                parseSegmentWhole(props, segmentId2nextRepIdx, 
067                                                        msgMask, encodingChars, messageTokenizer.nextToken());
068                                        }
069                                }
070                        }
071                }
072                return ok;
073        }
074        
075        /** given segment, starting with "MSH", then encoding characters, etc...
076        put MSH[0]-1[0]-1-1 (== MSH-1) and MSH[0]-2[0]-1-1 (== MSH-2) into props, if found,
077        plus everything else found in 'segment' */
078        protected static boolean parseMSHSegmentWhole(/*out*/ Properties props, 
079                /*in*/ List<DatumPath> msgMask, /*in*/ EncodingCharacters encodingChars, 
080                /*in*/ String segment) 
081        {
082                boolean ret = false;
083                try {
084                        ER7SegmentHandler handler = new ER7SegmentHandler();
085                        handler.m_props = props;
086                        handler.m_encodingChars = encodingChars;
087                        handler.m_segmentId = "MSH";
088                        handler.m_segmentRepIdx = 0;
089                        if(msgMask != null)
090                                handler.m_msgMask = msgMask;
091                        else {
092                                handler.m_msgMask = new ArrayList<>();
093                                handler.m_msgMask.add(new DatumPath()); // everything will pass this
094                                        // (every DatumPath startsWith the zero-length DatumPath)
095                        }
096
097                        encodingChars.setFieldSeparator(segment.charAt(3));
098                        List<Integer> nodeKey = new ArrayList<>();
099                        nodeKey.add(0);
100                        handler.putDatum(nodeKey, String.valueOf(encodingChars.getFieldSeparator()));
101                        encodingChars.setComponentSeparator(segment.charAt(4));
102                        encodingChars.setRepetitionSeparator(segment.charAt(5));
103                        encodingChars.setEscapeCharacter(segment.charAt(6));
104                        encodingChars.setSubcomponentSeparator(segment.charAt(7));
105                        nodeKey.set(0, 1);
106                        handler.putDatum(nodeKey, encodingChars.toString());
107
108                        if(segment.charAt(8) == encodingChars.getFieldSeparator()) {    
109                                ret = true; 
110                                // now -- we recurse 
111                                // through fields / field-repetitions / components / subcomponents.
112                                nodeKey.clear();
113                                nodeKey.add(2);
114                                parseSegmentGuts(handler, segment.substring(9), nodeKey);
115                        }
116                }
117                catch(IndexOutOfBoundsException | NullPointerException ignored) {}
118
119                return ret;
120        }
121
122        /** pass in a whole segment (of type other than MSH), including message type
123        at the start, according to encodingChars, and we'll parse the contents and
124        put them in props. */
125        protected static void parseSegmentWhole(/*out*/ Properties props, 
126                /*in/out*/ Map<String, Integer> segmentId2nextRepIdx, 
127                /*in*/ List<DatumPath> msgMask, /*in*/ EncodingCharacters encodingChars, 
128                /*in*/ String segment)
129        {
130                try {
131                        String segmentId = segment.substring(0, 3);
132
133                        int currentSegmentRepIdx;
134                        if(segmentId2nextRepIdx.containsKey(segmentId))
135                                currentSegmentRepIdx = segmentId2nextRepIdx.get(segmentId);
136                        else
137                                currentSegmentRepIdx = 0;
138                        segmentId2nextRepIdx.put(segmentId, currentSegmentRepIdx + 1);
139
140                        // will only bother to parse this segment if any of it's contents will 
141                        // be dumped to props.
142                        boolean parseThisSegment = false;
143                        DatumPath segmentIdAsDatumPath = new DatumPath().add(segmentId);
144                        for(Iterator<DatumPath> maskIt = msgMask.iterator(); !parseThisSegment && maskIt.hasNext(); ) 
145                                parseThisSegment = segmentIdAsDatumPath.startsWith(maskIt.next());
146                        for(Iterator<DatumPath> maskIt = msgMask.iterator(); !parseThisSegment && maskIt.hasNext(); ) 
147                                parseThisSegment = maskIt.next().startsWith(segmentIdAsDatumPath);
148
149                        if(parseThisSegment && (segment.charAt(3) == encodingChars.getFieldSeparator())) {
150                                ER7SegmentHandler handler = new ER7SegmentHandler();
151                                handler.m_props = props;
152                                handler.m_encodingChars = encodingChars;
153                                handler.m_segmentId = segmentId;
154                                handler.m_msgMask = msgMask;
155                                handler.m_segmentRepIdx = currentSegmentRepIdx;
156
157                                List<Integer> nodeKey = new ArrayList<>();
158                                nodeKey.add(0);
159                                parseSegmentGuts(handler, segment.substring(4), nodeKey);
160                        }
161                }
162                catch(NullPointerException | IndexOutOfBoundsException ignored) {}
163        }
164
165        protected interface Handler
166        {
167                int specDepth();
168                char delim(int level);
169
170                void putDatum(List<Integer> nodeKey, String value);
171        }
172
173        static protected class ER7SegmentHandler implements Handler
174        {
175                Properties m_props;
176
177                EncodingCharacters m_encodingChars;
178
179                String m_segmentId;
180                int m_segmentRepIdx;
181
182                List<DatumPath> m_msgMask;
183
184                public int specDepth() {return 4;}
185
186                public char delim(int level)
187                {
188                        if(level == 0)
189                                return m_encodingChars.getFieldSeparator();
190                        else if(level == 1)
191                                return m_encodingChars.getRepetitionSeparator();
192                        else if(level == 2)
193                                return m_encodingChars.getComponentSeparator();
194                        else if(level == 3)
195                                return m_encodingChars.getSubcomponentSeparator();
196            else if(level == 4)
197                return m_encodingChars.getTruncationCharacter();
198                        else
199                                throw new java.lang.Error();
200                }
201
202                public void putDatum(List<Integer> valNodeKey, String value)
203                {
204                        // make a DatumPath from valNodeKey and info in this: 
205                        DatumPath valDatumPath = new DatumPath();
206                        valDatumPath.add(m_segmentId).add(m_segmentRepIdx);
207                        for(int i=0; i<valNodeKey.size(); ++i) {
208                                // valNodeKey: everything counts from 0 -- not so with DatumPath ... sigh. 
209                                int itval = valNodeKey.get(i);
210                                valDatumPath.add(Integer.valueOf(i == 1 ? itval : itval + 1));
211                        }
212
213                        // see if valDatumPath passes m_msgMask: 
214                        boolean valDatumPathPassesMask = false;
215                        for(Iterator<DatumPath> maskIt = m_msgMask.iterator(); 
216                                !valDatumPathPassesMask && maskIt.hasNext(); )
217                        {
218                                valDatumPathPassesMask = valDatumPath.startsWith(maskIt.next());
219                        }
220
221                        if(valDatumPathPassesMask)
222                                m_props.setProperty(valDatumPath.toString(), value);
223                }
224        }
225
226        /** recursively tokenize "guts" (a segment, or part of one) into tokens, 
227        according to separators (aka delimiters) which are different at each level
228        of recursion, and to a recursive depth which is discovered through "handler"
229        via handler.delim(int) and handler.specDepth()  As tokens are found, they
230        are reported to handler via handler.putDatum(), which presumably stashes them
231        away somewhere.  We tell the handler about the location in the message via
232        putDatum()'s key argument, which is a List of Integers representing the 
233        position in the parse tree (size() == depth of recursion).
234
235        TODO: say more.
236        */
237        protected static void parseSegmentGuts(/*in/out*/ Handler handler,  
238                /*in*/ String guts, /*in*/List<Integer> nodeKey)
239        {
240                char thisDepthsDelim = handler.delim(nodeKey.size()-1);
241                //nodeKey.add(new Integer(0)); // will change nodeKey back before function exits
242
243                StringTokenizer gutsTokenizer 
244                        = new StringTokenizer(guts, String.valueOf(thisDepthsDelim), true);
245                while(gutsTokenizer.hasMoreTokens()) {
246                        String gutsToken = gutsTokenizer.nextToken();
247
248                        if(gutsToken.charAt(0) == thisDepthsDelim) {
249                                // gutsToken is all delims -- skipping over as many fields or
250                                // components or whatevers as there are characters in the token: 
251                                int oldvalue = nodeKey.get(nodeKey.size() - 1);
252                                nodeKey.set(nodeKey.size()-1, oldvalue + gutsToken.length());
253                        }
254                        else {
255                                if(nodeKey.size() < handler.specDepth()) {
256                                        nodeKey.add(0);
257                                        parseSegmentGuts(handler, gutsToken, nodeKey);
258                                        nodeKey.remove(nodeKey.size()-1);
259                                }
260                                else 
261                                        handler.putDatum(nodeKey, gutsToken);
262                        }
263                }
264                //nodeKey.setSize(nodeKey.size()-1); // undoing add done at top of this func
265        }
266
267        public static void main(String[] args)
268        {
269                if(args.length >= 1) {
270                        //String message = "MSH|^~\\&||||foo|foo|foo";
271                        System.out.println(args[0]);
272
273                        Properties props = new Properties();
274
275                        List<DatumPath> msgMask = new ArrayList<>();
276                        msgMask.add(new DatumPath());
277
278                        System.err.println("ER7.parseMessage returned " + parseMessage(props, msgMask, args[0]));
279                        props.list(System.out);
280                }
281        }
282        
283}
284