hapifhir / hapi-hl7v2

277 stars 138 forks source link

Cannot set timeout for connection establishment of Client #89

Open effad opened 1 year ago

effad commented 1 year ago

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 commented 1 year ago

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 ...