blob: 2ab7c322eebb54088a775558cc25c83819184b81 [file] [log] [blame]
Anthony Chen12aec302018-04-25 16:41:48 -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.android.car;
18
19import android.annotation.Nullable;
20import android.annotation.RawRes;
21import android.content.Context;
22
23import java.io.BufferedReader;
24import java.io.IOException;
25import java.io.InputStream;
26import java.io.InputStreamReader;
27import java.io.Reader;
28
29/**
30 * An implementation of {@link com.android.car.CarConfigurationService.JsonReader} that will
31 * parse a JSON file on the system that is mapped to {@code R.raw.car_config}.
32 */
33public class JsonReaderImpl implements CarConfigurationService.JsonReader {
34 private static final int BUF_SIZE = 0x1000; // 2K chars (4K bytes)
35 private static final String JSON_FILE_ENCODING = "UTF-8";
36
37 /**
38 * Takes a resource file that is considered to be a JSON file and parses it into a String that
39 * is returned.
40 *
41 * @param resId The resource id pointing to the json file.
42 * @return A {@code String} representing the file contents, or {@code null} if
43 */
44 @Override
45 @Nullable
46 public String jsonFileToString(Context context, @RawRes int resId) {
47 InputStream is = context.getResources().openRawResource(resId);
48
49 // Note: this "try" will close the Reader, thus closing the associated InputStreamReader
50 // and InputStream.
51 try (Reader reader = new BufferedReader(new InputStreamReader(is, JSON_FILE_ENCODING))) {
52 char[] buffer = new char[BUF_SIZE];
53 StringBuilder stringBuilder = new StringBuilder();
54
55 int bufferedContent;
56 while ((bufferedContent = reader.read(buffer)) != -1) {
57 stringBuilder.append(buffer, /* offset= */ 0, bufferedContent);
58 }
59
60 return stringBuilder.toString();
61 } catch (IOException e) {
62 return null;
63 }
64 }
65}