aboutsummaryrefslogtreecommitdiffstats
path: root/gson/src/test/java/org/onap/policy/common/gson/internal/DataAdapterFactory.java
blob: 2799d8ba8088eea484a1537057abc07e8ba907f0 (plain)
1
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/*
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.common.gson.internal;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Factory used with test Data.
 */
public class DataAdapterFactory implements TypeAdapterFactory {

    /**
     * Output of {@link #makeList()}, encoded as json.
     */
    public static final String ENCODED_LIST = "[{'id':100},{'id':101}]".replace('\'', '"');

    /**
     * Output of {@link #makeMap()}, encoded as json.
     */
    public static final String ENCODED_MAP = "'data-100':{'id':100},'data-101':{'id':101}".replace('\'', '"');

    /**
     * Object handled by this factory.
     */
    public static class Data {
        private int id;

        public Data() {
            super();
        }

        public Data(int id) {
            this.id = id;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Override
        public String toString() {
            return "Data [id=" + id + "]";
        }
    }

    /**
     * Object derived from Data.
     */
    public static class DerivedData extends Data {
        private String text;

        public DerivedData() {
            super();
        }

        public DerivedData(int id, String text) {
            super(id);
            this.text = text;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        @Override
        public String toString() {
            return "DerivedData [text=" + text + ", toString()=" + super.toString() + "]";
        }
    }

    /**
     * Set to {@code true} when {@link #write(JsonWriter, Data)} has been invoked.
     */
    private boolean dataWritten = false;

    /**
     * Set to {@code true} when {@link #read(JsonReader)} has been invoked.
     */
    private boolean dataRead = false;

    /**
     * Clears the flags that indicate that "read" or "write" has been invoked.
     */
    public void reset() {
        dataWritten = true;
        dataRead = true;
    }

    public boolean isDataWritten() {
        return dataWritten;
    }

    public boolean isDataRead() {
        return dataRead;
    }

    /**
     * Makes a list of Data.
     *
     * @return a new list of Data
     */
    public static List<Data> makeList() {
        List<Data> listField = new ArrayList<>();

        listField.add(new Data(100));
        listField.add(new Data(101));

        return listField;
    }

    /**
     * Makes an array of Data.
     *
     * @return a new array of Data
     */
    public static JsonArray makeArray() {
        JsonArray arr = new JsonArray();

        for (Data data : makeList()) {
            JsonObject json = new JsonObject();
            json.addProperty("id", data.getId());
            arr.add(json);
        }

        return arr;
    }

    /**
     * Makes a map of Data.
     *
     * @return a new map of Data
     */
    public static Map<String, List<Data>> makeMap() {
        Map<String, List<Data>> map = new TreeMap<>();

        for (Data data : makeList()) {
            map.put("data-" + data.getId(), Arrays.asList(data));
        }

        return map;
    }

    /**
     * Adds Data objects to a tree, mirroring {@link #makeMap()}.
     *
     * @param tree tree into which objects are to be added
     */
    public static void addToObject(JsonObject tree) {
        for (JsonElement ent : makeArray()) {
            JsonObject obj = ent.getAsJsonObject();
            JsonArray arr = new JsonArray();
            arr.add(obj);
            tree.add("data-" + obj.get("id").getAsString(), arr);
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        if (type.getRawType() == Data.class) {
            return (TypeAdapter<T>) new DataTypeAdapter(gson.getDelegateAdapter(this, TypeToken.get(Data.class)),
                            gson.getAdapter(JsonElement.class));
        }

        if (type.getRawType() == DerivedData.class) {
            return (TypeAdapter<T>) new DerivedDataTypeAdapter(
                            gson.getDelegateAdapter(this, TypeToken.get(DerivedData.class)),
                            gson.getAdapter(JsonElement.class));
        }

        return null;
    }

    /**
     * Adapter for "Data".
     */
    private class DataTypeAdapter extends TypeAdapter<Data> {
        private TypeAdapter<Data> delegate;
        private TypeAdapter<JsonElement> elementAdapter;

        /**
         * Constructs the object.
         *
         * @param delegate delegate adapter
         * @param elementAdapter element adapter
         */
        public DataTypeAdapter(TypeAdapter<Data> delegate, TypeAdapter<JsonElement> elementAdapter) {
            this.delegate = delegate;
            this.elementAdapter = elementAdapter;
        }

        @Override
        public void write(JsonWriter out, Data data) throws IOException {
            dataWritten = true;

            JsonElement tree = delegate.toJsonTree(data);

            if (tree.isJsonObject()) {
                JsonObject jsonObj = tree.getAsJsonObject();
                jsonObj.addProperty("id", data.getId());
            }

            elementAdapter.write(out, tree);
        }

        @Override
        public Data read(JsonReader in) throws IOException {
            dataRead = true;

            JsonElement tree = elementAdapter.read(in);
            Data data = delegate.fromJsonTree(tree);

            if (tree.isJsonObject()) {
                JsonObject jsonObj = tree.getAsJsonObject();
                data.setId(jsonObj.get("id").getAsInt());
            }

            return data;
        }
    }

    /**
     * Adapter for "DerivedData".
     */
    private class DerivedDataTypeAdapter extends TypeAdapter<DerivedData> {
        private TypeAdapter<DerivedData> delegate;
        private TypeAdapter<JsonElement> elementAdapter;

        /**
         * Constructs the object.
         *
         * @param delegate delegate adapter
         * @param elementAdapter element adapter
         */
        public DerivedDataTypeAdapter(TypeAdapter<DerivedData> delegate, TypeAdapter<JsonElement> elementAdapter) {
            this.delegate = delegate;
            this.elementAdapter = elementAdapter;
        }

        @Override
        public void write(JsonWriter out, DerivedData data) throws IOException {
            dataWritten = true;

            JsonElement tree = delegate.toJsonTree(data);

            if (tree.isJsonObject()) {
                JsonObject jsonObj = tree.getAsJsonObject();
                jsonObj.addProperty("id", data.getId());
                jsonObj.addProperty("text", data.getText());
            }

            elementAdapter.write(out, tree);
        }

        @Override
        public DerivedData read(JsonReader in) throws IOException {
            dataRead = true;

            JsonElement tree = elementAdapter.read(in);
            DerivedData data = delegate.fromJsonTree(tree);

            if (tree.isJsonObject()) {
                JsonObject jsonObj = tree.getAsJsonObject();
                data.setId(jsonObj.get("id").getAsInt());
                data.setText(jsonObj.get("text").getAsString());
            }

            return data;
        }
    }
}