Example usage for com.google.gson.reflect TypeToken getRawType

List of usage examples for com.google.gson.reflect TypeToken getRawType

Introduction

In this page you can find the example usage for com.google.gson.reflect TypeToken getRawType.

Prototype

public final Class<? super T> getRawType() 

Source Link

Document

Returns the raw (non-generic) type for this type.

Usage

From source file:org.wso2.msf4j.internal.router.ParamConvertUtils.java

License:Open Source License

/**
 * Creates a converter function that converts value into a {@link List}, {@link Set} or {@link SortedSet}.
 *
 * @param resultType Result type//ww w  .  ja  v  a 2s . c  o m
 * @return A converter function or {@code null} if the given type is not a {@link ParameterizedType} with raw type
 * as {@link List}, {@link Set} or {@link SortedSet}. Also, for {@link SortedSet} type, if the element type
 * doesn't implements {@link Comparable}, {@code null} is returned.
 */
@SuppressWarnings("unchecked")
private static Function<List<String>, Object> createCollectionConverter(TypeToken<?> resultType) {
    final Class<?> rawType = resultType.getRawType();

    // Collection. It must be List or Set
    if (rawType != List.class && rawType != Set.class && rawType != SortedSet.class) {
        return null;
    }

    // Must be ParameterizedType
    if (!(resultType.getType() instanceof ParameterizedType)) {
        return null;
    }

    // Must have 1 type parameter
    ParameterizedType type = (ParameterizedType) resultType.getType();
    if (type.getActualTypeArguments().length != 1) {
        return null;
    }

    // For SortedSet, the entry type must be Comparable.
    Type elementType = type.getActualTypeArguments()[0];
    if (rawType == SortedSet.class
            && !Comparable.class.isAssignableFrom(TypeToken.get(elementType).getRawType())) {
        return null;
    }

    //We only support List type for java.io.File
    if (elementType == File.class && rawType != List.class) {
        throw new IllegalArgumentException("File doesn't support " + rawType);
    }

    // Get the converter for the collection element.
    final Function<List<String>, Object> elementConverter = createQueryParamConverter(elementType);

    return new Function<List<String>, Object>() {
        @Override
        public Object apply(List<String> values) {
            Collection<? extends Comparable> collection;
            if (rawType == List.class) {
                collection = new ArrayList<>();
            } else if (rawType == Set.class) {
                collection = new HashSet<>();
            } else {
                collection = new TreeSet<>();
            }

            if (values != null) {
                for (String value : values) {
                    add(collection, elementConverter.apply(Collections.singletonList(value)));
                }
            }
            return collection;
        }

        @SuppressWarnings("unchecked")
        private <T> void add(Collection<T> collection, Object element) {
            collection.add((T) element);
        }
    };
}

From source file:ro.cosu.vampires.server.util.gson.AutoValueAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  ww  w.  j  av  a  2s.com*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<? super T> rawType = type.getRawType();
    if (!rawType.isAnnotationPresent(AutoGson.class)) {
        return null;
    }

    String packageName = rawType.getPackage().getName();
    String className = rawType.getName().substring(packageName.length() + 1).replace('$', '_');
    String autoValueName = packageName + ".AutoValue_" + className;

    try {
        Class<?> autoValueType = Class.forName(autoValueName);
        return (TypeAdapter<T>) gson.getAdapter(autoValueType);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Could not load AutoValue providerType " + autoValueName, e);
    }
}

From source file:ro.cosu.vampires.server.util.gson.LowercaseEnumTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isEnum()) {
        return null;
    }//from   ww w  .  ja va 2  s . c  om

    final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
    for (T constant : rawType.getEnumConstants()) {
        lowercaseToConstant.put(toLowercase(constant), constant);
    }

    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(toLowercase(value));
            }
        }

        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            } else {
                return lowercaseToConstant.get(reader.nextString());
            }
        }
    };
}

