Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / cronet / android / test / src / org / chromium / net / CronetTestActivity.java
blob956cbacf3d2230a1f912e21dd19d3c39f6ada4bc
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 package org.chromium.net;
7 import android.app.Activity;
8 import android.content.Intent;
9 import android.os.Bundle;
10 import android.os.Environment;
12 import static junit.framework.Assert.assertEquals;
13 import static junit.framework.Assert.assertTrue;
15 import org.chromium.base.Log;
16 import org.chromium.base.PathUtils;
17 import org.chromium.base.annotations.SuppressFBWarnings;
18 import org.chromium.net.urlconnection.CronetURLStreamHandlerFactory;
20 import java.io.ByteArrayInputStream;
21 import java.io.File;
22 import java.io.InputStream;
24 import java.nio.channels.Channels;
25 import java.nio.channels.ReadableByteChannel;
26 import java.util.HashMap;
28 /**
29 * Activity for managing the Cronet Test.
31 @SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
32 public class CronetTestActivity extends Activity {
33 private static final String TAG = "CronetTestActivity";
35 public static final String COMMAND_LINE_ARGS_KEY = "commandLineArgs";
36 public static final String POST_DATA_KEY = "postData";
37 public static final String CONFIG_KEY = "config";
38 public static final String CACHE_KEY = "cache";
39 public static final String SDCH_KEY = "sdch";
41 public static final String LIBRARY_INIT_KEY = "libraryInit";
42 /**
43 * Skips library initialization.
45 public static final String LIBRARY_INIT_SKIP = "skip";
47 // Uses disk cache.
48 public static final String CACHE_DISK = "disk";
50 // Uses disk cache but does not store http data.
51 public static final String CACHE_DISK_NO_HTTP = "diskNoHttp";
53 // Uses in-memory cache.
54 public static final String CACHE_IN_MEMORY = "memory";
56 // Enables Sdch.
57 public static final String SDCH_ENABLE = "enable";
59 /**
60 * Initializes Cronet Async API only.
62 public static final String LIBRARY_INIT_CRONET_ONLY = "cronetOnly";
64 /**
65 * Initializes Cronet HttpURLConnection Wrapper API.
67 public static final String LIBRARY_INIT_WRAPPER = "wrapperOnly";
69 public CronetURLStreamHandlerFactory mStreamHandlerFactory;
70 public UrlRequestContext mUrlRequestContext;
71 HttpUrlRequestFactory mRequestFactory;
72 @SuppressFBWarnings("URF_UNREAD_FIELD")
73 HistogramManager mHistogramManager;
75 String mUrl;
77 boolean mLoading = false;
79 int mHttpStatusCode = 0;
81 // UrlRequestContextConfig used for this activity.
82 private UrlRequestContextConfig mConfig;
84 class TestHttpUrlRequestListener implements HttpUrlRequestListener {
85 public TestHttpUrlRequestListener() {
88 @Override
89 public void onResponseStarted(HttpUrlRequest request) {
90 mHttpStatusCode = request.getHttpStatusCode();
93 @Override
94 public void onRequestComplete(HttpUrlRequest request) {
95 mLoading = false;
99 @Override
100 protected void onCreate(final Bundle savedInstanceState) {
101 super.onCreate(savedInstanceState);
102 prepareTestStorage();
104 // Print out extra arguments passed in starting this activity.
105 Intent intent = getIntent();
106 Bundle extras = intent.getExtras();
107 Log.i(TAG, "Cronet extras: " + extras);
108 if (extras != null) {
109 String[] commandLine = extras.getStringArray(COMMAND_LINE_ARGS_KEY);
110 if (commandLine != null) {
111 assertEquals(0, commandLine.length % 2);
112 for (int i = 0; i < commandLine.length / 2; i++) {
113 Log.i(TAG, "Cronet commandLine %s = %s", commandLine[i * 2],
114 commandLine[i * 2 + 1]);
119 // Initializes UrlRequestContextConfig from commandLine args.
120 mConfig = initializeContextConfig();
121 Log.i(TAG, "Using Config: " + mConfig.toString());
123 String initString = getCommandLineArg(LIBRARY_INIT_KEY);
124 if (LIBRARY_INIT_SKIP.equals(initString)) {
125 return;
128 if (LIBRARY_INIT_WRAPPER.equals(initString)) {
129 mStreamHandlerFactory =
130 new CronetURLStreamHandlerFactory(this, mConfig);
133 mUrlRequestContext = initRequestContext();
134 mHistogramManager = HistogramManager.createHistogramManager();
136 if (LIBRARY_INIT_CRONET_ONLY.equals(initString)) {
137 return;
140 mRequestFactory = initRequestFactory();
141 String appUrl = getUrlFromIntent(getIntent());
142 if (appUrl != null) {
143 startWithURL(appUrl);
148 * Prepares the path for the test storage (http cache, QUIC server info).
150 private void prepareTestStorage() {
151 File storage = new File(getTestStorage());
152 if (storage.exists()) {
153 assertTrue(recursiveDelete(storage));
155 assertTrue(storage.mkdir());
158 String getTestStorage() {
159 return PathUtils.getDataDirectory(getApplicationContext()) + "/test_storage";
162 @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
163 private boolean recursiveDelete(File path) {
164 if (path.isDirectory()) {
165 for (File c : path.listFiles()) {
166 if (!recursiveDelete(c)) {
167 return false;
171 return path.delete();
174 UrlRequestContextConfig getContextConfig() {
175 return mConfig;
178 private UrlRequestContextConfig initializeContextConfig() {
179 UrlRequestContextConfig config = new UrlRequestContextConfig();
180 config.enableHTTP2(true).enableQUIC(true);
182 // Override config if it is passed from the launcher.
183 String configString = getCommandLineArg(CONFIG_KEY);
184 if (configString != null) {
185 try {
186 config = new UrlRequestContextConfig(configString);
187 } catch (org.json.JSONException e) {
188 Log.e(TAG, "Invalid Config.", e);
189 finish();
190 return null;
194 String cacheString = getCommandLineArg(CACHE_KEY);
195 if (CACHE_DISK.equals(cacheString)) {
196 config.setStoragePath(getTestStorage());
197 config.enableHttpCache(UrlRequestContextConfig.HTTP_CACHE_DISK, 1000 * 1024);
198 } else if (CACHE_DISK_NO_HTTP.equals(cacheString)) {
199 config.setStoragePath(getTestStorage());
200 config.enableHttpCache(UrlRequestContextConfig.HTTP_CACHE_DISK_NO_HTTP, 1000 * 1024);
201 } else if (CACHE_IN_MEMORY.equals(cacheString)) {
202 config.enableHttpCache(UrlRequestContextConfig.HTTP_CACHE_IN_MEMORY, 100 * 1024);
205 String sdchString = getCommandLineArg(SDCH_KEY);
206 if (SDCH_ENABLE.equals(sdchString)) {
207 config.enableSDCH(true);
210 // Setting this here so it isn't overridden on the command line
211 config.setLibraryName("cronet_tests");
212 return config;
215 // Helper function to initialize request context. Also used in testing.
216 public UrlRequestContext initRequestContext() {
217 return UrlRequestContext.createContext(this, mConfig);
220 // Helper function to initialize request factory. Also used in testing.
221 public HttpUrlRequestFactory initRequestFactory() {
222 return HttpUrlRequestFactory.createFactory(this, mConfig);
225 private static String getUrlFromIntent(Intent intent) {
226 return intent != null ? intent.getDataString() : null;
229 private String getCommandLineArg(String key) {
230 Intent intent = getIntent();
231 Bundle extras = intent.getExtras();
232 if (extras != null) {
233 String[] commandLine = extras.getStringArray(COMMAND_LINE_ARGS_KEY);
234 if (commandLine != null) {
235 for (int i = 0; i < commandLine.length; ++i) {
236 if (commandLine[i].equals(key)) {
237 return commandLine[++i];
242 return null;
245 private void applyCommandLineToHttpUrlRequest(HttpUrlRequest request) {
246 String postData = getCommandLineArg(POST_DATA_KEY);
247 if (postData != null) {
248 InputStream dataStream = new ByteArrayInputStream(
249 postData.getBytes());
250 ReadableByteChannel dataChannel = Channels.newChannel(dataStream);
251 request.setUploadChannel("text/plain", dataChannel,
252 postData.length());
253 request.setHttpMethod("POST");
257 public void startWithURL(String url) {
258 Log.i(TAG, "Cronet started: " + url);
259 mUrl = url;
260 mLoading = true;
262 HashMap<String, String> headers = new HashMap<String, String>();
263 HttpUrlRequestListener listener = new TestHttpUrlRequestListener();
264 HttpUrlRequest request = mRequestFactory.createRequest(
265 url, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
266 applyCommandLineToHttpUrlRequest(request);
267 request.start();
270 public String getUrl() {
271 return mUrl;
274 public boolean isLoading() {
275 return mLoading;
278 public int getHttpStatusCode() {
279 return mHttpStatusCode;
282 public void startNetLog() {
283 if (mRequestFactory != null) {
284 mRequestFactory.startNetLogToFile(Environment.getExternalStorageDirectory().getPath()
285 + "/cronet_sample_netlog_old_api.json",
286 false);
288 if (mUrlRequestContext != null) {
289 mUrlRequestContext.startNetLogToFile(Environment.getExternalStorageDirectory().getPath()
290 + "/cronet_sample_netlog_new_api.json",
291 false);
295 public void stopNetLog() {
296 if (mRequestFactory != null) {
297 mRequestFactory.stopNetLog();
299 if (mUrlRequestContext != null) {
300 mUrlRequestContext.stopNetLog();