View Javadoc
1   package fr.ifremer.quadrige2.core.dao.technical.gson;
2   
3   /*-
4    * #%L
5    * Quadrige2 Core :: Quadrige2 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.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   * <p>Gsons class.</p>
49   */
50  public class Gsons {
51  
52      /**
53       * Constant <code>DATE_PATTERN="yyyy-MM-dd'T'HH:mm:ss.SSSX"</code>
54       * With timezone and milliseconds
55       */
56      public static final String DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
57  
58      /**
59       * <p>newBuilder.</p>
60       *
61       * @return a {@link com.google.gson.GsonBuilder} object.
62       */
63      public static GsonBuilder newBuilder(TimeZone timezone) {
64          return new GsonBuilder()
65                  // make sure date will be serialized
66                  .setDateFormat(DATE_PATTERN)
67                  // Register special case for Timestamp - mantis #36465
68                  .registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter(DATE_PATTERN, timezone))
69                  // Register Multimap adapter
70                  .registerTypeAdapter(Multimap.class, new MultimapTypeAdapter());
71      }
72  
73      /**
74       * <p>newBuilder.</p>
75       *
76       * @return a {@link com.google.gson.GsonBuilder} object.
77       */
78      public static GsonBuilder newBuilder() {
79          return newBuilder(TimeZone.getDefault());
80      }
81  
82  
83      /**
84       * <p>deserializeFile.</p>
85       *
86       * @param file a {@link java.io.File} object.
87       * @param clazz      a {@link java.lang.Class} object.
88       * @param <T>        a T object.
89       * @return a T object.
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 }