1
2
3
4
5
6
7
8
9
10
11 package org.apache.maven.enforcer.rule;
12
13 import java.io.IOException;
14 import java.net.DatagramSocket;
15 import java.net.ServerSocket;
16
17 import org.apache.maven.enforcer.rule.api.EnforcerRule;
18 import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
19 import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
20 import org.apache.maven.plugin.logging.Log;
21
22 public class EnforcerPortRule implements EnforcerRule
23 {
24
25
26
27 private boolean shouldIfail = false;
28 private int port = 0;
29
30
31
32
33
34
35 public static boolean available(int port)
36 {
37 ServerSocket ss = null;
38 DatagramSocket ds = null;
39 try
40 {
41 ss = new ServerSocket(port);
42 ss.setReuseAddress(true);
43 ds = new DatagramSocket(port);
44 ds.setReuseAddress(true);
45 return true;
46 }
47 catch (IOException e)
48 {
49 }
50 finally
51 {
52 if (ds != null)
53 {
54 ds.close();
55 }
56
57 if (ss != null)
58 {
59 try
60 {
61 ss.close();
62 }
63 catch (IOException e)
64 {
65
66 }
67 }
68 }
69 return false;
70 }
71
72 public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException
73 {
74 Log log = helper.getLog();
75 log.info("checking availability of port : " + this.port);
76
77
78 if (!(this.port > 0))
79 {
80 throw new EnforcerRuleException("Port is not valid " + this.port);
81 }
82
83
84 if (!available(this.port))
85 {
86 throw new EnforcerRuleException("Port is not available " + this.port);
87 }
88
89 if (this.shouldIfail)
90 {
91 throw new EnforcerRuleException("Failing because my param said so.");
92 }
93 }
94
95
96
97
98
99
100
101
102 public String getCacheId()
103 {
104
105 return "" + this.shouldIfail;
106 }
107
108
109
110
111
112
113
114 public boolean isCacheable()
115 {
116 return false;
117 }
118
119
120
121
122
123
124
125
126 public boolean isResultValid(EnforcerRule arg0)
127 {
128 return false;
129 }
130 }