Revert of Refactor the avatar button/icon class (patchset #14 id:320001 of https...
[chromium-blink-merge.git] / components / cronet / android / cronet_url_request_adapter.cc
blob096b312356978df40c5b1a3fcd0546ec34128db9
1 // Copyright 2014 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.
5 #include "cronet_url_request_adapter.h"
7 #include <limits>
9 #include "base/bind.h"
10 #include "base/location.h"
11 #include "base/logging.h"
12 #include "components/cronet/android/cronet_url_request_context_adapter.h"
13 #include "jni/CronetUrlRequest_jni.h"
14 #include "net/base/io_buffer.h"
15 #include "net/base/load_flags.h"
16 #include "net/base/net_errors.h"
17 #include "net/base/request_priority.h"
18 #include "net/http/http_response_headers.h"
19 #include "net/http/http_status_code.h"
20 #include "net/http/http_util.h"
21 #include "net/url_request/redirect_info.h"
22 #include "net/url_request/url_request_context.h"
24 using base::android::ConvertUTF8ToJavaString;
26 namespace cronet {
28 // Explicitly register static JNI functions.
29 bool CronetUrlRequestAdapterRegisterJni(JNIEnv* env) {
30 return RegisterNativesImpl(env);
33 static jlong CreateRequestAdapter(JNIEnv* env,
34 jobject jurl_request,
35 jlong jurl_request_context_adapter,
36 jstring jurl_string,
37 jint jpriority) {
38 CronetURLRequestContextAdapter* context_adapter =
39 reinterpret_cast<CronetURLRequestContextAdapter*>(
40 jurl_request_context_adapter);
41 DCHECK(context_adapter);
43 GURL url(base::android::ConvertJavaStringToUTF8(env, jurl_string));
45 VLOG(1) << "New chromium network request_adapter: "
46 << url.possibly_invalid_spec();
48 CronetURLRequestAdapter* adapter =
49 new CronetURLRequestAdapter(context_adapter, env, jurl_request, url,
50 static_cast<net::RequestPriority>(jpriority));
52 return reinterpret_cast<jlong>(adapter);
55 // net::WrappedIOBuffer subclass for a buffer owned by a Java ByteBuffer. Keeps
56 // the ByteBuffer alive until destroyed. Uses WrappedIOBuffer because data() is
57 // owned by the embedder.
58 class CronetURLRequestAdapter::IOBufferWithByteBuffer
59 : public net::WrappedIOBuffer {
60 public:
61 // Creates a buffer wrapping the Java ByteBuffer |jbyte_buffer|. |data| points
62 // to the memory backed by the ByteBuffer, and position is the location to
63 // start writing.
64 IOBufferWithByteBuffer(
65 JNIEnv* env,
66 jobject jbyte_buffer,
67 void* data,
68 int position)
69 : net::WrappedIOBuffer(static_cast<char*>(data) + position),
70 initial_position_(position) {
71 DCHECK(data);
72 DCHECK_EQ(env->GetDirectBufferAddress(jbyte_buffer), data);
73 byte_buffer_.Reset(env, jbyte_buffer);
76 int initial_position() const { return initial_position_; }
78 jobject byte_buffer() const { return byte_buffer_.obj(); }
80 private:
81 ~IOBufferWithByteBuffer() override {}
83 base::android::ScopedJavaGlobalRef<jobject> byte_buffer_;
85 const int initial_position_;
88 CronetURLRequestAdapter::CronetURLRequestAdapter(
89 CronetURLRequestContextAdapter* context,
90 JNIEnv* env,
91 jobject jurl_request,
92 const GURL& url,
93 net::RequestPriority priority)
94 : context_(context),
95 initial_url_(url),
96 initial_priority_(priority),
97 initial_method_("GET"),
98 load_flags_(context->default_load_flags()) {
99 DCHECK(!context_->IsOnNetworkThread());
100 owner_.Reset(env, jurl_request);
103 CronetURLRequestAdapter::~CronetURLRequestAdapter() {
104 DCHECK(context_->IsOnNetworkThread());
107 jboolean CronetURLRequestAdapter::SetHttpMethod(JNIEnv* env,
108 jobject jcaller,
109 jstring jmethod) {
110 DCHECK(!context_->IsOnNetworkThread());
111 std::string method(base::android::ConvertJavaStringToUTF8(env, jmethod));
112 // Http method is a token, just as header name.
113 if (!net::HttpUtil::IsValidHeaderName(method))
114 return JNI_FALSE;
115 initial_method_ = method;
116 return JNI_TRUE;
119 jboolean CronetURLRequestAdapter::AddRequestHeader(JNIEnv* env,
120 jobject jcaller,
121 jstring jname,
122 jstring jvalue) {
123 DCHECK(!context_->IsOnNetworkThread());
124 std::string name(base::android::ConvertJavaStringToUTF8(env, jname));
125 std::string value(base::android::ConvertJavaStringToUTF8(env, jvalue));
126 if (!net::HttpUtil::IsValidHeaderName(name) ||
127 !net::HttpUtil::IsValidHeaderValue(value)) {
128 return JNI_FALSE;
130 initial_request_headers_.SetHeader(name, value);
131 return JNI_TRUE;
134 void CronetURLRequestAdapter::DisableCache(JNIEnv* env, jobject jcaller) {
135 DCHECK(!context_->IsOnNetworkThread());
136 load_flags_ |= net::LOAD_DISABLE_CACHE;
139 void CronetURLRequestAdapter::SetUpload(
140 scoped_ptr<net::UploadDataStream> upload) {
141 DCHECK(!context_->IsOnNetworkThread());
142 DCHECK(!upload_);
143 upload_ = upload.Pass();
146 void CronetURLRequestAdapter::Start(JNIEnv* env, jobject jcaller) {
147 DCHECK(!context_->IsOnNetworkThread());
148 context_->PostTaskToNetworkThread(
149 FROM_HERE, base::Bind(&CronetURLRequestAdapter::StartOnNetworkThread,
150 base::Unretained(this)));
153 void CronetURLRequestAdapter::FollowDeferredRedirect(JNIEnv* env,
154 jobject jcaller) {
155 DCHECK(!context_->IsOnNetworkThread());
156 context_->PostTaskToNetworkThread(
157 FROM_HERE,
158 base::Bind(
159 &CronetURLRequestAdapter::FollowDeferredRedirectOnNetworkThread,
160 base::Unretained(this)));
163 jboolean CronetURLRequestAdapter::ReadData(
164 JNIEnv* env, jobject jcaller, jobject jbyte_buffer, jint jposition,
165 jint jcapacity) {
166 DCHECK(!context_->IsOnNetworkThread());
167 DCHECK_LT(jposition, jcapacity);
169 void* data = env->GetDirectBufferAddress(jbyte_buffer);
170 if (!data)
171 return JNI_FALSE;
173 scoped_refptr<IOBufferWithByteBuffer> read_buffer(
174 new IOBufferWithByteBuffer(env, jbyte_buffer, data, jposition));
176 int remaining_capacity = jcapacity - jposition;
178 context_->PostTaskToNetworkThread(
179 FROM_HERE, base::Bind(&CronetURLRequestAdapter::ReadDataOnNetworkThread,
180 base::Unretained(this),
181 read_buffer,
182 remaining_capacity));
183 return JNI_TRUE;
186 void CronetURLRequestAdapter::Destroy(JNIEnv* env, jobject jcaller) {
187 DCHECK(!context_->IsOnNetworkThread());
188 context_->PostTaskToNetworkThread(
189 FROM_HERE, base::Bind(&CronetURLRequestAdapter::DestroyOnNetworkThread,
190 base::Unretained(this)));
193 void CronetURLRequestAdapter::PopulateResponseHeaders(JNIEnv* env,
194 jobject jurl_request,
195 jobject jheaders_list) {
196 DCHECK(context_->IsOnNetworkThread());
197 const net::HttpResponseHeaders* headers = url_request_->response_headers();
198 if (headers == nullptr)
199 return;
201 void* iter = nullptr;
202 std::string header_name;
203 std::string header_value;
204 while (headers->EnumerateHeaderLines(&iter, &header_name, &header_value)) {
205 base::android::ScopedJavaLocalRef<jstring> name =
206 ConvertUTF8ToJavaString(env, header_name);
207 base::android::ScopedJavaLocalRef<jstring> value =
208 ConvertUTF8ToJavaString(env, header_value);
209 Java_CronetUrlRequest_onAppendResponseHeader(
210 env, jurl_request, jheaders_list, name.obj(), value.obj());
214 base::android::ScopedJavaLocalRef<jstring>
215 CronetURLRequestAdapter::GetHttpStatusText(JNIEnv* env, jobject jcaller) const {
216 DCHECK(context_->IsOnNetworkThread());
217 const net::HttpResponseHeaders* headers = url_request_->response_headers();
218 return ConvertUTF8ToJavaString(env, headers->GetStatusText());
221 base::android::ScopedJavaLocalRef<jstring>
222 CronetURLRequestAdapter::GetNegotiatedProtocol(JNIEnv* env,
223 jobject jcaller) const {
224 DCHECK(context_->IsOnNetworkThread());
225 return ConvertUTF8ToJavaString(
226 env, url_request_->response_info().npn_negotiated_protocol);
229 jboolean CronetURLRequestAdapter::GetWasCached(JNIEnv* env,
230 jobject jcaller) const {
231 DCHECK(context_->IsOnNetworkThread());
232 return url_request_->response_info().was_cached;
235 // net::URLRequest::Delegate overrides (called on network thread).
237 void CronetURLRequestAdapter::OnReceivedRedirect(
238 net::URLRequest* request,
239 const net::RedirectInfo& redirect_info,
240 bool* defer_redirect) {
241 DCHECK(context_->IsOnNetworkThread());
242 DCHECK(request->status().is_success());
243 JNIEnv* env = base::android::AttachCurrentThread();
244 cronet::Java_CronetUrlRequest_onReceivedRedirect(
245 env, owner_.obj(),
246 ConvertUTF8ToJavaString(env, redirect_info.new_url.spec()).obj(),
247 redirect_info.status_code);
248 *defer_redirect = true;
251 void CronetURLRequestAdapter::OnResponseStarted(net::URLRequest* request) {
252 DCHECK(context_->IsOnNetworkThread());
253 if (MaybeReportError(request))
254 return;
255 JNIEnv* env = base::android::AttachCurrentThread();
256 cronet::Java_CronetUrlRequest_onResponseStarted(env, owner_.obj(),
257 request->GetResponseCode());
260 void CronetURLRequestAdapter::OnReadCompleted(net::URLRequest* request,
261 int bytes_read) {
262 DCHECK(context_->IsOnNetworkThread());
263 if (MaybeReportError(request))
264 return;
265 if (bytes_read != 0) {
266 JNIEnv* env = base::android::AttachCurrentThread();
267 cronet::Java_CronetUrlRequest_onReadCompleted(
268 env, owner_.obj(), read_buffer_->byte_buffer(), bytes_read,
269 read_buffer_->initial_position());
270 // Free the read buffer. This lets the Java ByteBuffer be freed, if the
271 // embedder releases it, too.
272 read_buffer_ = nullptr;
273 } else {
274 JNIEnv* env = base::android::AttachCurrentThread();
275 cronet::Java_CronetUrlRequest_onSucceeded(
276 env, owner_.obj(), url_request_->GetTotalReceivedBytes());
280 void CronetURLRequestAdapter::StartOnNetworkThread() {
281 DCHECK(context_->IsOnNetworkThread());
282 VLOG(1) << "Starting chromium request: "
283 << initial_url_.possibly_invalid_spec().c_str()
284 << " priority: " << RequestPriorityToString(initial_priority_);
285 url_request_ = context_->GetURLRequestContext()->CreateRequest(
286 initial_url_, net::DEFAULT_PRIORITY, this);
287 url_request_->SetLoadFlags(load_flags_);
288 url_request_->set_method(initial_method_);
289 url_request_->SetExtraRequestHeaders(initial_request_headers_);
290 url_request_->SetPriority(initial_priority_);
291 if (upload_)
292 url_request_->set_upload(upload_.Pass());
293 url_request_->Start();
296 void CronetURLRequestAdapter::FollowDeferredRedirectOnNetworkThread() {
297 DCHECK(context_->IsOnNetworkThread());
298 url_request_->FollowDeferredRedirect();
301 void CronetURLRequestAdapter::ReadDataOnNetworkThread(
302 scoped_refptr<IOBufferWithByteBuffer> read_buffer,
303 int buffer_size) {
304 DCHECK(context_->IsOnNetworkThread());
305 DCHECK(read_buffer);
306 DCHECK(!read_buffer_);
308 read_buffer_ = read_buffer;
310 int bytes_read = 0;
311 url_request_->Read(read_buffer_.get(), buffer_size, &bytes_read);
312 // If IO is pending, wait for the URLRequest to call OnReadCompleted.
313 if (url_request_->status().is_io_pending())
314 return;
316 OnReadCompleted(url_request_.get(), bytes_read);
319 void CronetURLRequestAdapter::DestroyOnNetworkThread() {
320 DCHECK(context_->IsOnNetworkThread());
321 delete this;
324 bool CronetURLRequestAdapter::MaybeReportError(net::URLRequest* request) const {
325 DCHECK_NE(net::URLRequestStatus::IO_PENDING, url_request_->status().status());
326 DCHECK_EQ(request, url_request_);
327 if (url_request_->status().is_success())
328 return false;
329 int net_error = url_request_->status().error();
330 VLOG(1) << "Error " << net::ErrorToString(net_error)
331 << " on chromium request: " << initial_url_.possibly_invalid_spec();
332 JNIEnv* env = base::android::AttachCurrentThread();
333 cronet::Java_CronetUrlRequest_onError(
334 env, owner_.obj(), net_error,
335 ConvertUTF8ToJavaString(env, net::ErrorToString(net_error)).obj());
336 return true;
339 } // namespace cronet