]> git.basschouten.com Git - openhab-addons.git/blob
2162ceab840486facd6e7635e4e94df3005c124c
[openhab-addons.git] /
1 /*
2  * Pulled from Stack Overflow answer located here: http://stackoverflow.com/a/11272452
3  * and placed in an appropriate package within this library.
4  */
5 package org.openhab.binding.lametrictime.api.common.impl.typeadapters.imported;
6
7 import java.io.IOException;
8 import java.io.ObjectStreamException;
9
10 import com.google.gson.Gson;
11 import com.google.gson.JsonElement;
12 import com.google.gson.TypeAdapter;
13 import com.google.gson.TypeAdapterFactory;
14 import com.google.gson.reflect.TypeToken;
15 import com.google.gson.stream.JsonReader;
16 import com.google.gson.stream.JsonWriter;
17
18 public abstract class CustomizedTypeAdapterFactory<C> implements TypeAdapterFactory
19 {
20     private final Class<C> customizedClass;
21
22     public CustomizedTypeAdapterFactory(Class<C> customizedClass)
23     {
24         this.customizedClass = customizedClass;
25     }
26
27     @Override
28     @SuppressWarnings("unchecked") // we use a runtime check to guarantee that 'C' and 'T' are equal
29     public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type)
30     {
31         return type.getRawType() == customizedClass
32                 ? (TypeAdapter<T>)customizeMyClassAdapter(gson, (TypeToken<C>)type)
33                 : null;
34     }
35
36     private TypeAdapter<C> customizeMyClassAdapter(Gson gson, TypeToken<C> type)
37     {
38         final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
39         final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
40         return new TypeAdapter<C>()
41         {
42             @Override
43             public void write(JsonWriter out, C value) throws IOException
44             {
45                 JsonElement tree = delegate.toJsonTree(value);
46                 beforeWrite(value, tree);
47                 elementAdapter.write(out, tree);
48             }
49
50             @Override
51             public C read(JsonReader in) throws IOException
52             {
53                 JsonElement tree = elementAdapter.read(in);
54                 afterRead(tree);
55                 if (tree == null) {
56                     throw new IOException("null reader");
57                 }
58                 return delegate.fromJsonTree(tree);
59             }
60         };
61     }
62
63     /**
64      * Override this to muck with {@code toSerialize} before it is written to
65      * the outgoing JSON stream.
66      */
67     protected void beforeWrite(C source, JsonElement toSerialize)
68     {
69     }
70
71     /**
72      * Override this to muck with {@code deserialized} before it parsed into the
73      * application type.
74      */
75     protected void afterRead(JsonElement deserialized)
76     {
77     }
78 }