Example usage for com.google.gson Gson toJson

List of usage examples for com.google.gson Gson toJson

Introduction

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

Prototype

public String toJson(JsonElement jsonElement) 

Source Link

Document

Converts a tree of JsonElement s into its equivalent JSON representation.

Usage

From source file:AddUserController.java

public AddUserController() {
    //try{//from  ww w  .j  a  v a 2  s .co  m
    post("/newuser", (req, res) -> {
        String id = UUID.randomUUID().toString();
        String username = req.queryParams("username");
        String name = req.queryParams("name");
        String email = req.queryParams("email");
        String bizname = req.queryParams("bizname");
        String website = req.queryParams("website");
        String craft = req.queryParams("craft");
        String about = req.queryParams("about");

        Map<String, Object> userData = new HashMap<>();
        userData.put("id", id);
        userData.put("username", username);
        userData.put("name", name);
        userData.put("email", email);
        userData.put("bizname", bizname);
        userData.put("website", website);
        userData.put("craft", craft);
        userData.put("about", about);
        Gson gson = new Gson();
        return gson.toJson(userData);
        /* 
                
                
        Map<String, Object> userData = new HashMap<>();
                
        Gson gson = new Gson();                
        return gson.toJson(userData);*/
    });

    /*}catch(Exception e){
    final JPanel panel = new JPanel();
            
    JOptionPane.showMessageDialog(panel, "Could not add user.", "Error", JOptionPane.ERROR_MESSAGE);
    }
    }*/
}

From source file:FriendController.java

public FriendController() {
    get("/friends", (req, res) -> {
        /*Map<String, User> userList = new HashMap<>();
        User user001 = new User("Summer Smith", "summer@randm.com", "Summer Sol", "rickandmorty.com");
        userList.put(user001.getId(), user001);
        Gson gson = new Gson();//from  w w w . j av a 2  s .co m
        return gson.toJson(userList);*/
        String id = UUID.randomUUID().toString();
        Map<String, Object> friendList = new HashMap<>();
        friendList.put("id", id);
        friendList.put("username", "schwiftytime");
        friendList.put("name", "Rick Sanchez");
        friendList.put("email", "rick@rick.com");
        friendList.put("bizname", "Curse Purge Plus!");
        friendList.put("website", "rickandmorty.com");
        friendList.put("craft", "Science");
        friendList.put("about", "*Burp*");
        /* friendList.put("id", "0001");
        friendList.put("username", "inferiorgenes");
        friendList.put("name", "Abradolf Lincler");
        friendList.put("email", "abe@rick.com");
        friendList.put("bizname", "Emancipation");
        friendList.put("website", "rickandmorty.com");
        friendList.put("craft", "Wood Burning");
        friendList.put("about", "Wood work is calming.");*/
        Gson gson = new Gson();
        return gson.toJson(friendList);
    });

    /*get("/users", (req, res) -> userService.getAllUsers(), json());
            
    get("/users/:id", (req, res) -> {
       String id = req.params(":id");
       User user = userService.getUser(id);
       if (user  != null) {
    return user;
       }
       res.status(400);
       return new ResponseError("No user with id '%s' found", id);
    }, json());
            
    wrote similar code elsewhere
        post("/users", (req, res) -> userService.createUser(
    req.queryParams("name"),
                        req.queryParams("email"),
                        req.queryParams("bizname"),
                        req.queryParams("website")
    ), json());
            
    exception(IllegalArgumentException.class, (e, req, res) -> {
       res.status(400);
       res.body(toJson(new ResponseError(e)));
    });*/
}

From source file:getNamesSv.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   www  .j av a2 s.  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/json;charset=UTF-8");
    try {
        PrintWriter out = response.getWriter();
        int estado = Integer.parseInt(request.getParameter("estado"));
        classList sr = new classList(estado);
        Gson gson = new Gson();
        out.println(gson.toJson(sr));
        out.close();
    } catch (Exception ex) {
        System.out.println("Error");
    }
}

From source file:Licenses.java

License:Open Source License

@Override
public String jsonProducer() {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    return gson.toJson(this);
}

From source file:SubscriberBatch.java

License:Open Source License

