Anthony Chen | 12aec30 | 2018-04-25 16:41:48 -0700 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | package com.android.car; |
| 18 | |
| 19 | import android.annotation.Nullable; |
| 20 | import android.annotation.RawRes; |
| 21 | import android.content.Context; |
| 22 | |
| 23 | import java.io.BufferedReader; |
| 24 | import java.io.IOException; |
| 25 | import java.io.InputStream; |
| 26 | import java.io.InputStreamReader; |
| 27 | import 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 | */ |
| 33 | public 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 | } |