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