private void applyReminderNotifications(Connection sd, Connection cResults, String basePath,
        String serverName) {//from   ww w.  j  ava  2 s. c o m

    // Sql to get notifications that need a reminder
    String sql = "select " + "t.id as t_id, " + "n.id as f_id, " + "a.id as a_id, " + "t.survey_ident, "
            + "t.update_id," + "t.p_id," + "n.target," + "n.remote_user," + "n.notify_details "
            + "from tasks t, assignments a, forward n " + "where t.tg_id = n.tg_id " + "and t.id = a.task_id "
            + "and n.enabled " + "and n.trigger = 'task_reminder' " + "and a.status = 'accepted' "
            //+ "and a.assigned_date < now() - cast(n.period as interval) "   // use schedule at however could allow assigned date to be used
            + "and t.schedule_at < now() - cast(n.period as interval) "
            + "and a.id not in (select a_id from reminder where n_id = n.id)";
    PreparedStatement pstmt = null;

    // Sql to record a reminder being sent
    String sqlSent = "insert into reminder (n_id, a_id, reminder_date) values (?, ?, now())";
    PreparedStatement pstmtSent = null;

    try {

        pstmt = sd.prepareStatement(sql);
        pstmtSent = sd.prepareStatement(sqlSent);

        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        HashMap<Integer, ResourceBundle> locMap = new HashMap<>();
        MessagingManager mm = new MessagingManager();

        ResultSet rs = pstmt.executeQuery();
        int idx = 0;
        while (rs.next()) {

            if (idx++ == 0) {
                System.out.println("\n-------------");
            }
            int tId = rs.getInt(1);
            int nId = rs.getInt(2);
            int aId = rs.getInt(3);
            String surveyIdent = rs.getString(4);
            String instanceId = rs.getString(5);
            int pId = rs.getInt(6);
            String target = rs.getString(7);
            String remoteUser = rs.getString(8);
            String notifyDetailsString = rs.getString(9);
            NotifyDetails nd = new Gson().fromJson(notifyDetailsString, NotifyDetails.class);

            int oId = GeneralUtilityMethods.getOrganisationIdForNotification(sd, nId);

            // Send the reminder
            SubmissionMessage subMgr = new SubmissionMessage(tId, surveyIdent, pId, instanceId, nd.from,
                    nd.subject, nd.content, nd.attach, nd.include_references, nd.launched_only,
                    nd.emailQuestion, nd.emailQuestionName, nd.emailMeta, nd.emails, target, remoteUser,
                    "https", serverName, basePath);
            mm.createMessage(sd, oId, "reminder", "", gson.toJson(subMgr));

            // record the sending of the notification
            pstmtSent.setInt(1, nId);
            pstmtSent.setInt(2, aId);
            pstmtSent.executeUpdate();

            // Write to the log
            ResourceBundle localisation = locMap.get(nId);
            if (localisation == null) {
                Organisation organisation = GeneralUtilityMethods.getOrganisation(sd, oId);
                Locale orgLocale = new Locale(organisation.locale);
                localisation = ResourceBundle.getBundle("org.smap.sdal.resources.SmapResources", orgLocale);
            }

            String logMessage = "Reminder sent for: " + nId;
            if (localisation != null) {
                logMessage = localisation.getString("lm_reminder");
                logMessage = logMessage.replaceAll("%s1", GeneralUtilityMethods.getNotificationName(sd, nId));
            }
            lm.writeLogOrganisation(sd, oId, "subscriber", LogManager.REMINDER, logMessage);

        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
        }
        try {
            if (pstmtSent != null) {
                pstmtSent.close();
            }
        } catch (SQLException e) {
        }

    }
}

