57092293e8789c392c1328d8c541ba08c3a2fc08
[platform/framework/web/crosswalk.git] / src / xwalk / runtime / android / java / src / org / xwalk / runtime / XWalkManifestReader.java
1 // Copyright (c) 2013 Intel Corporation. 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.runtime;
6
7 import android.app.Activity;
8 import android.content.res.AssetManager;
9 import android.util.Log;
10
11 import java.io.IOException;
12 import java.io.InputStream;
13 import java.net.URI;
14 import java.net.URISyntaxException;
15
16 /**
17  * This internal class parses manifest.json of current app.
18  */
19 public class XWalkManifestReader {
20     private final static String TAG = "XWalkManifestReader";
21     private final static String ASSETS_FILE_PATH = "file:///android_asset/";
22     private final static String WWW_FOLDER = "www";
23     private final static String APP_SCHEME = "app";
24
25     private Activity mActivity;
26
27     public XWalkManifestReader(Activity activity) {
28         mActivity = activity;
29     }
30
31     public String read(String manifestPath) {
32         manifestPath = getAssetsPath(manifestPath);
33
34         String manifestString = null;
35         try {
36             manifestString = getAssetsFileContent(mActivity.getAssets(), manifestPath);
37         } catch (IOException e) {
38             throw new RuntimeException("Failed to read manifest.json", e);
39         }
40         return manifestString;
41     }
42
43     private String getAssetsFileContent(AssetManager assetManager, String fileName) throws IOException {
44         String result = "";
45         InputStream inputStream = null;
46         try {
47             inputStream = assetManager.open(fileName);
48             int size = inputStream.available();
49             byte[] buffer = new byte[size];
50             inputStream.read(buffer);
51             result = new String(buffer);
52         } finally {
53             if (inputStream != null) {
54                 inputStream.close();
55             }
56         }
57         return result;
58     }
59
60     private String getAssetsPath(String path) {
61         if (path == null || path.isEmpty()) {
62             return null;
63         }
64
65         String assetsPath;
66         URI uri = null;
67         try {
68             uri = new URI(path);
69         } catch (URISyntaxException e) {
70             Log.e(TAG, "Invalid manifest URI: " + path, e);
71         }
72
73         if (uri.getScheme().equals(APP_SCHEME)) {
74             assetsPath = WWW_FOLDER + uri.getPath();
75         } else if (path.startsWith(ASSETS_FILE_PATH)) {
76             assetsPath = path.substring(ASSETS_FILE_PATH.length());
77         } else {
78             assetsPath = null;
79         }
80
81         return assetsPath;
82     }
83 }