Example usage for com.google.gson GsonBuilder GsonBuilder

List of usage examples for com.google.gson GsonBuilder GsonBuilder

Introduction

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

Prototype

public GsonBuilder() 

Source Link

Document

Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.

Usage

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w ww. j  av  a 2s  . c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    String urlPath = request.getServletPath();

    if (urlPath.equalsIgnoreCase("/resources")) {

        ArrayList<Environment> lcs = this.getEnvironmentResources();

        Integer min = Integer.MAX_VALUE;
        Integer max = Integer.MIN_VALUE;
        for (Environment e : lcs) {
            if (e.getArduinoloudness() != null && e.getArduinoloudness() < min) {
                min = e.getArduinoloudness();
            }
            if (e.getArduinoloudness() != null && e.getArduinoloudness() > max) {
                max = e.getArduinoloudness();
            }
        }

        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet StudyAssistant</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet StudyAssistant at " + request.getContextPath() + "</h1>");
            for (Environment e : lcs) {
                out.println(e.toString());
            }

            out.println("Noise MAX: " + max);
            out.println("Noise MIN: " + min);

            out.println("</body>");
            out.println("</html>");
        }
    } else if (urlPath.equalsIgnoreCase("/resources/gauge")) {
        Environment lastRecord = this.getLastEnvironmentRecord();

        StudyIndex inx = new StudyIndex(lastRecord);
        double index = inx.getStudyIndex();
        index *= 100;

        index = Math.round(index * 100.0) / 100.0;

        JsonObject obj = new JsonObject();

        // create an array called cols
        JsonArray cols = new JsonArray();
        JsonArray rows = new JsonArray();
        JsonArray messages = new JsonArray();

        JsonObject col = new JsonObject();
        col.addProperty("id", "Index");
        col.addProperty("label", "Index");
        col.addProperty("type", "string");
        cols.add(col);

        JsonObject col2 = new JsonObject();
        col2.addProperty("id", "Value");
        col2.addProperty("label", "Value");
        col2.addProperty("type", "number");
        cols.add(col2);

        obj.add("cols", cols);

        JsonObject c = new JsonObject();
        JsonArray row = new JsonArray();

        JsonObject v1 = new JsonObject();
        v1.addProperty("v", "Index");
        row.add(v1);

        JsonObject v2 = new JsonObject();
        v2.addProperty("v", index);
        row.add(v2);

        c.add("c", row);

        rows.add(c);

        obj.add("rows", rows);

        String msg = "";
        if ((inx.alcoholIndex < 0.90) || (inx.methaneIndex < 0.90)) {
            msg += "Room needs better air circulation.";
            JsonObject msg1 = new JsonObject();
            msg1.addProperty("text", msg);
            messages.add(msg1);
        }

        JsonObject msg2 = new JsonObject();
        msg = "";
        if (lastRecord.getArduinolight() < StudyIndex.lightOptimalValue) {
            msg += "Increase room luminance!";
        } else if (lastRecord.getArduinolight() > StudyIndex.lightOptimalValue) {
            msg += "Lower room luminance!";
        } else {
            msg += "Room luminance is optimal!";
        }
        msg2.addProperty("text", msg);
        messages.add(msg2);

        JsonObject msg3 = new JsonObject();
        msg = "";
        if (lastRecord.getDs18b20temp() < StudyIndex.temperatureOptimalValue) {
            msg += "Increase room temperature!";
        } else if (lastRecord.getDs18b20temp() > StudyIndex.temperatureOptimalValue) {
            msg += "Lower room temperature!";
        } else {
            msg += "Room temperature is optimal!";
        }
        msg3.addProperty("text", msg);
        messages.add(msg3);

        JsonObject msg4 = new JsonObject();
        msg = "";
        if (lastRecord.getArduinoloudness() > StudyIndex.loudnessOptimalValue) {
            msg += "Room is too noisy!";
            msg4.addProperty("text", msg);
            messages.add(msg4);
        }

        JsonObject msg5 = new JsonObject();
        msg = "";
        if (lastRecord.getDs18b20temp() < StudyIndex.temperatureOptimalValue) {
            msg += "Humidity is less than optimal.";
        } else if (lastRecord.getDs18b20temp() > StudyIndex.temperatureOptimalValue) {
            msg += "Humidity is above optimal.";
        } else {
            msg += "Humidity is optimal!";
        }
        msg5.addProperty("text", msg);
        messages.add(msg5);

        obj.add("messages", messages);

        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();

        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();

        out.print(gson.toJson(obj));
    } else if (urlPath.equalsIgnoreCase("/resources/humidity")) {
        JsonObject obj = this.getCoreChartsJson("Humidity");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/temperature")) {
        JsonObject obj = this.getCoreChartsJson("Temperature");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/loudness")) {
        JsonObject obj = this.getCoreChartsJson("Loudness");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/light")) {
        JsonObject obj = this.getCoreChartsJson("Light");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/bubbleindex")) {
        JsonObject obj = this.getCoreChartsJson("Environment Index Score");
        this.printJson(obj, response);
    } else if (urlPath.equalsIgnoreCase("/resources/minmax")) {
        JsonObject obj = this.findMinMax();
        this.printJson(obj, response);
    }
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

