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 "Receiver.java".  Description:
10   * "Listens for incoming messages on a certain input stream, and
11   * sends them to the appropriate location."
12   *
13   * The Initial Developer of the Original Code is University Health Network. Copyright (C)
14   * 2002.  All Rights Reserved.
15   *
16   * Contributor(s): _____________.
17   *
18   * Alternatively, the contents of this file may be used under the terms of the
19   * GNU General Public License (the "GPL"), in which case the provisions of the GPL are
20   * applicable instead of those above.  If you wish to allow use of your version of this
21   * file only under the terms of the GPL and not to allow others to use your version
22   * of this file under the MPL, indicate your decision by deleting  the provisions above
23   * and replace  them with the notice and other provisions required by the GPL License.
24   * If you do not delete the provisions above, a recipient may use your version of
25   * this file under either the MPL or the GPL.
26   */
27  
28  package ca.uhn.hl7v2.app;
29  
30  import java.io.IOException;
31  import java.net.SocketException;
32  
33  import org.slf4j.Logger;
34  import org.slf4j.LoggerFactory;
35  
36  import ca.uhn.hl7v2.concurrent.Service;
37  import ca.uhn.hl7v2.llp.HL7Reader;
38  import ca.uhn.hl7v2.llp.LLPException;
39  
40  /**
41   * Listens for incoming messages on a certain input stream, and sends them to
42   * the appropriate location.
43   * 
44   * @author Bryan Tripp
45   */
46  public class Receiver extends Service {
47  
48  	private static final Logger log = LoggerFactory.getLogger(Receiver.class);
49  
50  	private final ActiveConnection conn;
51  	private final HL7Reader in;
52  	private ReceiverParserExceptionHandler parserExeptionHandler;
53  
54  	/** Creates a new instance of Receiver, associated with the given Connection */
55  	public Receiver(ActiveConnection c, HL7Reader in) {
56  		super("Receiver", c.getExecutorService());
57  		this.conn = c;
58  		this.in = in;
59  	}
60  
61  	public void setParserExeptionHandler(ReceiverParserExceptionHandler parserExeptionHandler) {
62  		this.parserExeptionHandler = parserExeptionHandler;
63  	}
64  
65  	@Override
66  	protected void handle() {
67  		try {
68  			String message = in.getMessage();
69  			if (message == null) {
70  				log.debug("Failed to read a message");
71  			} else {
72  				processMessage(message);
73  			}
74  		} catch (LLPException e)  {
75  			//For any protocol exceptions on this particular connection notify the application about the same
76  			//and close the connection
77  			conn.close();
78  			log.info("LLPException: closing Connection from " + describeRemoteConnection() + ", will no longer read messages with this Receiver: " + e.getMessage());
79  			if(parserExeptionHandler!=null) {
80  				parserExeptionHandler.handle(e);
81  			}
82  		} catch (SocketException e)  {
83  			// This probably means that the client closed the server connection normally
84  			conn.close();
85  			log.info("SocketException: closing Connection from " + describeRemoteConnection() + ", will no longer read messages with this Receiver: " + e.getMessage());
86  		} catch (IOException e) {
87  			conn.close();
88  			log.warn("IOException: closing Connection from " + describeRemoteConnection() + ", will no longer read messages with this Receiver. ", e);
89  		} catch (Exception e) {
90  			conn.close();
91  			log.error("Unexpected error, closing connection from " + describeRemoteConnection() + " - ", e);
92  		}
93  
94  	}
95  
96  
97  	private String describeRemoteConnection() {
98  		return conn.getRemoteAddress().getHostAddress() + ":" + conn.getRemotePort();
99  	}
100 
101 
102 	/**
103 	 * Processes a single incoming message by sending it to the appropriate
104 	 * internal location. If an incoming message contains an MSA-2 field, it is
105 	 * assumed that this message is meant as a reply to a message that has been
106 	 * sent earlier. In this case an attempt is give the message to the object
107 	 * that sent the corresponding outbound message. If the message contains an
108 	 * MSA-2 but there are no objects that appear to be waiting for it, it is
109 	 * discarded and an exception is logged. If the message does not contain an
110 	 * MSA-2 field, it is concluded that the message has arrived unsolicited. In
111 	 * this case it is sent to the Responder (in a new Thread).
112 	 */
113 	protected void processMessage(String message) {
114 		String ackID = conn.getParser().getAckID(message);
115 		if (ackID == null) {
116 			log.debug("Unsolicited Message Received: {}", message);
117 			getExecutorService().submit(new Grunt(conn, message));
118 		} else {
119 			if ( conn.acceptAllMessages() ){
120 				getExecutorService().submit(new Grunt(conn, message));
121 			}else if (!conn.isRecipientWaiting(ackID, message)) {
122 				log.info("Unexpected Message Received. This message appears to be an acknowledgement (MSA-2 has a value) so it will be ignored: {}", message);
123 			} else {
124 				log.debug("Response Message Received: {}", message);
125 			}
126 		}
127 	}
128 
129 	/** Independent thread for processing a single message */
130 	private static class Grunt implements Runnable {
131 
132 		private final ActiveConnection conn;
133 		private final String m;
134 
135 		public Grunt(ActiveConnection conn, String message) {
136 			this.conn = conn;
137 			this.m = message;
138 		}
139 
140 		public void run() {
141 			try {
142 				String response = conn.getResponder().processMessage(m);
143 				if (response != null) {
144 					conn.getAckWriter().writeMessage(response);
145 				} else {
146 					log.debug("Not responding to incoming message");
147 				}
148 			} catch (Exception e) {
149 				log.error("Error while processing message: ", e);
150 			}
151 		}
152 	}
153 
154 	/**
155 	 * Handle any protocol level parsing exceptions and pass them on to an exception handler
156 	 */
157 	public static interface ReceiverParserExceptionHandler {
158 		void handle(Exception e);
159 	}
160 }