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 "MinLLPReader.java".  Description: 
010    "Title:        HL7Reader
011      Description:  A buffered reader specifically designed for use in reading
012                    HL7 ASCII strings" 
013    
014    The Initial Developer of the Original Code is University Health Network. Copyright (C) 
015    2001.  All Rights Reserved. 
016    
017    Contributor(s): ______________________________________. 
018    
019    Alternatively, the contents of this file may be used under the terms of the 
020    GNU General Public License (the  �GPL�), in which case the provisions of the GPL are 
021    applicable instead of those above.  If you wish to allow use of your version of this 
022    file only under the terms of the GPL and not to allow others to use your version 
023    of this file under the MPL, indicate your decision by deleting  the provisions above 
024    and replace  them with the notice and other provisions required by the GPL License.  
025    If you do not delete the provisions above, a recipient may use your version of 
026    this file under either the MPL or the GPL. 
027    
028    */
029    
030    package ca.uhn.hl7v2.llp;
031    
032    import java.io.BufferedReader;
033    import java.io.IOException;
034    import java.io.InputStream;
035    import java.io.InputStreamReader;
036    import java.net.Socket;
037    import java.net.SocketException;
038    import java.net.SocketTimeoutException;
039    import java.nio.charset.Charset;
040    
041    import org.slf4j.Logger;
042    import org.slf4j.LoggerFactory;
043    
044    /**
045     * Title:        HL7Reader
046     * Description:  A buffered reader specifically designed for use in reading
047     *               HL7 ASCII strings. This class assumes that the minimal lower
048     *               layer protocol is being used.
049     * Copyright:    Copyright (c) 2001
050     * Company:      University Health Network
051     * @author       Damian Horton (damian.horton@uhn.on.ca); mods by Bryan Tripp
052     */
053    
054    public class MinLLPReader implements HL7Reader
055    {
056        
057        /**
058         *<p>
059         * System property: If a value is set for this property, the value
060         * is interpreted as a character set, and this characterset is 
061         * used. A possible example is "UTF-8" if you are receiving messages
062         * from a system that transmits in UTF-8.
063         * </p>
064         * <p>
065         * If the system property is set to a value of "default" (in other words, a
066         * string containing only the word default), then the platform default
067         * is used.
068         * </p>
069         * <p>
070         * If the system property is not set, US-ASCII encoding is used.
071         * </p>
072         */
073        public static final String CHARSET_KEY = "ca.uhn.hl7v2.llp.charset";
074    
075        private static final Logger log = LoggerFactory.getLogger(MinLLPReader.class);
076        
077        private BufferedReader myReader;
078    
079            private Charset charset;
080    
081        /**
082         * Character indicating the termination of an HL7 message
083         */
084        public static final char END_MESSAGE = '\u001c'; 
085        
086        /**
087         * character indicating the start of an HL7 message
088         */
089        public static final char START_MESSAGE = '\u000b';
090        
091        /**
092         * The final character of a message: a carriage return. NB: This is per the minimal lower layer protocol.
093         */
094        public static final char LAST_CHARACTER = 13;
095    
096        /** Creates a MinLLPReader with no setup - setInputStream must be set later. 
097        */
098        public MinLLPReader() 
099        {
100        }
101        
102        /** Creates a MinLLPReader which reads from the given InputStream. The stream
103         *  is assumed to be an ASCII bit stream.
104         */
105        public MinLLPReader(InputStream in) throws IOException
106        {
107            setInputStream(in);
108        }
109    
110        /** Creates a MinLLPReader which reads from the given InputStream. The stream
111         *  is assumed to be an ASCII bit stream.
112         */
113        public MinLLPReader(InputStream in, Charset theCharset) throws IOException
114        {
115            charset = theCharset;
116            setInputStream(in);
117        }
118    
119        /**
120         * Sets the InputStream from which to read messages.  The InputStream must be set 
121         * before any calls to <code>getMessage()</code>.
122         */
123        public synchronized void setInputStream(InputStream in) throws IOException 
124        {
125            if (charset != null) {
126                myReader = new BufferedReader(new InputStreamReader(in, charset));
127            } else { 
128                    String charsetString = System.getProperty(CHARSET_KEY, "US-ASCII");
129                    if (charsetString.equals("default")) {
130                        myReader = new BufferedReader(new InputStreamReader(in));
131                    } else {
132                        myReader = new BufferedReader(new InputStreamReader(in, charsetString));
133                    }
134            }
135        }
136    
137        /** Calls the same method in the underlying BufferedReader. */
138        /**private int read(char[] parm1, int parm2, int parm3) throws java.io.IOException
139        {
140            return myReader.read(parm1, parm2, parm3);
141        }*/
142    
143        /** Reads an HL7 encoded message from this Reader's InputStream.
144            @return The message, in string format, without the lower level
145            protocol delimeters. Returns null if a -1 is received on the initial
146             read.
147         */
148        public synchronized String getMessage() throws LLPException, IOException 
149        {
150            StringBuffer s_buffer = new StringBuffer();
151    
152            boolean end_of_message = false;
153                            
154                int c = 0;
155                try {
156                    c = myReader.read();  
157                } catch (SocketTimeoutException e) {
158                    log.debug("SocketTimeoutException on read() attempt.");
159                    return null;               
160                } catch (SocketException e) {
161                    log.info("SocketException on read() attempt.  Socket appears to have been closed: " + e.getMessage());
162                    throw e;
163                }
164    
165                //trying to read when there is no data (stream may have been closed at other end)
166                if (c == -1) {
167                    log.info("End of input stream reached.");
168                    throw new SocketException("End of input stream reached."); 
169                }
170                LowerLayerProtocol.logCharacterReceived(c);
171    
172                if (c != START_MESSAGE)
173                {
174                    throw new LLPException("Message violates the "+
175                        "minimal lower layer protocol: no start of message indicator "+
176                        "received. Received: " + c);
177                }
178    
179                while (! end_of_message)
180                {
181                    c = myReader.read();
182    
183                    if (c == -1)
184                    {
185                        throw new LLPException("Message violates the "+
186                            "minimal lower protocol: message terminated without "+
187                            "a terminating character.");
188                    }
189                    LowerLayerProtocol.logCharacterReceived(c);
190                    
191                    if (c == END_MESSAGE)
192                    {
193                        //subsequent character should be a carriage return
194                        c = myReader.read();
195                        if (c >= 0) LowerLayerProtocol.logCharacterReceived(c);
196                        if (c != LAST_CHARACTER)
197                        {
198                            throw new LLPException("Message "+
199                                "violates the minimal lower layer protocol: "+
200                                "message terminator not followed by a return "+
201                                "character.");
202                        }
203                        end_of_message = true;
204                    }
205                    else
206                    {
207                    //the character wasn't the end of message, append it to the message
208                        s_buffer.append((char) c);
209                    }
210                } //end while
211    
212            return s_buffer.toString();
213        }
214    
215        /** Test driver for the program. Bounces a message off of an echo socket,
216         *  and ascertaines whether or not this class works.
217         */
218        public static void main(String args[])
219        {
220            try
221            {
222                Socket s = new Socket("142.224.51.2", 7);
223    
224                HL7Reader in = new MinLLPReader(s.getInputStream());
225                HL7Writer out = new MinLLPWriter(s.getOutputStream());
226    
227                out.writeMessage("Some message.");
228                System.out.println("wrote");
229                String str = in.getMessage();
230                System.out.println("read");
231    
232                System.out.println(str);
233            }
234            catch (Exception e)
235            {
236                System.out.println(e);
237            }
238        }
239    
240        /** 
241         * Closes the underlying BufferedReader.
242         */
243        public synchronized void close() throws java.io.IOException
244        {
245            myReader.close();
246        }
247        
248            
249    }
250