private void printJson(JsonObject obj, HttpServletResponse response) throws IOException {
    Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
            .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    PrintWriter out = response.getWriter();

    out.print(gson.toJson(obj));/*  www  .j  ava 2  s.co  m*/
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

private ArrayList<Environment> getEnvironmentResources() {
    URL url = null;//from  w ww. j  a v a2 s .  c om
    try {
        //url = new URL("https://192.168.2.33:8443/logs");
        url = new URL("https://demo3407181.mockable.io/logs");

    } catch (MalformedURLException ex) {
        Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex);
    }

    String jstring = null;
    try {
        jstring = NetworkUtility.request(url, false, false);
    } catch (Exception ex) {
        Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex);
    }

    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
    JsonParser parser = new JsonParser();
    JsonArray jArray = parser.parse(jstring).getAsJsonArray();

    ArrayList<Environment> lcs = new ArrayList<Environment>();

    for (JsonElement obj : jArray) {
        Environment cse = gson.fromJson(obj, Environment.class);
        lcs.add(cse);
    }

    return lcs;
}

From source file:be.uantwerpen.dc.studyassistant.StudyAssistant.java

private Environment getLastEnvironmentRecord() {
    URL url = null;/*from   w  ww .  j a  v  a  2 s .  co  m*/
    try {
        //url = new URL("https://192.168.2.33:8443/log");
        url = new URL("https://demo3407181.mockable.io/log");
    } catch (MalformedURLException ex) {
        Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex);
    }

    String jstring = null;
    try {
        jstring = NetworkUtility.request(url, false, false);
    } catch (Exception ex) {
        Logger.getLogger(StudyAssistant.class.getName()).log(Level.SEVERE, null, ex);
    }

    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
    JsonParser parser = new JsonParser();
    JsonArray jArray = parser.parse(jstring).getAsJsonArray();

    ArrayList<Environment> lcs = new ArrayList<Environment>();

    for (JsonElement obj : jArray) {
        Environment cse = gson.fromJson(obj, Environment.class);
        lcs.add(cse);
    }

    return lcs.get(0);

}

From source file:be.ugent.tiwi.sleroux.newsrec.recommendationstester.RecommenderAccess.java

public NewsItemCluster[] getRecommendations() {
    try {/*  w  ww .  ja  v  a  2s .c  om*/
        String res = doGet(baseUrl + "GetRecommendations.do?count=250&start=0");
        GsonBuilder b = new GsonBuilder();
        b.registerTypeAdapter(NewsItemCluster.class, new CustomDeserializer());
        Gson gson = b.create();
        NewsItemCluster[] results = gson.fromJson(res, NewsItemCluster[].class);

        return results;
    } catch (IOException ex) {
        Logger.getLogger(RecommenderAccess.class.getName()).log(Level.SEVERE, null, ex);
        return new NewsItemCluster[] {};
    }
}

From source file:be.uza.keratoconus.systemtrayapp.SystemTrayMenu.java

License:Open Source License

