OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2015 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 package org.chromium.net; | |
6 | |
7 import android.annotation.TargetApi; | |
8 import android.net.TrafficStats; | |
9 import android.os.Build; | |
10 import android.util.Log; | |
11 | |
12 import java.io.Closeable; | |
13 import java.io.IOException; | |
14 import java.net.HttpURLConnection; | |
15 import java.net.URI; | |
16 import java.net.URL; | |
17 import java.nio.ByteBuffer; | |
18 import java.nio.channels.Channels; | |
19 import java.nio.channels.ReadableByteChannel; | |
20 import java.nio.channels.WritableByteChannel; | |
21 import java.util.AbstractMap.SimpleEntry; | |
22 import java.util.ArrayList; | |
23 import java.util.Collections; | |
24 import java.util.List; | |
25 import java.util.Map; | |
26 import java.util.TreeMap; | |
27 import java.util.concurrent.Executor; | |
28 import java.util.concurrent.RejectedExecutionException; | |
29 import java.util.concurrent.atomic.AtomicReference; | |
30 | |
31 /** | |
32 * Pure java UrlRequest, backed by {@link HttpURLConnection}. | |
33 */ | |
34 @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) // TrafficStats only availabl e on ICS | |
35 final class JavaUrlRequest implements UrlRequest { | |
36 private static final String X_ANDROID = "X-Android"; | |
37 private static final String X_ANDROID_SELECTED_TRANSPORT = "X-Android-Select ed-Transport"; | |
38 private static final String TAG = "JavaUrlConnection"; | |
39 private static final int DEFAULT_UPLOAD_BUFFER_SIZE = 8192; | |
40 private static final int DEFAULT_CHUNK_LENGTH = DEFAULT_UPLOAD_BUFFER_SIZE; | |
41 private static final String USER_AGENT = "User-Agent"; | |
42 private final AsyncUrlRequestCallback mCallbackAsync; | |
43 private final Executor mExecutor; | |
44 private final String mUserAgent; | |
45 private final Map<String, String> mRequestHeaders = | |
46 new TreeMap<>(String.CASE_INSENSITIVE_ORDER); | |
47 private final List<String> mUrlChain = new ArrayList<>(); | |
48 /** | |
49 * This is the source of thread safety in this class - no other synchronizat ion is performed. | |
50 * By compare-and-swapping from one state to another, we guarantee that oper ations aren't | |
51 * running concurrently. Only the winner of a CAS proceeds. | |
52 * | |
53 * <p>A caller can lose a CAS for three reasons - user error (two calls to r ead() without | |
54 * waiting for the read to succeed), runtime error (network code or user cod e throws an | |
55 * exception), or cancellation. | |
56 */ | |
57 private final AtomicReference<State> mState = new AtomicReference<>(State.NO T_STARTED); | |
58 | |
59 /** | |
60 * Traffic stats tag to associate this requests' data use with. It's capture d when the request | |
61 * is created, so that applications doing work on behalf of another app can correctly attribute | |
62 * that data use. | |
63 */ | |
64 private final int mTrafficStatsTag; | |
65 | |
66 /* These don't change with redirects */ | |
67 private String mInitialMethod; | |
68 private UploadDataProvider mUploadDataProvider; | |
69 private Executor mUploadExecutor; | |
70 /** | |
71 * Holds a subset of StatusValues - {@link State#STARTED} can represent | |
72 * {@link Status#SENDING_REQUEST} or {@link Status#WAITING_FOR_RESPONSE}. Wh ile the distinction | |
73 * isn't needed to implement the logic in this class, it is needed to implem ent | |
74 * {@link #getStatus(StatusListener)}. | |
75 * | |
76 * <p>Concurrency notes - this value is not atomically updated with mState, so there is some | |
77 * risk that we'd get an inconsistent snapshot of both - however, it also ha ppens that this | |
78 * value is only used with the STARTED state, so it's inconsequential. | |
79 */ | |
80 @Status.StatusValues private volatile int mAdditionalStatusDetails = Status. INVALID; | |
81 | |
82 /* These change with redirects. */ | |
83 private String mCurrentUrl; | |
84 private ReadableByteChannel mResponseChannel; | |
85 private UrlResponseInfo mUrlResponseInfo; | |
86 private String mPendingRedirectUrl; | |
87 /** | |
88 * The happens-before edges created by the executor submission and AtomicRef erence setting are | |
89 * sufficient to guarantee the correct behavior of this field; however, this is an | |
90 * AtomicReference so that we can cleanly dispose of a new connection if we' re cancelled during | |
91 * a redirect, which requires get-and-set semantics. | |
92 * */ | |
93 private final AtomicReference<HttpURLConnection> mCurrentUrlConnection = | |
94 new AtomicReference<>(); | |
95 | |
96 /** | |
97 * /- AWAITING_FOLLOW_REDIRECT <- REDIRECT_RECEIVED <-\ /- READING <--\ | |
98 * | | | | | |
99 * \ / \ / | |
100 * NOT_STARTED ---> STARTED ----> AW AITING_READ ---> | |
101 * COMPLETE | |
102 */ | |
103 private enum State { | |
104 NOT_STARTED, | |
105 STARTED, | |
106 REDIRECT_RECEIVED, | |
107 AWAITING_FOLLOW_REDIRECT, | |
108 AWAITING_READ, | |
109 READING, | |
110 ERROR, | |
111 COMPLETE, | |
112 CANCELLED, | |
113 } | |
114 | |
115 /** | |
116 * @param executor The executor used for reading and writing from sockets | |
117 * @param userExecutor The executor used to dispatch to {@code callback} | |
118 */ | |
119 JavaUrlRequest(Callback callback, final Executor executor, Executor userExec utor, String url, | |
120 String userAgent) { | |
121 if (url == null) { | |
122 throw new NullPointerException("URL is required"); | |
123 } | |
124 if (callback == null) { | |
125 throw new NullPointerException("Listener is required"); | |
126 } | |
127 if (executor == null) { | |
128 throw new NullPointerException("Executor is required"); | |
129 } | |
130 if (userExecutor == null) { | |
131 throw new NullPointerException("userExecutor is required"); | |
132 } | |
133 this.mCallbackAsync = new AsyncUrlRequestCallback(callback, userExecutor ); | |
pauljensen
2016/01/07 17:00:00
nit: this.m -> m
| |
134 this.mTrafficStatsTag = TrafficStats.getThreadStatsTag(); | |
135 this.mExecutor = new Executor() { | |
136 @Override | |
137 public void execute(final Runnable command) { | |
138 executor.execute(new Runnable() { | |
139 @Override | |
140 public void run() { | |
141 int oldTag = TrafficStats.getThreadStatsTag(); | |
142 TrafficStats.setThreadStatsTag(mTrafficStatsTag); | |
143 try { | |
144 command.run(); | |
145 } finally { | |
146 TrafficStats.setThreadStatsTag(oldTag); | |
147 } | |
148 } | |
149 }); | |
150 } | |
151 }; | |
152 this.mCurrentUrl = url; | |
153 this.mUserAgent = userAgent; | |
154 } | |
155 | |
156 @Override | |
157 public void setHttpMethod(String method) { | |
158 checkNotStarted(); | |
159 if (method == null) { | |
160 throw new NullPointerException("Method is required."); | |
161 } | |
162 if ("OPTIONS".equalsIgnoreCase(method) || "GET".equalsIgnoreCase(method) | |
163 || "HEAD".equalsIgnoreCase(method) || "POST".equalsIgnoreCase(me thod) | |
164 || "PUT".equalsIgnoreCase(method) || "DELETE".equalsIgnoreCase(m ethod) | |
165 || "TRACE".equalsIgnoreCase(method) || "PATCH".equalsIgnoreCase( method)) { | |
166 mInitialMethod = method; | |
167 } else { | |
168 throw new IllegalArgumentException("Invalid http method " + method); | |
169 } | |
170 } | |
171 | |
172 private void checkNotStarted() { | |
173 State state = mState.get(); | |
174 if (state != State.NOT_STARTED) { | |
175 throw new IllegalStateException("Request is already started. State i s: " + state); | |
176 } | |
177 } | |
178 | |
179 @Override | |
180 public void addHeader(String header, String value) { | |
181 checkNotStarted(); | |
182 if (!isValidHeaderName(header) || value.contains("\r\n")) { | |
183 throw new IllegalArgumentException("Invalid header " + header + "=" + value); | |
184 } | |
185 if (mRequestHeaders.containsKey(header)) { | |
186 mRequestHeaders.remove(header); | |
187 } | |
188 mRequestHeaders.put(header, value); | |
189 } | |
190 | |
191 private boolean isValidHeaderName(String header) { | |
192 for (int i = 0; i < header.length(); i++) { | |
193 char c = header.charAt(i); | |
194 switch (c) { | |
195 case '(': | |
196 case ')': | |
197 case '<': | |
198 case '>': | |
199 case '@': | |
200 case ',': | |
201 case ';': | |
202 case ':': | |
203 case '\\': | |
204 case '\'': | |
205 case '/': | |
206 case '[': | |
207 case ']': | |
208 case '?': | |
209 case '=': | |
210 case '{': | |
211 case '}': | |
212 return false; | |
213 default: { | |
214 if (Character.isISOControl(c) || Character.isWhitespace(c)) { | |
215 return false; | |
216 } | |
217 } | |
218 } | |
219 } | |
220 return true; | |
221 } | |
222 | |
223 @Override | |
224 public void setUploadDataProvider(UploadDataProvider uploadDataProvider, Exe cutor executor) { | |
225 if (uploadDataProvider == null) { | |
226 throw new NullPointerException("Invalid UploadDataProvider."); | |
227 } | |
228 if (!mRequestHeaders.containsKey("Content-Type")) { | |
229 throw new IllegalArgumentException( | |
230 "Requests with upload data must have a Content-Type."); | |
231 } | |
232 checkNotStarted(); | |
233 if (mInitialMethod == null) { | |
234 mInitialMethod = "POST"; | |
235 } | |
236 this.mUploadDataProvider = uploadDataProvider; | |
237 this.mUploadExecutor = executor; | |
238 } | |
239 | |
240 private enum SinkState { | |
241 AWAITING_READ_RESULT, | |
242 AWAITING_REWIND_RESULT, | |
243 UPLOADING, | |
244 NOT_STARTED, | |
245 } | |
246 | |
247 private final class OutputStreamDataSink implements UploadDataSink { | |
248 final AtomicReference<SinkState> mSinkState = new AtomicReference<>(Sink State.NOT_STARTED); | |
249 final Executor mUserExecutor; | |
250 final Executor mExecutor; | |
251 final HttpURLConnection mUrlConnection; | |
252 WritableByteChannel mOutputChannel; | |
253 final UploadDataProvider mUploadProvider; | |
254 ByteBuffer mBuffer; | |
255 /** This holds the total bytes to send (the content-length). -1 if unkno wn. */ | |
256 long mTotalBytes; | |
257 /** This holds the bytes written so far */ | |
258 long mWrittenBytes = 0; | |
259 | |
260 OutputStreamDataSink(final Executor userExecutor, Executor executor, | |
261 HttpURLConnection urlConnection, UploadDataProvider provider) { | |
262 this.mUserExecutor = new Executor() { | |
263 @Override | |
264 public void execute(Runnable runnable) { | |
265 try { | |
266 userExecutor.execute(runnable); | |
267 } catch (RejectedExecutionException e) { | |
268 enterUploadErrorState(e); | |
269 } | |
270 } | |
271 }; | |
272 this.mExecutor = executor; | |
273 this.mUrlConnection = urlConnection; | |
274 this.mUploadProvider = provider; | |
275 } | |
276 | |
277 @Override | |
278 public void onReadSucceeded(final boolean finalChunk) { | |
279 if (!mSinkState.compareAndSet(SinkState.AWAITING_READ_RESULT, SinkSt ate.UPLOADING)) { | |
280 throw new IllegalStateException( | |
281 "Not expecting a read result, expecting: " + mSinkState. get()); | |
282 } | |
283 mExecutor.execute(errorSetting(State.STARTED, new CheckedRunnable() { | |
284 @Override | |
285 public void run() throws Exception { | |
286 mBuffer.flip(); | |
287 while (mBuffer.hasRemaining()) { | |
288 mWrittenBytes += mOutputChannel.write(mBuffer); | |
289 } | |
290 if (mWrittenBytes < mTotalBytes || (mTotalBytes == -1 && !fi nalChunk)) { | |
291 mBuffer.clear(); | |
292 mSinkState.set(SinkState.AWAITING_READ_RESULT); | |
293 mUserExecutor.execute(uploadErrorSetting(new CheckedRunn able() { | |
294 @Override | |
295 public void run() throws Exception { | |
296 mUploadProvider.read(OutputStreamDataSink.this, mBuffer); | |
297 } | |
298 })); | |
299 } else if (mTotalBytes == -1) { | |
300 finish(); | |
301 } else if (mTotalBytes == mWrittenBytes) { | |
302 finish(); | |
303 } else { | |
304 throw new IllegalStateException("Wrote more bytes than w ere available"); | |
305 } | |
306 } | |
307 })); | |
308 } | |
309 | |
310 @Override | |
311 public void onRewindSucceeded() { | |
312 if (!mSinkState.compareAndSet(SinkState.AWAITING_REWIND_RESULT, Sink State.UPLOADING)) { | |
313 throw new IllegalStateException("Not expecting a read result"); | |
314 } | |
315 startRead(); | |
316 } | |
317 | |
318 @Override | |
319 public void onReadError(Exception exception) { | |
320 enterUploadErrorState(exception); | |
321 } | |
322 | |
323 @Override | |
324 public void onRewindError(Exception exception) { | |
325 enterUploadErrorState(exception); | |
326 } | |
327 | |
328 void startRead() { | |
329 mUserExecutor.execute(uploadErrorSetting(new CheckedRunnable() { | |
330 @Override | |
331 public void run() throws Exception { | |
332 if (mOutputChannel == null) { | |
333 mAdditionalStatusDetails = Status.CONNECTING; | |
334 mUrlConnection.connect(); | |
335 mAdditionalStatusDetails = Status.SENDING_REQUEST; | |
336 mOutputChannel = Channels.newChannel(mUrlConnection.getO utputStream()); | |
337 } | |
338 mSinkState.set(SinkState.AWAITING_READ_RESULT); | |
339 mUploadProvider.read(OutputStreamDataSink.this, mBuffer); | |
340 } | |
341 })); | |
342 } | |
343 | |
344 void finish() throws IOException { | |
345 if (mOutputChannel != null) { | |
346 mOutputChannel.close(); | |
347 } | |
348 fireGetHeaders(); | |
349 } | |
350 | |
351 void start(final boolean firstTime) { | |
352 mUserExecutor.execute(uploadErrorSetting(new CheckedRunnable() { | |
353 @Override | |
354 public void run() throws Exception { | |
355 mTotalBytes = mUploadProvider.getLength(); | |
356 if (mTotalBytes == 0) { | |
357 finish(); | |
358 } else { | |
359 // If we know how much data we have to upload, and it's small, we can save | |
360 // memory by allocating a reasonably sized buffer to rea d into. | |
361 if (mTotalBytes > 0 && mTotalBytes < DEFAULT_UPLOAD_BUFF ER_SIZE) { | |
362 // Allocate one byte more than necessary, to detect callers uploading | |
363 // more bytes than they specified in length. | |
364 mBuffer = ByteBuffer.allocateDirect((int) mTotalByte s + 1); | |
365 } else { | |
366 mBuffer = ByteBuffer.allocateDirect(DEFAULT_UPLOAD_B UFFER_SIZE); | |
367 } | |
368 | |
369 if (mTotalBytes > 0 && mTotalBytes <= Integer.MAX_VALUE) { | |
370 mUrlConnection.setFixedLengthStreamingMode((int) mTo talBytes); | |
371 } else if (mTotalBytes > Integer.MAX_VALUE | |
372 && Build.VERSION.SDK_INT >= Build.VERSION_CODES. KITKAT) { | |
373 mUrlConnection.setFixedLengthStreamingMode(mTotalByt es); | |
374 } else { | |
375 // If we know the length, but we're running pre-kitk at and it's larger | |
376 // than an int can hold, we have to use chunked - ot herwise we'll end up | |
377 // buffering the whole response in memory. | |
378 mUrlConnection.setChunkedStreamingMode(DEFAULT_CHUNK _LENGTH); | |
379 } | |
380 if (firstTime) { | |
381 startRead(); | |
382 } else { | |
383 mSinkState.set(SinkState.AWAITING_REWIND_RESULT); | |
384 mUploadProvider.rewind(OutputStreamDataSink.this); | |
385 } | |
386 } | |
387 } | |
388 })); | |
389 } | |
390 } | |
391 | |
392 @Override | |
393 public void start() { | |
394 mAdditionalStatusDetails = Status.CONNECTING; | |
395 transitionStates(State.NOT_STARTED, State.STARTED, new Runnable() { | |
396 @Override | |
397 public void run() { | |
398 mUrlChain.add(mCurrentUrl); | |
399 fireOpenConnection(); | |
400 } | |
401 }); | |
402 } | |
403 | |
404 private void enterErrorState(State previousState, final UrlRequestException error) { | |
405 if (mState.compareAndSet(previousState, State.ERROR)) { | |
406 fireDisconnect(); | |
407 mCallbackAsync.onFailed(mUrlResponseInfo, error); | |
408 } | |
409 } | |
410 | |
411 /** Ends the reqeust with an error, caused by an exception thrown from user code. */ | |
412 private void enterUserErrorState(State previousState, final Throwable error) { | |
413 enterErrorState(previousState, new UrlRequestException("User Error", err or)); | |
414 } | |
415 | |
416 /** Ends the requst with an error, caused by an exception thrown from user c ode. */ | |
417 private void enterUploadErrorState(final Throwable error) { | |
418 enterErrorState(State.STARTED, | |
419 new UrlRequestException("Exception received from UploadDataProvi der", error)); | |
420 } | |
421 | |
422 private void enterCronetErrorState(State previousState, final Throwable erro r) { | |
423 // TODO(clm) mapping from Java exception (UnknownHostException, for exam ple) to net error | |
424 // code goes here. | |
425 enterErrorState(previousState, new UrlRequestException("System error", e rror)); | |
426 } | |
427 | |
428 /** | |
429 * Atomically swaps from the expected state to a new state. If the swap fail s, and it's not | |
430 * due to an earlier error or cancellation, throws an exception. | |
431 * | |
432 * @param afterTransition Callback to run after transition completes success fully. | |
433 */ | |
434 private void transitionStates(State expected, State newState, Runnable after Transition) { | |
435 if (!mState.compareAndSet(expected, newState)) { | |
436 State state = mState.get(); | |
437 if (!(state == State.CANCELLED || state == State.ERROR)) { | |
438 throw new IllegalStateException( | |
439 "Invalid state transition - expected " + expected + " bu t was " + state); | |
440 } | |
441 } else { | |
442 afterTransition.run(); | |
443 } | |
444 } | |
445 | |
446 @Override | |
447 public void followRedirect() { | |
448 transitionStates(State.AWAITING_FOLLOW_REDIRECT, State.STARTED, new Runn able() { | |
449 @Override | |
450 public void run() { | |
451 mCurrentUrl = mPendingRedirectUrl; | |
452 mPendingRedirectUrl = null; | |
453 fireOpenConnection(); | |
454 } | |
455 }); | |
456 } | |
457 | |
458 private void fireGetHeaders() { | |
459 mAdditionalStatusDetails = Status.WAITING_FOR_RESPONSE; | |
460 mExecutor.execute(errorSetting(State.STARTED, new CheckedRunnable() { | |
461 @Override | |
462 public void run() throws Exception { | |
463 HttpURLConnection connection = mCurrentUrlConnection.get(); | |
464 if (connection == null) { | |
465 return; // We've been cancelled | |
466 } | |
467 final List<Map.Entry<String, String>> headerList = new ArrayList <>(); | |
468 String selectedTransport = "http/1.1"; | |
469 String headerKey; | |
470 for (int i = 0; (headerKey = connection.getHeaderFieldKey(i)) != null; i++) { | |
471 if (X_ANDROID_SELECTED_TRANSPORT.equalsIgnoreCase(headerKey) ) { | |
472 selectedTransport = connection.getHeaderField(i); | |
473 } | |
474 if (!headerKey.startsWith(X_ANDROID)) { | |
475 headerList.add(new SimpleEntry<>(headerKey, connection.g etHeaderField(i))); | |
476 } | |
477 } | |
478 | |
479 int responseCode = connection.getResponseCode(); | |
480 // Important to copy the list here, because although we never co ncurrently modify | |
481 // the list ourselves, user code might iterate over it while we' re redirecting, and | |
482 // that would throw ConcurrentModificationException. | |
483 mUrlResponseInfo = new UrlResponseInfo(new ArrayList<>(mUrlChain ), responseCode, | |
484 connection.getResponseMessage(), Collections.unmodifiabl eList(headerList), | |
485 false, selectedTransport, ""); | |
486 // TODO(clm) actual redirect handling? post -> get and whatnot? | |
487 if (responseCode >= 300 && responseCode < 400) { | |
488 fireRedirectReceived(mUrlResponseInfo.getAllHeaders()); | |
489 } else if (responseCode >= 400) { | |
490 mResponseChannel = InputStreamChannel.wrap(connection.getErr orStream()); | |
491 mCallbackAsync.onResponseStarted(mUrlResponseInfo); | |
492 } else { | |
493 mResponseChannel = InputStreamChannel.wrap(connection.getInp utStream()); | |
494 mCallbackAsync.onResponseStarted(mUrlResponseInfo); | |
495 } | |
496 } | |
497 })); | |
498 } | |
499 | |
500 private void fireRedirectReceived(final Map<String, List<String>> headerFiel ds) { | |
501 transitionStates(State.STARTED, State.REDIRECT_RECEIVED, new Runnable() { | |
502 @Override | |
503 public void run() { | |
504 mPendingRedirectUrl = URI.create(mCurrentUrl) | |
505 .resolve(headerFields.get("locatio n").get(0)) | |
506 .toString(); | |
507 mUrlChain.add(mPendingRedirectUrl); | |
508 transitionStates( | |
509 State.REDIRECT_RECEIVED, State.AWAITING_FOLLOW_REDIRECT, new Runnable() { | |
510 @Override | |
511 public void run() { | |
512 mCallbackAsync.onRedirectReceived( | |
513 mUrlResponseInfo, mPendingRedirectUrl); | |
514 } | |
515 }); | |
516 } | |
517 }); | |
518 } | |
519 | |
520 private void fireOpenConnection() { | |
521 mExecutor.execute(errorSetting(State.STARTED, new CheckedRunnable() { | |
522 @Override | |
523 public void run() throws Exception { | |
524 // If we're cancelled, then our old connection will be disconnec ted for us and | |
525 // we shouldn't open a new one. | |
526 if (mState.get() == State.CANCELLED) { | |
527 return; | |
528 } | |
529 | |
530 final URL url = new URL(mCurrentUrl); | |
531 HttpURLConnection newConnection = (HttpURLConnection) url.openCo nnection(); | |
532 HttpURLConnection oldConnection = mCurrentUrlConnection.getAndSe t(newConnection); | |
533 if (oldConnection != null) { | |
534 oldConnection.disconnect(); | |
535 } | |
536 newConnection.setInstanceFollowRedirects(false); | |
537 if (!mRequestHeaders.containsKey(USER_AGENT)) { | |
538 mRequestHeaders.put(USER_AGENT, mUserAgent); | |
539 } | |
540 for (Map.Entry<String, String> entry : mRequestHeaders.entrySet( )) { | |
541 newConnection.setRequestProperty(entry.getKey(), entry.getVa lue()); | |
542 } | |
543 if (mInitialMethod == null) { | |
544 mInitialMethod = "GET"; | |
545 } | |
546 newConnection.setRequestMethod(mInitialMethod); | |
547 if (mUploadDataProvider != null) { | |
548 OutputStreamDataSink dataSink = new OutputStreamDataSink( | |
549 mUploadExecutor, mExecutor, newConnection, mUploadDa taProvider); | |
550 dataSink.start(mUrlChain.size() == 1); | |
551 } else { | |
552 mAdditionalStatusDetails = Status.CONNECTING; | |
553 newConnection.connect(); | |
554 fireGetHeaders(); | |
555 } | |
556 } | |
557 })); | |
558 } | |
559 | |
560 @Override | |
561 public void read(final ByteBuffer buffer) { | |
562 Preconditions.checkDirect(buffer); | |
563 if (!(buffer.capacity() - buffer.position() > 0)) { | |
564 throw new IllegalArgumentException("ByteBuffer is already full."); | |
565 } | |
566 transitionStates(State.AWAITING_READ, State.READING, new Runnable() { | |
567 @Override | |
568 public void run() { | |
569 mExecutor.execute(errorSetting(State.READING, new CheckedRunnabl e() { | |
570 @Override | |
571 public void run() throws IOException { | |
572 int oldPosition = buffer.position(); | |
573 buffer.limit(buffer.capacity()); | |
574 int read = mResponseChannel.read(buffer); | |
575 buffer.limit(buffer.position()); | |
576 buffer.position(oldPosition); | |
577 processReadResult(read, buffer); | |
578 } | |
579 })); | |
580 } | |
581 }); | |
582 } | |
583 | |
584 private Runnable errorSetting(final State expectedState, final CheckedRunnab le delegate) { | |
585 return new Runnable() { | |
586 @Override | |
587 public void run() { | |
588 try { | |
589 delegate.run(); | |
590 } catch (Throwable t) { | |
591 enterCronetErrorState(expectedState, t); | |
592 } | |
593 } | |
594 }; | |
595 } | |
596 | |
597 private Runnable userErrorSetting(final State expectedState, final CheckedRu nnable delegate) { | |
598 return new Runnable() { | |
599 @Override | |
600 public void run() { | |
601 try { | |
602 delegate.run(); | |
603 } catch (Throwable t) { | |
604 enterUserErrorState(expectedState, t); | |
605 } | |
606 } | |
607 }; | |
608 } | |
609 | |
610 private Runnable uploadErrorSetting(final CheckedRunnable delegate) { | |
611 return new Runnable() { | |
612 @Override | |
613 public void run() { | |
614 try { | |
615 delegate.run(); | |
616 } catch (Throwable t) { | |
617 enterUploadErrorState(t); | |
618 } | |
619 } | |
620 }; | |
621 } | |
622 | |
623 private interface CheckedRunnable { void run() throws Exception; } | |
624 | |
625 @Override | |
626 public void readNew(final ByteBuffer buffer) { | |
627 Preconditions.checkDirect(buffer); | |
628 Preconditions.checkHasRemaining(buffer); | |
629 transitionStates(State.AWAITING_READ, State.READING, new Runnable() { | |
630 @Override | |
631 public void run() { | |
632 mExecutor.execute(errorSetting(State.READING, new CheckedRunnabl e() { | |
633 @Override | |
634 public void run() throws Exception { | |
635 int read = mResponseChannel.read(buffer); | |
636 processReadResult(read, buffer); | |
637 } | |
638 })); | |
639 } | |
640 }); | |
641 } | |
642 | |
643 private void processReadResult(int read, final ByteBuffer buffer) throws IOE xception { | |
644 if (read != -1) { | |
645 mCallbackAsync.onReadCompleted(mUrlResponseInfo, buffer); | |
646 } else { | |
647 mResponseChannel.close(); | |
648 if (mState.compareAndSet(State.READING, State.COMPLETE)) { | |
649 fireDisconnect(); | |
650 mCallbackAsync.onSucceeded(mUrlResponseInfo); | |
651 } | |
652 } | |
653 } | |
654 | |
655 private void fireDisconnect() { | |
656 final HttpURLConnection connection = mCurrentUrlConnection.getAndSet(nul l); | |
657 if (connection != null) { | |
658 mExecutor.execute(new Runnable() { | |
659 @Override | |
660 public void run() { | |
661 connection.disconnect(); | |
662 } | |
663 }); | |
664 } | |
665 } | |
666 | |
667 @Override | |
668 public void cancel() { | |
669 State oldState = mState.getAndSet(State.CANCELLED); | |
670 switch (oldState) { | |
671 // We've just scheduled some user code to run. When they perform the ir next operation, | |
672 // they'll observe it and fail. However, if user code is cancelling in response to one | |
673 // of these callbacks, we'll never actually cancel! | |
674 // TODO(clm) figure out if it's possible to avoid concurrency in use r callbacks. | |
675 case REDIRECT_RECEIVED: | |
676 case AWAITING_FOLLOW_REDIRECT: | |
677 case AWAITING_READ: | |
678 | |
679 // User code is waiting on us - cancel away! | |
680 case STARTED: | |
681 case READING: | |
682 fireDisconnect(); | |
683 mCallbackAsync.onCanceled(mUrlResponseInfo); | |
684 break; | |
685 // The rest are all termination cases - we're too late to cancel. | |
686 case ERROR: | |
687 case COMPLETE: | |
688 case CANCELLED: | |
689 break; | |
690 } | |
691 } | |
692 | |
693 @Override | |
694 public boolean isDone() { | |
695 State state = mState.get(); | |
696 return state == State.COMPLETE | state == State.ERROR | state == State.C ANCELLED; | |
697 } | |
698 | |
699 @Override | |
700 public void disableCache() { | |
701 // We have no cache | |
702 } | |
703 | |
704 @Override | |
705 public void getStatus(StatusListener listener) { | |
706 State state = mState.get(); | |
707 int extraStatus = this.mAdditionalStatusDetails; | |
708 | |
709 @Status.StatusValues final int status; | |
710 switch (state) { | |
711 case ERROR: | |
712 case COMPLETE: | |
713 case CANCELLED: | |
714 case NOT_STARTED: | |
715 status = Status.INVALID; | |
716 break; | |
717 case STARTED: | |
718 status = extraStatus; | |
719 break; | |
720 case REDIRECT_RECEIVED: | |
721 case AWAITING_FOLLOW_REDIRECT: | |
722 case AWAITING_READ: | |
723 status = Status.IDLE; | |
724 break; | |
725 case READING: | |
726 status = Status.READING_RESPONSE; | |
727 break; | |
728 default: | |
729 throw new IllegalStateException("Switch is exhaustive: " + state ); | |
730 } | |
731 | |
732 mCallbackAsync.sendStatus(listener, status); | |
733 } | |
734 | |
735 /** This wrapper ensures that callbacks are always called on the correct exe cutor */ | |
736 private final class AsyncUrlRequestCallback { | |
737 final UrlRequest.Callback mCallback; | |
738 final Executor mUserExecutor; | |
739 | |
740 AsyncUrlRequestCallback(Callback callback, final Executor userExecutor) { | |
741 this.mCallback = callback; | |
742 this.mUserExecutor = userExecutor; | |
743 } | |
744 | |
745 void sendStatus(final StatusListener listener, final int status) { | |
746 mUserExecutor.execute(new Runnable() { | |
747 @Override | |
748 public void run() { | |
749 listener.onStatus(status); | |
750 } | |
751 }); | |
752 } | |
753 | |
754 void execute(State currentState, CheckedRunnable runnable) { | |
755 try { | |
756 mUserExecutor.execute(userErrorSetting(currentState, runnable)); | |
757 } catch (RejectedExecutionException e) { | |
758 enterUserErrorState(currentState, e); | |
759 } | |
760 } | |
761 | |
762 void onRedirectReceived(final UrlResponseInfo info, final String newLoca tionUrl) { | |
763 execute(State.AWAITING_FOLLOW_REDIRECT, new CheckedRunnable() { | |
764 @Override | |
765 public void run() throws Exception { | |
766 mCallback.onRedirectReceived(JavaUrlRequest.this, info, newL ocationUrl); | |
767 } | |
768 }); | |
769 } | |
770 | |
771 void onResponseStarted(UrlResponseInfo info) { | |
772 execute(State.AWAITING_READ, new CheckedRunnable() { | |
773 @Override | |
774 public void run() { | |
775 if (mState.compareAndSet(State.STARTED, State.AWAITING_READ) ) { | |
776 mCallback.onResponseStarted(JavaUrlRequest.this, mUrlRes ponseInfo); | |
777 } | |
778 } | |
779 }); | |
780 } | |
781 | |
782 void onReadCompleted(final UrlResponseInfo info, final ByteBuffer byteBu ffer) { | |
783 execute(State.AWAITING_READ, new CheckedRunnable() { | |
784 @Override | |
785 public void run() { | |
786 if (mState.compareAndSet(State.READING, State.AWAITING_READ) ) { | |
787 mCallback.onReadCompleted(JavaUrlRequest.this, info, byt eBuffer); | |
788 } | |
789 } | |
790 }); | |
791 } | |
792 | |
793 void onCanceled(final UrlResponseInfo info) { | |
794 closeQuietly(mResponseChannel); | |
795 mUserExecutor.execute(new Runnable() { | |
796 @Override | |
797 public void run() { | |
798 try { | |
799 mCallback.onCanceled(JavaUrlRequest.this, info); | |
800 } catch (Exception exception) { | |
801 Log.e(TAG, "Exception in onCanceled method", exception); | |
802 } | |
803 } | |
804 }); | |
805 } | |
806 | |
807 void onSucceeded(final UrlResponseInfo info) { | |
808 mUserExecutor.execute(new Runnable() { | |
809 @Override | |
810 public void run() { | |
811 try { | |
812 mCallback.onSucceeded(JavaUrlRequest.this, info); | |
813 } catch (Exception exception) { | |
814 Log.e(TAG, "Exception in onSucceeded method", exception) ; | |
815 } | |
816 } | |
817 }); | |
818 } | |
819 | |
820 void onFailed(final UrlResponseInfo urlResponseInfo, final UrlRequestExc eption e) { | |
821 closeQuietly(mResponseChannel); | |
822 mUserExecutor.execute(new Runnable() { | |
823 @Override | |
824 public void run() { | |
825 try { | |
826 mCallback.onFailed(JavaUrlRequest.this, urlResponseInfo, e); | |
827 } catch (Exception exception) { | |
828 Log.e(TAG, "Exception in onFailed method", exception); | |
829 } | |
830 } | |
831 }); | |
832 } | |
833 } | |
834 | |
835 private static void closeQuietly(Closeable closeable) { | |
836 if (closeable == null) { | |
837 return; | |
838 } | |
839 try { | |
840 closeable.close(); | |
841 } catch (IOException e) { | |
842 e.printStackTrace(); | |
843 } | |
844 } | |
845 } | |
OLD | NEW |