hapi-hl7v2 icon indicating copy to clipboard operation
hapi-hl7v2 copied to clipboard

Cannot set timeout for connection establishment of Client

Open effad opened this issue 3 years ago • 1 comments

Consider this example:

import java.io.IOException;

import ca.uhn.hl7v2.*;
import ca.uhn.hl7v2.app.Connection;

public class HAPITest {

	public static void main(String[] args) throws IOException, HL7Exception {
		try(HapiContext context = new DefaultHapiContext()) {
			// TODO :: connection timeout
			Connection connection = context.newClient("google.com", 6666, false);				
			System.out.println("Established connection " + connection);
		} 
	}
}

since google.com will not answer the attempt to connect, the program will wait forever (i.e. hang). There seems to be no way to fix the problem, since ca.uhn.hl7v2.app.ConnectionFactory.createSocket(SocketFactory, String, int, boolean) calls socket.connect(new InetSocketAddress(host, port));, which will in fact wait forever for the connection to be established. ConnectionFactory cannot be overridden (all static methods), so it seems we're out of luck and would require to implement a completely new HapiContext.

effad avatar Nov 24 '22 12:11 effad

Technically you can try to workaround be implementing a

public class ConnectTimeoutSocket extends Socket {
	@Override
	public void connect(SocketAddress endpoint) throws IOException {
		connect(endpoint, 10000);
	}
}

and

public class ConnectTimoutSocketFactory implements SocketFactory {

	@Override
	public Socket createSocket() throws IOException {
		return new ConnectTimeoutSocket();
	}
        ...

but this seems very hacky ...

effad avatar Nov 24 '22 12:11 effad