1 30 31 package org.apache.commons.httpclient.protocol; 32 33 import java.io.IOException ; 34 import java.net.InetAddress ; 35 import java.net.Socket ; 36 import java.net.UnknownHostException ; 37 38 import org.apache.commons.httpclient.ConnectTimeoutException; 39 import org.apache.commons.httpclient.util.TimeoutController; 40 41 53 public final class ControllerThreadSocketFactory { 54 55 private ControllerThreadSocketFactory() { 56 super(); 57 } 58 59 80 public static Socket createSocket( 81 final ProtocolSocketFactory socketfactory, 82 final String host, 83 final int port, 84 final InetAddress localAddress, 85 final int localPort, 86 int timeout) 87 throws IOException , UnknownHostException , ConnectTimeoutException 88 { 89 SocketTask task = new SocketTask() { 90 public void doit() throws IOException { 91 setSocket(socketfactory.createSocket(host, port, localAddress, localPort)); 92 } 93 }; 94 try { 95 TimeoutController.execute(task, timeout); 96 } catch (TimeoutController.TimeoutException e) { 97 throw new ConnectTimeoutException( 98 "The host did not accept the connection within timeout of " 99 + timeout + " ms"); 100 } 101 Socket socket = task.getSocket(); 102 if (task.exception != null) { 103 throw task.exception; 104 } 105 return socket; 106 } 107 108 public static Socket createSocket(final SocketTask task, int timeout) 109 throws IOException , UnknownHostException , ConnectTimeoutException 110 { 111 try { 112 TimeoutController.execute(task, timeout); 113 } catch (TimeoutController.TimeoutException e) { 114 throw new ConnectTimeoutException( 115 "The host did not accept the connection within timeout of " 116 + timeout + " ms"); 117 } 118 Socket socket = task.getSocket(); 119 if (task.exception != null) { 120 throw task.exception; 121 } 122 return socket; 123 } 124 125 128 public static abstract class SocketTask implements Runnable { 129 130 private Socket socket; 131 132 private IOException exception; 133 134 138 protected void setSocket(final Socket newSocket) { 139 socket = newSocket; 140 } 141 142 146 protected Socket getSocket() { 147 return socket; 148 } 149 153 public abstract void doit() throws IOException ; 154 155 156 public void run() { 157 try { 158 doit(); 159 } catch (IOException e) { 160 exception = e; 161 } 162 } 163 } 164 } 165 | Popular Tags |