blob: 089f8b2f27c7c747ccf9f97dd2be98ec8a1b20cd [file] [log] [blame]
Zhomart Mukhamejanovf4d280c2018-04-17 13:20:22 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.example.android.systemupdatersample.util;
18
19import android.content.Context;
20
21import com.example.android.systemupdatersample.UpdateConfig;
22
23import java.io.File;
24import java.nio.charset.StandardCharsets;
25import java.nio.file.Files;
26import java.nio.file.Paths;
27import java.util.ArrayList;
28import java.util.List;
29
30/**
31 * Utility class for working with json update configurations.
32 */
33public final class UpdateConfigs {
34
35 private static final String UPDATE_CONFIGS_ROOT = "configs/";
36
37 /**
38 * @param configs update configs
39 * @return list of names
40 */
41 public static String[] configsToNames(List<UpdateConfig> configs) {
42 return configs.stream().map(UpdateConfig::getName).toArray(String[]::new);
43 }
44
45 /**
46 * @param context app context
47 * @return configs root directory
48 */
49 public static String getConfigsRoot(Context context) {
50 return Paths.get(context.getFilesDir().toString(),
51 UPDATE_CONFIGS_ROOT).toString();
52 }
53
54 /**
55 * It parses only {@code .json} files.
56 *
57 * @param context application context
58 * @return list of configs from directory {@link UpdateConfigs#getConfigsRoot}
59 */
60 public static List<UpdateConfig> getUpdateConfigs(Context context) {
61 File root = new File(getConfigsRoot(context));
62 ArrayList<UpdateConfig> configs = new ArrayList<>();
63 if (!root.exists()) {
64 return configs;
65 }
66 for (final File f : root.listFiles()) {
67 if (!f.isDirectory() && f.getName().endsWith(".json")) {
68 try {
69 String json = new String(Files.readAllBytes(f.toPath()),
70 StandardCharsets.UTF_8);
71 configs.add(UpdateConfig.fromJson(json));
72 } catch (Exception e) {
73 throw new RuntimeException(
74 "Can't read/parse config file " + f.getName(), e);
75 }
76 }
77 }
78 return configs;
79 }
80
81 private UpdateConfigs() {}
82}