aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/net/sowgro/npehero/main/JSONFile.java
blob: ed76369fc0694adef7d1496622e8859886613dad (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package net.sowgro.npehero.main;

import net.sowgro.npehero.Driver;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.*;

/**
 * An ergonomic JSON API wrapper inspired by the Bukkit YAML API
 */
public class JSONFile {

    private final File file;
    private JSONObject jsonObject = new JSONObject();

    public JSONFile(File file) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        this.file = file;
    }

    public String getString(String key, String def) {
        if (!jsonObject.containsKey(key)) {
            return def;
        }
        return jsonObject.get(key).toString();
    }

    public int getInt(String key, int def) {
        if (!jsonObject.containsKey(key)) {
            return def;
        }
        try {
            return Integer.parseInt(jsonObject.get(key).toString());
        }
        catch (NumberFormatException e) {
            return def;
        }
    }

    public double getDouble(String key, double def) {
        if (jsonObject.containsKey(key)) {
            try {
                return Double.parseDouble(jsonObject.get(key).toString());
            }
            catch (NumberFormatException e) {
                return def;
            }
        }
        else {
            return def;
        }
    }

    public boolean getBoolean(String key, boolean def) {
        if (!jsonObject.containsKey(key)) {
            return def;
        }
        try {
            return Boolean.parseBoolean(jsonObject.get(key).toString());
        }
        catch (NumberFormatException e) {
            return def;
        }
    }

    public void set(String key, Object value) {
        if (value == null) {
            return;
        }
        jsonObject.put(key, value);
    }

    public boolean containsKey(String key) {
        return jsonObject.containsKey(key);
    }

    public void read() throws Exception {
        try {
            if (file.length() == 0) {
                return;
            }
            FileReader fileReader = new FileReader(file);
            jsonObject = (JSONObject) new JSONParser().parse(fileReader);
        }
        catch (Exception e) {
            throw e;
        }
    }

    public void write() throws IOException {
        FileWriter fileWriter = new FileWriter(file);
        jsonObject.writeJSONString(fileWriter);
        fileWriter.close();
    }

}