View Javadoc
1   /**
2    * Copyright 2004-2013 The Kuali Foundation
3    *
4    * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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  package org.kuali.common.dns.http;
17  
18  import static java.lang.System.currentTimeMillis;
19  import static org.kuali.common.util.base.Threads.sleep;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  
24  import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
25  import org.apache.commons.httpclient.Header;
26  import org.apache.commons.httpclient.HttpClient;
27  import org.apache.commons.httpclient.HttpMethod;
28  import org.apache.commons.httpclient.HttpMethodRetryHandler;
29  import org.apache.commons.httpclient.methods.GetMethod;
30  import org.apache.commons.httpclient.params.HttpClientParams;
31  import org.apache.commons.httpclient.params.HttpMethodParams;
32  import org.apache.commons.io.IOUtils;
33  import org.slf4j.Logger;
34  import org.slf4j.LoggerFactory;
35  
36  public class HttpUtil {
37  
38  	private final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
39  
40  	int requestTimeout = 8000;
41  	int sleepInterval = 3000;
42  	int timeout = 300;
43  
44  	protected String getTimeout(long l) {
45  		if (l == -1) {
46  			return "";
47  		} else {
48  			return " - (Timeout in " + l + "s)";
49  		}
50  	}
51  
52  	public void log(String url, HttpRequestResult result, int secondsRemaining) {
53  		StringBuilder sb = new StringBuilder();
54  		sb.append("Status for '" + url + "' is '" + getMsg(result) + "'");
55  		sb.append(getTimeout(secondsRemaining));
56  		logger.info(sb.toString());
57  	}
58  
59  	protected String getMsg(HttpRequestResult result) {
60  		switch (result.getType()) {
61  		case EXCEPTION:
62  			Exception exception = result.getException();
63  			return exception.getMessage();
64  		case COMPLETED:
65  			int statusCode = result.getStatusCode();
66  			String statusText = result.getStatusText();
67  			return statusCode + ":" + statusText;
68  		case TIMEOUT:
69  			return "Timeout exceeded";
70  		default:
71  			throw new IllegalArgumentException(result.getType() + " is an unknown type");
72  		}
73  	}
74  
75  	protected int getSecondsRemaining(long endMillis) {
76  		long currentMillis = currentTimeMillis();
77  		long millisRemaining = endMillis - currentMillis;
78  		double secondsRemaining = millisRemaining / 1000D;
79  		return (int) Math.ceil(secondsRemaining);
80  	}
81  
82  	public HttpRequestResult doWait(String url) {
83  		HttpClient client = getHttpClient();
84  		long now = currentTimeMillis();
85  		long timeoutMillis = timeout * 1000;
86  		long end = now + timeoutMillis;
87  		logger.info("Determining status for '" + url + "'");
88  		for (;;) {
89  			HttpRequestResult result = executeMethod(client, url);
90  			int secondsRemaining = getSecondsRemaining(end);
91  			log(url, result, secondsRemaining);
92  			if (HttpRequestResultType.COMPLETED.equals(result.getType())) {
93  				return result;
94  			}
95  			if (currentTimeMillis() > end) {
96  				result.setType(HttpRequestResultType.TIMEOUT);
97  				log(url, result, -1);
98  				return result;
99  			}
100 			sleep(sleepInterval);
101 		}
102 	}
103 
104 	public HttpClient getHttpClient() {
105 		HttpClient client = new HttpClient();
106 		HttpClientParams clientParams = client.getParams();
107 		HttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(0, false);
108 		clientParams.setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
109 		clientParams.setParameter(HttpMethodParams.SO_TIMEOUT, requestTimeout);
110 		return client;
111 	}
112 
113 	protected String getResponseBody(HttpMethod method) throws IOException {
114 		InputStream in = null;
115 		try {
116 			in = method.getResponseBodyAsStream();
117 			return IOUtils.toString(in);
118 		} finally {
119 			IOUtils.closeQuietly(in);
120 		}
121 	}
122 
123 	public HttpRequestResult executeMethod(HttpMethod method) {
124 		return executeMethod(getHttpClient(), method);
125 	}
126 
127 	public HttpRequestResult executeMethod(HttpClient client, HttpMethod method) {
128 		HttpRequestResult result = new HttpRequestResult();
129 		try {
130 			client.executeMethod(method);
131 			int statusCode = method.getStatusCode();
132 			String statusText = method.getStatusText();
133 			String responseBody = getResponseBody(method);
134 			Header[] responseHeaders = method.getResponseHeaders();
135 			method.releaseConnection();
136 			result.setStatusCode(statusCode);
137 			result.setStatusText(statusText);
138 			result.setResponseBody(responseBody);
139 			result.setResponseHeaders(responseHeaders);
140 			result.setType(HttpRequestResultType.COMPLETED);
141 		} catch (Exception e) {
142 			result.setType(HttpRequestResultType.EXCEPTION);
143 			result.setException(e);
144 		}
145 		return result;
146 	}
147 
148 	public HttpRequestResult executeMethod(HttpClient client, String url) {
149 		HttpMethod method = new GetMethod(url);
150 		return executeMethod(client, method);
151 	}
152 
153 	public int getRequestTimeout() {
154 		return requestTimeout;
155 	}
156 
157 	public void setRequestTimeout(int requestTimeout) {
158 		this.requestTimeout = requestTimeout;
159 	}
160 
161 	public int getSleepInterval() {
162 		return sleepInterval;
163 	}
164 
165 	public void setSleepInterval(int sleepInterval) {
166 		this.sleepInterval = sleepInterval;
167 	}
168 
169 	public int getTimeout() {
170 		return timeout;
171 	}
172 
173 	public void setTimeout(int waitTimeout) {
174 		this.timeout = waitTimeout;
175 	}
176 
177 	public Logger getLogger() {
178 		return logger;
179 	}
180 }