1
2
3
4
5
6
7 package org.mule.tck;
8
9 import java.io.IOException;
10 import java.net.ServerSocket;
11 import java.util.ArrayList;
12 import java.util.List;
13
14 import org.apache.commons.logging.Log;
15 import org.apache.commons.logging.LogFactory;
16
17
18
19
20 public class PortUtils
21 {
22 final static private int MIN_PORT = 5000;
23 final static private int MAX_PORT = 6000;
24 final static Log logger = LogFactory.getLog(PortUtils.class);
25
26
27
28
29
30
31 public static List<Integer> findFreePorts(int numberOfPorts)
32 {
33 List<Integer> freePorts = new ArrayList<Integer>();
34 for (int port = MIN_PORT; freePorts.size() != numberOfPorts && port < MAX_PORT; ++port)
35 {
36 if (isPortFree(port))
37 {
38 freePorts.add(port);
39 }
40 }
41
42 if (freePorts.size() != numberOfPorts)
43 {
44 logger.info("requested " + numberOfPorts + " open ports, but returning " + freePorts.size());
45 }
46 return freePorts;
47 }
48
49
50
51
52
53
54 public static void checkPorts(boolean failIfTaken, String prefix, List<Integer> ports) throws Exception
55 {
56 for (Integer port : ports)
57 {
58 if (isPortFree(port))
59 {
60 logger.info(prefix + " port is free : " + port);
61 }
62 else
63 {
64 logger.info(prefix + " port is not free : " + port);
65 if (failIfTaken)
66 {
67 throw new Exception("port is not free : " + port);
68 }
69 }
70 }
71 }
72
73
74
75
76
77
78
79 public static boolean isPortFree(int port)
80 {
81 boolean portIsFree = true;
82
83 ServerSocket server = null;
84 try
85 {
86 server = new ServerSocket(port);
87 }
88 catch (IOException e)
89 {
90 portIsFree = false;
91 }
92 finally
93 {
94 if (server != null)
95 {
96 try
97 {
98 server.close();
99 }
100 catch (IOException e)
101 {
102
103 }
104 }
105 }
106 return portIsFree;
107 }
108 }