Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / components / cronet / android / sample / src / org / chromium / cronet_sample_apk / CronetSampleActivity.java
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.
4
5 package org.chromium.cronet_sample_apk;
6
7 import android.app.Activity;
8 import android.app.AlertDialog;
9 import android.content.DialogInterface;
10 import android.content.Intent;
11 import android.os.Bundle;
12 import android.os.Environment;
13 import android.util.Log;
14 import android.widget.EditText;
15 import android.widget.Toast;
16
17 import org.chromium.net.HttpUrlRequest;
18 import org.chromium.net.HttpUrlRequestFactory;
19 import org.chromium.net.HttpUrlRequestFactoryConfig;
20 import org.chromium.net.HttpUrlRequestListener;
21
22 import java.io.ByteArrayInputStream;
23 import java.io.InputStream;
24
25 import java.nio.channels.Channels;
26 import java.nio.channels.ReadableByteChannel;
27 import java.util.HashMap;
28
29 /**
30  * Activity for managing the Cronet Sample.
31  */
32 public class CronetSampleActivity extends Activity {
33     private static final String TAG = "CronetSampleActivity";
34
35     public static final String COMMAND_LINE_ARGS_KEY = "commandLineArgs";
36
37     public static final String POST_DATA_KEY = "postData";
38     public static final String CONFIG_KEY = "config";
39
40     HttpUrlRequestFactory mRequestFactory;
41
42     String mUrl;
43
44     boolean mLoading = false;
45
46     int mHttpStatusCode = 0;
47
48     class SampleHttpUrlRequestListener implements HttpUrlRequestListener {
49         public SampleHttpUrlRequestListener() {
50         }
51
52         @Override
53         public void onResponseStarted(HttpUrlRequest request) {
54             Log.i(TAG, "****** Response Started, content length is "
55                     + request.getContentLength());
56             Log.i(TAG, "*** Headers Are *** " + request.getAllHeaders());
57         }
58
59         @Override
60         public void onRequestComplete(HttpUrlRequest request) {
61             Log.i(TAG, "****** Request Complete, status code is "
62                     + getHttpStatusCode());
63             Intent intent = new Intent(getApplicationContext(),
64                     CronetSampleActivity.class);
65             startActivity(intent);
66             final String url = request.getUrl();
67             final CharSequence text = "Completed " + request.getUrl() + " ("
68                     + request.getHttpStatusCode() + ")";
69             mHttpStatusCode = request.getHttpStatusCode();
70             CronetSampleActivity.this.runOnUiThread(new Runnable() {
71                 public void run() {
72                     mLoading = false;
73                     Toast toast = Toast.makeText(getApplicationContext(), text,
74                             Toast.LENGTH_SHORT);
75                     toast.show();
76                     promptForURL(url);
77                 }
78             });
79         }
80     }
81
82     @Override
83     protected void onCreate(final Bundle savedInstanceState) {
84         super.onCreate(savedInstanceState);
85
86         HttpUrlRequestFactoryConfig config = new HttpUrlRequestFactoryConfig();
87         config.enableHttpCache(HttpUrlRequestFactoryConfig.HttpCache.IN_MEMORY,
88                                100 * 1024)
89               .enableSPDY(true)
90               .enableQUIC(true);
91
92         // Override config if it is passed from the launcher.
93         String configString = getCommandLineArg(CONFIG_KEY);
94         if (configString != null) {
95             try {
96                 Log.i(TAG, "Using Config: " + configString);
97                 config = new HttpUrlRequestFactoryConfig(configString);
98             } catch (org.json.JSONException e) {
99                 Log.e(TAG, "Invalid Config.", e);
100                 finish();
101                 return;
102             }
103         }
104
105         mRequestFactory = HttpUrlRequestFactory.createFactory(
106                 getApplicationContext(), config);
107
108         String appUrl = getUrlFromIntent(getIntent());
109         if (appUrl == null) {
110             promptForURL("https://");
111         } else {
112             startWithURL(appUrl);
113         }
114     }
115
116     private void promptForURL(String url) {
117         Log.i(TAG, "No URL provided via intent, prompting user...");
118         AlertDialog.Builder alert = new AlertDialog.Builder(this);
119         alert.setTitle("Enter a URL");
120         alert.setMessage("Enter a URL");
121         final EditText input = new EditText(this);
122         input.setText(url);
123         alert.setView(input);
124         alert.setPositiveButton("Load", new DialogInterface.OnClickListener() {
125             public void onClick(DialogInterface dialog, int button) {
126                 String url = input.getText().toString();
127                 startWithURL(url);
128             }
129         });
130         alert.show();
131     }
132
133     private static String getUrlFromIntent(Intent intent) {
134         return intent != null ? intent.getDataString() : null;
135     }
136
137     private String getCommandLineArg(String key) {
138         Intent intent = getIntent();
139         Bundle extras = intent.getExtras();
140         Log.i(TAG, "Cronet extras: " + extras);
141         if (extras != null) {
142             String[] commandLine = extras.getStringArray(COMMAND_LINE_ARGS_KEY);
143             if (commandLine != null) {
144                 for (int i = 0; i < commandLine.length; ++i) {
145                     Log.i(TAG,
146                             "Cronet commandLine[" + i + "]=" + commandLine[i]);
147                     if (commandLine[i].equals(key)) {
148                         return commandLine[++i];
149                     }
150                 }
151             }
152         }
153         return null;
154     }
155
156     private void applyCommandLineToHttpUrlRequest(HttpUrlRequest request) {
157         String postData = getCommandLineArg(POST_DATA_KEY);
158         if (postData != null) {
159             InputStream dataStream = new ByteArrayInputStream(
160                     postData.getBytes());
161             ReadableByteChannel dataChannel = Channels.newChannel(dataStream);
162             request.setUploadChannel("text/plain", dataChannel,
163                     postData.length());
164             request.setHttpMethod("POST");
165         }
166     }
167
168     public void startWithURL(String url) {
169         Log.i(TAG, "Cronet started: " + url);
170         mUrl = url;
171         mLoading = true;
172
173         HashMap<String, String> headers = new HashMap<String, String>();
174         HttpUrlRequestListener listener = new SampleHttpUrlRequestListener();
175         HttpUrlRequest request = mRequestFactory.createRequest(
176                 url, HttpUrlRequest.REQUEST_PRIORITY_MEDIUM, headers, listener);
177         applyCommandLineToHttpUrlRequest(request);
178         request.start();
179     }
180
181     public String getUrl() {
182         return mUrl;
183     }
184
185     public boolean isLoading() {
186         return mLoading;
187     }
188
189     public int getHttpStatusCode() {
190         return mHttpStatusCode;
191     }
192
193     public void startNetLog() {
194         mRequestFactory.startNetLogToFile(
195                 Environment.getExternalStorageDirectory().getPath() +
196                         "/cronet_sample_netlog.json");
197     }
198
199     public void stopNetLog() {
200         mRequestFactory.stopNetLog();
201     }
202 }