KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > remoting > TestUtil


1 /*
2  * JBoss, the OpenSource J2EE webOS
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7 package org.jboss.test.remoting;
8
9 import java.io.IOException JavaDoc;
10 import java.net.ServerSocket JavaDoc;
11 import java.security.SecureRandom JavaDoc;
12 import org.jboss.logging.Logger;
13
14 /**
15  * @author <a HREF="mailto:tom.elrod@jboss.com">Tom Elrod</a>
16  */

17 public class TestUtil
18 {
19    private static final Logger log = Logger.getLogger(TestUtil.class);
20
21    public static int getRandomPort()
22    {
23       Integer JavaDoc port = null;
24       while(port == null)
25       {
26          port = getFreePort();
27       }
28       return port.intValue();
29    }
30
31    private static Integer JavaDoc getFreePort()
32    {
33       Integer JavaDoc port = null;
34       ServerSocket JavaDoc socket = null;
35
36       int p = Math.abs(new SecureRandom JavaDoc(String.valueOf(System.currentTimeMillis()).getBytes()).nextInt(2000));
37
38       try
39       {
40          socket = new ServerSocket JavaDoc(p);
41          port = new Integer JavaDoc(p);
42       }
43       catch(IOException JavaDoc e)
44       {
45          log.debug("port " + p + " already in use. Will try another.");
46       }
47       finally
48       {
49          if(socket != null)
50          {
51             try
52             {
53                socket.close();
54             }
55             catch(IOException JavaDoc e)
56             {
57
58             }
59          }
60       }
61       return port;
62    }
63 }
Popular Tags