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

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

Introduction

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

Prototype

public final Type getType() 

Source Link

Document

Gets underlying Type instance.

Usage

From source file:org.commonjava.web.json.ser.JsonSerializer.java

License:Open Source License

public <T> T fromString(final String src, final TypeToken<T> token) {
    final T result = getGson(token.getType()).fromJson(src, token.getType());

    return result;
}

From source file:org.commonjava.web.json.ser.JsonSerializer.java

License:Open Source License

public <T> T fromStream(final InputStream stream, String encoding, final TypeToken<T> token) {
    if (encoding == null) {
        encoding = "UTF-8";
    }/*from  w  w w  .  j a v  a2 s . c o m*/

    try {
        final Reader reader = new InputStreamReader(stream, encoding);
        final String json = IOUtils.toString(reader);
        logger.debug("JSON:\n\n{}\n\n", json);

        final T result = getGson(token.getType()).fromJson(json, token.getType());

        return result;
    } catch (final UnsupportedEncodingException e) {
        logger.error("Failed to deserialize type: {}. Error: {}", e, token.getType(), e.getMessage());
        throw new RuntimeException("Cannot read stream.");
    } catch (final IOException e) {
        logger.error("Failed to deserialize type: {}. Error: {}", e, token.getType(), e.getMessage());
        throw new RuntimeException("Cannot read stream.");
    }
}

From source file:org.commonjava.web.json.ser.JsonSerializer.java

License:Open Source License

public <T> Listing<T> listingFromStream(final InputStream stream, String encoding,
        final TypeToken<Listing<T>> token, final DeserializerPostProcessor<T>... postProcessors) {
    if (encoding == null) {
        encoding = "UTF-8";
    }//from   w w w  .  java  2  s . c om

    try {
        Listing<T> result = getGson(null).fromJson(new InputStreamReader(stream, encoding), token.getType());

        if (result != null && result.getItems() != null) {
            final List<T> items = result.getItems();
            Collections.reverse(items);

            result = new Listing<T>(items);
            for (final T item : result.getItems()) {
                for (final DeserializerPostProcessor<T> proc : postProcessors) {
                    proc.process(item);
                }
            }
        }

        return result;
    } catch (final UnsupportedEncodingException e) {
        logger.error("Failed to deserialize type: {}. Error: {}", e, token.getType(), e.getMessage());

        throw new RuntimeException("Cannot read stream.");
    }
}

From source file:org.commonjava.web.json.ser.JsonSerializer.java

License:Open Source License

public <T> Listing<T> listingFromString(final String src, final TypeToken<Listing<T>> token,
        final DeserializerPostProcessor<T>... postProcessors) {
    Listing<T> result = getGson(null).fromJson(src, token.getType());

    if (result != null && result.getItems() != null) {
        final List<T> items = result.getItems();
        Collections.reverse(items);

        result = new Listing<T>(items);
        for (final T item : result.getItems()) {
            for (final DeserializerPostProcessor<T> proc : postProcessors) {
                proc.process(item);/* w w w . j a va  2s.co  m*/
            }
        }
    }

    return result;
}

From source file:org.commonjava.web.json.ser.ServletSerializerUtils.java

License:Open Source License

public static <T> T fromRequestBody(final HttpServletRequest req, final JsonSerializer serializer,
        final TypeToken<T> token) {
    String encoding = req.getCharacterEncoding();
    if (encoding == null) {
        encoding = "UTF-8";
    }/*from w ww. j ava  2  s.  com*/

    try {
        return serializer.fromStream(req.getInputStream(), encoding, token);
    } catch (final IOException e) {
        LOGGER.error("Failed to deserialize type: {} from HttpServletRequest body. Error: {}", e,
                token.getType(), e.getMessage());

        throw new RuntimeException("Cannot read request.");
    }
}

From source file:org.commonjava.web.user.rest.PermissionAdminResource.java

License:Apache License

@GET
@Path("/list")
@Produces({ MediaType.APPLICATION_JSON })
public Response getAll() {
    SecurityUtils.getSubject().isPermitted(Permission.name(Permission.NAMESPACE, Permission.ADMIN));

    try {//from w w  w .  j  a v  a  2 s .c o m
        final Listing<Permission> listing = new Listing<Permission>(dataManager.getAllPermissions());
        final TypeToken<Listing<Permission>> tt = new TypeToken<Listing<Permission>>() {
        };

        return Response.ok().entity(jsonSerializer.toString(listing, tt.getType())).build();
    } catch (final UserDataException e) {
        logger.error(e.getMessage(), e);
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.commonjava.web.user.rest.RoleAdminResource.java

License:Apache License

@GET
@Path("/list")
@Produces({ MediaType.APPLICATION_JSON })
public Response getAll() {
    SecurityUtils.getSubject().isPermitted(Permission.name(Role.NAMESPACE, Permission.ADMIN));

    try {//from   www .ja  va2 s.com
        final Listing<Role> listing = new Listing<Role>(dataManager.getAllRoles());
        final TypeToken<Listing<Role>> tt = new TypeToken<Listing<Role>>() {
        };

        return Response.ok().entity(jsonSerializer.toString(listing, tt.getType())).build();
    } catch (final UserDataException e) {
        logger.error(e.getMessage(), e);
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.commonjava.web.user.rest.UserAdminResource.java

License:Apache License

@GET
@Path("/list")
@Produces({ MediaType.APPLICATION_JSON })
public Response getAll() {
    SecurityUtils.getSubject().isPermitted(Permission.name(User.NAMESPACE, Permission.ADMIN));

    try {/*from  w ww.jav a2s  .c om*/
        final Listing<User> listing = new Listing<User>(dataManager.getAllUsers());
        final TypeToken<Listing<User>> tt = new TypeToken<Listing<User>>() {
        };

        return Response.ok().entity(jsonSerializer.toString(listing, tt.getType())).build();
    } catch (final UserDataException e) {
        logger.error(e.getMessage(), e);
        throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
    }
}

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

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from  w w w . j  av a2 s  .c  o  m*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    if (!TypeUtils.isEither(typeToken.getType())) {
        return null;
    }
    return new Adapter(gson, typeToken);
}

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 ww .j a v  a2  s  .  com*/
public static Type[] getElementTypes(TypeToken<?> typeToken, Class<?> targetType) {
    return getElementTypes(typeToken.getType(), typeToken.getRawType(), targetType);
}