View Javadoc

1   /*
2       Copyright 2006 Ernest Micklei @ PhilemonWorks.com
3   
4      Licensed under the Apache License, Version 2.0 (the "License");
5      you may not use this file except in compliance with the License.
6      You may obtain a copy of the License at
7   
8          http://www.apache.org/licenses/LICENSE-2.0
9   
10     Unless required by applicable law or agreed to in writing, software
11     distributed under the License is distributed on an "AS IS" BASIS,
12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13     See the License for the specific language governing permissions and
14     limitations under the License.
15     
16  */
17  package com.philemonworks.selfdiagnose.check;
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.io.InputStreamReader;
22  import java.net.MalformedURLException;
23  import java.net.URL;
24  import java.net.URLConnection;
25  
26  import javax.servlet.http.HttpServletRequest;
27  
28  import org.xml.sax.Attributes;
29  
30  import com.philemonworks.selfdiagnose.DiagnoseException;
31  import com.philemonworks.selfdiagnose.DiagnoseUtil;
32  import com.philemonworks.selfdiagnose.DiagnosticTaskResult;
33  import com.philemonworks.selfdiagnose.ExecutionContext;
34  import com.philemonworks.selfdiagnose.PatternMatchingTask;
35  import com.philemonworks.selfdiagnose.SelfDiagnoseServlet;
36  
37  /**
38   * CheckURLReachable is a DiagnosticTask that verifies that an URL is reachable
39   * by connecting to it and inspecting the (http) response code.
40   * The url parameter may refer to a variable in the execution context with a String or URL value.
41   * <p/>
42   * <pre>
43  &lt;checkurlreachable url="http://www.philemonworks.com" /&gt;
44   * </pre>
45   * Stores the contents returned from the URL into the (optional) specified variable.  
46   * @author emicklei
47   */
48  public class CheckURLReachable extends PatternMatchingTask {
49      private static final long serialVersionUID = 5997980187300815588L;
50      private static final String PARAMETER_URL = "url";
51  	private String url;
52  
53  	/*
54  	 * (non-Javadoc)
55  	 * 
56  	 * @see com.philemonworks.selfdiagnose.DiagnosticTask#initializeFromAttributes(Attributes)
57  	 */
58  	public void initializeFromAttributes(Attributes attributes) {
59  		super.initializeFromAttributes(attributes);
60  		this.setUrl(attributes.getValue(PARAMETER_URL));
61  	}
62  	public String getDescription() {
63  		return "Check whether the url is reachable and data is available";
64  	}
65  	public void setUp(ExecutionContext ctx) throws DiagnoseException {
66  		super.setUp(ctx);
67  		DiagnoseUtil.verifyNonEmptyString(PARAMETER_URL, url, CheckURLReachable.class);
68  	}
69  	public void run(ExecutionContext ctx, DiagnosticTaskResult result) throws DiagnoseException {
70  		Object urlOrString = ctx.resolveValue(url);
71  		boolean urlIsString = false;
72  		URL newURL = null;
73  		try {
74  			if (urlOrString instanceof String) {
75  				urlIsString = true;
76  				newURL = new URL((String)urlOrString);				
77  			} else if (urlOrString instanceof URL)
78  				newURL = (URL)urlOrString;
79  			else throw new DiagnoseException(DiagnoseUtil.format(
80  					"Variable for url [{0}] is [{1}] but a String or URL was expected.", 
81  					 url, urlOrString == null ? "null" : urlOrString.toString()));
82  		} catch (MalformedURLException e) {
83  			if (urlIsString) {
84  				// Try expanding the URL with an URL base taken from the request
85  				HttpServletRequest request = SelfDiagnoseServlet.getCurrentRequest();
86  				String base=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();			
87  				try {
88  					newURL = new URL(base + "/" + url);
89  				} catch (MalformedURLException ex) {
90  					throw new DiagnoseException(ex);
91  				}
92  			}
93  		}
94  		URLConnection newConnection = null;
95  		try {
96  			newConnection = newURL.openConnection();			
97  			InputStream content = (InputStream)newConnection.getContent();
98  			if (this.getPattern() != null || this.getVariableName() != null) {
99  			    InputStreamReader isr = new InputStreamReader(content);
100                 StringBuilder sb = new StringBuilder();
101                 while (isr.ready()) { sb.append((char)isr.read()); }
102                 isr.close();
103                 String data = sb.toString();
104                 ctx.setValue(this.getVariableName(),data);
105                 this.checkValueAgainstPattern(result, url, "downloaded","contents", data);  
106 			}
107 		} catch (IOException e1) {
108 			result.setFailedMessage("URL [" + newURL + "] is not reachable or no connection could be opened because [" + e1.getMessage() +"]");
109 			return;
110 		} finally {
111 		    newConnection = null;
112 		}
113 		result.setPassedMessage("URL [" + newURL + "] is reachable and content could be retrieved.");
114 	}
115 	/**
116 	 * Set the URL to test.
117 	 * 
118 	 * @param url : String
119 	 */
120 	public void setUrl(String urlSpec) {
121 		url = urlSpec;
122 	}
123 }