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