From source file:Api.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  ww  .ja  v a2 s . com
 *
 * @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");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        ArrayList lista = new ArrayList();
        String modulo = request.getParameter("modulo");
        String idCiudad = request.getParameter("id_ciudad");
        String idPais = request.getParameter("id_pais");

        Country pais = new Country();
        // Paises

        if (modulo.equals("paises")) {

            ResultSet fila = pais.showAll();
            try {

                while (fila.next()) {
                    Country country = new Country();
                    country.setName(fila.getString("name"));
                    country.setCountry_id(fila.getInt("country_id"));

                    lista.add(country);
                }

            } catch (Exception ex) {

            }
        }

        // Ciudades

        if (modulo.equals("ciudades")) {

            if (idCiudad != null) {
                // devolvemos la ciudad con el id ciudad
                City ciudad = new City();
                ciudad.setCity_id(Integer.parseInt(idCiudad));
                ResultSet fila = ciudad.getOne();

                try {

                    while (fila.next()) {
                        City c = new City();
                        c.setName(fila.getString("name"));
                        c.setCity_id(fila.getInt("city_id"));
                        c.setCountry_id(fila.getInt("country_id"));
                        c.setState(fila.getInt("state"));

                        lista.add(c);
                    }

                } catch (Exception ex) {

                }

            }

            else if (idPais != null) {
                // devolvemos las ciudades con el pais al que pertenece
                City ciudad = new City();
                ResultSet fila = ciudad.showAllFrom(Integer.parseInt(idPais));
                try {

                    while (fila.next()) {
                        City c = new City();
                        c.setName(fila.getString("name"));
                        c.setCity_id(fila.getInt("city_id"));
                        c.setCountry_id(fila.getInt("country_id"));
                        c.setState(fila.getInt("state"));

                        lista.add(c);
                    }

                } catch (Exception ex) {

                }
            }

            else {
                City ciudad = new City();
                ResultSet fila = ciudad.showAll();
                try {

                    while (fila.next()) {
                        City c = new City();
                        c.setName(fila.getString("name"));
                        c.setCity_id(fila.getInt("city_id"));
                        c.setCountry_id(fila.getInt("country_id"));
                        c.setState(fila.getInt("state"));
                        lista.add(c);
                    }

                } catch (Exception ex) {

                }
            }
        }

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(lista);
        response.setContentType("application/json;charset=UTF-8");
        out.write(json);

    }
}

From source file:InventoryIncrementItemServlet.java

License:Open Source License

@Override
public HttpResponse doWork(HttpRequest request, String rootDirectory) {
    HttpResponse response;/*  w  ww.ja  v  a2 s.  c  o  m*/
    try {
        String inventoryUrl = "./web/inventory.json";
        File inventory = new File(inventoryUrl);

        StringBuilder sb = new StringBuilder();
        Scanner sc = new Scanner(inventory);
        while (sc.hasNext()) {
            sb.append(sc.nextLine());
        }
        sc.close();

        // Add this new book to the list of existing books
        Gson gson = new Gson();
        InventoryObject[] inventoryArray = gson.fromJson(sb.toString(), InventoryObject[].class);
        ArrayList<InventoryObject> inventoryList = new ArrayList<InventoryObject>(
                Arrays.asList(inventoryArray));

        String body = new String(request.getBody());
        System.out.println(body);
        String[] newItem = body.split("&");

        // Find existing item and add passed quantity
        int id = Integer.parseInt(newItem[0].split("=")[1]);
        int quant = Integer.parseInt(newItem[1].split("=")[1]);
        for (InventoryObject item : inventoryList) {
            if (item.getID() == id) {
                if (item.getQuantity() == 0 && quant == -1) {
                    return HttpResponseFactory.create400BadRequest(Protocol.CLOSE);
                } else {
                    item.setQuantity(item.getQuantity() + quant);
                }
            }
        }

        // Serialize new list
        Gson gsonBuilder = new GsonBuilder().setPrettyPrinting().create();
        String arrayListToJson = gsonBuilder.toJson(inventoryList);

        BufferedWriter bw = new BufferedWriter(new FileWriter(inventory));
        bw.write(arrayListToJson);
        bw.close();

        response = HttpResponseFactory.create200OK(inventory, Protocol.CLOSE);
    } catch (Exception e) {
        response = HttpResponseFactory.create404NotFound(Protocol.CLOSE);
    }
    return response;
}

