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