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