private UserPrefsDAO readConfig() {
    GsonBuilder builder = new GsonBuilder();
    builder.enableComplexMapKeySerialization();
    Gson gson = builder.create();//w w  w  .ja va 2 s.c  o  m
    Path path = prefsDirPath.resolve(configFilePath);
    try {
        if (Files.exists(path) && Files.size(path) > 0) {
            try (InputStream fileInputStream = Files.newInputStream(path)) {
                final UserPrefsDAO config = gson.fromJson(new InputStreamReader(fileInputStream),
                        UserPrefsDAO.class);
                return config;
            }
        }
    } catch (IOException ioe) {
        logService.log(LogService.LOG_WARNING, "Exception thrown when reading user configuration", ioe);
    }

    UserPrefsDAO defaultConfig = createDefaultUserConfig();
    defaultConfig.animateEnabled = true;
    defaultConfig.popupsEnabled = true;
    defaultConfig.displayTimeSeconds = new HashMap<>();
    writeConfig(defaultConfig);
    return defaultConfig;
}

From source file:bean.EJBean.java

License:Open Source License

public void createUsuario(Usuario u) {
    final Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
    final String gson = prettyGson.toJson(u);

    // System.out.println(gson);

    client = ClientBuilder.newClient();/*from   w w  w. ja v  a 2 s  . c o m*/
    Response response = client.target(baseURI).path("usuarios").request(MediaType.APPLICATION_JSON)
            .post(Entity.entity(gson, MediaType.APPLICATION_JSON), Response.class);
    client.close();
}

From source file:bean.EJBean.java

License:Open Source License

public Edificio getEdificio(String id) {

    client = ClientBuilder.newClient();/*from w ww.  j  av  a  2 s  .c  o  m*/
    String edificio = client.target(baseURI).path("edificios").path(id).request(MediaType.APPLICATION_JSON)
            .get(String.class);
    client.close();

    /// Deserializar///

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Edificio> deserializer = new JsonDeserializer<Edificio>() {

        @Override
        public Edificio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jsonObject = json.getAsJsonObject();

            Edificio e = new Edificio();

            e.setIdedificio(jsonObject.get("idedificio").getAsString());

            if (jsonObject.has("nombreen")) {
                e.setNombreen(jsonObject.get("nombreen").getAsString());
            }
            if (jsonObject.has("nombrevl")) {
                e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            }
            if (jsonObject.has("nombrees")) {
                e.setNombrees(jsonObject.get("nombrees").getAsString());
            }
            if (jsonObject.has("direccion")) {
                e.setDireccion(jsonObject.get("direccion").getAsString());
            }
            if (jsonObject.has("telefono")) {
                e.setTelefono(jsonObject.get("telefono").getAsString());
            }
            if (jsonObject.has("enlace")) {
                e.setEnlace(jsonObject.get("enlace").getAsString());
            }
            e.setXano(jsonObject.get("xano").getAsString());
            e.setTopleft(jsonObject.get("topleft").getAsString());
            e.setTopright(jsonObject.get("topright").getAsString());
            e.setBottomleft(jsonObject.get("bottomleft").getAsString());

            // System.out.println("Deserializer: Edi Obj: "+e.toString());

            List<Usuario> lu = new ArrayList<Usuario>();
            JsonArray usuariosArray = jsonObject.getAsJsonArray("usuarios");
            for (JsonElement usuario : usuariosArray) {
                Usuario u = new Usuario();
                JsonObject usuarioObj = usuario.getAsJsonObject();
                u.setUsuario(usuarioObj.get("usuario").getAsString());
                lu.add(u);
            }
            // System.out.println("Deserializer: usu Obj: "+e.toString());

            e.setUsuarios(lu);
            // System.out.println("Deserializer: usu Obj: " + e.getUsuarios().size());
            List<Plano> lp = new ArrayList<Plano>();
            JsonArray planoArray = jsonObject.getAsJsonArray("planos");
            for (JsonElement plano : planoArray) {
                Plano p = new Plano();
                PlanoPK pk = new PlanoPK();
                JsonObject planoObj = plano.getAsJsonObject();
                pk.setIdedificio(e.getIdedificio());
                pk.setIdplano(planoObj.get("idplano").getAsString());
                p.setId(pk);
                p.setEnlace(planoObj.get("enlace").getAsString());
                p.setNivel(planoObj.get("nivel").getAsInt());
                Edificio edAux = new Edificio();
                edAux.setIdedificio(edAux.getIdedificio());
                p.setEdificio(edAux);

                lp.add(p);
            }

            e.setPlanos(lp);

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());

            e.setCoordenada(coordenada);

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Edificio.class, deserializer);

    System.out.println("GSON" + edificio);

    Gson customGson = gsonBuilder.create();
    Edificio jsonToEdificio = customGson.fromJson(edificio, Edificio.class);
    System.out.print("Size users EJB: " + jsonToEdificio.getUsuarios().size());

    return jsonToEdificio;
}

