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.brunocvcunha.digesteroids.Digesteroids.java

License:Apache License

/**
 * Convert given original object to targetType, using the mappings from the source parameter.
 * @param source Source name/*w ww. jav a2  s  .  c  om*/
 * @param original Original data
 * @param targetType Target type
 * @return Converted object
 * @throws InstantiationException Can not create instance of target object
 * @throws IllegalAccessException Access violation
 * @param <T> Type to return
 */
public <T> T convertObjectToType(String source, Object original, Type targetType)
        throws InstantiationException, IllegalAccessException {

    if (original == null) {
        return null;
    }

    TypeToken<T> typeToken = (TypeToken<T>) TypeToken.get(targetType);

    Class<T> targetClass = (Class<T>) typeToken.getRawType();
    T target = targetClass.newInstance();

    // at this point, we starting doing comparisons
    for (Field entryField : targetClass.getDeclaredFields()) {
        entryField.setAccessible(true);

        DigesterMapping reference = null;

        try {
            DigesterMapping[] references = entryField.getAnnotationsByType(DigesterMapping.class);

            for (DigesterMapping candidate : references) {
                if (candidate.source().equalsIgnoreCase(source)) {
                    reference = candidate;
                    break;
                }
            }
        } catch (Exception e) {
            // it's ok
        }

        if (reference != null) {
            log.debug("Found reference, using field: " + reference.value() + ". Field name: "
                    + entryField.getName() + ", Base Class: " + targetClass + ", object: "
                    + original.getClass());

            PropertyDescriptor descriptor;
            Method writerMethod;

            try {
                descriptor = new PropertyDescriptor(entryField.getName(), targetClass);

                writerMethod = descriptor.getWriteMethod();

            } catch (Exception e) {
                e.printStackTrace();
                log.warn("Exception converting record: ", e);
                continue;
            }

            Type valueType = writerMethod.getGenericParameterTypes()[0];

            log.debug("Reference for field " + entryField.getName() + " - " + reference);
            Object resolvedValue = resolveValue(original, reference, valueType);

            if (resolvedValue != null) {
                try {

                    if (reference.trim() && resolvedValue instanceof String) {
                        resolvedValue = ((String) resolvedValue).replaceAll("", " ")
                                .replaceAll("[\\s\\t]", " ").trim();
                    }

                    invokeSetter(target, writerMethod, resolvedValue);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

    return target;
}

From source file:org.brunocvcunha.digesteroids.Digesteroids.java

License:Apache License

/**
 * @param originalData Original data to resolve
 * @param reference Reference annotation
 * @param valueType Value to return//from   w w  w.  j  av  a 2  s. c om
 * @return Value resolved based on the annotation
 * @throws InstantiationException Can not create instance of target object
 * @throws IllegalAccessException Access violation
 */
public Object resolveValue(Object originalData, DigesterMapping reference, Type valueType)
        throws InstantiationException, IllegalAccessException {

    TypeToken<?> typeToken = TypeToken.get(valueType);
    Class<?> targetClass = typeToken.getRawType();

    Object resolvedValue = null;

    if (reference.refType() == ReferenceTypeEnum.NORMAL) {
        resolvedValue = resolveValueNormal(reference.source(), originalData, reference.value(), valueType,
                targetClass);
    } else if (reference.refType() == ReferenceTypeEnum.PASS_THROUGH) {
        resolvedValue = resolveValuePassthrough(reference.source(), originalData, valueType, targetClass);
    } else if (reference.refType() == ReferenceTypeEnum.JSON_PATH) {
        resolvedValue = resolveValueJsonPath(originalData, reference.value());
    } else if (reference.refType() == ReferenceTypeEnum.HTML_ID) {
        resolvedValue = resolveValueHTMLId(originalData, reference.value(), reference.htmlText(),
                reference.textNode(), reference.attribute());
    } else if (reference.refType() == ReferenceTypeEnum.HTML_CSS) {
        resolvedValue = resolveValueHTMLCss(originalData, reference.value(), reference.htmlText(),
                reference.textNode(), reference.attribute());
    } else if (reference.refType() == ReferenceTypeEnum.HTML_XPATH) {
        resolvedValue = resolveValueHTMLXPath(originalData, reference.value(), reference.htmlText(),
                reference.textNode(), reference.attribute());
    } else if (reference.refType() == ReferenceTypeEnum.HARDCODE) {
        resolvedValue = reference.value();
    }

    // make sure that it's the type
    Object returnValue = caster.cast(resolvedValue, valueType);

    if (reference.rule() != null && !reference.rule().isInterface()) {
        return reference.rule().newInstance().apply(returnValue);
    }

    return returnValue;
}

From source file:org.codice.admin.router.RuntimeTypeAdapterFactory.java

License:Open Source License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (null == type || !baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }/* www .j  a  va 2  s  .  c om*/

    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?");
            }
            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:org.eclipse.che.dto.server.SerializableInterfaceAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (Serializable.class.equals(type.getRawType())) {
        return (TypeAdapter<T>) new SerializableAdapter(gson.getAdapter(Object.class));
    }/*from w w w.  java2 s  . com*/
    return null;
}

From source file:org.eclipse.lsp4j.adapters.ResourceOperationTypeAdapter.java

License:Open Source License

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

    if (!ResourceOperation.class.isAssignableFrom(type.getRawType())) {
        return null;
    }

    return (TypeAdapter<T>) new InnerResourceOperationTypeAdapter(this, gson).nullSafe();
}

From source file:org.eclipse.lsp4j.jsonrpc.json.adapters.CollectionTypeAdapterFactory.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    if (!Collection.class.isAssignableFrom(typeToken.getRawType()))
        return null;

    Type[] elementTypes = TypeUtils.getElementTypes(typeToken, Collection.class);
    if (elementTypes.length != 1)
        return null;
    TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementTypes[0]));
    Supplier<Collection<Object>> constructor = getConstructor(
            (Class<Collection<Object>>) typeToken.getRawType());
    return new Adapter(gson, elementTypes[0], elementTypeAdapter, constructor);
}

From source file:org.eclipse.lsp4j.jsonrpc.json.adapters.EnumTypeAdapterFactory.java

License:Open Source License

@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Class<?> rawType = typeToken.getRawType();
    if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class)
        return null;
    if (!rawType.isEnum())
        rawType = rawType.getSuperclass();
    try {// w ww  . ja v a  2s .c o m
        return new Adapter(rawType);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.lsp4j.jsonrpc.json.adapters.MessageTypeAdapterFactory.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    if (!Message.class.isAssignableFrom(typeToken.getRawType()))
        return null;
    return (TypeAdapter<T>) new Adapter(handler, gson);
}

From source file:org.eclipse.lsp4j.jsonrpc.json.adapters.TypeUtils.java

License:Open Source License

/**
 * Determine the actual type arguments of the given type token with regard to the given target type.
 *//*from  w w w  .j ava 2 s  . c  om*/
public static Type[] getElementTypes(TypeToken<?> typeToken, Class<?> targetType) {
    return getElementTypes(typeToken.getType(), typeToken.getRawType(), targetType);
}

From source file:org.eclipse.recommenders.utils.gson.MultisetTypeAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (typeToken.getRawType() != Multiset.class || !(type instanceof ParameterizedType)) {
        return null;
    }/*from w w  w.jav  a  2  s. c om*/

    Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
    TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
    return (TypeAdapter<T>) newMultisetAdapter(elementAdapter);
}