• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors
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.net;
6 
7 import android.content.Context;
8 import android.content.res.AssetManager;
9 import java.io.File;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.nio.file.Files;
13 import java.nio.file.StandardCopyOption;
14 import java.util.ArrayDeque;
15 import java.util.ArrayList;
16 import java.util.List;
17 import java.util.Queue;
18 
19 /**
20  * Helper class to install test files. This moves the files to an accessible storage directory.
21  */
22 public final class TestFilesInstaller {
23     private static final String INSTALLED_PATH_SUFFIX = "cronet_test_data";
24 
25     /**
26      * Installs test files if files have not been installed.
27      */
installIfNeeded(Context context)28     public static void installIfNeeded(Context context) {
29         File testDataDir = new File(context.getCacheDir(), INSTALLED_PATH_SUFFIX);
30 
31         if (testDataDir.exists()) {
32             return;
33         }
34 
35         AssetManager assets = context.getAssets();
36         try {
37             for (String assetPath : listAllAssets(assets)) {
38                 File copiedAssetFile = new File(testDataDir, assetPath);
39                 copiedAssetFile.getParentFile().mkdirs();
40                 try (InputStream inputStream = assets.open(assetPath)) {
41                     Files.copy(inputStream, copiedAssetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
42                 }
43             }
44         } catch (IOException e) {
45             throw new AssertionError("Failed to copy test files", e);
46         }
47     }
48 
49     /**
50      * Returns the installed path of the test files.
51      */
getInstalledPath(Context context)52     public static String getInstalledPath(Context context) {
53         return new File(context.getCacheDir(), INSTALLED_PATH_SUFFIX).getAbsolutePath();
54     }
55 
listAllAssets(AssetManager assets)56     private static List<String> listAllAssets(AssetManager assets) throws IOException {
57         Queue<String> toProcess = new ArrayDeque<>();
58         toProcess.add("");
59         List<String> result = new ArrayList<>();
60         while (!toProcess.isEmpty()) {
61             String parent = toProcess.remove();
62             String[] children = assets.list(parent);
63             if (children.length > 0) {
64                 // It's a folder
65                 for (String child : children) {
66                     toProcess.add(new File(parent, child).toString());
67                 }
68             } else if (!parent.isEmpty()) {
69                 // It's a file
70                 result.add(parent);
71             } // Else it's the empty root folder, in which case do nothing
72         }
73         return result;
74     }
75 }
76