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 package org.apache.http.impl.client.cache;
28
29 import java.io.Closeable;
30 import java.io.IOException;
31 import java.util.Collections;
32 import java.util.HashSet;
33 import java.util.Set;
34 import java.util.concurrent.RejectedExecutionException;
35
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.apache.http.client.cache.HttpCacheEntry;
39 import org.apache.http.client.methods.HttpExecutionAware;
40 import org.apache.http.client.methods.HttpRequestWrapper;
41 import org.apache.http.client.protocol.HttpClientContext;
42 import org.apache.http.conn.routing.HttpRoute;
43
44
45
46
47
48 class AsynchronousValidator implements Closeable {
49 private final SchedulingStrategy schedulingStrategy;
50 private final Set<String> queued;
51 private final CacheKeyGenerator cacheKeyGenerator;
52 private final FailureCache failureCache;
53
54 private final Log log = LogFactory.getLog(getClass());
55
56
57
58
59
60
61
62
63
64
65
66 public AsynchronousValidator(final CacheConfig config) {
67 this(new ImmediateSchedulingStrategy(config));
68 }
69
70
71
72
73
74
75
76
77 AsynchronousValidator(final SchedulingStrategy schedulingStrategy) {
78 this.schedulingStrategy = schedulingStrategy;
79 this.queued = new HashSet<String>();
80 this.cacheKeyGenerator = new CacheKeyGenerator();
81 this.failureCache = new DefaultFailureCache();
82 }
83
84 @Override
85 public void close() throws IOException {
86 schedulingStrategy.close();
87 }
88
89
90
91
92 public synchronized void revalidateCacheEntry(
93 final CachingExec cachingExec,
94 final HttpRoute route,
95 final HttpRequestWrapper request,
96 final HttpClientContext context,
97 final HttpExecutionAware execAware,
98 final HttpCacheEntry entry) {
99
100 final String uri = cacheKeyGenerator.getVariantURI(context.getTargetHost(), request, entry);
101
102 if (!queued.contains(uri)) {
103 final int consecutiveFailedAttempts = failureCache.getErrorCount(uri);
104 final AsynchronousValidationRequest revalidationRequest =
105 new AsynchronousValidationRequest(
106 this, cachingExec, route, request, context, execAware, entry, uri, consecutiveFailedAttempts);
107
108 try {
109 schedulingStrategy.schedule(revalidationRequest);
110 queued.add(uri);
111 } catch (final RejectedExecutionException ree) {
112 log.debug("Revalidation for [" + uri + "] not scheduled: " + ree);
113 }
114 }
115 }
116
117
118
119
120
121
122
123
124 synchronized void markComplete(final String identifier) {
125 queued.remove(identifier);
126 }
127
128
129
130
131
132
133
134 void jobSuccessful(final String identifier) {
135 failureCache.resetErrorCount(identifier);
136 }
137
138
139
140
141
142
143
144 void jobFailed(final String identifier) {
145 failureCache.increaseErrorCount(identifier);
146 }
147
148 Set<String> getScheduledIdentifiers() {
149 return Collections.unmodifiableSet(queued);
150 }
151 }