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 package org.apache.http.impl.execchain;
29
30 import java.io.IOException;
31 import java.io.InterruptedIOException;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.apache.http.HttpException;
36 import org.apache.http.annotation.Immutable;
37 import org.apache.http.client.ServiceUnavailableRetryStrategy;
38 import org.apache.http.client.methods.CloseableHttpResponse;
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 import org.apache.http.util.Args;
44
45
46
47
48
49
50
51 @Immutable
52 public class ServiceUnavailableRetryExec implements ClientExecChain {
53
54 private final Log log = LogFactory.getLog(getClass());
55
56 private final ClientExecChain requestExecutor;
57 private final ServiceUnavailableRetryStrategy retryStrategy;
58
59 public ServiceUnavailableRetryExec(
60 final ClientExecChain requestExecutor,
61 final ServiceUnavailableRetryStrategy retryStrategy) {
62 super();
63 Args.notNull(requestExecutor, "HTTP request executor");
64 Args.notNull(retryStrategy, "Retry strategy");
65 this.requestExecutor = requestExecutor;
66 this.retryStrategy = retryStrategy;
67 }
68
69 public CloseableHttpResponse execute(
70 final HttpRoute route,
71 final HttpRequestWrapper request,
72 final HttpClientContext context,
73 final HttpExecutionAware execAware) throws IOException, HttpException {
74 for (int c = 1;; c++) {
75 final CloseableHttpResponse response = this.requestExecutor.execute(
76 route, request, context, execAware);
77 try {
78 if (this.retryStrategy.retryRequest(response, c, context)) {
79 response.close();
80 final long nextInterval = this.retryStrategy.getRetryInterval();
81 try {
82 this.log.trace("Wait for " + nextInterval);
83 Thread.sleep(nextInterval);
84 } catch (final InterruptedException e) {
85 Thread.currentThread().interrupt();
86 throw new InterruptedIOException();
87 }
88 } else {
89 return response;
90 }
91 } catch (final RuntimeException ex) {
92 response.close();
93 throw ex;
94 } catch (final IOException ex) {
95 response.close();
96 throw ex;
97 }
98 }
99 }
100
101 }