001/* 002The 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. 004You may obtain a copy of the License at http://www.mozilla.org/MPL/ 005Software distributed under the License is distributed on an "AS IS" basis, 006WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the 007specific language governing rights and limitations under the License. 008 009The Original Code is "ServerSocketStreamSource.java". Description: 010"A StreamSource that gets streams from ServerSockets." 011 012The Initial Developer of the Original Code is University Health Network. Copyright (C) 0132004. All Rights Reserved. 014 015Contributor(s): ______________________________________. 016 017Alternatively, the contents of this file may be used under the terms of the 018GNU General Public License (the �GPL�), in which case the provisions of the GPL are 019applicable instead of those above. If you wish to allow use of your version of this 020file only under the terms of the GPL and not to allow others to use your version 021of this file under the MPL, indicate your decision by deleting the provisions above 022and replace them with the notice and other provisions required by the GPL License. 023If you do not delete the provisions above, a recipient may use your version of 024this file under either the MPL or the GPL. 025*/ 026 027package ca.uhn.hl7v2.protocol.impl; 028 029import java.io.IOException; 030import java.net.ServerSocket; 031import java.net.Socket; 032import java.net.SocketTimeoutException; 033 034import org.slf4j.Logger; 035import org.slf4j.LoggerFactory; 036 037/** 038 * A <code>StreamSource</code> that gets streams from ServerSockets. This 039 * allows you to communicate over sockets that are established by the remote 040 * party (ie as a TCP/IP server). 041 * 042 * @author <a href="mailto:bryan.tripp@uhn.on.ca">Bryan Tripp</a> 043 * @version $Revision: 1.4 $ updated on $Date: 2009-12-19 20:01:20 $ by $Author: jamesagnew $ 044 */ 045public class ServerSocketStreamSource extends SocketStreamSource { 046 047 /** The default SO_TIMEOUT value for sockets returned by this class */ 048 public static final int TIMEOUT = 500; 049 050 private final ServerSocket myServerSocket; 051 private final String myExpectedAddress; 052 private Socket mySocket; 053 054 /** 055 * @param theServerSocket a ServerSocket at which to listen for incoming connections 056 * @param theExpectedAddress the IP address from which to accept connections (null means 057 * accept from any address) 058 */ 059 public ServerSocketStreamSource(ServerSocket theServerSocket, String theExpectedAddress) { 060 myServerSocket = theServerSocket; 061 myExpectedAddress = theExpectedAddress; 062 } 063 064 /** 065 * @see ca.uhn.hl7v2.protocol.impl.SocketStreamSource#getSocket() 066 */ 067 public Socket getSocket() { 068 return mySocket; 069 } 070 071 /** 072 * Accepts new connections on underlying ServerSocket, replacing 073 * any existing socket with the new one, blocking until a connection 074 * is available. See {@link DualTransportConnector} for a method of 075 * connecting two <code>TransportLayer</code>s in a way that avoids deadlock. 076 * 077 * @see ca.uhn.hl7v2.protocol.StreamSource#connect() 078 */ 079 public void connect() { 080 Acceptor a = new Acceptor(myServerSocket, myExpectedAddress); 081 mySocket = a.waitForSocket(); 082 } 083 084 /** 085 * A thing with which waiting for inbound socket connections can 086 * be done in a separate thread. This is needed because we may have to 087 * start waiting at two ports before pending on either. Otherwise if 088 * we accept() in a different order than the remote system connects, 089 * we will deadlock. 090 * 091 * @author <a href="mailto:bryan.tripp@uhn.on.ca">Bryan Tripp</a> 092 * @version $Revision: 1.4 $ updated on $Date: 2009-12-19 20:01:20 $ by $Author: jamesagnew $ 093 */ 094 private static class Acceptor { 095 096 private static final Logger log = LoggerFactory.getLogger(Acceptor.class); 097 098 private Socket mySocket; 099 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}