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
36
37
38 public static boolean available(int port)
39 {
40 ServerSocket ss = null;
41 DatagramSocket ds = null;
42 try
43 {
44 ss = new ServerSocket(port);
45 ss.setReuseAddress(true);
46 ds = new DatagramSocket(port);
47 ds.setReuseAddress(true);
48 return true;
49 }
50 catch (IOException e)
51 {
52 }
53 finally
54 {
55 if (ds != null)
56 {
57 ds.close();
58 }
59
60 if (ss != null)
61 {
62 try
63 {
64 ss.close();
65 }
66 catch (IOException e)
67 {
68
69 }
70 }
71 }
72 return false;
73 }
74
75 public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException
76 {
77 Log log = helper.getLog();
78 log.info("checking availability of port : " + this.port);
79
80
81 if (!(this.port > 0))
82 {
83 throw new EnforcerRuleException("Port is not valid " + this.port);
84 }
85
86
87 if (!available(this.port))
88 {
89 throw new EnforcerRuleException("Port is not available " + this.port);
90 }
91
92 if (this.shouldIfail)
93 {
94 throw new EnforcerRuleException("Failing because my param said so.");
95 }
96 }
97
98
99
100
101
102
103
104
105 public String getCacheId()
106 {
107
108 return "" + this.shouldIfail;
109 }
110
111
112
113
114
115
116
117 public boolean isCacheable()
118 {
119 return false;
120 }
121
122
123
124
125
126
127
128
129 public boolean isResultValid(EnforcerRule arg0)
130 {
131 return false;
132 }
133 }