From source file:bean.EJBean.java

License:Open Source License

public Espacio getEspacio(String id) {
    client = ClientBuilder.newClient();//  w  ww . j  a v a 2  s. com
    String espacio = client.target(baseURI).path("espacios").path(id).request(MediaType.APPLICATION_JSON)
            .get(String.class);
    client.close();

    /// Deserializar///

    //      System.out.println(espacio);

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() {

        @Override
        public Espacio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            JsonObject jsonObject = json.getAsJsonObject();

            Espacio e = new Espacio();

            e.setIdespacio(jsonObject.get("idespacio").getAsString());

            if (jsonObject.has("nombreen")) {
                e.setNombreen(jsonObject.get("nombreen").getAsString());
            }
            if (jsonObject.has("nombrevl")) {
                e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            }
            if (jsonObject.has("nombrees")) {
                e.setNombrees(jsonObject.get("nombrees").getAsString());
            }
            if (jsonObject.has("bloque")) {
                e.setBloque(jsonObject.get("bloque").getAsString());
            }
            if (jsonObject.has("piso")) {
                e.setPiso(jsonObject.get("piso").getAsInt());
            }
            if (jsonObject.has("tipo")) {
                e.setTipo(jsonObject.get("tipo").getAsString());
            }
            e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean());
            if (jsonObject.has("boundingbox")) {
                e.setBoundingbox(jsonObject.get("boundingbox").getAsString());
            }

            // System.out.println("Deserializer: Edi Obj: "+e.toString());
            JsonObject edificioObj = jsonObject.getAsJsonObject("edificio");
            Edificio edificio = new Edificio();
            edificio.setIdedificio(edificioObj.get("idedificio").getAsString());

            e.setEdificio(edificio);

            List<Panorama> lp = new ArrayList<Panorama>();
            JsonArray panoArray = jsonObject.getAsJsonArray("panoramas");
            for (JsonElement pano : panoArray) {
                Panorama p = new Panorama();
                JsonObject panoObj = pano.getAsJsonObject();
                p.setIdpanorama(panoObj.get("idpanorama").getAsString());
                p.setEnlace(panoObj.get("enlace").getAsString());
                lp.add(p);
            }

            e.setPanoramas(lp);

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());

            e.setCoordenada(coordenada);

            if (jsonObject.has("profesores")) {
                List<Profesor> lprof = new ArrayList<Profesor>();
                JsonArray profArray = jsonObject.getAsJsonArray("profesores");
                for (JsonElement prof : profArray) {
                    Profesor p = new Profesor();
                    JsonObject profObj = prof.getAsJsonObject();
                    p.setIdprofesor(profObj.get("idprofesor").getAsString());
                    p.setUsuario(profObj.get("usuario").getAsString());
                    p.setVisibilidad(profObj.get("visibilidad").getAsBoolean());

                    lprof.add(p);
                }

                e.setProfesores(lprof);
            }

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Espacio.class, deserializer);

    // System.out.println("GSON"+espacio);

    Gson customGson = gsonBuilder.create();
    Espacio jsonToEspacio = customGson.fromJson(espacio, Espacio.class);

    return jsonToEspacio;
}

From source file:bean.EJBean.java

License:Open Source License

