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