Project

General

Profile

Download (7.36 KB) Statistics
| Branch: | Tag: | Revision:
1
// $Id$
2
/**
3
* Copyright (C) 2007 EDIT
4
* European Distributed Institute of Taxonomy 
5
* http://www.e-taxonomy.eu
6
* 
7
* The contents of this file are subject to the Mozilla Public License Version 1.1
8
* See LICENSE.TXT at the top of this package for the full license terms.
9
*/
10

    
11
package eu.etaxonomy.cdm.common;
12

    
13
import java.io.File;
14
import java.io.FileInputStream;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.net.InetAddress;
18
import java.net.URI;
19
import java.net.URISyntaxException;
20
import java.net.URL;
21
import java.net.UnknownHostException;
22
import java.util.ArrayList;
23
import java.util.HashMap;
24
import java.util.List;
25
import java.util.Map;
26

    
27
import org.apache.http.HttpException;
28
import org.apache.http.HttpResponse;
29
import org.apache.http.HttpStatus;
30
import org.apache.http.NameValuePair;
31
import org.apache.http.StatusLine;
32
import org.apache.http.client.ClientProtocolException;
33
import org.apache.http.client.HttpClient;
34
import org.apache.http.client.methods.HttpGet;
35
import org.apache.http.client.methods.HttpHead;
36
import org.apache.http.client.methods.HttpUriRequest;
37
import org.apache.http.client.utils.URIUtils;
38
import org.apache.http.client.utils.URLEncodedUtils;
39
import org.apache.http.impl.client.DefaultHttpClient;
40
import org.apache.log4j.Logger;
41

    
42
/**
43
 * @author n.hoffmann
44
 * @created Sep 23, 2010
45
 * @version 1.0
46
 */
