698e394f9d66415abc19e02f5f510ac4a514518d
[platform/framework/web/crosswalk.git] / src / xwalk / runtime / android / core / src / org / xwalk / core / AndroidProtocolHandler.java
1 // Copyright (c) 2012 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.xwalk.core;
6
7 import android.content.Context;
8 import android.content.res.AssetManager;
9 import android.net.Uri;
10 import android.util.Log;
11 import android.util.TypedValue;
12
13 import java.io.InputStream;
14 import java.io.IOException;
15 import java.net.URI;
16 import java.net.URISyntaxException;
17 import java.net.URLConnection;
18 import java.util.List;
19
20 import org.chromium.base.CalledByNativeUnchecked;
21 import org.chromium.base.JNINamespace;
22
23 /**
24  * Implements the Java side of Android URL protocol jobs.
25  * See android_protocol_handler.cc.
26  */
27 @JNINamespace("xwalk")
28 class AndroidProtocolHandler {
29     private static final String TAG = "AndroidProtocolHandler";
30
31     // Supported URL schemes. This needs to be kept in sync with
32     // clank/native/framework/chrome/url_request_android_job.cc.
33     public static final String FILE_SCHEME = "file";
34     private static final String CONTENT_SCHEME = "content";
35     public static final String APP_SCHEME = "app";
36     private static final String APP_SRC = "www";
37     private static final String SCHEME_SEPARATOR = "//";
38
39     /**
40      * Open an InputStream for an Android resource.
41      * @param context The context manager.
42      * @param url The url to load.
43      * @return An InputStream to the Android resource.
44      */
45     // TODO(bulach): this should have either a throw clause, or
46     // handle the exception in the java side rather than the native side.
47     @CalledByNativeUnchecked
48     public static InputStream open(Context context, String url) {
49         Uri uri = verifyUrl(url);
50         if (uri == null) {
51             return null;
52         }
53         String path = uri.getPath();
54         if (uri.getScheme().equals(FILE_SCHEME)) {
55             if (path.startsWith(nativeGetAndroidAssetPath())) {
56                 return openAsset(context, uri);
57             } else if (path.startsWith(nativeGetAndroidResourcePath())) {
58                 return openResource(context, uri);
59             }
60         } else if (uri.getScheme().equals(CONTENT_SCHEME)) {
61             return openContent(context, uri);
62         } else if (uri.getScheme().equals(APP_SCHEME)) {
63             // The host should be the same as the lower case of the package
64             // name, otherwise the resource request should be rejected.
65             if (!uri.getHost().equals(context.getPackageName().toLowerCase())) return null;
66
67             // path == "/" or path == ""
68             if (path.length() <= 1) return null;
69
70             return openAsset(context, appUriToFileUri(uri));
71         }
72
73         return null;
74     }
75
76     // Get the asset path of file:///android_asset/* url.
77     public static String getAssetPath(Uri uri) {
78         assert(uri.getScheme().equals(FILE_SCHEME));
79         assert(uri.getPath() != null);
80         assert(uri.getPath().startsWith(nativeGetAndroidAssetPath()));
81         String path = uri.getPath();
82         // Remove duplicate slashes and normalize the URL.
83         path = (new java.io.File(path)).getAbsolutePath();
84         return path.replaceFirst(nativeGetAndroidAssetPath(), "");
85     }
86
87     // Convert app uri to file uri to access the actual files in assets.
88     public static Uri appUriToFileUri(Uri uri) {
89         assert(uri.getScheme().equals(APP_SCHEME));
90         assert(uri.getPath() != null);
91
92         try {
93             URI fileUri = new URI(FILE_SCHEME, SCHEME_SEPARATOR +
94                 nativeGetAndroidAssetPath() + APP_SRC + uri.getPath(), null);
95             return Uri.parse(fileUri.normalize().toString());
96         } catch (URISyntaxException e) {
97             Log.e(TAG, "Unable to convert app URI to file URI: " + uri, e);
98             return null;
99         }
100     }
101
102     private static int getFieldId(Context context, String assetType, String assetName)
103         throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
104         Class<?> d = context.getClassLoader()
105             .loadClass(context.getPackageName() + ".R$" + assetType);
106         java.lang.reflect.Field field = d.getField(assetName);
107         int id = field.getInt(null);
108         return id;
109     }
110
111     private static int getValueType(Context context, int field_id) {
112       TypedValue value = new TypedValue();
113       context.getResources().getValue(field_id, value, true);
114       return value.type;
115     }
116
117     private static InputStream openResource(Context context, Uri uri) {
118         assert(uri.getScheme().equals(FILE_SCHEME));
119         assert(uri.getPath() != null);
120         assert(uri.getPath().startsWith(nativeGetAndroidResourcePath()));
121         // The path must be of the form "/android_res/asset_type/asset_name.ext".
122         List<String> pathSegments = uri.getPathSegments();
123         if (pathSegments.size() != 3) {
124             Log.e(TAG, "Incorrect resource path: " + uri);
125             return null;
126         }
127         String assetPath = pathSegments.get(0);
128         String assetType = pathSegments.get(1);
129         String assetName = pathSegments.get(2);
130         if (!("/" + assetPath + "/").equals(nativeGetAndroidResourcePath())) {
131             Log.e(TAG, "Resource path does not start with " + nativeGetAndroidResourcePath() +
132                   ": " + uri);
133             return null;
134         }
135         // Drop the file extension.
136         assetName = assetName.split("\\.")[0];
137         try {
138             // Use the application context for resolving the resource package name so that we do
139             // not use the browser's own resources. Note that if 'context' here belongs to the
140             // test suite, it does not have a separate application context. In that case we use
141             // the original context object directly.
142             if (context.getApplicationContext() != null) {
143                 context = context.getApplicationContext();
144             }
145             int field_id = getFieldId(context, assetType, assetName);
146             int value_type = getValueType(context, field_id);
147             if (value_type == TypedValue.TYPE_STRING) {
148                 return context.getResources().openRawResource(field_id);
149             } else {
150                 Log.e(TAG, "Asset not of type string: " + uri);
151                 return null;
152             }
153         } catch (ClassNotFoundException e) {
154             Log.e(TAG, "Unable to open resource URL: " + uri, e);
155             return null;
156         } catch (NoSuchFieldException e) {
157             Log.e(TAG, "Unable to open resource URL: " + uri, e);
158             return null;
159         } catch (IllegalAccessException e) {
160             Log.e(TAG, "Unable to open resource URL: " + uri, e);
161             return null;
162         }
163     }
164
165     private static InputStream openAsset(Context context, Uri uri) {
166         try {
167             AssetManager assets = context.getAssets();
168             return assets.open(getAssetPath(uri), AssetManager.ACCESS_STREAMING);
169         } catch (IOException e) {
170             Log.e(TAG, "Unable to open asset URL: " + uri);
171             return null;
172         }
173     }
174
175     private static InputStream openContent(Context context, Uri uri) {
176         assert(uri.getScheme().equals(CONTENT_SCHEME));
177         try {
178             // We strip the query parameters before opening the stream to
179             // ensure that the URL we try to load exactly matches the URL
180             // we have permission to read.
181             Uri baseUri = stripQueryParameters(uri);
182             return context.getContentResolver().openInputStream(baseUri);
183         } catch (Exception e) {
184             Log.e(TAG, "Unable to open content URL: " + uri);
185             return null;
186         }
187     }
188
189     /**
190      * Determine the mime type for an Android resource.
191      * @param context The context manager.
192      * @param stream The opened input stream which to examine.
193      * @param url The url from which the stream was opened.
194      * @return The mime type or null if the type is unknown.
195      */
196     // TODO(bulach): this should have either a throw clause, or
197     // handle the exception in the java side rather than the native side.
198     @CalledByNativeUnchecked
199     public static String getMimeType(Context context, InputStream stream, String url) {
200         Uri uri = verifyUrl(url);
201         if (uri == null) {
202             return null;
203         }
204         String path = uri.getPath();
205         // The content URL type can be queried directly.
206         if (uri.getScheme().equals(CONTENT_SCHEME)) {
207             return context.getContentResolver().getType(uri);
208         // Asset files may have a known extension.
209         } else if (uri.getScheme().equals(APP_SCHEME) ||
210                    uri.getScheme().equals(FILE_SCHEME) &&
211                    path.startsWith(nativeGetAndroidAssetPath())) {
212             String mimeType = URLConnection.guessContentTypeFromName(path);
213             if (mimeType != null) {
214                 return mimeType;
215             }
216         }
217         // Fall back to sniffing the type from the stream.
218         try {
219             return URLConnection.guessContentTypeFromStream(stream);
220         } catch (IOException e) {
221             return null;
222         }
223     }
224
225     /**
226      * Get the package name of the current Activity.
227      * @param context The context manager.
228      * @return Package name.
229      */
230     @CalledByNativeUnchecked
231     public static String getPackageName(Context context) {
232         // Make sure the context is the application context.
233         // Or it will get the wrong package name in shared mode.
234         return context.getPackageName();
235     }
236
237     /**
238      * Make sure the given string URL is correctly formed and parse it into a Uri.
239      * @return a Uri instance, or null if the URL was invalid.
240      */
241     private static Uri verifyUrl(String url) {
242         if (url == null) {
243             return null;
244         }
245         Uri uri = Uri.parse(url);
246         if (uri == null) {
247             Log.e(TAG, "Malformed URL: " + url);
248             return null;
249         }
250         String path = uri.getPath();
251         if (path == null || path.length() == 0) {
252             Log.e(TAG, "URL does not have a path: " + url);
253             return null;
254         }
255         return uri;
256     }
257
258     /**
259      * Remove query parameters from a Uri.
260      * @param uri The input uri.
261      * @return The given uri without query parameters.
262      */
263     private static Uri stripQueryParameters(Uri uri) {
264         assert(uri.getAuthority() != null);
265         assert(uri.getPath() != null);
266         Uri.Builder builder = new Uri.Builder();
267         builder.scheme(uri.getScheme());
268         builder.encodedAuthority(uri.getAuthority());
269         builder.encodedPath(uri.getPath());
270         return builder.build();
271     }
272
273     /**
274      * Set the context to be used for resolving resource queries.
275      * @param context Context to be used, or null for the default application
276      *                context.
277      */
278     public static void setResourceContextForTesting(Context context) {
279         nativeSetResourceContextForTesting(context);
280     }
281
282     private static native void nativeSetResourceContextForTesting(Context context);
283     private static native String nativeGetAndroidAssetPath();
284     private static native String nativeGetAndroidResourcePath();
285 }