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