0fb7edaf6e5eae861a607775767880eba22bdd3c
[chesshog-scanner.git] / src / main / java / org / hedgecode / chess / scanner / json / JSONSettingsBuilder.java
1 /*
2  * Copyright (c) 2019-2020. Developed by Hedgecode.
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 org.hedgecode.chess.scanner.json;
18
19 import java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStreamReader;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25
26 import org.hedgecode.chess.scanner.ChessHogScannerException;
27 import org.hedgecode.chess.scanner.Settings;
28 import org.hedgecode.chess.scanner.SettingsBuilder;
29
30 /**
31  * JSONSettingsBuilder
32  *
33  * @author Dmitry Samoshin aka gotty
34  */
35 public class JSONSettingsBuilder implements SettingsBuilder {
36
37     private static final String SETTINGS_RESOURCE_DIR = "/settings/";
38
39     private static final Gson GSON = new GsonBuilder().create();
40
41     @Override
42     public Settings build(String jsonFileName) throws ChessHogScannerException {
43         Settings settings;
44         try (BufferedReader jsonReader = new BufferedReader(
45                 new InputStreamReader(
46                         getClass().getResourceAsStream(
47                                 SETTINGS_RESOURCE_DIR.concat(jsonFileName)
48                         )
49                 )
50         )) {
51             settings = GSON.fromJson(
52                     jsonReader,
53                     JSONSettings.class
54             );
55         } catch (IOException cause) {
56             throw new ChessHogScannerException(
57                     String.format("Failed to get settings from resource file: %s", jsonFileName), cause
58             );
59         }
60         return settings;
61     }
62
63 }