1 /* 2 * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.net.http; 27 28 import java.io.IOException; 29 import java.util.List; 30 import java.util.concurrent.CompletableFuture; 31 import java.util.concurrent.CompletionException; 32 import java.util.concurrent.ExecutionException; 33 import java.util.function.BiFunction; 34 35 import static java.net.http.Pair.pair; 36 37 /** 38 * Encapsulates multiple Exchanges belonging to one HttpRequestImpl. 39 * - manages filters 40 * - retries due to filters. 41 * - I/O errors and most other exceptions get returned directly to user 42 * 43 * Creates a new Exchange for each request/response interaction 44 */ 45 class MultiExchange { 46 47 final HttpRequestImpl request; // the user request 48 final HttpClientImpl client; 49 HttpRequestImpl currentreq; // used for async only 50 Exchange exchange; // the current exchange 51 Exchange previous; 52 int attempts; 53 // Maximum number of times a request will be retried/redirected 54 // for any reason 55 56 final static int DEFAULT_MAX_ATTEMPTS = 5; 57 final static int max_attempts = Utils.getIntegerNetProperty( 58 "java.net.httpclient.redirects.retrylimit", DEFAULT_MAX_ATTEMPTS 59 ); 60 61 private final List<HeaderFilter> filters; 62 TimedEvent td; 63 boolean cancelled = false; 64 65 /** 66 * Filter fields. These are attached as required by filters 67 * and only used by the filter implementations. This could be 68 * generalised into Objects that are passed explicitly to the filters 69 * (one per MultiExchange object, and one per Exchange object possibly) 70 */ 71 volatile AuthenticationFilter.AuthInfo serverauth, proxyauth; 72 // RedirectHandler 73 volatile int numberOfRedirects = 0; 74 75 /** 76 */ 77 MultiExchange(HttpRequestImpl request) { 78 this.exchange = new Exchange(request); 79 this.previous = null; 80 this.request = request; 81 this.currentreq = request; 82 this.attempts = 0; 83 this.client = request.client(); 84 this.filters = client.filterChain(); 85 } 86 87 public HttpResponseImpl response() throws IOException, InterruptedException { 88 HttpRequestImpl r = request; 89 if (r.timeval() != 0) { 90 // set timer 91 td = new TimedEvent(r.timeval()); 92 client.registerTimer(td); 93 } 94 while (attempts < max_attempts) { 95 try { 96 attempts++; 97 Exchange currExchange = getExchange(); 98 requestFilters(r); 99 HttpResponseImpl response = currExchange.response(); 100 Pair<HttpResponse, HttpRequestImpl> filterResult = responseFilters(response); 101 HttpRequestImpl newreq = filterResult.second; 102 if (newreq == null) { 103 if (attempts > 1) { 104 Log.logError("Succeeded on attempt: " + attempts); 105 } 106 cancelTimer(); 107 return response; 108 } 109 response.body(HttpResponse.ignoreBody()); 110 setExchange(new Exchange(newreq, currExchange.getAccessControlContext() )); 111 r = newreq; 112 } catch (IOException e) { 113 if (cancelled) { 114 throw new HttpTimeoutException("Request timed out"); 115 } 116 throw e; 117 } 118 } 119 cancelTimer(); 120 throw new IOException("Retry limit exceeded"); 121 } 122 123 private synchronized Exchange getExchange() { 124 return exchange; 125 } 126 127 private synchronized void setExchange(Exchange exchange) { 128 this.exchange = exchange; 129 } 130 131 private void cancelTimer() { 132 if (td != null) { 133 client.cancelTimer(td); 134 } 135 } 136 137 private void requestFilters(HttpRequestImpl r) throws IOException { 138 for (HeaderFilter filter : filters) { 139 filter.request(r); 140 } 141 } 142 143 // Filters are assumed to be non-blocking so the async 144 // versions of these methods just call the blocking ones 145 146 private CompletableFuture<Void> requestFiltersAsync(HttpRequestImpl r) { 147 CompletableFuture<Void> cf = new CompletableFuture<>(); 148 try { 149 requestFilters(r); 150 cf.complete(null); 151 } catch(Throwable e) { 152 cf.completeExceptionally(e); 153 } 154 return cf; 155 } 156 157 158 private Pair<HttpResponse,HttpRequestImpl> 159 responseFilters(HttpResponse response) throws IOException 160 { 161 for (HeaderFilter filter : filters) { 162 HttpRequestImpl newreq = filter.response((HttpResponseImpl)response); 163 if (newreq != null) { 164 return pair(null, newreq); 165 } 166 } 167 return pair(response, null); 168 } 169 170 private CompletableFuture<Pair<HttpResponse,HttpRequestImpl>> 171 responseFiltersAsync(HttpResponse response) 172 { 173 CompletableFuture<Pair<HttpResponse,HttpRequestImpl>> cf = new CompletableFuture<>(); 174 try { 175 Pair<HttpResponse,HttpRequestImpl> n = responseFilters(response); // assumed to be fast 176 cf.complete(n); 177 } catch (Throwable e) { 178 cf.completeExceptionally(e); 179 } 180 return cf; 181 } 182 183 public void cancel() { 184 cancelled = true; 185 getExchange().cancel(); 186 } 187 188 public CompletableFuture<HttpResponseImpl> responseAsync(Void v) { 189 CompletableFuture<HttpResponseImpl> cf; 190 if (++attempts > max_attempts) { 191 cf = CompletableFuture.failedFuture(new IOException("Too many retries")); 192 } else { 193 if (currentreq.timeval() != 0) { 194 // set timer 195 td = new TimedEvent(currentreq.timeval()); 196 client.registerTimer(td); 197 } 198 Exchange exch = getExchange(); 199 cf = requestFiltersAsync(currentreq) 200 .thenCompose(exch::responseAsync) 201 .thenCompose(this::responseFiltersAsync) 202 .thenCompose((Pair<HttpResponse,HttpRequestImpl> pair) -> { 203 HttpResponseImpl resp = (HttpResponseImpl)pair.first; 204 if (resp != null) { 205 if (attempts > 1) { 206 Log.logError("Succeeded on attempt: " + attempts); 207 } 208 return CompletableFuture.completedFuture(resp); 209 } else { 210 currentreq = pair.second; 211 Exchange previous = exch; 212 setExchange(new Exchange(currentreq, 213 currentreq.getAccessControlContext())); 214 //reads body off previous, and then waits for next response 215 return previous 216 .responseBodyAsync(HttpResponse.ignoreBody()) 217 .thenCompose(this::responseAsync); 218 } 219 }) 220 .handle((BiFunction<HttpResponse, Throwable, Pair<HttpResponse, Throwable>>) Pair::new) 221 .thenCompose((Pair<HttpResponse,Throwable> obj) -> { 222 HttpResponseImpl response = (HttpResponseImpl)obj.first; 223 if (response != null) { 224 return CompletableFuture.completedFuture(response); 225 } 226 // all exceptions thrown are handled here 227 CompletableFuture<HttpResponseImpl> error = getExceptionalCF(obj.second); 228 if (error == null) { 229 cancelTimer(); 230 return responseAsync(null); 231 } else { 232 return error; 233 } 234 }); 235 } 236 return cf; 237 } 238 239 /** 240 * Take a Throwable and return a suitable CompletableFuture that is 241 * completed exceptionally. 242 */ 243 private CompletableFuture<HttpResponseImpl> getExceptionalCF(Throwable t) { 244 if ((t instanceof CompletionException) || (t instanceof ExecutionException)) { 245 if (t.getCause() != null) { 246 t = t.getCause(); 247 } 248 } 249 if (cancelled && t instanceof IOException) { 250 t = new HttpTimeoutException("request timed out"); 251 } 252 return CompletableFuture.failedFuture(t); 253 } 254 255 <T> T responseBody(HttpResponse.BodyProcessor<T> processor) { 256 return getExchange().responseBody(processor); 257 } 258 259 <T> CompletableFuture<T> responseBodyAsync(HttpResponse.BodyProcessor<T> processor) { 260 return getExchange().responseBodyAsync(processor); 261 } 262 263 class TimedEvent extends TimeoutEvent { 264 TimedEvent(long timeval) { 265 super(timeval); 266 } 267 @Override 268 public void handle() { 269 cancel(); 270 } 271 272 } 273 }