KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > taskdefs > condition > IsReachable


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18
19 package org.apache.tools.ant.taskdefs.condition;
20
21 import org.apache.tools.ant.BuildException;
22 import org.apache.tools.ant.Project;
23 import org.apache.tools.ant.ProjectComponent;
24
25 import java.lang.reflect.InvocationTargetException JavaDoc;
26 import java.lang.reflect.Method JavaDoc;
27 import java.net.InetAddress JavaDoc;
28 import java.net.MalformedURLException JavaDoc;
29 import java.net.URL JavaDoc;
30 import java.net.UnknownHostException JavaDoc;
31
32 /**
33  * Test for a host being reachable using ICMP "ping" packets & echo operations.
34  * Ping packets are very reliable for assessing reachability in a LAN or WAN,
35  * but they do not get through any well-configured firewall. Echo (port 7) may.
36  * <p/>
37  * This condition turns unknown host exceptions into false conditions. This is
38  * because on a laptop, DNS is one of the first services lost when the network
39  * goes; you are implicitly offline.
40  * <p/>
41  * If a URL is supplied instead of a host, the hostname is extracted and used in
42  * the test--all other parts of the URL are discarded.
43  * <p/>
44  * The test may not work through firewalls; that is, something may be reachable
45  * using a protocol such as HTTP, while the lower level ICMP packets get dropped
46  * on the floor. Similarly, a host may be detected as reachable with ICMP, but not
47  * reachable on other ports (i.e. port 80), because of firewalls.
48  * <p/>
49  * Requires Java1.5+ to work properly. On Java1.4 and earlier, if a hostname
50  * can be resolved, the destination is assumed to be reachable.
51  *
52  * @since Ant 1.7
53  */

54 public class IsReachable extends ProjectComponent implements Condition {
55
56     private static final int SECOND = 1000; // millis per second
57
private String JavaDoc host;
58     private String JavaDoc url;
59
60     /**
61      * The default timeout.
62      */

63     public static final int DEFAULT_TIMEOUT = 30;
64     private int timeout = DEFAULT_TIMEOUT;
65     /**
66      * Error when no hostname is defined
67      */

68     public static final String JavaDoc ERROR_NO_HOSTNAME = "No hostname defined";
69     /**
70      * Error when invalid timeout value is defined
71      */

72     public static final String JavaDoc ERROR_BAD_TIMEOUT = "Invalid timeout value";
73     /**
74      * Unknown host message is seen.
75      */

76     private static final String JavaDoc WARN_UNKNOWN_HOST = "Unknown host: ";
77     /**
78      * Network error message is seen.
79      */

80     public static final String JavaDoc ERROR_ON_NETWORK = "network error to ";
81     /** Error message when url and host are specified. */
82     public static final String JavaDoc ERROR_BOTH_TARGETS
83         = "Both url and host have been specified";
84     /** Error message when no reachably test avail. */
85     public static final String JavaDoc MSG_NO_REACHABLE_TEST
86         = "cannot do a proper reachability test on this Java version";
87     /** Error message when an invalid url is used. */
88     public static final String JavaDoc ERROR_BAD_URL = "Bad URL ";
89     /** Error message when no hostname in url. */
90     public static final String JavaDoc ERROR_NO_HOST_IN_URL = "No hostname in URL ";
91     /** The method name to look for in InetAddress */
92     public static final String JavaDoc METHOD_NAME = "isReachable";
93
94     /**
95      * Set the host to ping.
96      *
97      * @param host the host to ping.
98      */

99     public void setHost(String JavaDoc host) {
100         this.host = host;
101     }
102
103     /**
104      * Set the URL from which to extract the hostname.
105      *
106      * @param url a URL object.
107      */

108     public void setUrl(String JavaDoc url) {
109         this.url = url;
110     }
111
112     /**
113      * Set the timeout for the reachability test in seconds.
114      *
115      * @param timeout the timeout in seconds.
116      */

117     public void setTimeout(int timeout) {
118         this.timeout = timeout;
119     }
120
121     /**
122      * emptyness test
123      *
124      * @param string param to check
125      *
126      * @return true if it is empty
127      */

128     private boolean empty(String JavaDoc string) {
129         return string == null || string.length() == 0;
130     }
131
132     private static Class JavaDoc[] parameterTypes = {Integer.TYPE};
133
134     /**
135      * Evaluate the condition.
136      *
137      * @return true if the condition is true.
138      *
139      * @throws org.apache.tools.ant.BuildException
140      * if an error occurs
141      */

142     public boolean eval() throws BuildException {
143         if (empty(host) && empty(url)) {
144             throw new BuildException(ERROR_NO_HOSTNAME);
145         }
146         if (timeout < 0) {
147             throw new BuildException(ERROR_BAD_TIMEOUT);
148         }
149         String JavaDoc target = host;
150         if (!empty(url)) {
151             if (!empty(host)) {
152                 throw new BuildException(ERROR_BOTH_TARGETS);
153             }
154             try {
155                 //get the host of a url
156
URL JavaDoc realURL = new URL JavaDoc(url);
157                 target = realURL.getHost();
158                 if (empty(target)) {
159                     throw new BuildException(ERROR_NO_HOST_IN_URL + url);
160                 }
161             } catch (MalformedURLException JavaDoc e) {
162                 throw new BuildException(ERROR_BAD_URL + url, e);
163             }
164         }
165         log("Probing host " + target, Project.MSG_VERBOSE);
166         InetAddress JavaDoc address;
167         try {
168             address = InetAddress.getByName(target);
169         } catch (UnknownHostException JavaDoc e1) {
170             log(WARN_UNKNOWN_HOST + target);
171             return false;
172         }
173         log("Host address = " + address.getHostAddress(),
174                 Project.MSG_VERBOSE);
175         boolean reachable;
176         //Java1.5: reachable = address.isReachable(timeout * 1000);
177
Method JavaDoc reachableMethod = null;
178         try {
179             reachableMethod = InetAddress JavaDoc.class.getMethod(METHOD_NAME,
180                     parameterTypes);
181             Object JavaDoc[] params = new Object JavaDoc[1];
182             params[0] = new Integer JavaDoc(timeout * SECOND);
183             try {
184                 reachable = ((Boolean JavaDoc) reachableMethod.invoke(address, params))
185                         .booleanValue();
186             } catch (IllegalAccessException JavaDoc e) {
187                 //utterly implausible, but catered for anyway
188
throw new BuildException("When calling " + reachableMethod);
189             } catch (InvocationTargetException JavaDoc e) {
190                 //assume this is an IOexception about un readability
191
Throwable JavaDoc nested = e.getTargetException();
192                 log(ERROR_ON_NETWORK + target + ": " + nested.toString());
193                 //any kind of fault: not reachable.
194
reachable = false;
195             }
196         } catch (NoSuchMethodException JavaDoc e) {
197             //java1.4 or earlier
198
log("Not found: InetAddress." + METHOD_NAME, Project.MSG_VERBOSE);
199             log(MSG_NO_REACHABLE_TEST);
200             reachable = true;
201
202         }
203
204         log("host is" + (reachable ? "" : " not") + " reachable", Project.MSG_VERBOSE);
205         return reachable;
206     }
207 }
208
Popular Tags