blob: 71d4df8aba35333b12a465c4950cf60df3925c56 [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;
Zhomart Mukhamejanov963e3ee2018-04-26 21:07:05 -070020import android.util.Log;
Zhomart Mukhamejanovf4d280c2018-04-17 13:20:22 -070021
22import com.example.android.systemupdatersample.UpdateConfig;
23
24import java.io.File;
25import java.nio.charset.StandardCharsets;
26import java.nio.file.Files;
27import java.nio.file.Paths;
28import java.util.ArrayList;
29import java.util.List;
30
31/**
32 * Utility class for working with json update configurations.
33 */
34public final class UpdateConfigs {
35
36 private static final String UPDATE_CONFIGS_ROOT = "configs/";
37
38 /**
39 * @param configs update configs
40 * @return list of names
41 */
42 public static String[] configsToNames(List<UpdateConfig> configs) {
43 return configs.stream().map(UpdateConfig::getName).toArray(String[]::new);
44 }
45
46 /**
47 * @param context app context
48 * @return configs root directory
49 */
50 public static String getConfigsRoot(Context context) {
51 return Paths.get(context.getFilesDir().toString(),
52 UPDATE_CONFIGS_ROOT).toString();
53 }
54
55 /**
56 * It parses only {@code .json} files.
57 *
58 * @param context application context
59 * @return list of configs from directory {@link UpdateConfigs#getConfigsRoot}
60 */
61 public static List<UpdateConfig> getUpdateConfigs(Context context) {
62 File root = new File(getConfigsRoot(context));
63 ArrayList<UpdateConfig> configs = new ArrayList<>();
64 if (!root.exists()) {
65 return configs;
66 }
67 for (final File f : root.listFiles()) {
68 if (!f.isDirectory() && f.getName().endsWith(".json")) {
69 try {
70 String json = new String(Files.readAllBytes(f.toPath()),
71 StandardCharsets.UTF_8);
72 configs.add(UpdateConfig.fromJson(json));
73 } catch (Exception e) {
Zhomart Mukhamejanov963e3ee2018-04-26 21:07:05 -070074 Log.e("UpdateConfigs", "Can't read/parse config file " + f.getName(), e);
Zhomart Mukhamejanovf4d280c2018-04-17 13:20:22 -070075 throw new RuntimeException(
76 "Can't read/parse config file " + f.getName(), e);
77 }
78 }
79 }
80 return configs;
81 }
82
83 private UpdateConfigs() {}
84}