KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > network > TCPProxyFixture


1 /*
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.network;
5
6 import com.tc.net.proxy.TCPProxy;
7 import com.tc.util.Assert;
8
9 import java.io.IOException JavaDoc;
10 import java.net.InetAddress JavaDoc;
11 import java.net.InetSocketAddress JavaDoc;
12 import java.net.Socket JavaDoc;
13 import java.net.UnknownHostException JavaDoc;
14
15 public final class TCPProxyFixture {
16
17   private final TCPProxy proxy;
18   private final int localPort;
19   private boolean up;
20
21   /**
22    * There is a bit of a race condition here where someone can use our local socket in between us stopping and starting --
23    * but that's just too bad and a risk we will have to take.
24    */

25   public TCPProxyFixture(String JavaDoc remoteHost, int remotePort) throws UnknownHostException JavaDoc {
26     Assert.assertNotNull(remoteHost);
27     localPort = findAvailableLocalPort();
28     proxy = new TCPProxy(localPort, InetAddress.getByName(remoteHost), remotePort, 0, false, null);
29     up = false;
30   }
31
32   public int localPort() {
33     return localPort;
34   }
35
36   public synchronized void severeConnection() {
37     Assert.eval("Connection must be started in order to severe it", up);
38     proxy.stop();
39     up = false;
40   }
41
42   public synchronized void establishConnection() throws IOException JavaDoc {
43     Assert.eval("Connection must be stopped to start it", !up);
44     proxy.start();
45     up = true;
46   }
47
48   private static int findAvailableLocalPort() {
49     int port = 18456;
50     while (true) {
51       Socket JavaDoc socket = new Socket JavaDoc();
52       try {
53         socket.connect(new InetSocketAddress JavaDoc(port));
54         // Already being used, try the next port
55
socket.close();
56         ++port;
57       } catch (IOException JavaDoc e) {
58         // Found an unused port
59
break;
60       }
61     }
62     return port;
63   }
64
65 }
66
Popular Tags