From source file:AuthServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    Gson gson = new Gson();

    try {/*from w  w w . j  ava  2 s . c om*/
        //parsing json
        StringBuilder sb = new StringBuilder();
        String s;
        while ((s = request.getReader().readLine()) != null) {
            sb.append(s);
        }

        Token token = (Token) gson.fromJson(sb.toString(), Token.class);

        Connection conn = null;
        //PreparedStatement preparedStatement = null;

        Class.forName("com.mysql.jdbc.Driver");

        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        String sql = "SELECT userID, tokenexpired FROM account WHERE token=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, token.getAccessToken());
        ResultSet rs = preparedStatement.executeQuery();

        Status status = new Status();

        if (rs.next()) {
            java.sql.Timestamp tokenexpired = rs.getTimestamp("tokenexpired");
            java.util.Date now = new java.util.Date();
            long nowms = now.getTime();
            long expms = tokenexpired.getTime();

            if (nowms < expms) {
                //token valid
                int userid = rs.getInt("userID");
                status.setSuccess(true);
                status.setDescription("valid");
                status.setUserID(userid);

                response.getOutputStream().print(gson.toJson(status));
                response.getOutputStream().flush();
            } else {
                status.setSuccess(false);
                status.setDescription("expired");
                response.getOutputStream().print(gson.toJson(status));
                response.getOutputStream().flush();
            }
        } else {
            status.setSuccess(false);
            status.setDescription("invalid");
            response.getOutputStream().print(gson.toJson(status));
            response.getOutputStream().flush();
        }

        rs.close();

    } catch (Exception ex) {
        ex.printStackTrace();

    }
}

From source file:NoPartitionLeaderWatcher.java

License:Open Source License

private static void reassignPartitionWithNoLeader(
        List<Tuple2<Partition, String[]>> partitionsToBeReassignedList, NoPartitionLeaderWatchHelper helper)
        throws Exception {
    String reassignmentConfigFileName = "partitions-to-move.json." + System.currentTimeMillis();

    Gson gson = new Gson();
    //build json string
    MovePartitionsJsonHelper mvPartitionsHelper = new MovePartitionsJsonHelper(
            partitionsToBeReassignedList.size());
    for (int i = 0; i < partitionsToBeReassignedList.size(); i++) {
        Tuple2<Partition, String[]> partitionToBeReassigned = partitionsToBeReassignedList.get(i);
        PartitionToMoveJsonHelper partitionObj = new PartitionToMoveJsonHelper(
                partitionToBeReassigned._1.topicName, partitionToBeReassigned._1.partitionId,
                partitionToBeReassigned._2);
        mvPartitionsHelper.partitions[i] = partitionObj;
    }/*  ww w  . j a v a  2 s  .c om*/

    String reassignmentJson = gson.toJson(mvPartitionsHelper);
    //do kafka reassignment
    PrintWriter out = new PrintWriter(reassignmentConfigFileName);
    out.println(reassignmentJson);
    out.close();
    logger.debug("Reassignment will be kicked for {}", reassignmentJson);
    String[] reassignCmdArgs = { "--reassignment-json-file=" + reassignmentConfigFileName,
            "--zookeeper=" + Utils.getZookeeperConnectionString(2181), "--execute" };
    ReassignPartitionsCommand.main(reassignCmdArgs);
    //Hacky: Restart kafka controller. Controller seems buggy sometimes
    helper.restartKafkaController();
    //Hacky: Sleep for sometime to let the reassignment process complete
    logger.debug("Reassignment command has been initiated. Will sleep for {} ms", 5 * 60000);
    Thread.sleep(5 * 60000);

    try {
        Files.deleteIfExists(Paths.get(reassignmentConfigFileName));
    } catch (Exception ex) {
        //ignore
    }
}

From source file:WSClient.java

public Response doRequest(String path, Object object) throws IOException {

    Response response = null;//from   w  w  w  .  j  a v a  2s .c  om

    try {
        URL url = new URL(BASE_URL + path);
        System.out.println("##### utl : " + BASE_URL + path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        //String input = "{\"qty\":100,\"name\":\"iPad 4\"}";
        Gson gson = new Gson();
        String input = gson.toJson(object);

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        /*if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
           throw new RuntimeException("Failed : HTTP error code : "
              + conn.getResponseCode());
        }*/

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        StringBuilder content = new StringBuilder("");
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            content.append(output);

        }
        conn.disconnect();

        System.out.println(" content :" + content.toString());
        response = gson.fromJson(content.toString(), Response.class);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();

    }

    return response;
}