47
public class UriUtils {
48
	private static final Logger logger = Logger.getLogger(UriUtils.class);
49
		
50
	/**
51
	 * see {@link #getInputStream(URI, Map)}
52
	 * 
53
	 * @param uri
54
	 * @return
55
	 * @throws IOException
56
	 * @throws HttpException
57
	 */
58
	public static InputStream getInputStream(URI uri) throws IOException, HttpException{
59
		return getInputStream(uri, null);
60
	}
61
	
62
	/**
63
	 * Retrieves an {@link InputStream input stream} of the resource located at the given uri.
64
	 * 
65
	 * @param uri
66
	 * @return
67
	 * @throws IOException
68
	 * @throws HttpException 
69
	 */
70
	public static InputStream getInputStream(URI uri, Map<String, String> requestHeaders) throws IOException, HttpException{
71
		
72
		if(requestHeaders == null){
73
			requestHeaders = new HashMap<String, String>();
74
		}
75
		
76
		if (uri.getScheme().equals("http") || uri.getScheme().equals("https")){
77
			HttpResponse response = UriUtils.getResponse(uri, requestHeaders);
78
			if(UriUtils.isOk(response)){
79
	        	InputStream stream = response.getEntity().getContent();
80
	        	return stream;
81
	        } else {
82
	        	throw new HttpException("HTTP Reponse code is not = 200 (OK): " + UriUtils.getStatus(response));
83
	        }
84
		}else if (uri.getScheme().equals("file")){
85
			File file = new File(uri);
86
			return new FileInputStream(file);
87
		}else{
88
			throw new RuntimeException("Protokoll not yet handled: " + uri.getScheme()); 
89
		}
90
	}
91
	
92
	/**
93
	 * 
94
	 * @param response
95
	 * @return
96
	 */
97
	public static boolean isOk(HttpResponse response){
98
		return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
99
	}
100
	
101
	/**
102
	 * 
103
	 * @param response
104
	 * @return
105
	 * @throws IOException
106
	 */
107
	public static InputStream getContent(HttpResponse response) throws IOException{
108
		return response.getEntity().getContent();
109
	}
110
	
111
	public static String getStatus(HttpResponse response){
112
		StatusLine statusLine = response.getStatusLine();
113
		return "(" + statusLine.getStatusCode() + ")" + statusLine.getReasonPhrase();
114
	}
115
	
116
	/**
117
	 * Returns a {@link HttpResponse} object for given uri
118
	 * 
119
	 * @param uri
120
	 * @param requestHeaders
121
	 * @return
122
	 * @throws ClientProtocolException
123
	 * @throws IOException
124
	 */
125
	public static HttpResponse getResponse(URI uri, Map<String, String> requestHeaders) throws ClientProtocolException, IOException{
126
		// Create an instance of HttpClient.
127
		HttpClient  client = new DefaultHttpClient();
128
		
129
		HttpGet  method = new HttpGet(uri);
130
	    
131
        // configure the connection
132
        if(requestHeaders != null){
133
	       	for(String key : requestHeaders.keySet()){
134
	        	method.addHeader(key, requestHeaders.get(key));        	
135
	        }
136
		}
137
        
138
		//TODO  method.setFollowRedirects(followRedirects);
139

    
140
        logger.debug("sending GET request: " + uri);
141
        
142
        return client.execute(method);
143
	}
144
	
145
	public static URI createUri(URL baseUrl, String subPath, List<NameValuePair> qparams, String fragment) throws	URISyntaxException {
146
		
147
		String path = baseUrl.getPath();
148
		
149
		if(subPath != null){
150
			if(!path.endsWith("/")){
151
				path += "/";
152
			}
153
			if(subPath.startsWith("/")){
154
				subPath = subPath.substring(1);
155
			}
156
			path += subPath;
157
		}
158
		
159
		if(qparams == null){
160
			qparams = new ArrayList<NameValuePair>(0);
161
		}
162
		String query = null;
163
		if(! qparams.isEmpty()){
164
			query = URLEncodedUtils.format(qparams, "UTF-8");
165
		}
166
		
167
		URI uri = URIUtils.createURI(baseUrl.getProtocol(),
168
				baseUrl.getHost(), baseUrl.getPort(), path, query, fragment);
169

    
170
		return uri;
171
	}
172
	
173
	/**
174
	 * Tests internet connectivity by testing HEAD request for 4 known URL's.<BR>
175
	 * If non of them is available <code>false</code> is returned. Otherwise true.<BR> 
176
	 * @param firstUriToTest if not <code>null</code> this URI is tested before testing the standard URLs.
177
	 * @return true if internetconnectivity is given.
178
	 */
179
	public static boolean isInternetAvailable(URI firstUriToTest){
180
		boolean result = false;
181
		if (firstUriToTest != null && isServiceAvailable(firstUriToTest)){
182
			return true;
183
		}
184
		
185
		URI uri = URI.create("http://www.cnn.com/");
186
		if (isServiceAvailable(uri)){
187
			return true;
188
		}
189
		uri = URI.create("http://www.bahn.de/");
190
		if (isServiceAvailable(uri)){
191
			return true;
192
		}
193
		uri = URI.create("http://www.google.com/");
194
		if (isServiceAvailable(uri)){
195
			return true;
196
		}
197
		uri = URI.create("http://www.facebook.com/");
198
		if (isServiceAvailable(uri)){
199
			return true;
200
		}
201
		
202
		return result;
203
	}
204
	
205
	/**
206
	 * Performs HEAD request for the given URI.<BR>
207
	 * If any exception occurs <code>false</code> is returned. Otherwise true. <BR>
208
	 * @param serviceUri the URI to test.
209
	 * @return true if service is available.
210
	 */
211
	public static boolean isServiceAvailable(URI serviceUri){
212
		boolean result = false;
213
		
214
        //Http 
215
		HttpClient  client = new DefaultHttpClient();
216
		HttpUriRequest request = new HttpHead(serviceUri);
217
		 
218
		try {
219
			// Execute the request
220
			HttpResponse response = client.execute(request);
221
			// Examine the response status
222
			if (logger.isDebugEnabled()){
223
				logger.debug(response.getStatusLine());
224
			}
225
			 result = true;
226
			 
227
		} catch (UnknownHostException e1) {
228
			logger.info("Unknwon Host: " +e1.getMessage());
229
		} catch (ClientProtocolException e2) {
230
			logger.info("ClientProtocolException: " + e2.getMessage());
231
		} catch (IOException e3) {
232
			logger.info("IOException: " + e3.getMessage());
233
		}
234
	     
235
	     // When HttpClient instance is no longer needed, 
236
	     // shut down the connection manager to ensure
237
	     // immediate deallocation of all system resources
238
		//needed ?
239
//	     client.getConnectionManager().shutdown();   
240

    
241
		return result;
242
	}
243
	
244
	/**
245
	 * Tests reachability of a root server by trying to resolve a host name.
246
	 * @param hostNameToResolve the host name to resolve. If <code>null</code> 
247
	 * a default host name is tested.
248
	 * @return
249
	 */
250
	public static boolean isRootServerAvailable(String hostNameToResolve){
251
		try {
252
			if (hostNameToResolve == null){
253
				hostNameToResolve = "cnn.com";
254
			}
255
		    InetAddress inetHost = InetAddress.getByName(hostNameToResolve);
256
		    logger.debug("The hosts IP address is: " + inetHost.getHostAddress());
257
			return true;
258
		 } catch(UnknownHostException ex) {
259
			 logger.info("Unrecognized host");
260
		     return false;
261
		 }
262
	}
263
	
264
}
(13-13/14)