1/*
2 * Copyright (C) 2012 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.caliper.json;
18
19import com.google.common.collect.ImmutableList;
20import com.google.common.collect.Lists;
21import com.google.gson.Gson;
22import com.google.gson.TypeAdapter;
23import com.google.gson.TypeAdapterFactory;
24import com.google.gson.reflect.TypeToken;
25import com.google.gson.stream.JsonReader;
26import com.google.gson.stream.JsonWriter;
27
28import java.io.IOException;
29import java.lang.reflect.ParameterizedType;
30import java.lang.reflect.Type;
31import java.util.ArrayList;
32import java.util.List;
33
34/**
35 * Serializes and deserializes {@link ImmutableList} instances using an {@link ArrayList} as an
36 * intermediary.
37 */
38final class ImmutableListTypeAdatperFactory implements TypeAdapterFactory {
39  @SuppressWarnings("unchecked")
40  @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
41    Type type = typeToken.getType();
42    if (typeToken.getRawType() != ImmutableList.class
43        || !(type instanceof ParameterizedType)) {
44      return null;
45    }
46
47    com.google.common.reflect.TypeToken<ImmutableList<?>> betterToken =
48        (com.google.common.reflect.TypeToken<ImmutableList<?>>)
49            com.google.common.reflect.TypeToken.of(typeToken.getType());
50    final TypeAdapter<ArrayList<?>> arrayListAdapter =
51        (TypeAdapter<ArrayList<?>>) gson.getAdapter(
52            TypeToken.get(betterToken.getSupertype(List.class).getSubtype(ArrayList.class)
53                .getType()));
54    return new TypeAdapter<T>() {
55      @Override public void write(JsonWriter out, T value) throws IOException {
56        ArrayList<?> arrayList = Lists.newArrayList((List<?>) value);
57        arrayListAdapter.write(out, arrayList);
58      }
59
60      @Override public T read(JsonReader in) throws IOException {
61        ArrayList<?> arrayList = arrayListAdapter.read(in);
62        return (T) ImmutableList.copyOf(arrayList);
63      }
64    };
65  }
66}
67