From source file:ru.teamrocket.csrsysteamdesktop.Service.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (null == type || !baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }/*from ww  w  .ja v  a2  s.  c o m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                //throw new JsonParseException("cannot serialize " + srcType.getName()
                //        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    }.nullSafe();
}

From source file:saulmm.avengers.model.rest.CharacterItemAdapterFactory.java

License:Mozilla Public License

@Override
public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) {

    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

    final TypeAdapter<T> customTypeAdapter = new TypeAdapter<T>() {

        @Override//  ww  w.  j a v  a2s  . co m
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {

            JsonElement jsonElement = elementAdapter.read(in);

            if (type.getRawType() == saulmm.avengers.model.Character.class)
                return adaptJsonToCharacter(jsonElement, type);

            if (type.getRawType() == List.class)
                return adaptJsonToComic(jsonElement, type);

            return delegate.fromJsonTree(jsonElement);
        }

    }.nullSafe();

    return customTypeAdapter;
}

From source file:se.joelpet.android.toyreaderforreddit.gson.typeadapters.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*  w ww .  j a v  a 2 s.  co m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }

            // joep: take the "data" jsonElement
            return delegate.fromJsonTree(jsonElement.getAsJsonObject().remove("data"));
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    };
}

From source file:teste.adapter.ArrayAdapterFactory.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from   w  w  w.  j a  v a2 s  . co  m*/
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {

    TypeAdapter<T> typeAdapter = null;

    try {
        if (type.getRawType() == List.class)
            typeAdapter = new ArrayAdapter(
                    (Class) ((ParameterizedType) type.getType()).getActualTypeArguments()[0]);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return typeAdapter;

}

From source file:TestGenerator.ArgumentCache.UniversalCollectionTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();

    /// hack to obtain hidden constructorConstructor from gson - guarantees that gson has already initialized
    // and the original CollectionTypeAdapterFactory has been assigned the same constructorConstructor.
    if (constructorConstructor == null) {
        try {/*from  w ww .  ja v a  2s .c o m*/
            Field conf = gson.getClass().getDeclaredField("constructorConstructor");
            conf.setAccessible(true);
            constructorConstructor = (ConstructorConstructor) conf.get(gson);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
    Class<? super T> rawType = typeToken.getRawType();
    if (!Collection.class.isAssignableFrom(rawType)) {
        return null;
    }

    Type elementType = $Gson$Types.getCollectionElementType(type, rawType);
    TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
    ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);

    @SuppressWarnings({ "unchecked", "rawtypes" }) // create() doesn't define a type parameter
    TypeAdapter<T> result = new Adapter(gson, elementType, elementTypeAdapter, constructor);
    return result;
}

From source file:uk.ac.stfc.isis.ibex.epics.conversion.json.LowercaseEnumTypeAdapterFactory.java

License:Open Source License

/**
 * {@inheritDoc}//from ww  w.j  av a 2 s .co m
 */
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    @SuppressWarnings("unchecked")
    Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isEnum()) {
        return null;
    }

    final Map<String, T> lowercaseToConstant = new HashMap<String, T>();
    for (T constant : rawType.getEnumConstants()) {
        lowercaseToConstant.put(toLowercase(constant), constant);
    }

    return new TypeAdapter<T>() {
        @Override
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(toLowercase(value));
            }
        }

        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            } else {
                return lowercaseToConstant.get(reader.nextString());
            }
        }
    };
}

From source file:us.blanshard.sudoku.messages.Rpc.java

License:Apache License

/**
 * Registers type adapters in the given builder so that {@link Request} and
 * {@link Response} objects can be serialized and deserialized in a symmetric
 * way./*from  w  ww.j a v  a2  s . c  o m*/
 *
 * <p>
 * The request deserializer requires the "method" field of the request to come
 * before the "params" field, which requirement is not strictly conformant
 * with JSON. The serializer ensures that they are in that order.
 *
 * <p>
 * Likewise, the response's "id" field must come before the "result" field.
 */
public static GsonBuilder register(GsonBuilder builder, final Function<String, Type> methodToParamsType,
        final Function<Integer, Type> idToResultType) {

    builder.registerTypeAdapterFactory(new TypeAdapterFactory() {

        @SuppressWarnings("unchecked")
        @Override
        public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
            if (type.getRawType() == Request.class) {
                TypeAdapter<Request> typeAdapter = new RequestAdapter(gson, methodToParamsType);
                return (TypeAdapter<T>) typeAdapter.nullSafe();
            }
            if (type.getRawType() == Response.class) {
                TypeAdapter<Response<Object>> typeAdapter = new ResponseAdapter(gson, idToResultType);
                return (TypeAdapter<T>) typeAdapter.nullSafe();
            }
            return null;
        }
    });

    return builder.serializeSpecialFloatingPointValues();
}