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 "ServerSocketStreamSource.java".  Description: 
10  "A StreamSource that gets streams from ServerSockets." 
11  
12  The Initial Developer of the Original Code is University Health Network. Copyright (C) 
13  2004.  All Rights Reserved. 
14  
15  Contributor(s): ______________________________________. 
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  package ca.uhn.hl7v2.protocol.impl;
28  
29  import java.io.IOException;
30  import java.net.ServerSocket;
31  import java.net.Socket;
32  import java.net.SocketTimeoutException;
33  
34  import org.slf4j.Logger;
35  import org.slf4j.LoggerFactory;
36  
37  import ca.uhn.hl7v2.protocol.TransportException;
38  
39  /**
40   * A <code>StreamSource</code> that gets streams from ServerSockets.  This 
41   * allows you to communicate over sockets that are established by the remote 
42   * party (ie as a TCP/IP server).
43   * 
44   * @author <a href="mailto:bryan.tripp@uhn.on.ca">Bryan Tripp</a>
45   * @version $Revision: 1.4 $ updated on $Date: 2009-12-19 20:01:20 $ by $Author: jamesagnew $
46   */
47  public class ServerSocketStreamSource extends SocketStreamSource {
48  
49  	/** The default SO_TIMEOUT value for sockets returned by this class */
50  	public static final int TIMEOUT = 500;
51  	
52      private ServerSocket myServerSocket;
53      private String myExpectedAddress;
54      private Socket mySocket;
55      private Acceptor myAcceptor;
56      private boolean myProceedWithConnect;
57      
58      /**
59       * @param theServerSocket a ServerSocket at which to listen for incoming connections  
60       * @param theExpectedAddress the IP address from which to accept connections (null means 
61       *      accept from any address) 
62       * @throws TransportException
63       */
64      public ServerSocketStreamSource(ServerSocket theServerSocket, String theExpectedAddress) throws TransportException {
65          myServerSocket = theServerSocket;
66          myExpectedAddress = theExpectedAddress;
67      }
68  
69      /** 
70       * @see ca.uhn.hl7v2.protocol.impl.SocketStreamSource#getSocket()
71       */
72      public Socket getSocket() {
73          return mySocket;
74      }
75  
76      /** 
77       * Accepts new connections on underlying ServerSocket, replacing 
78       * any existing socket with the new one, blocking until a connection 
79       * is available.  See {@link DualTransportConnector} for a method of 
80       * connecting two <code>TransportLayer</code>s in a way that avoids deadlock.    
81       * 
82       * @see ca.uhn.hl7v2.protocol.StreamSource#connect()
83       */
84      public void connect() throws TransportException {
85          Acceptor a = new Acceptor(myServerSocket, myExpectedAddress);                
86          mySocket = a.waitForSocket();
87      }
88      
89      /**
90       * A thing with which waiting for inbound socket connections can 
91       * be done in a separate thread.  This is needed because we may have to 
92       * start waiting at two ports before pending on either.  Otherwise if 
93       * we accept() in a different order than the remote system connects, 
94       * we will deadlock.  
95       * 
96       * @author <a href="mailto:bryan.tripp@uhn.on.ca">Bryan Tripp</a>
97       * @version $Revision: 1.4 $ updated on $Date: 2009-12-19 20:01:20 $ by $Author: jamesagnew $
98       */
99      private static class Acceptor {
100         
101         private static final Logger log = LoggerFactory.getLogger(Acceptor.class);
102         
103         private Socket mySocket;
104         
105         /**
106          * Starts waiting in a separate thread for connections to the given 
107          * ServerSocket from the given IP address.  
108          * @param theServer 
109          * @param theAddress IP address from which to accept connections (null
110          *      means any) 
111          */
112         public Acceptor(final ServerSocket theServer, final String theAddress) {
113             final Acceptor a = this;
114             if (theAddress != null) {
115                 log.info("Server socket is about to try to accept a connection from {}", theAddress);
116             } else {
117                 log.info("Server socket is about to try to accept a connection from any addess");
118             }
119 
120             Runnable r = new Runnable() {
121                 public void run() {
122                     while (true) {
123 
124                         Socket s;
125                         try {
126 
127                         	if (!theServer.isClosed()) {
128 	                            s = theServer.accept();
129 	                            s.setSoTimeout(TIMEOUT);
130 	                            String address = s.getInetAddress().getHostAddress();
131 	                            if (theAddress == null || address.equals(theAddress)) {
132 	                                a.setSocket(s);
133 	                                synchronized (a) {
134 	                                    a.notifyAll();
135 	                                }
136 	                            } else {
137 	                                log.info("Ignoring connection from {}: expecting ", address, theAddress);
138 	                            }
139                         	}
140                         	
141                         } catch (SocketTimeoutException e) {
142                             log.debug("Socket timed out without receiving a connection");
143                         } catch (IOException e) {
144                             log.error("Error accepting remote connection", e); 
145                         } // try-catch
146 
147                         if (a.getSocket() != null) {
148                             log.info("Accepted connection from address: {}", a.getSocket().getInetAddress());
149                             return;
150                         }
151 
152                         if (theServer.isClosed()) {
153                             log.warn("Server socket closed, aborting");
154                             return;
155                         }
156 
157                         //if there's a problem, don't fill up the log at lightning speed
158                         try {
159                             Thread.sleep(1000);
160                         } catch (InterruptedException e2) {}
161 
162                     }
163                 }
164             };
165             
166             Thread thd = new Thread(r);
167             thd.start();
168         }
169         
170         public void setSocket(Socket theSocket) {
171             mySocket = theSocket;
172         }
173         
174         public Socket getSocket() {
175             return mySocket;
176         }
177         
178         /**
179          * @return as getSocket(), but doesn't return until getSocket() returns 
180          *  non-null.  
181          */
182         public Socket waitForSocket() {
183             while (getSocket() == null) {
184                 try {
185                     synchronized (this) {
186                         this.wait(100);
187                     }
188                 } catch (InterruptedException e) {}
189             }
190             return getSocket();
191         }
192         
193     }
194 
195 
196 }