Nav apraksta

AssetFilesystem.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing,
  11. software distributed under the License is distributed on an
  12. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13. KIND, either express or implied. See the License for the
  14. specific language governing permissions and limitations
  15. under the License.
  16. */
  17. package org.apache.cordova.file;
  18. import android.content.res.AssetManager;
  19. import android.net.Uri;
  20. import org.apache.cordova.CordovaResourceApi;
  21. import org.apache.cordova.LOG;
  22. import org.json.JSONArray;
  23. import org.json.JSONException;
  24. import org.json.JSONObject;
  25. import java.io.File;
  26. import java.io.FileNotFoundException;
  27. import java.io.IOException;
  28. import java.io.ObjectInputStream;
  29. import java.util.HashMap;
  30. import java.util.Map;
  31. public class AssetFilesystem extends Filesystem {
  32. private final AssetManager assetManager;
  33. // A custom gradle hook creates the cdvasset.manifest file, which speeds up asset listing a tonne.
  34. // See: http://stackoverflow.com/questions/16911558/android-assetmanager-list-incredibly-slow
  35. private static Object listCacheLock = new Object();
  36. private static boolean listCacheFromFile;
  37. private static Map<String, String[]> listCache;
  38. private static Map<String, Long> lengthCache;
  39. private static final String LOG_TAG = "AssetFilesystem";
  40. private void lazyInitCaches() {
  41. synchronized (listCacheLock) {
  42. if (listCache == null) {
  43. ObjectInputStream ois = null;
  44. try {
  45. ois = new ObjectInputStream(assetManager.open("cdvasset.manifest"));
  46. listCache = (Map<String, String[]>) ois.readObject();
  47. lengthCache = (Map<String, Long>) ois.readObject();
  48. listCacheFromFile = true;
  49. } catch (ClassNotFoundException e) {
  50. e.printStackTrace();
  51. } catch (IOException e) {
  52. // Asset manifest won't exist if the gradle hook isn't set up correctly.
  53. } finally {
  54. if (ois != null) {
  55. try {
  56. ois.close();
  57. } catch (IOException e) {
  58. LOG.d(LOG_TAG, e.getLocalizedMessage());
  59. }
  60. }
  61. }
  62. if (listCache == null) {
  63. LOG.w("AssetFilesystem", "Asset manifest not found. Recursive copies and directory listing will be slow.");
  64. listCache = new HashMap<String, String[]>();
  65. }
  66. }
  67. }
  68. }
  69. private String[] listAssets(String assetPath) throws IOException {
  70. if (assetPath.startsWith("/")) {
  71. assetPath = assetPath.substring(1);
  72. }
  73. if (assetPath.endsWith("/")) {
  74. assetPath = assetPath.substring(0, assetPath.length() - 1);
  75. }
  76. lazyInitCaches();
  77. String[] ret = listCache.get(assetPath);
  78. if (ret == null) {
  79. if (listCacheFromFile) {
  80. ret = new String[0];
  81. } else {
  82. ret = assetManager.list(assetPath);
  83. listCache.put(assetPath, ret);
  84. }
  85. }
  86. return ret;
  87. }
  88. private long getAssetSize(String assetPath) throws FileNotFoundException {
  89. if (assetPath.startsWith("/")) {
  90. assetPath = assetPath.substring(1);
  91. }
  92. lazyInitCaches();
  93. if (lengthCache != null) {
  94. Long ret = lengthCache.get(assetPath);
  95. if (ret == null) {
  96. throw new FileNotFoundException("Asset not found: " + assetPath);
  97. }
  98. return ret;
  99. }
  100. CordovaResourceApi.OpenForReadResult offr = null;
  101. try {
  102. offr = resourceApi.openForRead(nativeUriForFullPath(assetPath));
  103. long length = offr.length;
  104. if (length < 0) {
  105. // available() doesn't always yield the file size, but for assets it does.
  106. length = offr.inputStream.available();
  107. }
  108. return length;
  109. } catch (IOException e) {
  110. FileNotFoundException fnfe = new FileNotFoundException("File not found: " + assetPath);
  111. fnfe.initCause(e);
  112. throw fnfe;
  113. } finally {
  114. if (offr != null) {
  115. try {
  116. offr.inputStream.close();
  117. } catch (IOException e) {
  118. LOG.d(LOG_TAG, e.getLocalizedMessage());
  119. }
  120. }
  121. }
  122. }
  123. public AssetFilesystem(AssetManager assetManager, CordovaResourceApi resourceApi) {
  124. super(Uri.parse("file:///android_asset/"), "assets", resourceApi);
  125. this.assetManager = assetManager;
  126. }
  127. @Override
  128. public Uri toNativeUri(LocalFilesystemURL inputURL) {
  129. return nativeUriForFullPath(inputURL.path);
  130. }
  131. @Override
  132. public LocalFilesystemURL toLocalUri(Uri inputURL) {
  133. if (!"file".equals(inputURL.getScheme())) {
  134. return null;
  135. }
  136. File f = new File(inputURL.getPath());
  137. // Removes and duplicate /s (e.g. file:///a//b/c)
  138. Uri resolvedUri = Uri.fromFile(f);
  139. String rootUriNoTrailingSlash = rootUri.getEncodedPath();
  140. rootUriNoTrailingSlash = rootUriNoTrailingSlash.substring(0, rootUriNoTrailingSlash.length() - 1);
  141. if (!resolvedUri.getEncodedPath().startsWith(rootUriNoTrailingSlash)) {
  142. return null;
  143. }
  144. String subPath = resolvedUri.getEncodedPath().substring(rootUriNoTrailingSlash.length());
  145. // Strip leading slash
  146. if (!subPath.isEmpty()) {
  147. subPath = subPath.substring(1);
  148. }
  149. Uri.Builder b = new Uri.Builder()
  150. .scheme(LocalFilesystemURL.FILESYSTEM_PROTOCOL)
  151. .authority("localhost")
  152. .path(name);
  153. if (!subPath.isEmpty()) {
  154. b.appendEncodedPath(subPath);
  155. }
  156. if (isDirectory(subPath) || inputURL.getPath().endsWith("/")) {
  157. // Add trailing / for directories.
  158. b.appendEncodedPath("");
  159. }
  160. return LocalFilesystemURL.parse(b.build());
  161. }
  162. private boolean isDirectory(String assetPath) {
  163. try {
  164. return listAssets(assetPath).length != 0;
  165. } catch (IOException e) {
  166. return false;
  167. }
  168. }
  169. @Override
  170. public LocalFilesystemURL[] listChildren(LocalFilesystemURL inputURL) throws FileNotFoundException {
  171. String pathNoSlashes = inputURL.path.substring(1);
  172. if (pathNoSlashes.endsWith("/")) {
  173. pathNoSlashes = pathNoSlashes.substring(0, pathNoSlashes.length() - 1);
  174. }
  175. String[] files;
  176. try {
  177. files = listAssets(pathNoSlashes);
  178. } catch (IOException e) {
  179. FileNotFoundException fnfe = new FileNotFoundException();
  180. fnfe.initCause(e);
  181. throw fnfe;
  182. }
  183. LocalFilesystemURL[] entries = new LocalFilesystemURL[files.length];
  184. for (int i = 0; i < files.length; ++i) {
  185. entries[i] = localUrlforFullPath(new File(inputURL.path, files[i]).getPath());
  186. }
  187. return entries;
  188. }
  189. @Override
  190. public JSONObject getFileForLocalURL(LocalFilesystemURL inputURL,
  191. String path, JSONObject options, boolean directory)
  192. throws FileExistsException, IOException, TypeMismatchException, EncodingException, JSONException {
  193. if (options != null && options.optBoolean("create")) {
  194. throw new UnsupportedOperationException("Assets are read-only");
  195. }
  196. // Check whether the supplied path is absolute or relative
  197. if (directory && !path.endsWith("/")) {
  198. path += "/";
  199. }
  200. LocalFilesystemURL requestedURL;
  201. if (path.startsWith("/")) {
  202. requestedURL = localUrlforFullPath(normalizePath(path));
  203. } else {
  204. requestedURL = localUrlforFullPath(normalizePath(inputURL.path + "/" + path));
  205. }
  206. // Throws a FileNotFoundException if it doesn't exist.
  207. getFileMetadataForLocalURL(requestedURL);
  208. boolean isDir = isDirectory(requestedURL.path);
  209. if (directory && !isDir) {
  210. throw new TypeMismatchException("path doesn't exist or is file");
  211. } else if (!directory && isDir) {
  212. throw new TypeMismatchException("path doesn't exist or is directory");
  213. }
  214. // Return the directory
  215. return makeEntryForURL(requestedURL);
  216. }
  217. @Override
  218. public JSONObject getFileMetadataForLocalURL(LocalFilesystemURL inputURL) throws FileNotFoundException {
  219. JSONObject metadata = new JSONObject();
  220. long size = inputURL.isDirectory ? 0 : getAssetSize(inputURL.path);
  221. try {
  222. metadata.put("size", size);
  223. metadata.put("type", inputURL.isDirectory ? "text/directory" : resourceApi.getMimeType(toNativeUri(inputURL)));
  224. metadata.put("name", new File(inputURL.path).getName());
  225. metadata.put("fullPath", inputURL.path);
  226. metadata.put("lastModifiedDate", 0);
  227. } catch (JSONException e) {
  228. return null;
  229. }
  230. return metadata;
  231. }
  232. @Override
  233. public boolean canRemoveFileAtLocalURL(LocalFilesystemURL inputURL) {
  234. return false;
  235. }
  236. @Override
  237. long writeToFileAtURL(LocalFilesystemURL inputURL, String data, int offset, boolean isBinary) throws NoModificationAllowedException, IOException {
  238. throw new NoModificationAllowedException("Assets are read-only");
  239. }
  240. @Override
  241. long truncateFileAtURL(LocalFilesystemURL inputURL, long size) throws IOException, NoModificationAllowedException {
  242. throw new NoModificationAllowedException("Assets are read-only");
  243. }
  244. @Override
  245. String filesystemPathForURL(LocalFilesystemURL url) {
  246. return new File(rootUri.getPath(), url.path).toString();
  247. }
  248. @Override
  249. LocalFilesystemURL URLforFilesystemPath(String path) {
  250. return null;
  251. }
  252. @Override
  253. boolean removeFileAtLocalURL(LocalFilesystemURL inputURL) throws InvalidModificationException, NoModificationAllowedException {
  254. throw new NoModificationAllowedException("Assets are read-only");
  255. }
  256. @Override
  257. boolean recursiveRemoveFileAtLocalURL(LocalFilesystemURL inputURL) throws NoModificationAllowedException {
  258. throw new NoModificationAllowedException("Assets are read-only");
  259. }
  260. }