Commit f62a203e authored by clm's avatar clm Committed by Commit bot

Obliterate legacy cronet API. All of its users have been migrated.

Review-Url: https://codereview.chromium.org/2361413002
Cr-Commit-Position: refs/heads/master@{#420716}
parent ec9c7f30
...@@ -19,8 +19,6 @@ declare_args() { ...@@ -19,8 +19,6 @@ declare_args() {
generate_jni("cronet_jni_headers") { generate_jni("cronet_jni_headers") {
sources = [ sources = [
"java/src/org/chromium/net/impl/ChromiumUrlRequest.java",
"java/src/org/chromium/net/impl/ChromiumUrlRequestContext.java",
"java/src/org/chromium/net/impl/CronetBidirectionalStream.java", "java/src/org/chromium/net/impl/CronetBidirectionalStream.java",
"java/src/org/chromium/net/impl/CronetLibraryLoader.java", "java/src/org/chromium/net/impl/CronetLibraryLoader.java",
"java/src/org/chromium/net/impl/CronetUploadDataStream.java", "java/src/org/chromium/net/impl/CronetUploadDataStream.java",
...@@ -183,10 +181,7 @@ template("cronet_static_tmpl") { ...@@ -183,10 +181,7 @@ template("cronet_static_tmpl") {
sources = [ sources = [
"//components/cronet/android/cert/cert_verifier_cache_serializer.cc", "//components/cronet/android/cert/cert_verifier_cache_serializer.cc",
"//components/cronet/android/cert/cert_verifier_cache_serializer.h", "//components/cronet/android/cert/cert_verifier_cache_serializer.h",
"//components/cronet/android/chromium_url_request.cc",
"//components/cronet/android/chromium_url_request.h", "//components/cronet/android/chromium_url_request.h",
"//components/cronet/android/chromium_url_request_context.cc",
"//components/cronet/android/chromium_url_request_context.h",
"//components/cronet/android/cronet_bidirectional_stream_adapter.cc", "//components/cronet/android/cronet_bidirectional_stream_adapter.cc",
"//components/cronet/android/cronet_bidirectional_stream_adapter.h", "//components/cronet/android/cronet_bidirectional_stream_adapter.h",
"//components/cronet/android/cronet_in_memory_pref_store.cc", "//components/cronet/android/cronet_in_memory_pref_store.cc",
...@@ -203,14 +198,8 @@ template("cronet_static_tmpl") { ...@@ -203,14 +198,8 @@ template("cronet_static_tmpl") {
"//components/cronet/android/cronet_url_request_context_adapter.h", "//components/cronet/android/cronet_url_request_context_adapter.h",
"//components/cronet/android/io_buffer_with_byte_buffer.cc", "//components/cronet/android/io_buffer_with_byte_buffer.cc",
"//components/cronet/android/io_buffer_with_byte_buffer.h", "//components/cronet/android/io_buffer_with_byte_buffer.h",
"//components/cronet/android/url_request_adapter.cc",
"//components/cronet/android/url_request_adapter.h",
"//components/cronet/android/url_request_context_adapter.cc",
"//components/cronet/android/url_request_context_adapter.h",
"//components/cronet/android/url_request_error.cc", "//components/cronet/android/url_request_error.cc",
"//components/cronet/android/url_request_error.h", "//components/cronet/android/url_request_error.h",
"//components/cronet/android/wrapped_channel_upload_element_reader.cc",
"//components/cronet/android/wrapped_channel_upload_element_reader.h",
"//components/cronet/histogram_manager.cc", "//components/cronet/histogram_manager.cc",
"//components/cronet/histogram_manager.h", "//components/cronet/histogram_manager.h",
"//components/cronet/stale_host_resolver.cc", "//components/cronet/stale_host_resolver.cc",
...@@ -290,14 +279,8 @@ shared_library("cronet") { ...@@ -290,14 +279,8 @@ shared_library("cronet") {
android_library("cronet_api") { android_library("cronet_api") {
java_files = [ java_files = [
"api/src/org/chromium/net/BidirectionalStream.java", "api/src/org/chromium/net/BidirectionalStream.java",
"api/src/org/chromium/net/ChunkedWritableByteChannel.java",
"api/src/org/chromium/net/CronetEngine.java", "api/src/org/chromium/net/CronetEngine.java",
"api/src/org/chromium/net/CronetException.java", "api/src/org/chromium/net/CronetException.java",
"api/src/org/chromium/net/HttpUrlConnectionUrlRequest.java",
"api/src/org/chromium/net/HttpUrlConnectionUrlRequestFactory.java",
"api/src/org/chromium/net/HttpUrlRequest.java",
"api/src/org/chromium/net/HttpUrlRequestFactory.java",
"api/src/org/chromium/net/HttpUrlRequestListener.java",
"api/src/org/chromium/net/InlineExecutionProhibitedException.java", "api/src/org/chromium/net/InlineExecutionProhibitedException.java",
"api/src/org/chromium/net/InputStreamChannel.java", "api/src/org/chromium/net/InputStreamChannel.java",
"api/src/org/chromium/net/JavaCronetEngine.java", "api/src/org/chromium/net/JavaCronetEngine.java",
...@@ -307,7 +290,6 @@ android_library("cronet_api") { ...@@ -307,7 +290,6 @@ android_library("cronet_api") {
"api/src/org/chromium/net/Preconditions.java", "api/src/org/chromium/net/Preconditions.java",
"api/src/org/chromium/net/QuicException.java", "api/src/org/chromium/net/QuicException.java",
"api/src/org/chromium/net/RequestFinishedInfo.java", "api/src/org/chromium/net/RequestFinishedInfo.java",
"api/src/org/chromium/net/ResponseTooLargeException.java",
"api/src/org/chromium/net/UploadDataProvider.java", "api/src/org/chromium/net/UploadDataProvider.java",
"api/src/org/chromium/net/UploadDataProviders.java", "api/src/org/chromium/net/UploadDataProviders.java",
"api/src/org/chromium/net/UploadDataSink.java", "api/src/org/chromium/net/UploadDataSink.java",
...@@ -335,9 +317,6 @@ android_library("cronet_api") { ...@@ -335,9 +317,6 @@ android_library("cronet_api") {
android_library("cronet_java") { android_library("cronet_java") {
java_files = [ java_files = [
"java/src/org/chromium/net/impl/ChromiumUrlRequest.java",
"java/src/org/chromium/net/impl/ChromiumUrlRequestContext.java",
"java/src/org/chromium/net/impl/ChromiumUrlRequestFactory.java",
"java/src/org/chromium/net/impl/CronetBidirectionalStream.java", "java/src/org/chromium/net/impl/CronetBidirectionalStream.java",
"java/src/org/chromium/net/impl/CronetLibraryLoader.java", "java/src/org/chromium/net/impl/CronetLibraryLoader.java",
"java/src/org/chromium/net/impl/CronetMetrics.java", "java/src/org/chromium/net/impl/CronetMetrics.java",
...@@ -620,18 +599,13 @@ android_library("cronet_javatests") { ...@@ -620,18 +599,13 @@ android_library("cronet_javatests") {
java_files = [ java_files = [
"test/javatests/src/org/chromium/net/BidirectionalStreamQuicTest.java", "test/javatests/src/org/chromium/net/BidirectionalStreamQuicTest.java",
"test/javatests/src/org/chromium/net/BidirectionalStreamTest.java", "test/javatests/src/org/chromium/net/BidirectionalStreamTest.java",
"test/javatests/src/org/chromium/net/ChromiumUrlRequestTest.java",
"test/javatests/src/org/chromium/net/ChunkedWritableByteChannelTest.java",
"test/javatests/src/org/chromium/net/ContextInitTest.java",
"test/javatests/src/org/chromium/net/Criteria.java", "test/javatests/src/org/chromium/net/Criteria.java",
"test/javatests/src/org/chromium/net/CronetTestBase.java", "test/javatests/src/org/chromium/net/CronetTestBase.java",
"test/javatests/src/org/chromium/net/CronetUploadTest.java", "test/javatests/src/org/chromium/net/CronetUploadTest.java",
"test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java", "test/javatests/src/org/chromium/net/CronetUrlRequestContextTest.java",
"test/javatests/src/org/chromium/net/CronetUrlRequestTest.java", "test/javatests/src/org/chromium/net/CronetUrlRequestTest.java",
"test/javatests/src/org/chromium/net/CronetUrlTest.java",
"test/javatests/src/org/chromium/net/DiskStorageTest.java", "test/javatests/src/org/chromium/net/DiskStorageTest.java",
"test/javatests/src/org/chromium/net/GetStatusTest.java", "test/javatests/src/org/chromium/net/GetStatusTest.java",
"test/javatests/src/org/chromium/net/HttpUrlRequestFactoryTest.java",
"test/javatests/src/org/chromium/net/MetricsTestUtil.java", "test/javatests/src/org/chromium/net/MetricsTestUtil.java",
"test/javatests/src/org/chromium/net/NetworkChangeNotifierTest.java", "test/javatests/src/org/chromium/net/NetworkChangeNotifierTest.java",
"test/javatests/src/org/chromium/net/PkpTest.java", "test/javatests/src/org/chromium/net/PkpTest.java",
...@@ -640,13 +614,11 @@ android_library("cronet_javatests") { ...@@ -640,13 +614,11 @@ android_library("cronet_javatests") {
"test/javatests/src/org/chromium/net/SdchTest.java", "test/javatests/src/org/chromium/net/SdchTest.java",
"test/javatests/src/org/chromium/net/TestBidirectionalStreamCallback.java", "test/javatests/src/org/chromium/net/TestBidirectionalStreamCallback.java",
"test/javatests/src/org/chromium/net/TestDrivenDataProvider.java", "test/javatests/src/org/chromium/net/TestDrivenDataProvider.java",
"test/javatests/src/org/chromium/net/TestHttpUrlRequestListener.java",
"test/javatests/src/org/chromium/net/TestNetworkQualityRttListener.java", "test/javatests/src/org/chromium/net/TestNetworkQualityRttListener.java",
"test/javatests/src/org/chromium/net/TestNetworkQualityThroughputListener.java", "test/javatests/src/org/chromium/net/TestNetworkQualityThroughputListener.java",
"test/javatests/src/org/chromium/net/TestUploadDataProvider.java", "test/javatests/src/org/chromium/net/TestUploadDataProvider.java",
"test/javatests/src/org/chromium/net/TestUrlRequestCallback.java", "test/javatests/src/org/chromium/net/TestUrlRequestCallback.java",
"test/javatests/src/org/chromium/net/UploadDataProvidersTest.java", "test/javatests/src/org/chromium/net/UploadDataProvidersTest.java",
"test/javatests/src/org/chromium/net/UploadTest.java",
"test/javatests/src/org/chromium/net/urlconnection/CronetBufferedOutputStreamTest.java", "test/javatests/src/org/chromium/net/urlconnection/CronetBufferedOutputStreamTest.java",
"test/javatests/src/org/chromium/net/urlconnection/CronetChunkedOutputStreamTest.java", "test/javatests/src/org/chromium/net/urlconnection/CronetChunkedOutputStreamTest.java",
"test/javatests/src/org/chromium/net/urlconnection/CronetFixedModeOutputStreamTest.java", "test/javatests/src/org/chromium/net/urlconnection/CronetFixedModeOutputStreamTest.java",
......
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
/**
* A writable byte channel that is optimized for chunked writing. Each call to
* {@link #write} results in a ByteBuffer being created and remembered. Then all
* of those byte buffers are combined on demand. This approach allows to avoid
* the cost of reallocating a byte buffer.
* @deprecated This is no longer used in the new async API.
* {@hide as it's deprecated}
*/
@Deprecated
public class ChunkedWritableByteChannel implements WritableByteChannel {
private final ArrayList<ByteBuffer> mBuffers = new ArrayList<ByteBuffer>();
private ByteBuffer mInitialBuffer;
private ByteBuffer mBuffer;
private int mSize;
private boolean mClosed;
public void setCapacity(int capacity) {
if (!mBuffers.isEmpty() || mInitialBuffer != null) {
throw new IllegalStateException();
}
mInitialBuffer = ByteBuffer.allocateDirect(capacity);
}
@Override
public int write(ByteBuffer buffer) throws IOException {
if (mClosed) {
throw new ClosedChannelException();
}
int size = buffer.remaining();
mSize += size;
if (mInitialBuffer != null) {
if (size <= mInitialBuffer.remaining()) {
mInitialBuffer.put(buffer);
return size;
}
// The supplied initial size was incorrect. Keep the accumulated
// data and switch to the usual "sequence of buffers" mode.
mInitialBuffer.flip();
mBuffers.add(mInitialBuffer);
mInitialBuffer = null;
}
// We can't hold a reference to this buffer, because it may wrap native
// memory and is not guaranteed to be immutable.
ByteBuffer tmpBuf = ByteBuffer.allocateDirect(size);
tmpBuf.put(buffer).rewind();
mBuffers.add(tmpBuf);
return size;
}
/**
* Returns the entire content accumulated by the channel as a ByteBuffer.
*/
public ByteBuffer getByteBuffer() {
if (mInitialBuffer != null) {
mInitialBuffer.flip();
mBuffer = mInitialBuffer;
mInitialBuffer = null;
} else if (mBuffer != null && mSize == mBuffer.capacity()) {
// Cache hit
} else if (mBuffer == null && mBuffers.size() == 1) {
mBuffer = mBuffers.get(0);
} else {
mBuffer = ByteBuffer.allocateDirect(mSize);
int count = mBuffers.size();
for (int i = 0; i < count; i++) {
mBuffer.put(mBuffers.get(i));
}
mBuffer.rewind();
}
return mBuffer;
}
/**
* Returns the entire content accumulated by the channel as a byte array.
*/
public byte[] getBytes() {
byte[] bytes = new byte[mSize];
if (mInitialBuffer != null) {
mInitialBuffer.flip();
mInitialBuffer.get(bytes);
} else {
int bufferCount = mBuffers.size();
int offset = 0;
for (int i = 0; i < bufferCount; i++) {
ByteBuffer buffer = mBuffers.get(i);
int bufferSize = buffer.remaining();
buffer.get(bytes, offset, bufferSize);
buffer.rewind();
offset += bufferSize;
}
}
return bytes;
}
@Override
public void close() {
mClosed = true;
}
@Override
public boolean isOpen() {
return !mClosed;
}
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import android.content.Context;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.channels.WritableByteChannel;
import java.util.Map;
/**
* Network request using {@link java.net.HttpURLConnection}.
* @deprecated Use {@link CronetEngine} instead.
* {@hide as it's deprecated}
*/
@Deprecated
class HttpUrlConnectionUrlRequestFactory extends HttpUrlRequestFactory {
private final Context mContext;
private final String mDefaultUserAgent;
public HttpUrlConnectionUrlRequestFactory(Context context, CronetEngine.Builder config) {
mContext = context;
String userAgent = config.getUserAgent();
if (userAgent == null) {
// Cannot use config.getDefaultUserAgent() as config.mContext may be null.
userAgent = new CronetEngine.Builder(mContext).getDefaultUserAgent();
}
mDefaultUserAgent = userAgent;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String getName() {
return "HttpUrlConnection/" + ApiVersion.getVersion();
}
@Override
public HttpUrlRequest createRequest(String url, int requestPriority,
Map<String, String> headers, HttpUrlRequestListener listener) {
return new HttpUrlConnectionUrlRequest(mContext, mDefaultUserAgent, url,
requestPriority, headers, listener);
}
@Override
public HttpUrlRequest createRequest(String url, int requestPriority,
Map<String, String> headers, WritableByteChannel channel,
HttpUrlRequestListener listener) {
return new HttpUrlConnectionUrlRequest(mContext, mDefaultUserAgent, url,
requestPriority, headers, channel, listener);
}
@Override
public void startNetLogToFile(String fileName, boolean logAll) {
try {
PrintWriter out = new PrintWriter(fileName);
out.println("NetLog is not supported by " + getName());
out.close();
} catch (IOException e) {
// Ignore any exceptions.
}
}
@Override
public void stopNetLog() {
}
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.util.List;
import java.util.Map;
/**
* HTTP request (GET or POST).
* @deprecated Use {@link UrlRequest} instead.
* {@hide as it's deprecated}
*/
@Deprecated
public interface HttpUrlRequest {
public static final int REQUEST_PRIORITY_IDLE = 0;
public static final int REQUEST_PRIORITY_LOWEST = 1;
public static final int REQUEST_PRIORITY_LOW = 2;
public static final int REQUEST_PRIORITY_MEDIUM = 3;
public static final int REQUEST_PRIORITY_HIGHEST = 4;
/**
* Returns the URL associated with this request.
*/
String getUrl();
/**
* Requests a range starting at the given offset to the end of the resource.
* The server may or may not honor the offset request. The client must check
* the HTTP status code before processing the response.
*/
void setOffset(long offset);
/**
* Limits the size of the download.
*
* @param limit Maximum size of the downloaded response (post gzip)
* @param cancelEarly If true, cancel the download as soon as the size of
* the response is known. If false, download {@code responseSize}
* bytes and then cancel.
*/
void setContentLengthLimit(long limit, boolean cancelEarly);
/**
* Sets data to upload as part of a POST request.
*
* @param contentType MIME type of the post content or null if this is not a
* POST.
* @param data The content that needs to be uploaded if this is a POST
* request.
*/
void setUploadData(String contentType, byte[] data);
/**
* Sets a readable byte channel to upload as part of a POST request.
*
* <p>Once {@link #start()} is called, this channel is guaranteed to be
* closed, either when the upload completes, or when it is canceled.
*
* @param contentType MIME type of the post content or null if this is not a
* POST.
* @param channel The channel to read to read upload data from if this is a
* POST request.
* @param contentLength The length of data to upload.
*/
void setUploadChannel(String contentType, ReadableByteChannel channel,
long contentLength);
/**
* Sets the HTTP method verb to use for this request.
*
* <p>The default when this method is not called is "GET" if the request has
* no body or "POST" if it does.
*
* @param method "GET", "POST", etc. Must be all uppercase.
*/
void setHttpMethod(String method);
/**
* Disables redirect for this request.
*/
void disableRedirects();
/**
* Start executing the request.
* <p>
* If this is a streaming upload request using a ReadableByteChannel, the
* call will block while the request is uploaded.
*/
void start();
/**
* Cancel the request in progress.
*/
void cancel();
/**
* Returns {@code true} if the request has been canceled.
*/
boolean isCanceled();
/**
* Returns protocol (e.g. "quic/1+spdy/3") negotiated with server. Returns
* empty string if no protocol was negotiated, or the protocol is not known.
* Returns empty when using plain http or https. Must be called after
* onResponseStarted but before request is recycled.
*/
String getNegotiatedProtocol();
/**
* Returns whether the response is serviced from the cache.
*/
boolean wasCached();
/**
* Returns the entire response as a ByteBuffer.
*/
ByteBuffer getByteBuffer();
/**
* Returns the entire response as a byte array.
*/
byte[] getResponseAsBytes();
/**
* Returns the expected content length. It is not guaranteed to be correct
* and may be -1 if the content length is unknown.
*/
long getContentLength();
/**
* Returns the content MIME type if known or {@code null} otherwise.
*/
String getContentType();
/**
* Returns the HTTP status code. It may be 0 if the request has not started
* or failed before getting the status code from the server. If the status
* code is 206 (partial response) after {@link #setOffset} is called, the
* method returns 200.
*/
int getHttpStatusCode();
/**
* Returns the HTTP status text of the status line. For example, if the
* request has a "HTTP/1.1 200 OK" response, this method returns "OK". It
* returns null if the request has not started.
*/
String getHttpStatusText();
/**
* Returns the response header value for the given name or {@code null} if
* not found.
*/
String getHeader(String name);
/**
* Returns an unmodifiable map of the response-header fields and values.
* The null key is mapped to the HTTP status line for compatibility with
* HttpUrlConnection.
*/
Map<String, List<String>> getAllHeaders();
/**
* Returns the exception that occurred while executing the request of null
* if the request was successful.
*/
IOException getException();
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import android.content.Context;
import android.util.Log;
import java.lang.reflect.Constructor;
import java.nio.channels.WritableByteChannel;
import java.util.Map;
/**
* A factory for {@link HttpUrlRequest}'s, which uses the best HTTP stack
* available on the current platform.
* @deprecated Use {@link CronetEngine} instead.
* {@hide as it's deprecated}
*/
@Deprecated
public abstract class HttpUrlRequestFactory {
private static final String TAG = "HttpUrlRequestFactory";
private static final String CHROMIUM_URL_REQUEST_FACTORY =
"org.chromium.net.impl.ChromiumUrlRequestFactory";
public static HttpUrlRequestFactory createFactory(
Context context, CronetEngine.Builder config) {
HttpUrlRequestFactory factory = null;
if (!config.legacyMode()) {
factory = createChromiumFactory(context, config);
}
if (factory == null) {
// Default to HttpUrlConnection-based networking.
factory = new HttpUrlConnectionUrlRequestFactory(context, config);
}
Log.i(TAG, "Using network stack: " + factory.getName());
return factory;
}
/**
* Returns true if the factory is enabled.
*/
public abstract boolean isEnabled();
/**
* Returns a human-readable name of the factory.
*/
public abstract String getName();
/**
* Creates a new request intended for full-response buffering.
*/
public abstract HttpUrlRequest createRequest(String url,
int requestPriority, Map<String, String> headers,
HttpUrlRequestListener listener);
/**
* Creates a new request intended for streaming.
*/
public abstract HttpUrlRequest createRequest(String url,
int requestPriority, Map<String, String> headers,
WritableByteChannel channel, HttpUrlRequestListener listener);
/**
* Starts NetLog logging to a file named |fileName| in the
* application temporary directory. |fileName| must not be empty. Log may
* contain user's personal information (PII). If the file exists it is
* truncated before starting. If actively logging the call is ignored.
* @param fileName The complete file path. It must not be empty. If file
* exists, it is truncated before starting.
* @param logAll {@code true} to also include all transferred bytes in the
* log.
*/
public abstract void startNetLogToFile(String fileName, boolean logAll);
/**
* Stops NetLog logging and flushes file to disk. If a logging session is
* not in progress this call is ignored.
*/
public abstract void stopNetLog();
private static HttpUrlRequestFactory createChromiumFactory(
Context context, CronetEngine.Builder config) {
HttpUrlRequestFactory factory = null;
try {
Class<? extends HttpUrlRequestFactory> factoryClass =
HttpUrlRequestFactory.class.getClassLoader()
.loadClass(CHROMIUM_URL_REQUEST_FACTORY)
.asSubclass(HttpUrlRequestFactory.class);
Constructor<? extends HttpUrlRequestFactory> constructor =
factoryClass.getConstructor(Context.class, CronetEngine.Builder.class);
HttpUrlRequestFactory chromiumFactory =
constructor.newInstance(context, config);
if (chromiumFactory.isEnabled()) {
factory = chromiumFactory;
}
} catch (ClassNotFoundException e) {
// Leave as null
} catch (Exception e) {
throw new IllegalStateException(
"Cannot instantiate: " + CHROMIUM_URL_REQUEST_FACTORY,
e);
}
return factory;
}
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
/**
* Callback interface.
* @deprecated Use {@link UrlRequest.Callback} instead.
* {@hide as it's deprecated}
*/
@Deprecated
public interface HttpUrlRequestListener {
/**
* A callback invoked when the first chunk of the response has arrived and
* response headers have been read. The listener can only call request
* getHeader, getContentType and getContentLength. This method will always
* be called before {@code onRequestComplete}.
*/
void onResponseStarted(HttpUrlRequest request);
/**
* The listener should completely process the response in the callback
* method. Immediately after the callback, the request object will be
* recycled.
*/
void onRequestComplete(HttpUrlRequest request);
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import java.io.IOException;
/**
* Exception returned if a {@code HttpUrlRequest} attempts to download a
* response that exceeds the user-specified limit.
* @deprecated This is no longer used in the async API.
* {@hide as it's deprecated}
*/
@SuppressWarnings("serial")
@Deprecated
public class ResponseTooLargeException extends IOException {
public ResponseTooLargeException() {
}
}
This diff is collapsed.
...@@ -40,8 +40,6 @@ enum UrlRequestError { ...@@ -40,8 +40,6 @@ enum UrlRequestError {
REQUEST_ERROR_TOO_MANY_REDIRECTS = 5, REQUEST_ERROR_TOO_MANY_REDIRECTS = 5,
}; };
bool ChromiumUrlRequestRegisterJni(JNIEnv* env);
} // namespace cronet } // namespace cronet
#endif // COMPONENTS_CRONET_ANDROID_CHROMIUM_URL_REQUEST_H_ #endif // COMPONENTS_CRONET_ANDROID_CHROMIUM_URL_REQUEST_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/cronet/android/chromium_url_request_context.h"
#include <memory>
#include <string>
#include <utility>
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/metrics/statistics_recorder.h"
#include "base/values.h"
#include "components/cronet/android/chromium_url_request.h"
#include "components/cronet/android/url_request_adapter.h"
#include "components/cronet/android/url_request_context_adapter.h"
#include "components/cronet/url_request_context_config.h"
#include "jni/ChromiumUrlRequestContext_jni.h"
using base::android::ConvertUTF8ToJavaString;
using base::android::ConvertJavaStringToUTF8;
using base::android::JavaParamRef;
using base::android::ScopedJavaLocalRef;
namespace {
// Delegate of URLRequestContextAdapter that delivers callbacks to the Java
// layer.
class JniURLRequestContextAdapterDelegate
: public cronet::URLRequestContextAdapter::
URLRequestContextAdapterDelegate {
public:
JniURLRequestContextAdapterDelegate(JNIEnv* env, jobject owner)
: owner_(env->NewGlobalRef(owner)) {}
void OnContextInitialized(
cronet::URLRequestContextAdapter* context_adapter) override {
JNIEnv* env = base::android::AttachCurrentThread();
cronet::Java_ChromiumUrlRequestContext_initNetworkThread(env, owner_);
// TODO(dplotnikov): figure out if we need to detach from the thread.
// The documentation says we should detach just before the thread exits.
}
protected:
~JniURLRequestContextAdapterDelegate() override {
JNIEnv* env = base::android::AttachCurrentThread();
env->DeleteGlobalRef(owner_);
}
private:
jobject owner_;
};
} // namespace
namespace cronet {
// Explicitly register static JNI functions.
bool ChromiumUrlRequestContextRegisterJni(JNIEnv* env) {
return RegisterNativesImpl(env);
}
// Sets global user-agent to be used for all subsequent requests.
static jlong CreateRequestContextAdapter(
JNIEnv* env,
const JavaParamRef<jobject>& jcaller,
const JavaParamRef<jstring>& juser_agent,
jint jlog_level,
jlong jconfig) {
std::string user_agent = ConvertJavaStringToUTF8(env, juser_agent);
std::unique_ptr<URLRequestContextConfig> context_config(
reinterpret_cast<URLRequestContextConfig*>(jconfig));
// TODO(mef): MinLogLevel is global, shared by all URLRequestContexts.
// Revisit this if each URLRequestContext would need an individual log level.
logging::SetMinLogLevel(static_cast<int>(jlog_level));
// TODO(dplotnikov): set application context.
URLRequestContextAdapter* context_adapter = new URLRequestContextAdapter(
new JniURLRequestContextAdapterDelegate(env, jcaller), user_agent);
context_adapter->AddRef(); // Hold onto this ref-counted object.
context_adapter->Initialize(std::move(context_config));
return reinterpret_cast<jlong>(context_adapter);
}
// Releases native objects.
static void ReleaseRequestContextAdapter(JNIEnv* env,
const JavaParamRef<jobject>& jcaller,
jlong jurl_request_context_adapter) {
URLRequestContextAdapter* context_adapter =
reinterpret_cast<URLRequestContextAdapter*>(jurl_request_context_adapter);
// TODO(mef): Revisit this from thread safety point of view: Can we delete a
// thread while running on that thread?
// URLRequestContextAdapter is a ref-counted object, and may have pending
// tasks,
// so we need to release it instead of deleting here.
context_adapter->Release();
}
// Starts recording statistics.
static void InitializeStatistics(JNIEnv* env,
const JavaParamRef<jobject>& jcaller) {
base::StatisticsRecorder::Initialize();
}
// Gets current statistics with |jfilter| as a substring as JSON text (an empty
// |jfilter| will include all registered histograms).
static ScopedJavaLocalRef<jstring> GetStatisticsJSON(
JNIEnv* env,
const JavaParamRef<jobject>& jcaller,
const JavaParamRef<jstring>& jfilter) {
std::string query = ConvertJavaStringToUTF8(env, jfilter);
std::string json = base::StatisticsRecorder::ToJSON(query);
return ConvertUTF8ToJavaString(env, json);
}
// Starts recording NetLog into file with |jfilename|.
static void StartNetLogToFile(JNIEnv* env,
const JavaParamRef<jobject>& jcaller,
jlong jurl_request_context_adapter,
const JavaParamRef<jstring>& jfilename,
jboolean jlog_all) {
URLRequestContextAdapter* context_adapter =
reinterpret_cast<URLRequestContextAdapter*>(jurl_request_context_adapter);
std::string filename = ConvertJavaStringToUTF8(env, jfilename);
context_adapter->StartNetLogToFile(filename, jlog_all);
}
// Stops recording NetLog.
static void StopNetLog(JNIEnv* env,
const JavaParamRef<jobject>& jcaller,
jlong jurl_request_context_adapter) {
URLRequestContextAdapter* context_adapter =
reinterpret_cast<URLRequestContextAdapter*>(jurl_request_context_adapter);
context_adapter->StopNetLog();
}
// Called on application's main Java thread.
static void InitRequestContextOnMainThread(JNIEnv* env,
const JavaParamRef<jobject>& jcaller,
jlong jurl_request_context_adapter) {
URLRequestContextAdapter* context_adapter =
reinterpret_cast<URLRequestContextAdapter*>(jurl_request_context_adapter);
context_adapter->InitRequestContextOnMainThread();
}
} // namespace cronet
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_CRONET_ANDROID_URLREQUEST_CONTEXT_H_
#define COMPONENTS_CRONET_ANDROID_URLREQUEST_CONTEXT_H_
#include <jni.h>
namespace cronet {
bool ChromiumUrlRequestContextRegisterJni(JNIEnv* env);
} // namespace cronet
#endif // COMPONENTS_CRONET_ANDROID_URLREQUEST_CONTEXT_H_
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
#include "base/macros.h" #include "base/macros.h"
#include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop.h"
#include "components/cronet/android/chromium_url_request.h" #include "components/cronet/android/chromium_url_request.h"
#include "components/cronet/android/chromium_url_request_context.h"
#include "components/cronet/android/cronet_bidirectional_stream_adapter.h" #include "components/cronet/android/cronet_bidirectional_stream_adapter.h"
#include "components/cronet/android/cronet_upload_data_stream_adapter.h" #include "components/cronet/android/cronet_upload_data_stream_adapter.h"
#include "components/cronet/android/cronet_url_request_adapter.h" #include "components/cronet/android/cronet_url_request_adapter.h"
...@@ -44,8 +43,6 @@ namespace { ...@@ -44,8 +43,6 @@ namespace {
const base::android::RegistrationMethod kCronetRegisteredMethods[] = { const base::android::RegistrationMethod kCronetRegisteredMethods[] = {
{"BaseAndroid", base::android::RegisterJni}, {"BaseAndroid", base::android::RegisterJni},
{"ChromiumUrlRequest", ChromiumUrlRequestRegisterJni},
{"ChromiumUrlRequestContext", ChromiumUrlRequestContextRegisterJni},
{"CronetBidirectionalStreamAdapter", {"CronetBidirectionalStreamAdapter",
CronetBidirectionalStreamAdapter::RegisterJni}, CronetBidirectionalStreamAdapter::RegisterJni},
{"CronetLibraryLoader", RegisterNativesImpl}, {"CronetLibraryLoader", RegisterNativesImpl},
......
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net.impl;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.util.Log;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.net.CronetEngine;
/**
* Provides context for the native HTTP operations.
* @deprecated Use {@link CronetEngine} instead.
*/
@JNINamespace("cronet")
@Deprecated
public class ChromiumUrlRequestContext {
private static final int LOG_NONE = 3; // LOG(FATAL), no VLOG.
private static final int LOG_DEBUG = -1; // LOG(FATAL...INFO), VLOG(1)
private static final int LOG_VERBOSE = -2; // LOG(FATAL...INFO), VLOG(2)
static final String LOG_TAG = "ChromiumNetwork";
/**
* Native adapter object, owned by ChromiumUrlRequestContext.
*/
private long mChromiumUrlRequestContextAdapter;
/**
* Constructor.
*/
protected ChromiumUrlRequestContext(
final Context context, String userAgent, CronetEngine.Builder config) {
CronetLibraryLoader.ensureInitialized(context, config);
mChromiumUrlRequestContextAdapter = nativeCreateRequestContextAdapter(userAgent,
getLoggingLevel(),
CronetUrlRequestContext.createNativeUrlRequestContextConfig(context, config));
if (mChromiumUrlRequestContextAdapter == 0) {
throw new NullPointerException("Context Adapter creation failed");
}
// Post a task to UI thread to init native Chromium URLRequestContext.
// TODO(xunjieli): This constructor is not supposed to be invoked on
// the main thread. Consider making the following code into a blocking
// API to handle the case where we are already on main thread.
Runnable task = new Runnable() {
public void run() {
nativeInitRequestContextOnMainThread(mChromiumUrlRequestContextAdapter);
}
};
new Handler(Looper.getMainLooper()).post(task);
}
/**
* Returns the version of this network stack formatted as N.N.N.N/X where
* N.N.N.N is the version of Chromium and X is the revision number.
*/
public static String getVersion() {
return ImplVersion.getVersion();
}
/**
* Initializes statistics recorder.
*/
public void initializeStatistics() {
nativeInitializeStatistics();
}
/**
* Gets current statistics recorded since |initializeStatistics| with
* |filter| as a substring as JSON text (an empty |filter| will include all
* registered histograms).
*/
public String getStatisticsJSON(String filter) {
return nativeGetStatisticsJSON(filter);
}
/**
* Starts NetLog logging to a file. The NetLog capture mode is either
* NetLogCaptureMode::Default() or NetLogCaptureMode::IncludeSocketBytes().
* The IncludeSocketBytes() mode includes basic events, user cookies,
* credentials and all transferred bytes in the log.
* @param fileName The complete file path. It must not be empty. If file
* exists, it is truncated before starting. If actively logging,
* this method is ignored.
* @param logAll {@code true} to use the
* NetLogCaptureMode::IncludeSocketBytes() logging level. If
* false, NetLogCaptureMode::Default() is used instead.
*/
public void startNetLogToFile(String fileName, boolean logAll) {
nativeStartNetLogToFile(mChromiumUrlRequestContextAdapter, fileName, logAll);
}
/**
* Stops NetLog logging and flushes file to disk. If a logging session is
* not in progress, this call is ignored.
*/
public void stopNetLog() {
nativeStopNetLog(mChromiumUrlRequestContextAdapter);
}
@CalledByNative
private void initNetworkThread() {
Thread.currentThread().setName("ChromiumNet");
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
@Override
protected void finalize() throws Throwable {
if (mChromiumUrlRequestContextAdapter != 0) {
nativeReleaseRequestContextAdapter(mChromiumUrlRequestContextAdapter);
}
super.finalize();
}
@VisibleForTesting
public long getUrlRequestContextAdapter() {
return mChromiumUrlRequestContextAdapter;
}
/**
* @return loggingLevel see {@link #LOG_NONE}, {@link #LOG_DEBUG} and
* {@link #LOG_VERBOSE}.
*/
private int getLoggingLevel() {
int loggingLevel;
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
loggingLevel = LOG_VERBOSE;
} else if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
loggingLevel = LOG_DEBUG;
} else {
loggingLevel = LOG_NONE;
}
return loggingLevel;
}
// Returns an instance ChromiumUrlRequestContextAdapter to be stored in
// mChromiumUrlRequestContextAdapter.
private native long nativeCreateRequestContextAdapter(
String userAgent, int loggingLevel, long config);
private native void nativeReleaseRequestContextAdapter(long chromiumUrlRequestContextAdapter);
private native void nativeInitializeStatistics();
private native String nativeGetStatisticsJSON(String filter);
private native void nativeStartNetLogToFile(
long chromiumUrlRequestContextAdapter, String fileName, boolean logAll);
private native void nativeStopNetLog(long chromiumUrlRequestContextAdapter);
private native void nativeInitRequestContextOnMainThread(long chromiumUrlRequestContextAdapter);
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net.impl;
import android.content.Context;
import android.os.Build;
import org.chromium.base.annotations.UsedByReflection;
import org.chromium.net.CronetEngine;
import org.chromium.net.HttpUrlRequestFactory;
import org.chromium.net.HttpUrlRequestListener;
import java.nio.channels.WritableByteChannel;
import java.util.Map;
/**
* Network request factory using the native http stack implementation.
* @deprecated Use {@link CronetEngine} instead.
*/
@UsedByReflection("HttpUrlRequestFactory.java")
@Deprecated
public class ChromiumUrlRequestFactory extends HttpUrlRequestFactory {
private ChromiumUrlRequestContext mRequestContext;
@UsedByReflection("HttpUrlRequestFactory.java")
public ChromiumUrlRequestFactory(Context context, CronetEngine.Builder config) {
if (isEnabled()) {
String userAgent = config.getUserAgent();
if (userAgent == null) {
// Cannot use config.getDefaultUserAgent() as config.mContext may be null.
userAgent = new CronetEngine.Builder(context).getDefaultUserAgent();
}
mRequestContext = new ChromiumUrlRequestContext(context, userAgent, config);
}
}
@Override
public boolean isEnabled() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
@Override
public String getName() {
return "Chromium/" + ChromiumUrlRequestContext.getVersion();
}
@Override
public ChromiumUrlRequest createRequest(String url, int requestPriority,
Map<String, String> headers, HttpUrlRequestListener listener) {
return new ChromiumUrlRequest(mRequestContext, url, requestPriority, headers, listener);
}
@Override
public ChromiumUrlRequest createRequest(String url, int requestPriority,
Map<String, String> headers, WritableByteChannel channel,
HttpUrlRequestListener listener) {
return new ChromiumUrlRequest(
mRequestContext, url, requestPriority, headers, channel, listener);
}
@Override
public void startNetLogToFile(String fileName, boolean logAll) {
mRequestContext.startNetLogToFile(fileName, logAll);
}
@Override
public void stopNetLog() {
mRequestContext.stopNetLog();
}
public ChromiumUrlRequestContext getRequestContext() {
return mRequestContext;
}
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import android.content.ContextWrapper;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.test.util.Feature;
import org.chromium.net.test.EmbeddedTestServer;
import java.util.HashMap;
/**
* Tests that make sure ChromiumUrlRequestContext initialization will not
* affect embedders' ability to make requests.
*/
@SuppressWarnings("deprecation")
public class ContextInitTest extends CronetTestBase {
private EmbeddedTestServer mTestServer;
private String mUrl;
private String mUrl404;
@Override
protected void setUp() throws Exception {
super.setUp();
mTestServer = EmbeddedTestServer.createAndStartDefaultServer(getContext());
mUrl = mTestServer.getURL("/echo?status=200");
mUrl404 = mTestServer.getURL("/echo?status=404");
}
@Override
protected void tearDown() throws Exception {
mTestServer.stopAndDestroyServer();
super.tearDown();
}
@SmallTest
@Feature({"Cronet"})
public void testInitFactoryAndStartRequest() {
CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit();
// Immediately make a request after initializing the factory.
HttpUrlRequestFactory factory = testFramework.initRequestFactory();
TestHttpUrlRequestListener listener = makeRequest(factory, mUrl);
listener.blockForComplete();
assertEquals(200, listener.mHttpStatusCode);
}
@SmallTest
@Feature({"Cronet"})
public void testInitFactoryStartRequestAndCancel() {
CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit();
// Make a request and cancel it after initializing the factory.
HttpUrlRequestFactory factory = testFramework.initRequestFactory();
HashMap<String, String> headers = new HashMap<String, String>();
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
HttpUrlRequest request = factory.createRequest(
mUrl, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
request.start();
request.cancel();
listener.blockForComplete();
assertEquals(0, listener.mHttpStatusCode);
}
@SmallTest
@Feature({"Cronet"})
public void testInitFactoryStartTwoRequests() throws Exception {
CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit();
// Make two request right after initializing the factory.
int[] statusCodes = {0, 0};
String[] urls = {mUrl, mUrl404};
HttpUrlRequestFactory factory = testFramework.initRequestFactory();
for (int i = 0; i < 2; i++) {
TestHttpUrlRequestListener listener = makeRequest(factory, urls[i]);
listener.blockForComplete();
statusCodes[i] = listener.mHttpStatusCode;
}
assertEquals(200, statusCodes[0]);
assertEquals(404, statusCodes[1]);
}
class RequestThread extends Thread {
public TestHttpUrlRequestListener mCallback;
final CronetTestFramework mTestFramework;
final String mUrl;
public RequestThread(CronetTestFramework testFramework, String url) {
mTestFramework = testFramework;
mUrl = url;
}
@Override
public void run() {
HttpUrlRequestFactory factory = mTestFramework.initRequestFactory();
mCallback = makeRequest(factory, mUrl);
mCallback.blockForComplete();
}
}
@SmallTest
@Feature({"Cronet"})
public void testInitTwoFactoriesSimultaneously() throws Exception {
final CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit();
RequestThread thread1 = new RequestThread(testFramework, mUrl);
RequestThread thread2 = new RequestThread(testFramework, mUrl404);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
assertEquals(200, thread1.mCallback.mHttpStatusCode);
assertEquals(404, thread2.mCallback.mHttpStatusCode);
}
@SmallTest
@Feature({"Cronet"})
public void testInitTwoFactoriesInSequence() throws Exception {
final CronetTestFramework testFramework = startCronetTestFrameworkAndSkipLibraryInit();
RequestThread thread1 = new RequestThread(testFramework, mUrl);
RequestThread thread2 = new RequestThread(testFramework, mUrl404);
thread1.start();
thread1.join();
thread2.start();
thread2.join();
assertEquals(200, thread1.mCallback.mHttpStatusCode);
assertEquals(404, thread2.mCallback.mHttpStatusCode);
}
// Helper function to make a request.
private TestHttpUrlRequestListener makeRequest(
HttpUrlRequestFactory factory, String url) {
HashMap<String, String> headers = new HashMap<String, String>();
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
HttpUrlRequest request = factory.createRequest(
url, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
request.start();
return listener;
}
@SmallTest
@Feature({"Cronet"})
public void testInitDifferentContexts() throws Exception {
// Test that concurrently instantiating ChromiumUrlRequestContext's upon
// various different versions of the same Android Context does not cause
// crashes like crbug.com/453845
final CronetTestFramework testFramework = startCronetTestFramework();
HttpUrlRequestFactory firstFactory = HttpUrlRequestFactory.createFactory(
getContext(), testFramework.getCronetEngineBuilder());
HttpUrlRequestFactory secondFactory = HttpUrlRequestFactory.createFactory(
getContext().getApplicationContext(), testFramework.getCronetEngineBuilder());
HttpUrlRequestFactory thirdFactory = HttpUrlRequestFactory.createFactory(
new ContextWrapper(getContext()), testFramework.getCronetEngineBuilder());
// Meager attempt to extend lifetimes to ensure they're concurrently
// alive.
firstFactory.getName();
secondFactory.getName();
thirdFactory.getName();
}
}
...@@ -78,18 +78,6 @@ public class CronetTestBase extends AndroidTestCase { ...@@ -78,18 +78,6 @@ public class CronetTestBase extends AndroidTestCase {
return mCronetTestFramework; return mCronetTestFramework;
} }
/**
* Starts the CronetTest framework for the legacy API.
* @param url if non-null, a request will be made with that url.
*/
protected CronetTestFramework startCronetTestFrameworkForLegacyApi(String url) {
String[] commandLineArgs = {
CronetTestFramework.LIBRARY_INIT_KEY, CronetTestFramework.LibraryInitType.LEGACY};
mCronetTestFramework =
startCronetTestFrameworkWithUrlAndCommandLineArgs(url, commandLineArgs);
return mCronetTestFramework;
}
/** /**
* Returns {@code true} when test is being run against system HttpURLConnection implementation. * Returns {@code true} when test is being run against system HttpURLConnection implementation.
*/ */
......
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import android.content.Context;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.PathUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.net.test.EmbeddedTestServer;
import java.io.File;
import java.util.HashMap;
/**
* Test for deprecated {@link HttpUrlRequest} API.
*/
@SuppressWarnings("deprecation")
public class CronetUrlTest extends CronetTestBase {
private EmbeddedTestServer mTestServer;
private String mUrl;
@Override
protected void setUp() throws Exception {
super.setUp();
mTestServer = EmbeddedTestServer.createAndStartDefaultServer(getContext());
mUrl = mTestServer.getURL("/echo?status=200");
}
@Override
protected void tearDown() throws Exception {
mTestServer.stopAndDestroyServer();
super.tearDown();
}
@SmallTest
@Feature({"Cronet"})
public void testLoadUrl() throws Exception {
CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);
// Make sure that the URL is set as expected.
assertEquals(mUrl, testFramework.getUrl());
assertEquals(200, testFramework.getHttpStatusCode());
}
@SmallTest
@Feature({"Cronet"})
public void testInvalidUrl() throws Exception {
CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi("127.0.0.1:8000");
// The load should fail.
assertEquals(0, testFramework.getHttpStatusCode());
}
@SmallTest
@Feature({"Cronet"})
public void testPostData() throws Exception {
String[] commandLineArgs = {CronetTestFramework.POST_DATA_KEY, "test",
CronetTestFramework.LIBRARY_INIT_KEY, CronetTestFramework.LibraryInitType.LEGACY};
CronetTestFramework testFramework =
startCronetTestFrameworkWithUrlAndCommandLineArgs(mUrl, commandLineArgs);
// Make sure that the URL is set as expected.
assertEquals(mUrl, testFramework.getUrl());
assertEquals(200, testFramework.getHttpStatusCode());
}
@SmallTest
@Feature({"Cronet"})
@OnlyRunNativeCronet // No NetLog from HttpURLConnection
public void testNetLog() throws Exception {
Context context = getContext();
File directory = new File(PathUtils.getDataDirectory());
File file = File.createTempFile("cronet", "json", directory);
HttpUrlRequestFactory factory = HttpUrlRequestFactory.createFactory(
context, new CronetEngine.Builder(null /*context*/).setLibraryName("cronet_tests"));
// Start NetLog immediately after the request context is created to make
// sure that the call won't crash the app even when the native request
// context is not fully initialized. See crbug.com/470196.
factory.startNetLogToFile(file.getPath(), false);
// Starts a request.
HashMap<String, String> headers = new HashMap<String, String>();
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
HttpUrlRequest request = factory.createRequest(
mUrl, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
request.start();
listener.blockForComplete();
factory.stopNetLog();
assertTrue(file.exists());
assertTrue(file.length() != 0);
assertTrue(file.delete());
assertTrue(!file.exists());
}
static class BadHttpUrlRequestListener extends TestHttpUrlRequestListener {
static final String THROW_TAG = "BadListener";
public BadHttpUrlRequestListener() {
}
@Override
public void onResponseStarted(HttpUrlRequest request) {
throw new NullPointerException(THROW_TAG);
}
}
@SmallTest
@Feature({"Cronet"})
public void testCalledByNativeException() throws Exception {
CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);
HashMap<String, String> headers = new HashMap<String, String>();
BadHttpUrlRequestListener listener = new BadHttpUrlRequestListener();
// Create request with bad listener to trigger an exception.
HttpUrlRequest request = testFramework.mRequestFactory.createRequest(
mUrl, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
request.start();
listener.blockForComplete();
assertTrue(request.isCanceled());
assertNotNull(request.getException());
assertEquals(BadHttpUrlRequestListener.THROW_TAG,
request.getException().getCause().getMessage());
}
@SmallTest
@Feature({"Cronet"})
public void testSetUploadDataWithNullContentType() throws Exception {
CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);
HashMap<String, String> headers = new HashMap<String, String>();
BadHttpUrlRequestListener listener = new BadHttpUrlRequestListener();
// Create request.
HttpUrlRequest request = testFramework.mRequestFactory.createRequest(
mUrl, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
byte[] uploadData = new byte[] {1, 2, 3};
try {
request.setUploadData(null, uploadData);
fail("setUploadData should throw on null content type");
} catch (NullPointerException e) {
// Nothing to do here.
}
}
@SmallTest
@Feature({"Cronet"})
public void testLegacyLoadUrl() throws Exception {
CronetEngine.Builder builder = new CronetEngine.Builder(getContext());
builder.enableLegacyMode(true);
CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);
// Make sure that the URL is set as expected.
assertEquals(mUrl, testFramework.getUrl());
assertEquals(200, testFramework.getHttpStatusCode());
}
@SmallTest
@Feature({"Cronet"})
public void testRequestHead() throws Exception {
CronetTestFramework testFramework = startCronetTestFrameworkForLegacyApi(mUrl);
HashMap<String, String> headers = new HashMap<String, String>();
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
// Create request.
HttpUrlRequest request = testFramework.mRequestFactory.createRequest(
mUrl, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
request.setHttpMethod("HEAD");
request.start();
listener.blockForComplete();
assertEquals(200, listener.mHttpStatusCode);
// HEAD requests do not get any response data and Content-Length must be
// ignored.
assertEquals(0, listener.mResponseAsBytes.length);
}
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import android.content.Context;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.test.util.Feature;
import org.chromium.net.CronetTestBase.OnlyRunNativeCronet;
import org.chromium.net.test.EmbeddedTestServer;
import java.io.File;
import java.util.HashMap;
import java.util.regex.Pattern;
/**
* Tests for {@link HttpUrlRequestFactory}
*/
@SuppressWarnings("deprecation")
public class HttpUrlRequestFactoryTest extends CronetTestBase {
private EmbeddedTestServer mTestServer;
private String mUrl;
@Override
protected void setUp() throws Exception {
super.setUp();
mTestServer = EmbeddedTestServer.createAndStartDefaultServer(getContext());
mUrl = mTestServer.getURL("/echo?status=200");
}
@Override
protected void tearDown() throws Exception {
mTestServer.stopAndDestroyServer();
super.tearDown();
}
@SmallTest
@Feature({"Cronet"})
public void testCreateFactory() throws Throwable {
CronetEngine.Builder builder = new CronetEngine.Builder(null /*context*/);
builder.enableQuic(true);
builder.addQuicHint("www.google.com", 443, 443);
builder.addQuicHint("www.youtube.com", 443, 443);
builder.setLibraryName("cronet_tests");
HttpUrlRequestFactory factory = HttpUrlRequestFactory.createFactory(getContext(), builder);
assertNotNull("Factory should be created", factory);
assertTrue("Factory should be Chromium/n.n.n.n@r but is "
+ factory.getName(),
Pattern.matches("Chromium/\\d+\\.\\d+\\.\\d+\\.\\d+@\\w+",
factory.getName()));
}
@SmallTest
@Feature({"Cronet"})
@OnlyRunNativeCronet
public void testCreateLegacyFactory() {
CronetEngine.Builder builder = new CronetEngine.Builder(null /*context*/);
builder.enableLegacyMode(true);
HttpUrlRequestFactory factory = HttpUrlRequestFactory.createFactory(getContext(), builder);
assertNotNull("Factory should be created", factory);
assertTrue("Factory should be HttpUrlConnection/n.n.n.n@r but is "
+ factory.getName(),
Pattern.matches(
"HttpUrlConnection/\\d+\\.\\d+\\.\\d+\\.\\d+@\\w+",
factory.getName()));
HashMap<String, String> headers = new HashMap<String, String>();
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
HttpUrlRequest request = factory.createRequest(mUrl, 0, headers, listener);
request.start();
listener.blockForComplete();
assertEquals(200, listener.mHttpStatusCode);
assertEquals("OK", listener.mHttpStatusText);
}
@SmallTest
@Feature({"Cronet"})
@OnlyRunNativeCronet
public void testCreateLegacyFactoryUsingUrlRequestContextConfig() {
CronetEngine.Builder builder = new CronetEngine.Builder(null /*context*/);
builder.enableLegacyMode(true);
HttpUrlRequestFactory factory = HttpUrlRequestFactory.createFactory(getContext(), builder);
assertNotNull("Factory should be created", factory);
assertTrue("Factory should be HttpUrlConnection/n.n.n.n@r but is "
+ factory.getName(),
Pattern.matches(
"HttpUrlConnection/\\d+\\.\\d+\\.\\d+\\.\\d+@\\w+",
factory.getName()));
HashMap<String, String> headers = new HashMap<String, String>();
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
HttpUrlRequest request = factory.createRequest(mUrl, 0, headers, listener);
request.start();
listener.blockForComplete();
assertEquals(200, listener.mHttpStatusCode);
assertEquals("OK", listener.mHttpStatusText);
}
@SmallTest
@Feature({"Cronet"})
public void testQuicHintHost() {
CronetEngine.Builder builder = new CronetEngine.Builder(null /*context*/);
builder.addQuicHint("www.google.com", 443, 443);
try {
builder.addQuicHint("https://www.google.com", 443, 443);
} catch (IllegalArgumentException e) {
return;
}
fail("IllegalArgumentException must be thrown");
}
@SmallTest
@Feature({"Cronet"})
public void testConfigUserAgent() throws Throwable {
CronetEngine.Builder builder = new CronetEngine.Builder(null /*context*/);
String userAgentName = "User-Agent";
String userAgentValue = "User-Agent-Value";
builder.setUserAgent(userAgentValue);
builder.setLibraryName("cronet_tests");
HttpUrlRequestFactory factory = HttpUrlRequestFactory.createFactory(getContext(), builder);
assertTrue(NativeTestServer.startNativeTestServer(getContext()));
String url = NativeTestServer.getEchoHeaderURL(userAgentName);
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
HashMap<String, String> headers = new HashMap<String, String>();
HttpUrlRequest request = factory.createRequest(
url, 0, headers, listener);
request.start();
listener.blockForComplete();
assertEquals(userAgentValue, listener.mResponseAsString);
NativeTestServer.shutdownNativeTestServer();
}
@SmallTest
@Feature({"Cronet"})
public void testConfigUserAgentLegacy() throws Throwable {
CronetEngine.Builder builder = new CronetEngine.Builder(null /*context*/);
String userAgentName = "User-Agent";
String userAgentValue = "User-Agent-Value";
builder.setUserAgent(userAgentValue);
builder.enableLegacyMode(true);
HttpUrlRequestFactory factory = HttpUrlRequestFactory.createFactory(getContext(), builder);
assertTrue("Factory should be HttpUrlConnection/n.n.n.n@r but is "
+ factory.getName(),
Pattern.matches(
"HttpUrlConnection/\\d+\\.\\d+\\.\\d+\\.\\d+@\\w+",
factory.getName()));
// Load test library for starting the native test server.
System.loadLibrary("cronet_tests");
assertTrue(NativeTestServer.startNativeTestServer(getContext()));
String url = NativeTestServer.getEchoHeaderURL(userAgentName);
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
HashMap<String, String> headers = new HashMap<String, String>();
HttpUrlRequest request = factory.createRequest(
url, 0, headers, listener);
request.start();
listener.blockForComplete();
assertEquals(userAgentValue, listener.mResponseAsString);
NativeTestServer.shutdownNativeTestServer();
}
@SmallTest
@Feature({"Cronet"})
public void testEnableHttpCache() {
CronetEngine.Builder builder = new CronetEngine.Builder(null /*context*/);
builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISABLED, 0);
builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_IN_MEMORY, 0);
try {
builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK, 0);
fail("IllegalArgumentException must be thrown");
} catch (IllegalArgumentException e) {
assertEquals("Storage path must be set", e.getMessage());
}
try {
builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK_NO_HTTP, 0);
fail("IllegalArgumentException must be thrown");
} catch (IllegalArgumentException e) {
assertEquals("Storage path must be set", e.getMessage());
}
// Create a new directory to hold the disk cache data.
File dir = getContext().getDir("disk_cache_dir", Context.MODE_PRIVATE);
String path = dir.getPath();
builder.setStoragePath(path);
builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK, 100);
builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_DISK_NO_HTTP, 100);
try {
builder.enableHttpCache(CronetEngine.Builder.HTTP_CACHE_IN_MEMORY, 0);
fail("IllegalArgumentException must be thrown");
} catch (IllegalArgumentException e) {
assertEquals("Storage path must not be set", e.getMessage());
}
assertTrue(dir.delete());
}
}
...@@ -6,7 +6,6 @@ package org.chromium.net; ...@@ -6,7 +6,6 @@ package org.chromium.net;
import android.os.ConditionVariable; import android.os.ConditionVariable;
import android.test.suitebuilder.annotation.LargeTest; import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.Log; import org.chromium.base.Log;
import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.base.annotations.SuppressFBWarnings;
...@@ -18,7 +17,6 @@ import java.io.File; ...@@ -18,7 +17,6 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
/** /**
...@@ -68,34 +66,6 @@ public class QuicTest extends CronetTestBase { ...@@ -68,34 +66,6 @@ public class QuicTest extends CronetTestBase {
super.tearDown(); super.tearDown();
} }
@SmallTest
@Feature({"Cronet"})
@SuppressWarnings("deprecation")
@OnlyRunNativeCronet
public void testQuicLoadUrl_LegacyAPI() throws Exception {
String[] commandLineArgs = {
CronetTestFramework.LIBRARY_INIT_KEY, CronetTestFramework.LibraryInitType.LEGACY};
mTestFramework = new CronetTestFramework(null, commandLineArgs, getContext(), mBuilder);
String quicURL = QuicTestServer.getServerURL() + "/simple.txt";
HashMap<String, String> headers = new HashMap<String, String>();
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
// Although the native stack races QUIC and SPDY for the first request,
// since there is no http server running on the corresponding TCP port,
// QUIC will always succeed with a 200 (see
// net::HttpStreamFactoryImpl::Request::OnStreamFailed).
HttpUrlRequest request = mTestFramework.mRequestFactory.createRequest(
quicURL, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
request.start();
listener.blockForComplete();
assertEquals(200, listener.mHttpStatusCode);
assertEquals(
"This is a simple text file served by QUIC.\n",
listener.mResponseAsString);
assertEquals("quic/1+spdy/3", listener.mNegotiatedProtocol);
}
@LargeTest @LargeTest
@Feature({"Cronet"}) @Feature({"Cronet"})
@OnlyRunNativeCronet @OnlyRunNativeCronet
......
...@@ -9,7 +9,6 @@ import android.test.suitebuilder.annotation.SmallTest; ...@@ -9,7 +9,6 @@ import android.test.suitebuilder.annotation.SmallTest;
import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.Feature;
import org.chromium.net.CronetTestBase.OnlyRunNativeCronet; import org.chromium.net.CronetTestBase.OnlyRunNativeCronet;
import org.chromium.net.impl.ChromiumUrlRequestFactory;
import org.chromium.net.impl.CronetUrlRequestContext; import org.chromium.net.impl.CronetUrlRequestContext;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -19,9 +18,7 @@ import java.io.FileReader; ...@@ -19,9 +18,7 @@ import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Tests Sdch support. * Tests Sdch support.
...@@ -34,13 +31,8 @@ public class SdchTest extends CronetTestBase { ...@@ -34,13 +31,8 @@ public class SdchTest extends CronetTestBase {
DISABLED, DISABLED,
} }
private enum Api {
LEGACY,
ASYNC,
}
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private void setUp(Sdch setting, Api api) throws JSONException { private void setUp(Sdch setting) throws JSONException {
List<String> commandLineArgs = new ArrayList<String>(); List<String> commandLineArgs = new ArrayList<String>();
commandLineArgs.add(CronetTestFramework.CACHE_KEY); commandLineArgs.add(CronetTestFramework.CACHE_KEY);
commandLineArgs.add(CronetTestFramework.CACHE_DISK); commandLineArgs.add(CronetTestFramework.CACHE_DISK);
...@@ -49,13 +41,8 @@ public class SdchTest extends CronetTestBase { ...@@ -49,13 +41,8 @@ public class SdchTest extends CronetTestBase {
commandLineArgs.add(CronetTestFramework.SDCH_ENABLE); commandLineArgs.add(CronetTestFramework.SDCH_ENABLE);
} }
if (api == Api.LEGACY) { commandLineArgs.add(CronetTestFramework.LIBRARY_INIT_KEY);
commandLineArgs.add(CronetTestFramework.LIBRARY_INIT_KEY); commandLineArgs.add(CronetTestFramework.LibraryInitType.CRONET);
commandLineArgs.add(CronetTestFramework.LibraryInitType.LEGACY);
} else {
commandLineArgs.add(CronetTestFramework.LIBRARY_INIT_KEY);
commandLineArgs.add(CronetTestFramework.LibraryInitType.CRONET);
}
String[] args = new String[commandLineArgs.size()]; String[] args = new String[commandLineArgs.size()];
CronetEngine.Builder builder = new CronetEngine.Builder(getContext()); CronetEngine.Builder builder = new CronetEngine.Builder(getContext());
...@@ -75,85 +62,15 @@ public class SdchTest extends CronetTestBase { ...@@ -75,85 +62,15 @@ public class SdchTest extends CronetTestBase {
super.tearDown(); super.tearDown();
} }
@SmallTest
@Feature({"Cronet"})
@SuppressWarnings("deprecation")
@OnlyRunNativeCronet
public void testSdchEnabled_LegacyApi() throws Exception {
setUp(Sdch.ENABLED, Api.LEGACY);
String targetUrl = NativeTestServer.getSdchURL() + "/sdch/test";
long contextAdapter =
getContextAdapter((ChromiumUrlRequestFactory) mTestFramework.mRequestFactory);
DictionaryAddedObserver observer =
new DictionaryAddedObserver(targetUrl, contextAdapter, true /** Legacy Api */);
// Make a request to /sdch/index which advertises the dictionary.
TestHttpUrlRequestListener listener1 =
startAndWaitForComplete_LegacyApi(mTestFramework.mRequestFactory,
NativeTestServer.getSdchURL() + "/sdch/index?q=LeQxM80O");
assertEquals(200, listener1.mHttpStatusCode);
assertEquals("This is an index page.\n", listener1.mResponseAsString);
assertEquals(Arrays.asList("/sdch/dict/LeQxM80O"),
listener1.mResponseHeaders.get("Get-Dictionary"));
observer.waitForDictionaryAdded();
// Make a request to fetch encoded response at /sdch/test.
TestHttpUrlRequestListener listener2 =
startAndWaitForComplete_LegacyApi(mTestFramework.mRequestFactory, targetUrl);
assertEquals(200, listener2.mHttpStatusCode);
assertEquals("The quick brown fox jumps over the lazy dog.\n", listener2.mResponseAsString);
}
@SmallTest
@Feature({"Cronet"})
@SuppressWarnings("deprecation")
@OnlyRunNativeCronet
public void testSdchDisabled_LegacyApi() throws Exception {
setUp(Sdch.DISABLED, Api.LEGACY);
// Make a request to /sdch/index.
// Since Sdch is not enabled, no dictionary should be advertised.
TestHttpUrlRequestListener listener =
startAndWaitForComplete_LegacyApi(mTestFramework.mRequestFactory,
NativeTestServer.getSdchURL() + "/sdch/index?q=LeQxM80O");
assertEquals(200, listener.mHttpStatusCode);
assertEquals("This is an index page.\n", listener.mResponseAsString);
assertEquals(null, listener.mResponseHeaders.get("Get-Dictionary"));
}
@SmallTest
@Feature({"Cronet"})
@SuppressWarnings("deprecation")
@OnlyRunNativeCronet
public void testDictionaryNotFound_LegacyApi() throws Exception {
setUp(Sdch.ENABLED, Api.LEGACY);
// Make a request to /sdch/index which advertises a bad dictionary that
// does not exist.
TestHttpUrlRequestListener listener1 =
startAndWaitForComplete_LegacyApi(mTestFramework.mRequestFactory,
NativeTestServer.getSdchURL() + "/sdch/index?q=NotFound");
assertEquals(200, listener1.mHttpStatusCode);
assertEquals("This is an index page.\n", listener1.mResponseAsString);
assertEquals(Arrays.asList("/sdch/dict/NotFound"),
listener1.mResponseHeaders.get("Get-Dictionary"));
// Make a request to fetch /sdch/test, and make sure request succeeds.
TestHttpUrlRequestListener listener2 = startAndWaitForComplete_LegacyApi(
mTestFramework.mRequestFactory, NativeTestServer.getSdchURL() + "/sdch/test");
assertEquals(200, listener2.mHttpStatusCode);
assertEquals("Sdch is not used.\n", listener2.mResponseAsString);
}
@SmallTest @SmallTest
@Feature({"Cronet"}) @Feature({"Cronet"})
@OnlyRunNativeCronet @OnlyRunNativeCronet
public void testSdchEnabled() throws Exception { public void testSdchEnabled() throws Exception {
setUp(Sdch.ENABLED, Api.ASYNC); setUp(Sdch.ENABLED);
String targetUrl = NativeTestServer.getSdchURL() + "/sdch/test"; String targetUrl = NativeTestServer.getSdchURL() + "/sdch/test";
long contextAdapter = long contextAdapter =
getContextAdapter((CronetUrlRequestContext) mTestFramework.mCronetEngine); getContextAdapter((CronetUrlRequestContext) mTestFramework.mCronetEngine);
DictionaryAddedObserver observer = DictionaryAddedObserver observer = new DictionaryAddedObserver(targetUrl, contextAdapter);
new DictionaryAddedObserver(targetUrl, contextAdapter, false /** Legacy Api */);
// Make a request to /sdch which advertises the dictionary. // Make a request to /sdch which advertises the dictionary.
TestUrlRequestCallback callback1 = startAndWaitForComplete(mTestFramework.mCronetEngine, TestUrlRequestCallback callback1 = startAndWaitForComplete(mTestFramework.mCronetEngine,
...@@ -184,7 +101,7 @@ public class SdchTest extends CronetTestBase { ...@@ -184,7 +101,7 @@ public class SdchTest extends CronetTestBase {
CronetUrlRequestContext newContext = (CronetUrlRequestContext) mTestFramework.mCronetEngine; CronetUrlRequestContext newContext = (CronetUrlRequestContext) mTestFramework.mCronetEngine;
long newContextAdapter = getContextAdapter(newContext); long newContextAdapter = getContextAdapter(newContext);
DictionaryAddedObserver newObserver = DictionaryAddedObserver newObserver =
new DictionaryAddedObserver(targetUrl, newContextAdapter, false /** Legacy Api */); new DictionaryAddedObserver(targetUrl, newContextAdapter);
newObserver.waitForDictionaryAdded(); newObserver.waitForDictionaryAdded();
// Make a request to fetch encoded response at /sdch/test. // Make a request to fetch encoded response at /sdch/test.
...@@ -197,7 +114,7 @@ public class SdchTest extends CronetTestBase { ...@@ -197,7 +114,7 @@ public class SdchTest extends CronetTestBase {
@Feature({"Cronet"}) @Feature({"Cronet"})
@OnlyRunNativeCronet @OnlyRunNativeCronet
public void testSdchDisabled() throws Exception { public void testSdchDisabled() throws Exception {
setUp(Sdch.DISABLED, Api.ASYNC); setUp(Sdch.DISABLED);
// Make a request to /sdch. // Make a request to /sdch.
// Since Sdch is not enabled, no dictionary should be advertised. // Since Sdch is not enabled, no dictionary should be advertised.
TestUrlRequestCallback callback = startAndWaitForComplete(mTestFramework.mCronetEngine, TestUrlRequestCallback callback = startAndWaitForComplete(mTestFramework.mCronetEngine,
...@@ -211,7 +128,7 @@ public class SdchTest extends CronetTestBase { ...@@ -211,7 +128,7 @@ public class SdchTest extends CronetTestBase {
@Feature({"Cronet"}) @Feature({"Cronet"})
@OnlyRunNativeCronet @OnlyRunNativeCronet
public void testDictionaryNotFound() throws Exception { public void testDictionaryNotFound() throws Exception {
setUp(Sdch.ENABLED, Api.ASYNC); setUp(Sdch.ENABLED);
// Make a request to /sdch/index which advertises a bad dictionary that // Make a request to /sdch/index which advertises a bad dictionary that
// does not exist. // does not exist.
TestUrlRequestCallback callback1 = startAndWaitForComplete(mTestFramework.mCronetEngine, TestUrlRequestCallback callback1 = startAndWaitForComplete(mTestFramework.mCronetEngine,
...@@ -231,8 +148,8 @@ public class SdchTest extends CronetTestBase { ...@@ -231,8 +148,8 @@ public class SdchTest extends CronetTestBase {
private static class DictionaryAddedObserver extends SdchObserver { private static class DictionaryAddedObserver extends SdchObserver {
ConditionVariable mBlock = new ConditionVariable(); ConditionVariable mBlock = new ConditionVariable();
public DictionaryAddedObserver(String targetUrl, long contextAdapter, boolean isLegacyAPI) { public DictionaryAddedObserver(String targetUrl, long contextAdapter) {
super(targetUrl, contextAdapter, isLegacyAPI); super(targetUrl, contextAdapter);
} }
@Override @Override
...@@ -248,27 +165,10 @@ public class SdchTest extends CronetTestBase { ...@@ -248,27 +165,10 @@ public class SdchTest extends CronetTestBase {
} }
} }
@SuppressWarnings("deprecation")
private long getContextAdapter(ChromiumUrlRequestFactory factory) {
return factory.getRequestContext().getUrlRequestContextAdapter();
}
private long getContextAdapter(CronetUrlRequestContext requestContext) { private long getContextAdapter(CronetUrlRequestContext requestContext) {
return requestContext.getUrlRequestContextAdapter(); return requestContext.getUrlRequestContextAdapter();
} }
@SuppressWarnings("deprecation")
private TestHttpUrlRequestListener startAndWaitForComplete_LegacyApi(
HttpUrlRequestFactory factory, String url) throws Exception {
Map<String, String> headers = new HashMap<String, String>();
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
HttpUrlRequest request = factory.createRequest(
url, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
request.start();
listener.blockForComplete();
return listener;
}
private TestUrlRequestCallback startAndWaitForComplete(CronetEngine cronetEngine, String url) private TestUrlRequestCallback startAndWaitForComplete(CronetEngine cronetEngine, String url)
throws Exception { throws Exception {
TestUrlRequestCallback callback = new TestUrlRequestCallback(); TestUrlRequestCallback callback = new TestUrlRequestCallback();
......
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
import android.os.ConditionVariable;
import android.util.Log;
import java.util.List;
import java.util.Map;
/**
* A HttpUrlRequestListener that saves the response from a HttpUrlRequest.
* This class is used in testing.
*/
@SuppressWarnings("deprecation")
public class TestHttpUrlRequestListener implements HttpUrlRequestListener {
public static final String TAG = "TestHttpUrlRequestListener";
public int mHttpStatusCode = 0;
public String mHttpStatusText;
public String mNegotiatedProtocol;
public String mUrl;
public byte[] mResponseAsBytes;
public String mResponseAsString;
public Exception mException;
public Map<String, List<String>> mResponseHeaders;
private final ConditionVariable mStarted = new ConditionVariable();
private final ConditionVariable mComplete = new ConditionVariable();
public TestHttpUrlRequestListener() {
}
@Override
public void onResponseStarted(HttpUrlRequest request) {
Log.i(TAG, "****** Response Started, content length is "
+ request.getContentLength());
Log.i(TAG, "*** Headers Are *** " + request.getAllHeaders());
mHttpStatusCode = request.getHttpStatusCode();
mHttpStatusText = request.getHttpStatusText();
mNegotiatedProtocol = request.getNegotiatedProtocol();
mResponseHeaders = request.getAllHeaders();
mStarted.open();
}
@Override
public void onRequestComplete(HttpUrlRequest request) {
mUrl = request.getUrl();
mException = request.getException();
if (mException != null) {
// When there is an exception, onResponseStarted is often not
// invoked (e.g. when request fails or redirects are disabled).
// Populate status code and text in this case.
mHttpStatusCode = request.getHttpStatusCode();
mHttpStatusText = request.getHttpStatusText();
if (mException.getMessage().equals("Request failed "
+ "because there were too many redirects or redirects have "
+ "been disabled")) {
mResponseHeaders = request.getAllHeaders();
}
} else {
// Read the response body if there is not an exception.
mResponseAsBytes = request.getResponseAsBytes();
mResponseAsString = new String(mResponseAsBytes);
}
mComplete.open();
Log.i(TAG, "****** Request Complete over " + mNegotiatedProtocol
+ ", status code is " + mHttpStatusCode);
}
/**
* Blocks until the response starts.
*/
public void blockForStart() {
mStarted.block();
}
/**
* Blocks until the request completes.
*/
public void blockForComplete() {
mComplete.block();
}
public void resetComplete() {
mComplete.close();
}
}
...@@ -12,7 +12,6 @@ ...@@ -12,7 +12,6 @@
#include "base/bind.h" #include "base/bind.h"
#include "base/macros.h" #include "base/macros.h"
#include "components/cronet/android/cronet_url_request_context_adapter.h" #include "components/cronet/android/cronet_url_request_context_adapter.h"
#include "components/cronet/android/url_request_context_adapter.h"
#include "jni/SdchObserver_jni.h" #include "jni/SdchObserver_jni.h"
#include "net/base/sdch_manager.h" #include "net/base/sdch_manager.h"
#include "net/base/sdch_observer.h" #include "net/base/sdch_observer.h"
...@@ -89,15 +88,6 @@ void AddSdchObserverOnNetworkThread( ...@@ -89,15 +88,6 @@ void AddSdchObserverOnNetworkThread(
context_adapter->GetURLRequestContext()); context_adapter->GetURLRequestContext());
} }
// TODO(xunjieli): Delete this once legacy API is removed.
void AddSdchObserverOnNetworkThreadLegacyAPI(
const GURL& target_url,
const base::android::ScopedJavaGlobalRef<jobject>& jsdch_observer_ref,
URLRequestContextAdapter* context_adapter) {
AddSdchObserverHelper(target_url, jsdch_observer_ref,
context_adapter->GetURLRequestContext());
}
} // namespace } // namespace
void AddSdchObserver(JNIEnv* env, void AddSdchObserver(JNIEnv* env,
...@@ -119,24 +109,6 @@ void AddSdchObserver(JNIEnv* env, ...@@ -119,24 +109,6 @@ void AddSdchObserver(JNIEnv* env,
jsdch_observer_ref, base::Unretained(context_adapter))); jsdch_observer_ref, base::Unretained(context_adapter)));
} }
void AddSdchObserverLegacyAPI(JNIEnv* env,
const JavaParamRef<jobject>& jsdch_observer,
const JavaParamRef<jstring>& jtarget_url,
jlong jadapter) {
base::android::ScopedJavaGlobalRef<jobject> jsdch_observer_ref;
// ScopedJavaGlobalRef do not hold onto the env reference, so it is safe to
// use it across threads. |AddSdchObserverHelper| will acquire a new
// JNIEnv before calling into Java.
jsdch_observer_ref.Reset(env, jsdch_observer);
GURL target_url(base::android::ConvertJavaStringToUTF8(env, jtarget_url));
URLRequestContextAdapter* context_adapter =
reinterpret_cast<URLRequestContextAdapter*>(jadapter);
context_adapter->PostTaskToNetworkThread(
FROM_HERE,
base::Bind(&AddSdchObserverOnNetworkThreadLegacyAPI, target_url,
jsdch_observer_ref, base::Unretained(context_adapter)));
}
bool RegisterSdchTestUtil(JNIEnv* env) { bool RegisterSdchTestUtil(JNIEnv* env) {
return RegisterNativesImpl(env); return RegisterNativesImpl(env);
} }
......
...@@ -5,7 +5,6 @@ ...@@ -5,7 +5,6 @@
package org.chromium.net; package org.chromium.net;
import android.content.Context; import android.content.Context;
import android.os.ConditionVariable;
import android.os.Environment; import android.os.Environment;
import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertEquals;
...@@ -15,13 +14,8 @@ import org.chromium.base.Log; ...@@ -15,13 +14,8 @@ import org.chromium.base.Log;
import org.chromium.base.PathUtils; import org.chromium.base.PathUtils;
import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.base.annotations.SuppressFBWarnings;
import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.InputStream;
import java.net.URLStreamHandlerFactory; import java.net.URLStreamHandlerFactory;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashMap;
/** /**
* Framework for testing Cronet. * Framework for testing Cronet.
...@@ -55,8 +49,6 @@ public class CronetTestFramework { ...@@ -55,8 +49,6 @@ public class CronetTestFramework {
public static final class LibraryInitType { public static final class LibraryInitType {
// Initializes Cronet Async API. // Initializes Cronet Async API.
public static final String CRONET = "cronet"; public static final String CRONET = "cronet";
// Initializes Cronet legacy API.
public static final String LEGACY = "legacy";
// Initializes Cronet HttpURLConnection API. // Initializes Cronet HttpURLConnection API.
public static final String HTTP_URL_CONNECTION = "http_url_connection"; public static final String HTTP_URL_CONNECTION = "http_url_connection";
// Do not initialize. // Do not initialize.
...@@ -67,39 +59,13 @@ public class CronetTestFramework { ...@@ -67,39 +59,13 @@ public class CronetTestFramework {
public URLStreamHandlerFactory mStreamHandlerFactory; public URLStreamHandlerFactory mStreamHandlerFactory;
public CronetEngine mCronetEngine; public CronetEngine mCronetEngine;
@SuppressWarnings("deprecation")
HttpUrlRequestFactory mRequestFactory;
private final String[] mCommandLine; private final String[] mCommandLine;
private final Context mContext; private final Context mContext;
private String mUrl;
private int mHttpStatusCode = 0;
// CronetEngine.Builder used for this activity. // CronetEngine.Builder used for this activity.
private CronetEngine.Builder mCronetEngineBuilder; private CronetEngine.Builder mCronetEngineBuilder;
@SuppressWarnings("deprecation")
private class TestHttpUrlRequestListener implements HttpUrlRequestListener {
private final ConditionVariable mComplete = new ConditionVariable();
public TestHttpUrlRequestListener() {}
@Override
public void onResponseStarted(HttpUrlRequest request) {
mHttpStatusCode = request.getHttpStatusCode();
}
@Override
public void onRequestComplete(HttpUrlRequest request) {
mComplete.open();
}
public void blockForComplete() {
mComplete.block();
}
}
// TODO(crbug.com/547160): Fix this findbugs error and remove the suppression. // TODO(crbug.com/547160): Fix this findbugs error and remove the suppression.
@SuppressFBWarnings("EI_EXPOSE_REP2") @SuppressFBWarnings("EI_EXPOSE_REP2")
public CronetTestFramework( public CronetTestFramework(
...@@ -128,12 +94,6 @@ public class CronetTestFramework { ...@@ -128,12 +94,6 @@ public class CronetTestFramework {
switch (initString) { switch (initString) {
case LibraryInitType.NONE: case LibraryInitType.NONE:
break; break;
case LibraryInitType.LEGACY:
mRequestFactory = initRequestFactory();
if (appUrl != null) {
startWithURL(appUrl);
}
break;
case LibraryInitType.HTTP_URL_CONNECTION: case LibraryInitType.HTTP_URL_CONNECTION:
mCronetEngine = initCronetEngine(); mCronetEngine = initCronetEngine();
mStreamHandlerFactory = mCronetEngine.createURLStreamHandlerFactory(); mStreamHandlerFactory = mCronetEngine.createURLStreamHandlerFactory();
...@@ -244,12 +204,6 @@ public class CronetTestFramework { ...@@ -244,12 +204,6 @@ public class CronetTestFramework {
return mCronetEngineBuilder.build(); return mCronetEngineBuilder.build();
} }
// Helper function to initialize request factory. Also used in testing.
@SuppressWarnings("deprecation")
public HttpUrlRequestFactory initRequestFactory() {
return HttpUrlRequestFactory.createFactory(mContext, mCronetEngineBuilder);
}
private String getCommandLineArg(String key) { private String getCommandLineArg(String key) {
if (mCommandLine != null) { if (mCommandLine != null) {
for (int i = 0; i < mCommandLine.length; ++i) { for (int i = 0; i < mCommandLine.length; ++i) {
...@@ -261,45 +215,7 @@ public class CronetTestFramework { ...@@ -261,45 +215,7 @@ public class CronetTestFramework {
return null; return null;
} }
@SuppressWarnings("deprecation")
private void applyCommandLineToHttpUrlRequest(HttpUrlRequest request) {
String postData = getCommandLineArg(POST_DATA_KEY);
if (postData != null) {
InputStream dataStream = new ByteArrayInputStream(postData.getBytes());
ReadableByteChannel dataChannel = Channels.newChannel(dataStream);
request.setUploadChannel("text/plain", dataChannel, postData.length());
request.setHttpMethod("POST");
}
}
@SuppressWarnings("deprecation")
public void startWithURL(String url) {
Log.i(TAG, "Cronet started: %s", url);
mUrl = url;
HashMap<String, String> headers = new HashMap<String, String>();
TestHttpUrlRequestListener listener = new TestHttpUrlRequestListener();
HttpUrlRequest request = mRequestFactory.createRequest(
url, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
applyCommandLineToHttpUrlRequest(request);
request.start();
listener.blockForComplete();
}
public String getUrl() {
return mUrl;
}
public int getHttpStatusCode() {
return mHttpStatusCode;
}
public void startNetLog() { public void startNetLog() {
if (mRequestFactory != null) {
mRequestFactory.startNetLogToFile(Environment.getExternalStorageDirectory().getPath()
+ "/cronet_sample_netlog_old_api.json",
false);
}
if (mCronetEngine != null) { if (mCronetEngine != null) {
mCronetEngine.startNetLogToFile(Environment.getExternalStorageDirectory().getPath() mCronetEngine.startNetLogToFile(Environment.getExternalStorageDirectory().getPath()
+ "/cronet_sample_netlog_new_api.json", + "/cronet_sample_netlog_new_api.json",
...@@ -308,9 +224,6 @@ public class CronetTestFramework { ...@@ -308,9 +224,6 @@ public class CronetTestFramework {
} }
public void stopNetLog() { public void stopNetLog() {
if (mRequestFactory != null) {
mRequestFactory.stopNetLog();
}
if (mCronetEngine != null) { if (mCronetEngine != null) {
mCronetEngine.stopNetLog(); mCronetEngine.stopNetLog();
} }
......
...@@ -24,14 +24,9 @@ public class SdchObserver { ...@@ -24,14 +24,9 @@ public class SdchObserver {
* Constructor. * Constructor.
* @param targetUrl the target url on which sdch encoding will be used. * @param targetUrl the target url on which sdch encoding will be used.
* @param contextAdapter the native context adapter to register the observer. * @param contextAdapter the native context adapter to register the observer.
* @param isLegacyApi whether legacy api is used.
*/ */
public SdchObserver(String targetUrl, long contextAdapter, boolean isLegacyAPI) { public SdchObserver(String targetUrl, long contextAdapter) {
if (isLegacyAPI) { nativeAddSdchObserver(targetUrl, contextAdapter);
nativeAddSdchObserverLegacyAPI(targetUrl, contextAdapter);
} else {
nativeAddSdchObserver(targetUrl, contextAdapter);
}
mAddBlock.block(); mAddBlock.block();
mAddBlock.close(); mAddBlock.close();
} }
...@@ -57,5 +52,4 @@ public class SdchObserver { ...@@ -57,5 +52,4 @@ public class SdchObserver {
} }
private native void nativeAddSdchObserver(String targetUrl, long contextAdapter); private native void nativeAddSdchObserver(String targetUrl, long contextAdapter);
private native void nativeAddSdchObserverLegacyAPI(String targetUrl, long contextAdapter);
} }
This diff is collapsed.
This diff is collapsed.
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_CRONET_ANDROID_URL_REQUEST_CONTEXT_ADAPTER_H_
#define COMPONENTS_CRONET_ANDROID_URL_REQUEST_CONTEXT_ADAPTER_H_
#include <memory>
#include <queue>
#include <string>
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/threading/thread.h"
#include "net/log/net_log.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
namespace net {
class WriteToFileNetLogObserver;
class ProxyConfigService;
class SdchOwner;
} // namespace net
namespace cronet {
struct URLRequestContextConfig;
typedef base::Callback<void(void)> RunAfterContextInitTask;
// Implementation of the Chromium NetLog observer interface.
class NetLogObserver : public net::NetLog::ThreadSafeObserver {
public:
NetLogObserver() {}
~NetLogObserver() override {}
void OnAddEntry(const net::NetLog::Entry& entry) override;
private:
DISALLOW_COPY_AND_ASSIGN(NetLogObserver);
};
// Fully configured |URLRequestContext|.
class URLRequestContextAdapter : public net::URLRequestContextGetter {
public:
class URLRequestContextAdapterDelegate
: public base::RefCountedThreadSafe<URLRequestContextAdapterDelegate> {
public:
virtual void OnContextInitialized(URLRequestContextAdapter* context) = 0;
protected:
friend class base::RefCountedThreadSafe<URLRequestContextAdapterDelegate>;
virtual ~URLRequestContextAdapterDelegate() {}
};
URLRequestContextAdapter(URLRequestContextAdapterDelegate* delegate,
std::string user_agent);
void Initialize(std::unique_ptr<URLRequestContextConfig> config);
// Posts a task that might depend on the context being initialized
// to the network thread.
void PostTaskToNetworkThread(const tracked_objects::Location& posted_from,
const RunAfterContextInitTask& callback);
// Runs a task that might depend on the context being initialized.
// This method should only be run on the network thread.
void RunTaskAfterContextInitOnNetworkThread(
const RunAfterContextInitTask& callback);
const std::string& GetUserAgent(const GURL& url) const;
bool load_disable_cache() const { return load_disable_cache_; }
// net::URLRequestContextGetter implementation:
net::URLRequestContext* GetURLRequestContext() override;
scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner()
const override;
void StartNetLogToFile(const std::string& file_name, bool log_all);
void StopNetLog();
// Called on main Java thread to initialize URLRequestContext.
void InitRequestContextOnMainThread();
private:
~URLRequestContextAdapter() override;
// Initializes |context_| on the Network thread.
void InitRequestContextOnNetworkThread();
// Helper function to start writing NetLog data to file. This should only be
// run after context is initialized.
void StartNetLogToFileHelper(const std::string& file_name, bool log_all);
// Helper function to stop writing NetLog data to file. This should only be
// run after context is initialized.
void StopNetLogHelper();
scoped_refptr<URLRequestContextAdapterDelegate> delegate_;
std::unique_ptr<net::URLRequestContext> context_;
std::string user_agent_;
bool load_disable_cache_;
base::Thread* network_thread_;
std::unique_ptr<NetLogObserver> net_log_observer_;
std::unique_ptr<net::WriteToFileNetLogObserver> write_to_file_observer_;
std::unique_ptr<net::ProxyConfigService> proxy_config_service_;
std::unique_ptr<net::SdchOwner> sdch_owner_;
std::unique_ptr<URLRequestContextConfig> config_;
// A queue of tasks that need to be run after context has been initialized.
std::queue<RunAfterContextInitTask> tasks_waiting_for_context_;
bool is_context_initialized_;
DISALLOW_COPY_AND_ASSIGN(URLRequestContextAdapter);
};
} // namespace cronet
#endif // COMPONENTS_CRONET_ANDROID_URL_REQUEST_CONTEXT_ADAPTER_H_
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment