1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
package org.mule.util; |
8 | |
|
9 | |
import java.io.IOException; |
10 | |
import java.io.InterruptedIOException; |
11 | |
import java.net.Socket; |
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
public final class TimedSocket |
17 | |
{ |
18 | |
private static final int WATCHDOG_FREQUENCY = 100; |
19 | |
|
20 | |
private TimedSocket() |
21 | 0 | { |
22 | |
|
23 | 0 | } |
24 | |
|
25 | |
|
26 | |
|
27 | |
|
28 | |
|
29 | |
|
30 | |
|
31 | |
|
32 | |
|
33 | |
|
34 | |
|
35 | |
public static Socket createSocket(String host, int port, int timeout) throws IOException |
36 | |
{ |
37 | 0 | SocketConnector connector = new SocketConnector(host, port); |
38 | 0 | connector.start(); |
39 | |
|
40 | 0 | int timer = 0; |
41 | |
|
42 | 0 | while (!connector.isConnected()) |
43 | |
{ |
44 | 0 | if (connector.hasException()) |
45 | |
{ |
46 | 0 | throw (connector.getException()); |
47 | |
} |
48 | |
|
49 | |
try |
50 | |
{ |
51 | 0 | Thread.sleep(WATCHDOG_FREQUENCY); |
52 | |
} |
53 | 0 | catch (InterruptedException unexpectedInterruption) |
54 | |
{ |
55 | 0 | throw new InterruptedIOException("Connection interruption: " + unexpectedInterruption.getMessage()); |
56 | 0 | } |
57 | |
|
58 | 0 | timer += WATCHDOG_FREQUENCY; |
59 | |
|
60 | 0 | if (timer >= timeout) |
61 | |
{ |
62 | 0 | throw new InterruptedIOException("Connection timeout on " + host + ":" + port + " after " + timer + " milliseconds"); |
63 | |
} |
64 | |
} |
65 | |
|
66 | 0 | return connector.getSocket(); |
67 | |
} |
68 | |
|
69 | |
static class SocketConnector extends Thread |
70 | |
{ |
71 | |
private volatile Socket connectedSocket; |
72 | |
private String host; |
73 | |
private int port; |
74 | |
private IOException exception; |
75 | |
|
76 | |
public SocketConnector(String host, int port) |
77 | 0 | { |
78 | 0 | this.host = host; |
79 | 0 | this.port = port; |
80 | 0 | } |
81 | |
|
82 | |
public void run() |
83 | |
{ |
84 | |
try |
85 | |
{ |
86 | 0 | connectedSocket = new Socket(host, port); |
87 | |
} |
88 | 0 | catch (IOException ioe) |
89 | |
{ |
90 | 0 | exception = ioe; |
91 | 0 | } |
92 | 0 | } |
93 | |
|
94 | |
public boolean isConnected() |
95 | |
{ |
96 | 0 | return connectedSocket != null; |
97 | |
} |
98 | |
|
99 | |
public boolean hasException() |
100 | |
{ |
101 | 0 | return exception != null; |
102 | |
} |
103 | |
|
104 | |
public Socket getSocket() |
105 | |
{ |
106 | 0 | return connectedSocket; |
107 | |
} |
108 | |
|
109 | |
public IOException getException() |
110 | |
{ |
111 | 0 | return exception; |
112 | |
} |
113 | |
} |
114 | |
} |