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.
5 package org.xwalk.core;
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;
13 import java.io.InputStream;
14 import java.io.IOException;
16 import java.net.URISyntaxException;
17 import java.net.URLConnection;
18 import java.util.List;
20 import org.chromium.base.CalledByNativeUnchecked;
21 import org.chromium.base.JNINamespace;
24 * Implements the Java side of Android URL protocol jobs.
25 * See android_protocol_handler.cc.
27 @JNINamespace("xwalk")
28 class AndroidProtocolHandler {
29 private static final String TAG = "AndroidProtocolHandler";
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 = "//";
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.
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);
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);
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;
67 // path == "/" or path == ""
68 if (path.length() <= 1) return null;
70 return openAsset(context, appUriToFileUri(uri));
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(), "");
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);
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);
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);
111 private static int getValueType(Context context, int field_id) {
112 TypedValue value = new TypedValue();
113 context.getResources().getValue(field_id, value, true);
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);
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() +
135 // Drop the file extension.
136 assetName = assetName.split("\\.")[0];
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();
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);
150 Log.e(TAG, "Asset not of type string: " + uri);
153 } catch (ClassNotFoundException e) {
154 Log.e(TAG, "Unable to open resource URL: " + uri, e);
156 } catch (NoSuchFieldException e) {
157 Log.e(TAG, "Unable to open resource URL: " + uri, e);
159 } catch (IllegalAccessException e) {
160 Log.e(TAG, "Unable to open resource URL: " + uri, e);
165 private static InputStream openAsset(Context context, Uri uri) {
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);
175 private static InputStream openContent(Context context, Uri uri) {
176 assert(uri.getScheme().equals(CONTENT_SCHEME));
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);
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.
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);
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) {
217 // Fall back to sniffing the type from the stream.
219 return URLConnection.guessContentTypeFromStream(stream);
220 } catch (IOException e) {
226 * Get the package name of the current Activity.
227 * @param context The context manager.
228 * @return Package name.
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();
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.
241 private static Uri verifyUrl(String url) {
245 Uri uri = Uri.parse(url);
247 Log.e(TAG, "Malformed URL: " + url);
250 String path = uri.getPath();
251 if (path == null || path.length() == 0) {
252 Log.e(TAG, "URL does not have a path: " + url);
259 * Remove query parameters from a Uri.
260 * @param uri The input uri.
261 * @return The given uri without query parameters.
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();
274 * Set the context to be used for resolving resource queries.
275 * @param context Context to be used, or null for the default application
278 public static void setResourceContextForTesting(Context context) {
279 nativeSetResourceContextForTesting(context);
282 private static native void nativeSetResourceContextForTesting(Context context);
283 private static native String nativeGetAndroidAssetPath();
284 private static native String nativeGetAndroidResourcePath();