public List<Espacio> getEspaciosFromEdificio(String id) {

    client = ClientBuilder.newClient();// w  ww .  j a  va 2 s  . c o m
    String espaciosJSON = client.target(baseURI).path("edificios").path(id).path("espacios")
            .request(MediaType.APPLICATION_JSON).get(String.class);
    client.close();

    GsonBuilder gsonBuilder = new GsonBuilder();

    JsonDeserializer<Espacio> deserializer = new JsonDeserializer<Espacio>() {

        @Override
        public Espacio deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
            JsonObject jsonObject = json.getAsJsonObject();

            Espacio e = new Espacio();

            // System.out.println("HOLA "+jsonObject.get("bloque").getAsString());

            e.setIdespacio(jsonObject.get("idespacio").getAsString());
            e.setNombrees(jsonObject.get("nombrees").getAsString());
            // e.setNombreen(jsonObject.get("nombreen").getAsString());
            // e.setNombrevl(jsonObject.get("nombrevl").getAsString());
            e.setBloque(jsonObject.get("bloque").getAsString());
            e.setBoundingbox(jsonObject.get("boundingbox").getAsString());
            e.setPiso(jsonObject.get("piso").getAsInt());
            e.setTipo(jsonObject.get("tipo").getAsString());
            e.setVisibilidad(jsonObject.get("visibilidad").getAsBoolean());

            JsonObject coordenadaObj = jsonObject.getAsJsonObject("coordenada");
            Coordenada coordenada = new Coordenada();
            coordenada.setIdcoordenada(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setDescripcion(coordenadaObj.get("idcoordenada").getAsString());
            coordenada.setLatitud(coordenadaObj.get("latitud").getAsDouble());
            coordenada.setLongitud(coordenadaObj.get("longitud").getAsDouble());
            e.setCoordenada(coordenada);

            JsonObject edificioObj = jsonObject.getAsJsonObject("edificio");
            Edificio edificio = new Edificio();
            edificio.setIdedificio(edificioObj.get("idedificio").getAsString());
            /*
             * edificio.setNombrees(edificioObj.get("nombrees").getAsString());
             * edificio.setNombreen(edificioObj.get("nombreen").getAsString());
             * edificio.setNombrevl(edificioObj.get("nombrevl").getAsString());
             * edificio.setEnlace(edificioObj.get("enlace").getAsString());
             * edificio.setXano(edificioObj.get("xano").getAsString());
             * edificio.setTopleft(edificioObj.get("topleft").getAsString());
             * edificio.setTopright(edificioObj.get("topright").getAsString());
             * edificio.setBottomleft(edificioObj.get("bottomleft").getAsString());
             */
            e.setEdificio(edificio);

            List<Panorama> lu = new ArrayList<Panorama>();
            JsonArray panoramaArray = jsonObject.getAsJsonArray("panoramas");
            for (JsonElement panorama : panoramaArray) {
                Panorama p = new Panorama();

                JsonObject panoramaObj = panorama.getAsJsonObject();

                p.setIdpanorama(panoramaObj.get("idpanorama").getAsString());
                p.setEnlace(panoramaObj.get("enlace").getAsString());
                if (panoramaObj.has("panorama")) {
                    p.setPanorama(panoramaObj.get("panorama").getAsInt());
                }

                lu.add(p);
            }

            e.setPanoramas(lu);

            List<Profesor> lp = new ArrayList<Profesor>();
            if (jsonObject.has("profesores")) {
                JsonArray profesorArray = jsonObject.getAsJsonArray("profesores");
                for (JsonElement profesor : profesorArray) {
                    Profesor p = new Profesor();

                    JsonObject profesorObj = profesor.getAsJsonObject();
                    p.setIdprofesor(profesorObj.get("idprofesor").getAsString());
                    p.setUsuario(profesorObj.get("usuario").getAsString());
                    p.setVisibilidad(profesorObj.get("visibilidad").getAsBoolean());
                    lp.add(p);
                }
            }
            e.setProfesores(lp);

            return e;
        }

    };
    gsonBuilder.registerTypeAdapter(Espacio.class, deserializer);

    Type listType = new TypeToken<List<Espacio>>() {
    }.getType();

    Gson customGson = gsonBuilder.create();
    List<Espacio> jsonToEspacios = customGson.fromJson(espaciosJSON, listType);

    // System.out.println("Success Espacio: "+ jsonToEspacios.size());

    return jsonToEspacios;

}