-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGsonFileHandler.java
More file actions
80 lines (71 loc) · 2.7 KB
/
GsonFileHandler.java
File metadata and controls
80 lines (71 loc) · 2.7 KB
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
package net.theevilreaper.aves.file;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.minestom.server.utils.validate.Check;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
/**
* The class represents the implementation of the {@link FileHandler} for the {@link com.google.gson.Gson} library.
* @author theEvilReaper
* @version 1.0.0
* @since 1.1.0
* @deprecated This class is deprecated since version 1.9.0 and will be removed in a future release. Use {@link ModernGsonFileHandler} instead.
**/
@Deprecated(since = "1.9.0", forRemoval = true)
public final class GsonFileHandler implements FileHandler {
private final Gson gson;
/**
* Creates a new instance from the file handler.
*/
public GsonFileHandler() {
this.gson = new Gson();
}
/**
* Creates a new instance from the file handler.
* @param gson the gson instance to deserialize or serialize data
*/
public GsonFileHandler(Gson gson) {
this.gson = gson;
}
/**
* Saves a given object into a file.
* @param path The path where the file is located
* @param object The object to save
* @param <T> A generic type for the object value
*/
@Override
public <T> void save(Path path, T object) {
Check.argCondition(Files.isDirectory(path), "Unable to save a directory. Please check the used path");
try (var outputStream = Files.newBufferedWriter(path, UTF_8)) {
if (!Files.exists(path)) {
var file = Files.createFile(path).getFileName();
LOGGER.info("Created new file: {}", file);
}
gson.toJson(object, TypeToken.get(object.getClass()).getType(), outputStream);
} catch (IOException exception) {
LOGGER.warn("Unable to save file", exception);
}
}
/**
* Load a given file and parse to the give class.
* @param path is the where the file is located
* @param clazz is the generic class object
* @param <T> is generic type for the object value
* @return a {@link Optional} with the object instance
*/
@Override
public <T> Optional<T> load(Path path, Class<T> clazz) {
Check.argCondition(Files.isDirectory(path), "Unable to load a directory. Please check the used path");
if (!Files.exists(path)) {
return Optional.empty();
}
try (var reader = Files.newBufferedReader(path, UTF_8)) {
return Optional.ofNullable(gson.fromJson(reader, clazz));
} catch (IOException exception) {
LOGGER.warn("Unable to load file", exception);
}
return Optional.empty();
}
}