1 package fr.ifremer.quadrige3.core.dao.technical.gson;
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 import com.google.common.base.Charsets;
27 import com.google.common.collect.Multimap;
28 import com.google.gson.Gson;
29 import com.google.gson.GsonBuilder;
30 import com.google.gson.JsonIOException;
31 import com.google.gson.JsonSyntaxException;
32 import fr.ifremer.quadrige3.core.exception.QuadrigeTechnicalException;
33
34 import java.io.File;
35 import java.io.IOException;
36 import java.io.Reader;
37 import java.io.Writer;
38 import java.lang.reflect.Type;
39 import java.nio.file.Files;
40 import java.util.Date;
41 import java.util.Map;
42 import java.util.TimeZone;
43
44 import static org.nuiton.i18n.I18n.t;
45
46
47
48
49 public class Gsons {
50
51
52
53
54
55 static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
56
57
58
59
60
61
62 public static GsonBuilder newBuilder(TimeZone timezone) {
63 return new GsonBuilder()
64
65 .setDateFormat(DATE_PATTERN)
66
67 .registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter(DATE_PATTERN, timezone))
68
69 .registerTypeAdapter(Multimap.class, new MultimapTypeAdapter());
70 }
71
72
73
74
75
76
77 public static GsonBuilder newBuilder() {
78 return newBuilder(TimeZone.getDefault());
79 }
80
81
82
83
84
85
86
87
88
89 public static <T> T deserializeFile(File file, Class<T> clazz) {
90
91 return deserializeFile(file, clazz, null);
92 }
93
94 public static <T> T deserializeFile(File file, Class<T> clazz, Map<Type, Object> additionalTypeAdapter) {
95
96 T result;
97 if (!file.exists() || !file.isFile()) {
98 return null;
99 }
100
101 try (Reader reader = Files.newBufferedReader(file.toPath(), Charsets.UTF_8)) {
102
103 GsonBuilder gsonBuilder = newBuilder();
104 if (additionalTypeAdapter != null) {
105 for (Type type : additionalTypeAdapter.keySet()) {
106 gsonBuilder.registerTypeAdapter(type, additionalTypeAdapter.get(type));
107 }
108 }
109 result = gsonBuilder.create().fromJson(reader, clazz);
110
111 } catch (IOException | JsonSyntaxException | JsonIOException ex) {
112 throw new QuadrigeTechnicalException(t("quadrige3.error.read.file", file.getAbsolutePath(), ex.getMessage()), ex);
113 }
114
115 return result;
116 }
117
118 public static void serializeToFile(Object object, File file) {
119
120 try (Writer writer = Files.newBufferedWriter(file.toPath(), Charsets.UTF_8)) {
121
122 Gson gson = newBuilder().enableComplexMapKeySerialization().create();
123 gson.toJson(object, writer);
124
125 } catch (IOException | JsonIOException ex) {
126 throw new QuadrigeTechnicalException(t("quadrige3.error.write.file", file.getAbsolutePath(), ex.getMessage()), ex);
127 }
128 }
129 }