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

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
protected TypeToken() 

Source Link

Document

Constructs a new type literal.

Usage

From source file:ar.com.mapfre.ejemploajaxjsonarray.ServletCargarTabla.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ArrayList<Paises> pais = new ArrayList<>();
    pais = ObtenerDatos.getAllCountries();
    Gson gson = new Gson();
    JsonElement element = gson.toJsonTree(pais, new TypeToken<List<Paises>>() {
    }.getType());/*from  ww  w  .  j a  v a 2  s . co  m*/

    JsonArray jsonArray = element.getAsJsonArray();
    response.setContentType("application/json");
    response.getWriter().print(jsonArray);

}

From source file:ar.edu.ubp.das.src.chat.actions.ActualizarMensajesAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        //prepare http get
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        String ultimo_mensaje = String.valueOf(request.getSession().getAttribute("ultimo_mensaje"));
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        if (ultimo_mensaje.equals("null") || ultimo_mensaje.isEmpty()) {
            ultimo_mensaje = "-1";
        }//  ww  w.  ja v a2  s  . c o m

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/mensajes/sala/" + sala.getId());
        builder.setParameter("ultimo_mensaje", ultimo_mensaje);

        HttpGet getRequest = new HttpGet();
        getRequest.setURI(builder.build());
        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        //parse message data from response
        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<MensajeBean>>() {
        }.getType();
        List<MensajeBean> mensajes = gson.fromJson(restResp, listType);

        if (!mensajes.isEmpty()) {
            MensajeBean ultimo = mensajes.get(mensajes.size() - 1);
            request.getSession().removeAttribute("ultimo_mensaje");
            request.getSession().setAttribute("ultimo_mensaje", ultimo.getId_mensaje());
        }

        if (!ultimo_mensaje.equals("-1")) {
            request.setAttribute("mensajes", mensajes);
        }

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        String id_sala = (String) request.getSession().getAttribute("id_sala");
        request.setAttribute("message",
                "Error al intentar actualizar mensajes de Sala " + id_sala + ": " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:ar.edu.ubp.das.src.chat.actions.ActualizarUsuariosAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        //prepare http get
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        String ultima_actualizacion = String.valueOf(request.getSession().getAttribute("ultima_actualizacion"));
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        if (ultima_actualizacion.equals("null") || ultima_actualizacion.isEmpty()) {
            ultima_actualizacion = String.valueOf(System.currentTimeMillis());
        }//from w  w w .  j a va2  s .  c o  m

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/actualizaciones/sala/" + sala.getId());
        builder.setParameter("ultima_act", ultima_actualizacion);

        HttpGet getRequest = new HttpGet();
        getRequest.setURI(builder.build());
        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        if (restResp.equals("null") || restResp.isEmpty()) {
            return mapping.getForwardByName("success");
        }
        //parse actualizacion data from response
        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<ActualizacionBean>>() {
        }.getType();
        List<ActualizacionBean> actualizaciones = gson.fromJson(restResp, listType);
        List<UsuarioBean> usuarios = actualizaciones.stream()
                .filter(a -> a.getNombre_tipo().equals("UsuarioSala")).map(m -> m.getUsuario())
                .collect(Collectors.toList());

        request.getSession().setAttribute("ultima_actualizacion", String.valueOf(System.currentTimeMillis()));

        if (!usuarios.isEmpty()) {
            request.setAttribute("usuarios", usuarios);
        }

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        request.setAttribute("message",
                "Error al intentar actualizar usuarios de Sala " + sala.getId() + ": " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:ar.edu.ubp.das.src.chat.actions.DashboardAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        String url = "http://25.136.78.82:8080/salas";
        HttpGet getRequest = new HttpGet(url);
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }/*from  www . j a va 2 s .c o m*/

        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<SalaBean>>() {
        }.getType();
        List<SalaBean> salas = gson.fromJson(restResp, listType);
        request.getSession().setAttribute("salas", salas);
        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar listar Salas " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:ar.edu.ubp.das.src.chat.actions.MessagesListAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        Gson gson = new Gson();

        //prepare http get
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        String login_tmst = (String) request.getSession().getAttribute("login_tmst");
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/mensajes/sala/" + sala.getId());
        builder.setParameter("fecha_desde", login_tmst);

        HttpGet getRequest = new HttpGet();
        getRequest.setURI(builder.build());
        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }// w  ww.  ja v  a2 s.  co  m

        //parse message data from response
        Type listType = new TypeToken<LinkedList<MensajeBean>>() {
        }.getType();
        List<MensajeBean> mensajes = gson.fromJson(restResp, listType);

        if (!mensajes.isEmpty()) {
            request.getSession().setAttribute("ultimo_mensaje",
                    mensajes.get(mensajes.size() - 1).getId_mensaje());
        }

        request.setAttribute("mensajes", mensajes);

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar mostrar mensajes: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("error");
    }
}

