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 org.chromium.base.Log; |
| 8 import org.chromium.base.VisibleForTesting; |
| 9 import org.chromium.base.annotations.CalledByNative; |
| 10 import org.chromium.base.annotations.JNINamespace; |
| 11 import org.chromium.base.annotations.NativeClassQualifiedName; |
| 12 |
| 13 import java.nio.ByteBuffer; |
| 14 import java.util.AbstractMap; |
| 15 import java.util.ArrayList; |
| 16 import java.util.List; |
| 17 import java.util.Map; |
| 18 import java.util.concurrent.Executor; |
| 19 import java.util.concurrent.RejectedExecutionException; |
| 20 |
| 21 import javax.annotation.concurrent.GuardedBy; |
| 22 |
| 23 /** |
| 24 * {@link BidirectionalStream} implementation using Chromium network stack. |
| 25 * All @CalledByNative methods are called on the native network thread |
| 26 * and post tasks with callback calls onto Executor. Upon returning from callbac
k, the native |
| 27 * stream is called on Executor thread and posts native tasks to the native netw
ork thread. |
| 28 */ |
| 29 @JNINamespace("cronet") |
| 30 class CronetBidirectionalStream extends BidirectionalStream { |
| 31 /** |
| 32 * States of BidirectionalStream are tracked in mReadState and mWriteState. |
| 33 * The write state is separated out as it changes independently of the read
state. |
| 34 * There is one initial state: State.NOT_STARTED. There is one normal final
state: |
| 35 * State.SUCCESS, reached after State.READING_DONE and State.WRITING_DONE. T
here are two |
| 36 * exceptional final states: State.CANCELED and State.ERROR, which can be re
ached from |
| 37 * any other non-final state. |
| 38 */ |
| 39 private enum State { |
| 40 /* Initial state, stream not started. */ |
| 41 NOT_STARTED, |
| 42 /* Stream started, request headers are being sent. */ |
| 43 STARTED, |
| 44 /* Waiting for {@code read()} to be called. */ |
| 45 WAITING_FOR_READ, |
| 46 /* Reading from the remote, {@code onReadCompleted()} callback will be c
alled when done. */ |
| 47 READING, |
| 48 /* There is no more data to read and stream is half-closed by the remote
side. */ |
| 49 READING_DONE, |
| 50 /* Stream is canceled. */ |
| 51 CANCELED, |
| 52 /* Error has occured, stream is closed. */ |
| 53 ERROR, |
| 54 /* Reading and writing are done, and the stream is closed successfully.
*/ |
| 55 SUCCESS, |
| 56 /* Waiting for {@code write()} to be called. */ |
| 57 WAITING_FOR_WRITE, |
| 58 /* Writing to the remote, {@code onWriteCompleted()} callback will be ca
lled when done. */ |
| 59 WRITING, |
| 60 /* There is no more data to write and stream is half-closed by the local
side. */ |
| 61 WRITING_DONE, |
| 62 } |
| 63 |
| 64 private final CronetUrlRequestContext mRequestContext; |
| 65 private final Executor mExecutor; |
| 66 private final Callback mCallback; |
| 67 private final String mInitialUrl; |
| 68 private final int mInitialPriority; |
| 69 private final String mInitialMethod; |
| 70 private final String mRequestHeaders[]; |
| 71 |
| 72 /* |
| 73 * Synchronizes access to mNativeStream, mReadState and mWriteState. |
| 74 */ |
| 75 private final Object mNativeStreamLock = new Object(); |
| 76 |
| 77 /* Native BidirectionalStream object, owned by CronetBidirectionalStream. */ |
| 78 @GuardedBy("mNativeStreamLock") private long mNativeStream; |
| 79 |
| 80 /** |
| 81 * Read state is tracking reading flow. |
| 82 * / <--- READING <--- \ |
| 83 * | | |
| 84 * \ / |
| 85 * NOT_STARTED -> STARTED --> WAITING_FOR_READ -> READING_DONE -> SUCCESS |
| 86 */ |
| 87 @GuardedBy("mNativeStreamLock") private State mReadState = State.NOT_STARTED
; |
| 88 |
| 89 /** |
| 90 * Write state is tracking writing flow. |
| 91 * / <--- WRITING <--- \ |
| 92 * | | |
| 93 * \ / |
| 94 * NOT_STARTED -> STARTED --> WAITING_FOR_WRITE -> WRITING_DONE -> SUCCESS |
| 95 */ |
| 96 @GuardedBy("mNativeStreamLock") private State mWriteState = State.NOT_STARTE
D; |
| 97 |
| 98 private UrlResponseInfo mResponseInfo; |
| 99 |
| 100 /* |
| 101 * OnReadCompleted callback is repeatedly invoked when each read is complete
d, so it |
| 102 * is cached as a member variable. |
| 103 */ |
| 104 private OnReadCompletedRunnable mOnReadCompletedTask; |
| 105 |
| 106 /* |
| 107 * OnWriteCompleted callback is repeatedly invoked when each write is comple
ted, so it |
| 108 * is cached as a member variable. |
| 109 */ |
| 110 private OnWriteCompletedRunnable mOnWriteCompletedTask; |
| 111 |
| 112 private Runnable mOnDestroyedCallbackForTesting; |
| 113 |
| 114 private final class OnReadCompletedRunnable implements Runnable { |
| 115 // Buffer passed back from current invocation of onReadCompleted. |
| 116 ByteBuffer mByteBuffer; |
| 117 // End of stream flag from current invocation of onReadCompleted. |
| 118 boolean mEndOfStream; |
| 119 |
| 120 @Override |
| 121 public void run() { |
| 122 try { |
| 123 // Null out mByteBuffer, to pass buffer ownership to callback or
release if done. |
| 124 ByteBuffer buffer = mByteBuffer; |
| 125 mByteBuffer = null; |
| 126 synchronized (mNativeStreamLock) { |
| 127 if (isDoneLocked()) { |
| 128 return; |
| 129 } |
| 130 if (mEndOfStream) { |
| 131 mReadState = State.READING_DONE; |
| 132 if (maybeSucceedLocked()) { |
| 133 return; |
| 134 } |
| 135 } else { |
| 136 mReadState = State.WAITING_FOR_READ; |
| 137 } |
| 138 } |
| 139 mCallback.onReadCompleted(CronetBidirectionalStream.this, mRespo
nseInfo, buffer); |
| 140 } catch (Exception e) { |
| 141 onCallbackException(e); |
| 142 } |
| 143 } |
| 144 } |
| 145 |
| 146 private final class OnWriteCompletedRunnable implements Runnable { |
| 147 // Buffer passed back from current invocation of onWriteCompleted. |
| 148 ByteBuffer mByteBuffer; |
| 149 // End of stream flag from current call to write. |
| 150 boolean mEndOfStream; |
| 151 |
| 152 @Override |
| 153 public void run() { |
| 154 try { |
| 155 // Null out mByteBuffer, to pass buffer ownership to callback or
release if done. |
| 156 ByteBuffer buffer = mByteBuffer; |
| 157 mByteBuffer = null; |
| 158 synchronized (mNativeStreamLock) { |
| 159 if (isDoneLocked()) { |
| 160 return; |
| 161 } |
| 162 if (mEndOfStream) { |
| 163 mWriteState = State.WRITING_DONE; |
| 164 if (maybeSucceedLocked()) { |
| 165 return; |
| 166 } |
| 167 } else { |
| 168 mWriteState = State.WAITING_FOR_WRITE; |
| 169 } |
| 170 } |
| 171 mCallback.onWriteCompleted(CronetBidirectionalStream.this, mResp
onseInfo, buffer); |
| 172 } catch (Exception e) { |
| 173 onCallbackException(e); |
| 174 } |
| 175 } |
| 176 } |
| 177 |
| 178 CronetBidirectionalStream(CronetUrlRequestContext requestContext, String url
, |
| 179 @BidirectionalStream.Builder.StreamPriority int priority, Callback c
allback, |
| 180 Executor executor, String httpMethod, List<Map.Entry<String, String>
> requestHeaders) { |
| 181 mRequestContext = requestContext; |
| 182 mInitialUrl = url; |
| 183 mInitialPriority = convertStreamPriority(priority); |
| 184 mCallback = callback; |
| 185 mExecutor = executor; |
| 186 mInitialMethod = httpMethod; |
| 187 mRequestHeaders = stringsFromHeaderList(requestHeaders); |
| 188 } |
| 189 |
| 190 @Override |
| 191 public void start() { |
| 192 synchronized (mNativeStreamLock) { |
| 193 if (mReadState != State.NOT_STARTED) { |
| 194 throw new IllegalStateException("Stream is already started."); |
| 195 } |
| 196 try { |
| 197 mNativeStream = nativeCreateBidirectionalStream( |
| 198 mRequestContext.getUrlRequestContextAdapter()); |
| 199 mRequestContext.onRequestStarted(); |
| 200 // Non-zero startResult means an argument error. |
| 201 int startResult = nativeStart(mNativeStream, mInitialUrl, mIniti
alPriority, |
| 202 mInitialMethod, mRequestHeaders, !doesMethodAllowWriteDa
ta(mInitialMethod)); |
| 203 if (startResult == -1) { |
| 204 throw new IllegalArgumentException("Invalid http method " +
mInitialMethod); |
| 205 } |
| 206 if (startResult > 0) { |
| 207 int headerPos = startResult - 1; |
| 208 throw new IllegalArgumentException("Invalid header " |
| 209 + mRequestHeaders[headerPos] + "=" + mRequestHeaders
[headerPos + 1]); |
| 210 } |
| 211 mReadState = mWriteState = State.STARTED; |
| 212 } catch (RuntimeException e) { |
| 213 // If there's an exception, clean up and then throw the |
| 214 // exception to the caller. |
| 215 destroyNativeStreamLocked(false); |
| 216 throw e; |
| 217 } |
| 218 } |
| 219 } |
| 220 |
| 221 @Override |
| 222 public void read(ByteBuffer buffer) { |
| 223 synchronized (mNativeStreamLock) { |
| 224 Preconditions.checkHasRemaining(buffer); |
| 225 Preconditions.checkDirect(buffer); |
| 226 if (mReadState != State.WAITING_FOR_READ) { |
| 227 throw new IllegalStateException("Unexpected read attempt."); |
| 228 } |
| 229 if (isDoneLocked()) { |
| 230 return; |
| 231 } |
| 232 if (mOnReadCompletedTask == null) { |
| 233 mOnReadCompletedTask = new OnReadCompletedRunnable(); |
| 234 } |
| 235 mReadState = State.READING; |
| 236 if (!nativeReadData(mNativeStream, buffer, buffer.position(), buffer
.limit())) { |
| 237 // Still waiting on read. This is just to have consistent |
| 238 // behavior with the other error cases. |
| 239 mReadState = State.WAITING_FOR_READ; |
| 240 throw new IllegalArgumentException("Unable to call native read")
; |
| 241 } |
| 242 } |
| 243 } |
| 244 |
| 245 @Override |
| 246 public void write(ByteBuffer buffer, boolean endOfStream) { |
| 247 synchronized (mNativeStreamLock) { |
| 248 Preconditions.checkDirect(buffer); |
| 249 if (!buffer.hasRemaining() && !endOfStream) { |
| 250 throw new IllegalArgumentException("Empty buffer before end of s
tream."); |
| 251 } |
| 252 if (mWriteState != State.WAITING_FOR_WRITE) { |
| 253 throw new IllegalStateException("Unexpected write attempt."); |
| 254 } |
| 255 if (isDoneLocked()) { |
| 256 return; |
| 257 } |
| 258 if (mOnWriteCompletedTask == null) { |
| 259 mOnWriteCompletedTask = new OnWriteCompletedRunnable(); |
| 260 } |
| 261 mOnWriteCompletedTask.mEndOfStream = endOfStream; |
| 262 mWriteState = State.WRITING; |
| 263 if (!nativeWriteData( |
| 264 mNativeStream, buffer, buffer.position(), buffer.limit()
, endOfStream)) { |
| 265 // Still waiting on write. This is just to have consistent |
| 266 // behavior with the other error cases. |
| 267 mWriteState = State.WAITING_FOR_WRITE; |
| 268 throw new IllegalArgumentException("Unable to call native write"
); |
| 269 } |
| 270 } |
| 271 } |
| 272 |
| 273 @Override |
| 274 public void ping(PingCallback callback, Executor executor) { |
| 275 // TODO(mef): May be last thing to be implemented on Android. |
| 276 throw new UnsupportedOperationException("ping is not supported yet."); |
| 277 } |
| 278 |
| 279 @Override |
| 280 public void windowUpdate(int windowSizeIncrement) { |
| 281 // TODO(mef): Understand the needs and semantics of this method. |
| 282 throw new UnsupportedOperationException("windowUpdate is not supported y
et."); |
| 283 } |
| 284 |
| 285 @Override |
| 286 public void cancel() { |
| 287 synchronized (mNativeStreamLock) { |
| 288 if (isDoneLocked() || mReadState == State.NOT_STARTED) { |
| 289 return; |
| 290 } |
| 291 mReadState = mWriteState = State.CANCELED; |
| 292 destroyNativeStreamLocked(true); |
| 293 } |
| 294 } |
| 295 |
| 296 @Override |
| 297 public boolean isDone() { |
| 298 synchronized (mNativeStreamLock) { |
| 299 return isDoneLocked(); |
| 300 } |
| 301 } |
| 302 |
| 303 @GuardedBy("mNativeStreamLock") |
| 304 private boolean isDoneLocked() { |
| 305 return mReadState != State.NOT_STARTED && mNativeStream == 0; |
| 306 } |
| 307 |
| 308 @SuppressWarnings("unused") |
| 309 @CalledByNative |
| 310 private void onRequestHeadersSent() { |
| 311 postTaskToExecutor(new Runnable() { |
| 312 public void run() { |
| 313 synchronized (mNativeStreamLock) { |
| 314 if (isDoneLocked()) { |
| 315 return; |
| 316 } |
| 317 if (doesMethodAllowWriteData(mInitialMethod)) { |
| 318 mWriteState = State.WAITING_FOR_WRITE; |
| 319 } else { |
| 320 mWriteState = State.WRITING_DONE; |
| 321 } |
| 322 } |
| 323 |
| 324 try { |
| 325 mCallback.onRequestHeadersSent(CronetBidirectionalStream.thi
s); |
| 326 } catch (Exception e) { |
| 327 onCallbackException(e); |
| 328 } |
| 329 } |
| 330 }); |
| 331 } |
| 332 |
| 333 /** |
| 334 * Called when the final set of headers, after all redirects, |
| 335 * is received. Can only be called once for each stream. |
| 336 */ |
| 337 @SuppressWarnings("unused") |
| 338 @CalledByNative |
| 339 private void onResponseHeadersReceived(int httpStatusCode, String negotiated
Protocol, |
| 340 String[] headers, long receivedBytesCount) { |
| 341 try { |
| 342 mResponseInfo = prepareResponseInfoOnNetworkThread( |
| 343 httpStatusCode, negotiatedProtocol, headers, receivedBytesCo
unt); |
| 344 } catch (Exception e) { |
| 345 failWithException(new CronetException("Cannot prepare ResponseInfo",
null)); |
| 346 return; |
| 347 } |
| 348 postTaskToExecutor(new Runnable() { |
| 349 public void run() { |
| 350 synchronized (mNativeStreamLock) { |
| 351 if (isDoneLocked()) { |
| 352 return; |
| 353 } |
| 354 mReadState = State.WAITING_FOR_READ; |
| 355 } |
| 356 |
| 357 try { |
| 358 mCallback.onResponseHeadersReceived( |
| 359 CronetBidirectionalStream.this, mResponseInfo); |
| 360 } catch (Exception e) { |
| 361 onCallbackException(e); |
| 362 } |
| 363 } |
| 364 }); |
| 365 } |
| 366 |
| 367 @SuppressWarnings("unused") |
| 368 @CalledByNative |
| 369 private void onReadCompleted(final ByteBuffer byteBuffer, int bytesRead, int
initialPosition, |
| 370 int initialLimit, long receivedBytesCount) { |
| 371 mResponseInfo.setReceivedBytesCount(receivedBytesCount); |
| 372 if (byteBuffer.position() != initialPosition || byteBuffer.limit() != in
itialLimit) { |
| 373 failWithException( |
| 374 new CronetException("ByteBuffer modified externally during r
ead", null)); |
| 375 return; |
| 376 } |
| 377 if (bytesRead < 0 || initialPosition + bytesRead > initialLimit) { |
| 378 failWithException(new CronetException("Invalid number of bytes read"
, null)); |
| 379 return; |
| 380 } |
| 381 byteBuffer.position(initialPosition + bytesRead); |
| 382 assert mOnReadCompletedTask.mByteBuffer == null; |
| 383 mOnReadCompletedTask.mByteBuffer = byteBuffer; |
| 384 mOnReadCompletedTask.mEndOfStream = (bytesRead == 0); |
| 385 postTaskToExecutor(mOnReadCompletedTask); |
| 386 } |
| 387 |
| 388 @SuppressWarnings("unused") |
| 389 @CalledByNative |
| 390 private void onWriteCompleted( |
| 391 final ByteBuffer byteBuffer, int initialPosition, int initialLimit)
{ |
| 392 if (byteBuffer.position() != initialPosition || byteBuffer.limit() != in
itialLimit) { |
| 393 failWithException( |
| 394 new CronetException("ByteBuffer modified externally during w
rite", null)); |
| 395 return; |
| 396 } |
| 397 // Current implementation always writes the complete buffer. |
| 398 byteBuffer.position(byteBuffer.limit()); |
| 399 assert mOnWriteCompletedTask.mByteBuffer == null; |
| 400 mOnWriteCompletedTask.mByteBuffer = byteBuffer; |
| 401 postTaskToExecutor(mOnWriteCompletedTask); |
| 402 } |
| 403 |
| 404 @SuppressWarnings("unused") |
| 405 @CalledByNative |
| 406 private void onResponseTrailersReceived(String[] trailers) { |
| 407 final UrlResponseInfo.HeaderBlock trailersBlock = |
| 408 new UrlResponseInfo.HeaderBlock(headersListFromStrings(trailers)
); |
| 409 postTaskToExecutor(new Runnable() { |
| 410 public void run() { |
| 411 synchronized (mNativeStreamLock) { |
| 412 if (isDoneLocked()) { |
| 413 return; |
| 414 } |
| 415 } |
| 416 try { |
| 417 mCallback.onResponseTrailersReceived( |
| 418 CronetBidirectionalStream.this, mResponseInfo, trail
ersBlock); |
| 419 } catch (Exception e) { |
| 420 onCallbackException(e); |
| 421 } |
| 422 } |
| 423 }); |
| 424 } |
| 425 |
| 426 @SuppressWarnings("unused") |
| 427 @CalledByNative |
| 428 private void onError(final int nativeError, final String errorString, long r
eceivedBytesCount) { |
| 429 if (mResponseInfo != null) { |
| 430 mResponseInfo.setReceivedBytesCount(receivedBytesCount); |
| 431 } |
| 432 failWithException(new CronetException( |
| 433 "Exception in BidirectionalStream: " + errorString, nativeError)
); |
| 434 } |
| 435 |
| 436 /** |
| 437 * Called when request is canceled, no callbacks will be called afterwards. |
| 438 */ |
| 439 @SuppressWarnings("unused") |
| 440 @CalledByNative |
| 441 private void onCanceled() { |
| 442 postTaskToExecutor(new Runnable() { |
| 443 public void run() { |
| 444 try { |
| 445 mCallback.onCanceled(CronetBidirectionalStream.this, mRespon
seInfo); |
| 446 } catch (Exception e) { |
| 447 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception in onCance
led method", e); |
| 448 } |
| 449 } |
| 450 }); |
| 451 } |
| 452 |
| 453 @VisibleForTesting |
| 454 public void setOnDestroyedCallbackForTesting(Runnable onDestroyedCallbackFor
Testing) { |
| 455 mOnDestroyedCallbackForTesting = onDestroyedCallbackForTesting; |
| 456 } |
| 457 |
| 458 private static boolean doesMethodAllowWriteData(String methodName) { |
| 459 return !methodName.equals("GET") && !methodName.equals("HEAD"); |
| 460 } |
| 461 |
| 462 private static ArrayList<Map.Entry<String, String>> headersListFromStrings(S
tring[] headers) { |
| 463 ArrayList<Map.Entry<String, String>> headersList = new ArrayList<>(heade
rs.length / 2); |
| 464 for (int i = 0; i < headers.length; i += 2) { |
| 465 headersList.add(new AbstractMap.SimpleImmutableEntry<>(headers[i], h
eaders[i + 1])); |
| 466 } |
| 467 return headersList; |
| 468 } |
| 469 |
| 470 private static String[] stringsFromHeaderList(List<Map.Entry<String, String>
> headersList) { |
| 471 String headersArray[] = new String[headersList.size() * 2]; |
| 472 int i = 0; |
| 473 for (Map.Entry<String, String> requestHeader : headersList) { |
| 474 headersArray[i++] = requestHeader.getKey(); |
| 475 headersArray[i++] = requestHeader.getValue(); |
| 476 } |
| 477 return headersArray; |
| 478 } |
| 479 |
| 480 private static int convertStreamPriority( |
| 481 @BidirectionalStream.Builder.StreamPriority int priority) { |
| 482 switch (priority) { |
| 483 case Builder.STREAM_PRIORITY_IDLE: |
| 484 return RequestPriority.IDLE; |
| 485 case Builder.STREAM_PRIORITY_LOWEST: |
| 486 return RequestPriority.LOWEST; |
| 487 case Builder.STREAM_PRIORITY_LOW: |
| 488 return RequestPriority.LOW; |
| 489 case Builder.STREAM_PRIORITY_MEDIUM: |
| 490 return RequestPriority.MEDIUM; |
| 491 case Builder.STREAM_PRIORITY_HIGHEST: |
| 492 return RequestPriority.HIGHEST; |
| 493 default: |
| 494 throw new IllegalArgumentException("Invalid stream priority."); |
| 495 } |
| 496 } |
| 497 |
| 498 /** |
| 499 * Checks whether reading and writing are done. |
| 500 * @return false if either reading or writing is not done. If both reading a
nd writing |
| 501 * are done, then posts cleanup task and returns true. |
| 502 */ |
| 503 @GuardedBy("mNativeStreamLock") |
| 504 private boolean maybeSucceedLocked() { |
| 505 if (mReadState != State.READING_DONE || mWriteState != State.WRITING_DON
E) { |
| 506 return false; |
| 507 } |
| 508 |
| 509 mReadState = mWriteState = State.SUCCESS; |
| 510 postTaskToExecutor(new Runnable() { |
| 511 public void run() { |
| 512 synchronized (mNativeStreamLock) { |
| 513 if (isDoneLocked()) { |
| 514 return; |
| 515 } |
| 516 // Destroy native stream first, so UrlRequestContext could b
e shut |
| 517 // down from the listener. |
| 518 destroyNativeStreamLocked(false); |
| 519 } |
| 520 try { |
| 521 mCallback.onSucceeded(CronetBidirectionalStream.this, mRespo
nseInfo); |
| 522 } catch (Exception e) { |
| 523 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception in onSucce
eded method", e); |
| 524 } |
| 525 } |
| 526 }); |
| 527 return true; |
| 528 } |
| 529 |
| 530 /** |
| 531 * Posts task to application Executor. Used for callbacks |
| 532 * and other tasks that should not be executed on network thread. |
| 533 */ |
| 534 private void postTaskToExecutor(Runnable task) { |
| 535 try { |
| 536 mExecutor.execute(task); |
| 537 } catch (RejectedExecutionException failException) { |
| 538 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception posting task to ex
ecutor", |
| 539 failException); |
| 540 // If posting a task throws an exception, then there is no choice |
| 541 // but to destroy the stream without invoking the callback. |
| 542 synchronized (mNativeStreamLock) { |
| 543 mReadState = mWriteState = State.ERROR; |
| 544 destroyNativeStreamLocked(false); |
| 545 } |
| 546 } |
| 547 } |
| 548 |
| 549 private UrlResponseInfo prepareResponseInfoOnNetworkThread(int httpStatusCod
e, |
| 550 String negotiatedProtocol, String[] headers, long receivedBytesCount
) { |
| 551 synchronized (mNativeStreamLock) { |
| 552 if (mNativeStream == 0) { |
| 553 return null; |
| 554 } |
| 555 } |
| 556 |
| 557 ArrayList<String> urlChain = new ArrayList<>(); |
| 558 urlChain.add(mInitialUrl); |
| 559 |
| 560 UrlResponseInfo responseInfo = new UrlResponseInfo(urlChain, httpStatusC
ode, "", |
| 561 headersListFromStrings(headers), false, negotiatedProtocol, null
); |
| 562 |
| 563 responseInfo.setReceivedBytesCount(receivedBytesCount); |
| 564 return responseInfo; |
| 565 } |
| 566 |
| 567 @GuardedBy("mNativeStreamLock") |
| 568 private void destroyNativeStreamLocked(boolean sendOnCanceled) { |
| 569 Log.i(CronetUrlRequestContext.LOG_TAG, "destroyNativeStreamLocked " + th
is.toString()); |
| 570 if (mNativeStream == 0) { |
| 571 return; |
| 572 } |
| 573 nativeDestroy(mNativeStream, sendOnCanceled); |
| 574 mNativeStream = 0; |
| 575 mRequestContext.onRequestDestroyed(); |
| 576 if (mOnDestroyedCallbackForTesting != null) { |
| 577 mOnDestroyedCallbackForTesting.run(); |
| 578 } |
| 579 } |
| 580 |
| 581 /** |
| 582 * Fails the stream with an exception. Only called on the Executor. |
| 583 */ |
| 584 private void failWithExceptionOnExecutor(CronetException e) { |
| 585 // Do not call into listener if request is complete. |
| 586 synchronized (mNativeStreamLock) { |
| 587 if (isDoneLocked()) { |
| 588 return; |
| 589 } |
| 590 mReadState = mWriteState = State.ERROR; |
| 591 destroyNativeStreamLocked(false); |
| 592 } |
| 593 try { |
| 594 mCallback.onFailed(this, mResponseInfo, e); |
| 595 } catch (Exception failException) { |
| 596 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception notifying of faile
d request", |
| 597 failException); |
| 598 } |
| 599 } |
| 600 |
| 601 /** |
| 602 * If callback method throws an exception, stream gets canceled |
| 603 * and exception is reported via onFailed callback. |
| 604 * Only called on the Executor. |
| 605 */ |
| 606 private void onCallbackException(Exception e) { |
| 607 CronetException streamError = |
| 608 new CronetException("CalledByNative method has thrown an excepti
on", e); |
| 609 Log.e(CronetUrlRequestContext.LOG_TAG, "Exception in CalledByNative meth
od", e); |
| 610 failWithExceptionOnExecutor(streamError); |
| 611 } |
| 612 |
| 613 /** |
| 614 * Fails the stream with an exception. Can be called on any thread. |
| 615 */ |
| 616 private void failWithException(final CronetException exception) { |
| 617 postTaskToExecutor(new Runnable() { |
| 618 public void run() { |
| 619 failWithExceptionOnExecutor(exception); |
| 620 } |
| 621 }); |
| 622 } |
| 623 |
| 624 // Native methods are implemented in cronet_bidirectional_stream_adapter.cc. |
| 625 private native long nativeCreateBidirectionalStream(long urlRequestContextAd
apter); |
| 626 |
| 627 @NativeClassQualifiedName("CronetBidirectionalStreamAdapter") |
| 628 private native int nativeStart(long nativePtr, String url, int priority, Str
ing method, |
| 629 String[] headers, boolean endOfStream); |
| 630 |
| 631 @NativeClassQualifiedName("CronetBidirectionalStreamAdapter") |
| 632 private native boolean nativeReadData( |
| 633 long nativePtr, ByteBuffer byteBuffer, int position, int limit); |
| 634 |
| 635 @NativeClassQualifiedName("CronetBidirectionalStreamAdapter") |
| 636 private native boolean nativeWriteData( |
| 637 long nativePtr, ByteBuffer byteBuffer, int position, int limit, bool
ean endOfStream); |
| 638 |
| 639 @NativeClassQualifiedName("CronetBidirectionalStreamAdapter") |
| 640 private native void nativeDestroy(long nativePtr, boolean sendOnCanceled); |
| 641 } |
OLD | NEW |