View Javadoc
1   package fr.ifremer.quadrige3.core.dao.technical.gson;
2   
3   /*-
4    * #%L
5    * Quadrige3 Core :: Quadrige3 Core Shared
6    * $Id:$
7    * $HeadURL:$
8    * %%
9    * Copyright (C) 2017 Ifremer
10   * %%
11   * This program is free software: you can redistribute it and/or modify
12   * it under the terms of the GNU Affero General Public License as published by
13   * the Free Software Foundation, either version 3 of the License, or
14   * (at your option) any later version.
15   *
16   * This program is distributed in the hope that it will be useful,
17   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   * GNU General Public License for more details.
20   *
21   * You should have received a copy of the GNU Affero General Public License
22   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23   * #L%
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   * <p>Gson utility class.</p>
48   */
49  public class Gsons {
50  
51      /**
52       * Constant <code>DATE_PATTERN="yyyy-MM-dd'T'HH:mm:ss.SSSX"</code>
53       * With timezone and milliseconds
54       */
55      static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
56  
57      /**
58       * <p>newBuilder.</p>
59       *
60       * @return a {@link com.google.gson.GsonBuilder} object.
61       */
62      public static GsonBuilder newBuilder(TimeZone timezone) {
63          return new GsonBuilder()
64                  // make sure date will be serialized
65                  .setDateFormat(DATE_PATTERN)
66                  // Register special case for Timestamp - mantis #36465
67                  .registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter(DATE_PATTERN, timezone))
68                  // Register Multimap adapter
69                  .registerTypeAdapter(Multimap.class, new MultimapTypeAdapter());
70      }
71  
72      /**
73       * <p>newBuilder.</p>
74       *
75       * @return a {@link com.google.gson.GsonBuilder} object.
76       */
77      public static GsonBuilder newBuilder() {
78          return newBuilder(TimeZone.getDefault());
79      }
80  
81      /**
82       * <p>deserializeFile.</p>
83       *
84       * @param file  a {@link java.io.File} object.
85       * @param clazz a {@link java.lang.Class} object.
86       * @param <T>   a T object.
87       * @return a T object.
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 }