forked from jbufu/openid4java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpCache.java
More file actions
559 lines (467 loc) · 16.9 KB
/
HttpCache.java
File metadata and controls
559 lines (467 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
/*
* Copyright 2006-2008 Sxip Identity Corporation
*/
package org.openid4java.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.AllClientPNames;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Date;
import javax.net.ssl.SSLContext;
/**
* Wrapper cache around HttpClient providing caching for HTTP requests.
* Intended to be used to optimize the number of HTTP requests performed
* during OpenID discovery.
*
* @author Marius Scurtescu, Johnny Bufu
*/
public class HttpCache extends AbstractHttpFetcher
{
private static Log _log = LogFactory.getLog(HttpCache.class);
private static final boolean DEBUG = _log.isDebugEnabled();
/**
* HttpClient used to place the HTTP requests.
*/
private HttpClient _client;
/**
* Cache for GET requests. Map of URL -> HttpResponse.
*/
private Map _getCache = new HashMap();
// todo: cache management
/**
* Cache for HEAD requests. Map of URL -> HttpResponse.
*/
private Map _headCache = new HashMap();
public HttpCache()
{
this(null);
}
public HttpCache(SSLContext sslContext)
{
this(sslContext, null);
}
/**
* Constructs a new HttpCache object, that will be initialized with the
* default set of HttpRequestOptions.
*
* @see HttpRequestOptions
*/
public HttpCache(SSLContext sslContext, X509HostnameVerifier hostnameVerifier)
{
super();
_client = HttpClientFactory.getInstance(
getDefaultRequestOptions().getMaxRedirects(),
getDefaultRequestOptions().getAllowCircularRedirects(),
getDefaultRequestOptions().getSocketTimeout(),
getDefaultRequestOptions().getConnTimeout(),
null, sslContext, hostnameVerifier);
}
/**
* Removes a cached GET response.
*
* @param url The URL for which to remove the cached response.
*/
private void removeGet(String url)
{
if (_getCache.keySet().contains(url))
{
_log.info("Removing cached GET response for " + url);
_getCache.remove(url);
}
else
_log.info("NOT removing cached GET for " + url + " NOT FOUND.");
}
/* (non-Javadoc)
* @see org.openid4java.util.HttpFetcher#get(java.lang.String, org.openid4java.util.HttpRequestOptions)
*/
public HttpResponse get(String url, HttpRequestOptions requestOptions)
throws IOException
{
DefaultHttpResponse resp = (DefaultHttpResponse) _getCache.get(url);
if (resp != null)
{
if (match(resp, requestOptions))
{
_log.info("Returning cached GET response for " + url);
return resp;
} else
{
_log.info("Removing cached GET for " + url);
removeGet(url);
}
}
HttpGet get = new HttpGet(url);
org.apache.http.HttpResponse httpResponse = null;
HttpEntity responseEntity = null;
try
{
get.getParams().setParameter(AllClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
HttpUtils.setRequestOptions(get, requestOptions);
httpResponse = _client.execute(get);
responseEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
String statusLine = httpResponse.getStatusLine().getReasonPhrase();
ResponseBody body = getResponseBody(responseEntity,
requestOptions.getMaxBodySize());
resp = new DefaultHttpResponse(statusCode, statusLine,
requestOptions.getMaxRedirects(), get.getURI().toString(),
httpResponse.getAllHeaders(), body.getBody());
resp.setBodySizeExceeded(body.isBodyTruncated());
// save result in cache
_getCache.put(url, resp);
}
finally
{
HttpUtils.dispose(responseEntity);
}
return resp;
}
private List<NameValuePair> toList(Map<String, String> parameters) {
List<NameValuePair> list = new ArrayList<NameValuePair>(parameters.size());
for (Entry<String, String> entry : parameters.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return list;
}
@Override
public HttpResponse post(String url, Map<String, String> parameters,
HttpRequestOptions requestOptions) throws IOException {
// we don't actually cache posts, since they are used for
// association requests and signature verification
// build the post message with the parameters from the request
HttpPost post = new HttpPost(url);
DefaultHttpResponse resp;
org.apache.http.HttpResponse httpResponse = null;
try
{
// can't follow redirects on a POST (w/o user intervention)
post.getParams().setBooleanParameter(AllClientPNames.HANDLE_REDIRECTS, false);
HttpUtils.setRequestOptions(post, requestOptions);
post.setEntity(new UrlEncodedFormEntity(toList(parameters), "UTF-8"));
// place the http call to the OP
if (DEBUG) _log.debug("Performing HTTP POST on " + url);
httpResponse = _client.execute(post);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String statusLine = httpResponse.getStatusLine().getReasonPhrase();
ResponseBody body = getResponseBody(httpResponse.getEntity(),
requestOptions.getMaxBodySize());
resp = new DefaultHttpResponse(statusCode, statusLine,
requestOptions.getMaxRedirects(), post.getURI().toString(),
httpResponse.getAllHeaders(), body.getBody());
resp.setBodySizeExceeded(body.isBodyTruncated());
}
finally
{
HttpUtils.dispose(httpResponse);
}
return resp;
}
/**
* Returns content of an HTTP response entitity, but no more than maxBytes.
* @throws IOException
*/
private ResponseBody getResponseBody(HttpEntity response, int maxBodySize) throws IOException {
InputStream httpBodyInput = response.getContent();
if (httpBodyInput == null) {
return new ResponseBody(null, false);
}
// trim down maxBodySize if we know the content is smaller than
// maxBodySize
if ((response.getContentLength() > 0)
&& (response.getContentLength() < maxBodySize)) {
maxBodySize = (int) response.getContentLength();
}
byte data[] = new byte[maxBodySize];
int totalRead = 0;
int currentRead;
while (totalRead < maxBodySize)
{
currentRead = httpBodyInput.read(
data, totalRead, maxBodySize - totalRead);
if (currentRead == -1) break;
totalRead += currentRead;
}
boolean bodySizeExceeded = (httpBodyInput.read() > 0);
httpBodyInput.close();
if (DEBUG) _log.debug("Read " + totalRead + " bytes.");
return new ResponseBody(new String(data, 0, totalRead), bodySizeExceeded);
}
private boolean match(DefaultHttpResponse resp, HttpRequestOptions requestOptions)
{
// use cache?
if ( resp != null && ! requestOptions.isUseCache())
{
_log.info("Explicit fresh GET requested; removing cached copy");
return false;
}
//is cache fresh?
if ( resp != null && (requestOptions.getCacheTTLSeconds() >= 0))
{
long cacheTTL = requestOptions.getCacheTTLSeconds() * 1000;
Date now = new Date();
long currentTime = now.getTime();
long cacheExpTime = resp.getTimestamp() + cacheTTL;
if (cacheExpTime < currentTime)
{
String cacheExpTimeStr = (new Date(cacheExpTime)).toString();
_log.info("Cache Expired at " + cacheExpTimeStr + "; removing cached copy");
return false;
}
}
// content type rules
String requiredContentType = requestOptions.getContentType();
if (resp != null && requiredContentType != null)
{
Header responseContentType = resp.getResponseHeader("content-type");
if ( responseContentType != null &&
responseContentType.getValue() != null &&
!responseContentType.getValue().split(";")[0]
.equalsIgnoreCase(requiredContentType) )
{
_log.info("Cached GET response does not match " +
"the required content type, removing.");
return false;
}
}
if (resp != null &&
resp.getMaxRedirectsFollowed() > requestOptions.getMaxRedirects())
{
_log.info("Cached GET response used " +
resp.getMaxRedirectsFollowed() +
" max redirects; current requirement is: " +
requestOptions.getMaxRedirects());
return false;
}
return true;
}
/* (non-Javadoc)
* @see org.openid4java.util.HttpFetcher#head(java.lang.String, org.openid4java.util.HttpRequestOptions)
*/
public HttpResponse head(String url, HttpRequestOptions requestOptions)
throws IOException
{
DefaultHttpResponse resp = (DefaultHttpResponse) _headCache.get(url);
if (resp != null)
{
if (match(resp, requestOptions))
{
_log.info("Returning cached HEAD response for " + url);
return resp;
} else
{
_log.info("Removing cached HEAD for " + url);
removeGet(url);
}
}
HttpHead head = new HttpHead(url);
org.apache.http.HttpResponse httpResponse = null;
HttpEntity responseEntity = null;
try
{
head.getParams().setParameter(AllClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
HttpUtils.setRequestOptions(head, requestOptions);
httpResponse = _client.execute(head);
responseEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
String statusLine = httpResponse.getStatusLine().getReasonPhrase();
resp = new DefaultHttpResponse(statusCode, statusLine,
requestOptions.getMaxRedirects(), head.getURI().toString(),
httpResponse.getAllHeaders(), null);
// save result in cache
_headCache.put(url, resp);
}
finally
{
HttpUtils.dispose(responseEntity);
}
return resp;
}
private static class DefaultHttpResponse implements HttpResponse
{
/**
* The status code of the HTTP response.
*/
private int _statusCode;
/**
* The status line of the HTTP response.
*/
private String _statusLine;
/**
* The maximum HTTP redirects limit that was configured
* when this HTTP response was obtained.
*/
private int _maxRedirectsFollowed;
/**
* The final URI from where the document was obtained,
* after following redirects.
*/
private String _finalUri;
/**
* Map of header names List of Header objects of the HTTP response.
*/
private Map _responseHeaders;
/**
* The HTTP response body.
*/
private String _body;
/**
* Flag to indicate if the HTTP response size exceeded the maximum
* allowed by the (default) HttpRequestOptions.
*/
private boolean _bodySizeExceeded = false;
/**
* timestamp of creation
*
*(number of milliseconds since January 1, 1970, 00:00:00 GMT)
*/
private long _timestamp;
/**
* Constructs a new HttpResponse with the provided parameters.
*/
public DefaultHttpResponse(int statusCode, String statusLine,
int redirectsFollowed, String finalUri,
Header[] responseHeaders, String body)
{
_statusCode = statusCode;
_statusLine = statusLine;
_maxRedirectsFollowed = redirectsFollowed;
_finalUri = finalUri;
_responseHeaders = new HashMap();
if (responseHeaders != null)
{
String headerName;
Header header;
for (int i=0; i < responseHeaders.length; i++)
{
// HTTP header names are case-insensitive
headerName = responseHeaders[i].getName().toLowerCase();
header = responseHeaders[i];
List headerList = (List) _responseHeaders.get(headerName);
if (headerList != null)
headerList.add(responseHeaders[i]);
else
_responseHeaders.put(headerName,
new ArrayList(Arrays.asList(new Header[] {header})));
}
}
_body = body;
Date now = new Date();
_timestamp = now.getTime();
}
/**
* Gets the status code of the HttpResponse.
*/
public int getStatusCode()
{
return _statusCode;
}
/**
* Gets the status line of the HttpResponse.
*/
public String getStatusLine()
{
return _statusLine;
}
/**
* Gets the maximum HTTP redirects limit that was configured
* when this HTTP response was obtained.
*/
public int getMaxRedirectsFollowed()
{
return _maxRedirectsFollowed;
}
/**
* Gets the final URI from where the document was obtained,
* after following redirects.
*/
public String getFinalUri()
{
return _finalUri;
}
/**
* Gets the first header matching the provided headerName parameter,
* or null if no header with that name exists.
*/
public Header getResponseHeader(String headerName)
{
List headerList = (List) _responseHeaders.get(headerName.toLowerCase());
if (headerList != null && headerList.size() > 0)
return (Header) headerList.get(0);
else
return null;
}
/**
* Gets an array of Header objects for the provided headerName parameter.
*/
public Header[] getResponseHeaders(String headerName)
{
List headerList = (List) _responseHeaders.get(headerName.toLowerCase());
if (headerList != null)
return (Header[]) headerList.toArray(new Header[headerList.size()]);
else
return new Header[]{}; // empty array, same as HttpClient's method
}
/**
* Gets the HttpResponse body.
*/
public String getBody()
{
return _body;
}
/**
* Returns true if the HTTP response size exceeded the maximum
* allowed by the (default) HttpRequestOptions.
* @return
*/
public boolean isBodySizeExceeded()
{
return _bodySizeExceeded;
}
/**
* Sets the flag to indicate whether the HTTP response size exceeded
* the maximum allowed by the (default) HttpRequestOptions.
*/
public void setBodySizeExceeded(boolean bodySizeExceeded)
{
this._bodySizeExceeded = bodySizeExceeded;
}
public long getTimestamp()
{
return _timestamp;
}
}
private static class ResponseBody {
private final String body;
private final boolean bodyIsTruncated;
public ResponseBody(String body, boolean truncated)
{
this.body = body;
this.bodyIsTruncated = truncated;
}
public String getBody()
{
return body;
}
public boolean isBodyTruncated()
{
return bodyIsTruncated;
}
}
}