From source file:ar.edu.ubp.das.src.chat.actions.SalasJoinAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        //get user data from session storage
        Gson gson = new Gson();
        Type usuarioType = new TypeToken<LoginTempBean>() {
        }.getType();/*from www  .ja v  a 2s. co m*/
        String sessUser = String.valueOf(request.getSession().getAttribute("user"));
        LoginTempBean user = gson.fromJson(sessUser, usuarioType);

        //prepare http post
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/usuarios-salas/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("id_usuario", user.getId()));
        params.add(new BasicNameValuePair("id_sala", form.getItem("id_sala")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        httpPost.addHeader("Authorization", "BEARER " + request.getSession().getAttribute("token"));
        httpPost.addHeader("accept", "application/json");

        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        //get user data from session storage
        String salas = String.valueOf(request.getSession().getAttribute("salas"));
        List<SalaBean> salaList = gson.fromJson(salas, new TypeToken<List<SalaBean>>() {
        }.getType());
        SalaBean actual = salaList.stream().filter(s -> s.getId() == Integer.parseInt(form.getItem("id_sala")))
                .collect(Collectors.toList()).get(0);

        request.getSession().setAttribute("sala", actual);
        request.getSession().setAttribute("ultima_actualizacion", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al intentar ingresar a Sala: " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:at.ac.tuwien.big.we14.lab2.api.impl.JSONQuestionDataProvider.java

License:Open Source License

@Override
public List<Category> loadCategoryData() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Category.class, new CategoryDeserializer(factory));

    gsonBuilder.registerTypeAdapter(Question.class, new QuestionDeserialzier(factory));

    Gson gson = gsonBuilder.create();/*ww  w .  j  a  v a 2 s .co  m*/

    Type collectionType = new TypeToken<List<Category>>() {
    }.getType();
    List<Category> categories = gson.fromJson(new InputStreamReader(inputStream, Charsets.UTF_8),
            collectionType);

    return categories;
}

From source file:at.ac.tuwien.big.we14.lab2.api.impl.JSONQuestionDataProvider.java

License:Open Source License

@Override
public Category deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    Category category = factory.createCategory();
    JsonObject object = json.getAsJsonObject();

    category.setName(object.get("name").getAsString());

    for (JsonElement jsonquestion : object.get("questions").getAsJsonArray()) {
        Question question = context.deserialize(jsonquestion, new TypeToken<Question>() {
        }.getType());//from   w  w w  . ja  va2 s .  c o  m
        category.addQuestion(question);
    }

    return category;
}

From source file:at.ac.tuwien.big.we14.lab2.api.impl.JSONQuestionDataProvider.java

License:Open Source License

@Override
public Question deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {

    Question question = factory.createQuestion();

    JsonObject object = json.getAsJsonObject();
    question.setId(object.get("id").getAsInt());
    question.setText(object.get("text").getAsString());

    for (JsonElement wrongChoice : object.get("wrongChoices").getAsJsonArray()) {
        SimpleChoice choice = context.deserialize(wrongChoice, new TypeToken<SimpleChoice>() {
        }.getType());/*  www. jav a2  s  .co m*/
        choice.setId(lastChoiceId++);
        question.addChoice(choice, false);
    }

    question.setMaxTime(object.get("maxTime").getAsLong());

    for (JsonElement correctChoice : object.get("correctChoices").getAsJsonArray()) {
        SimpleChoice choice = context.deserialize(correctChoice, new TypeToken<SimpleChoice>() {
        }.getType());
        choice.setId(lastChoiceId++);
        question.addChoice(choice, true);
    }

    return question;
}

From source file:at.ac.tuwien.big.we15.lab2.api.impl.JSONQuestionDataProvider.java

License:Open Source License

@Override
public List<Category> getCategoryData() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Category.class, new CategoryDeserializer());
    gsonBuilder.registerTypeAdapter(Question.class, new QuestionDeserialzier());

    Gson gson = gsonBuilder.create();/* w w  w  . jav  a2  s  .co  m*/
    Type collectionType = new TypeToken<List<Category>>() {
    }.getType();
    List<Category> categories = gson.fromJson(new InputStreamReader(inputStream, Charsets.UTF_8),
            collectionType);

    return categories;
}