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 "ServerSocketStreamSource.java". Description:
010 "A StreamSource that gets streams from ServerSockets."
011
012 The Initial Developer of the Original Code is University Health Network. Copyright (C)
013 2004. All Rights Reserved.
014
015 Contributor(s): ______________________________________.
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 package ca.uhn.hl7v2.protocol.impl;
028
029 import java.io.IOException;
030 import java.net.ServerSocket;
031 import java.net.Socket;
032 import java.net.SocketTimeoutException;
033
034 import org.slf4j.Logger;
035 import org.slf4j.LoggerFactory;
036
037 import ca.uhn.hl7v2.protocol.TransportException;
038
039 /**
040 * A <code>StreamSource</code> that gets streams from ServerSockets. This
041 * allows you to communicate over sockets that are established by the remote
042 * party (ie as a TCP/IP server).
043 *
044 * @author <a href="mailto:bryan.tripp@uhn.on.ca">Bryan Tripp</a>
045 * @version $Revision: 1.4 $ updated on $Date: 2009-12-19 20:01:20 $ by $Author: jamesagnew $
046 */
047 public class ServerSocketStreamSource extends SocketStreamSource {
048
049 /** The default SO_TIMEOUT value for sockets returned by this class */
050 public static final int TIMEOUT = 500;
051
052 private ServerSocket myServerSocket;
053 private String myExpectedAddress;
054 private Socket mySocket;
055 private Acceptor myAcceptor;
056 private boolean myProceedWithConnect;
057
058 /**
059 * @param theServerSocket a ServerSocket at which to listen for incoming connections
060 * @param theExpectedAddress the IP address from which to accept connections (null means
061 * accept from any address)
062 * @throws TransportException
063 */
064 public ServerSocketStreamSource(ServerSocket theServerSocket, String theExpectedAddress) throws TransportException {
065 myServerSocket = theServerSocket;
066 myExpectedAddress = theExpectedAddress;
067 }
068
069 /**
070 * @see ca.uhn.hl7v2.protocol.impl.SocketStreamSource#getSocket()
071 */
072 public Socket getSocket() {
073 return mySocket;
074 }
075
076 /**
077 * Accepts new connections on underlying ServerSocket, replacing
078 * any existing socket with the new one, blocking until a connection
079 * is available. See {@link DualTransportConnector} for a method of
080 * connecting two <code>TransportLayer</code>s in a way that avoids deadlock.
081 *
082 * @see ca.uhn.hl7v2.protocol.StreamSource#connect()
083 */
084 public void connect() throws TransportException {
085 Acceptor a = new Acceptor(myServerSocket, myExpectedAddress);
086 mySocket = a.waitForSocket();
087 }
088
089 /**
090 * A thing with which waiting for inbound socket connections can
091 * be done in a separate thread. This is needed because we may have to
092 * start waiting at two ports before pending on either. Otherwise if
093 * we accept() in a different order than the remote system connects,
094 * we will deadlock.
095 *
096 * @author <a href="mailto:bryan.tripp@uhn.on.ca">Bryan Tripp</a>
097 * @version $Revision: 1.4 $ updated on $Date: 2009-12-19 20:01:20 $ by $Author: jamesagnew $
098 */
099 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 }