001: /* Copyright 2004 The JA-SIG Collaborative. All rights reserved.
002: * See license distributed with this file and
003: * available online at http://www.uportal.org/license.html
004: */
005:
006: package org.jasig.portal.utils;
007:
008: import java.io.InterruptedIOException;
009: import java.net.HttpURLConnection;
010: import java.net.MalformedURLException;
011: import java.net.URL;
012: import java.net.URLConnection;
013: import java.util.Timer;
014: import java.util.TimerTask;
015:
016: import org.apache.commons.logging.Log;
017: import org.apache.commons.logging.LogFactory;
018:
019: /**
020: *
021: * This class checks a URL or a webserver hosting a URL. It only allows a specific time allocated for
022: * connecting to the URL rather than waiting for a timeout.
023: * This class uses the <code>java.util.Timer</code> to schedule a task which is cancelling the attempt of calling
024: * httpURLConnection.
025: *
026: * @author <a href="mailto:kazemnaderi@yahoo.ca">Kazem Naderi</a>
027: * @version $Revision: 36736 $
028: * @since uPortal 2.2
029: * @deprecated Use {@link HttpClientManager#getNewHTTPClient} instead
030: */
031:
032: public class AddressTester {
033:
034: private static final Log log = LogFactory
035: .getLog(AddressTester.class);
036:
037: /**The timer object that takes a timerTask as a parameter when constructed*/
038: private static final Timer timer = new Timer();
039:
040: /**The connection thread inwhich the connection attempt is made*/
041: Thread connectionThread;
042:
043: /* urlConnectio to be used */
044: private HttpURLConnection urlConnect = null;
045:
046: /**The connectioncode returned from connetion attempt*/
047: private int connectionCode = 0;
048:
049: /**This the url to try. the value is set through the class constructor*/
050: private String urlToTry = "";
051:
052: /**The amount of time connection attempt can take, the default is 100 ms*/
053: int timeToWait = 100;
054: static final int defaultTimeToWait = 100;
055:
056: /** Get header data only **/
057: private boolean headOnly = false;
058:
059: /** Debug the code */
060: private static boolean DEBUG = false;
061:
062: static {
063: Runtime.getRuntime().addShutdownHook(
064: new Thread("AddressTester JVM shutdown hook") {
065: public void run() {
066: timer.cancel();
067: }
068: });
069: }
070:
071: /**
072: * Constructor
073: * @param milliSeconds the number of milliseconds to let the connectioon attempt run
074: * @param urlString the String representing a URL
075: * @param getHead use setRequestMathod("HEAD")
076: */
077: public AddressTester(final String urlString,
078: final int milliSeconds, final boolean getHead)
079: throws Exception {
080: urlToTry = urlString;
081: timeToWait = milliSeconds;
082: connectionThread = new Thread() {
083: public void run() {
084: try {
085: URL url = new URL(urlToTry);
086: if (DEBUG) {
087: System.out.println("URL to try is " + urlToTry);
088: }
089:
090: RemindTask rt = new RemindTask();
091: try {
092: timer.schedule(rt, timeToWait);
093: urlConnect = (HttpURLConnection) url
094: .openConnection();
095: if (headOnly) {
096: urlConnect.setRequestMethod("HEAD");
097: }
098: urlConnect.setInstanceFollowRedirects(false);
099: connectionCode = urlConnect.getResponseCode();
100: } catch (InterruptedIOException iie) { /* Thread Interrupt */
101: if (DEBUG) {
102: System.out.println("timed out on "
103: + urlToTry);
104: }
105: if (log.isInfoEnabled())
106: log
107: .info("AddressTest::checkURL(): timed out on "
108: + urlToTry);
109:
110: } catch (Exception e) { /* Something went wrong */
111: if (DEBUG) {
112: System.out.println(urlToTry
113: + " generated exception: "
114: + e.getMessage());
115: }
116: if (log.isInfoEnabled())
117: log.info("AddressTest::checkURL(): "
118: + urlToTry
119: + " generated exception: ", e);
120: } finally {
121: rt.cancel();
122: }
123:
124: } catch (MalformedURLException mue) { /* Garbage In */
125: if (DEBUG) {
126: System.out.println("Bad URL: " + urlToTry);
127: }
128: log.error("AddressTest::checkURL(): Bad URL: "
129: + urlToTry);
130: }
131: }
132: };
133:
134: connectionThread.start();
135: }
136:
137: /**
138: * Constructor
139: * @param urlString
140: * @param getHead
141: * @throws java.lang.Exception
142: * @deprecated Use {@link HttpClientManager#getNewHTTPClient()} instead
143: */
144: public AddressTester(String urlString, boolean getHead)
145: throws Exception {
146: this (urlString, defaultTimeToWait, getHead);
147: }
148:
149: /**
150: * Constructor
151: * @param milliSeconds - the number of milliseconds to let the connectioon attempt run
152: * @param urlString - the String representing a URL
153: * @deprecated Use {@link HttpClientManager#getNewHTTPClient()} instead
154: */
155: public AddressTester(int milliSeconds, String urlString)
156: throws Exception {
157: this (urlString, milliSeconds, false);
158: }
159:
160: /**
161: * Constructor
162: * @param urlString the String representing a URL
163: * @deprecated Use {@link HttpClientManager#getNewHTTPClient()} instead
164: */
165: public AddressTester(String urlString) throws Exception {
166: this (urlString, defaultTimeToWait, false);
167: }
168:
169: /**
170: * This method returns the response code that was set in checkURL ()
171: * @return the response code
172: */
173: public int getResponseCode() {
174: //make sure we wait for connection thread to finish
175: if (connectionThread.isAlive()) {
176: try {
177: connectionThread.join();
178: } catch (InterruptedException e) {
179: return 0;
180: }
181: }
182: return this .connectionCode;
183: }
184:
185: /**
186: * Get the (valid) URL connection
187: * @return URL connection
188: */
189: public URLConnection getConnection() {
190: //make sure we wait for connection thread to finish
191: if (connectionThread.isAlive()) {
192: try {
193: connectionThread.join();
194: } catch (InterruptedException e) {
195: return null;
196: }
197: }
198: return urlConnect;
199: }
200:
201: /**
202: * Shut down the connection
203: */
204: public void disconnect() {
205: if (urlConnect != null) {
206: urlConnect.disconnect();
207: }
208: }
209:
210: /**
211: *
212: * @return <code>false</code> if the address is not available. <code>True</code> otherwise
213: */
214: public boolean URLAvailable() {
215: //make sure we wait for connection thread to finish
216: if (connectionThread.isAlive()) {
217: try {
218: connectionThread.join();
219: } catch (InterruptedException e) {
220: return false;
221: }
222: }
223: return connectionCode == HttpURLConnection.HTTP_OK;
224: }
225:
226: /**
227: * Class RemidTask
228: * @author knaderi
229: *
230: * This is a TimerTask class that interuupts the connectionThread
231: * After the timer scheduled time.
232: *
233: */
234: class RemindTask extends TimerTask {
235: public void run() {
236: if (connectionThread.isAlive()) {
237: if (DEBUG) {
238: System.out.println("Canceled");
239: }
240: connectionThread.interrupt();
241: }
242: }
243: }
244:
245: /**
246: * This is the main method and is left as a usage sample
247: * @param args
248: */
249: public static void main(String[] args) {
250: String[] testUrl = new String[] {
251: "http://www.cbcsrc.ca/cbcsrc/1010991/11566",
252: "http://www.theweathernetwork.com/weatherbutton/test.js",
253: "http://localhost:666/a.nothere",
254: "http://www.linuxmandrake.com",
255: "https://localhost:443/a.nothere" };
256: for (int i = 0; i < testUrl.length; i++) {
257: try {
258: System.out.println("About to schedule task: "
259: + testUrl[i]);
260: AddressTester myReminder = new AddressTester(
261: testUrl[i], false);
262: System.out.println(" Running the test URL");
263: System.out.println("available: "
264: + myReminder.URLAvailable() + ", HTTP code: "
265: + myReminder.getResponseCode());
266: } catch (Exception e) {
267: }
268: }
269: }
270:
271: }
|