Example usage for com.google.gson JsonArray add

List of usage examples for com.google.gson JsonArray add

Introduction

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

Prototype

public void add(JsonElement element) 

Source Link

Document

Adds the specified element to self.

Usage

From source file:com.dmr.project.controller.TransformerHandler.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  ww. j ava2s.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, SQLException {
    String[] area;
    area = request.getParameterValues("area[]");
    Transformers transformersList = new Transformers();
    ResultSet rs = transformersList.getTransformers(area);
    //String transformer = request.getParameter("transformer");
    //        for(int i=0;i < area.length;i++){
    //            System.out.println("ss" + area[i]);
    //        }

    //            Transformers transformersList = new Transformers();
    //            ResultSet rs = transformersList.getData(area);
    //
    JsonObject jsonResponse = new JsonObject();
    JsonArray data = new JsonArray();
    while (rs.next()) {
        JsonArray row = new JsonArray();
        row.add(new JsonPrimitive(rs.getString("location")));
        data.add(row);
    }
    jsonResponse.add("data", data);

    response.setContentType("application/json");
    try (PrintWriter out = response.getWriter()) {

        out.print(jsonResponse);
        out.flush();
    }

    //            }
    //        response.setContentType("text/html;charset=UTF-8");
    //        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 NewServlet</title>");
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("Output"+area);
    //            out.println(area.length);
    //
    ////            for (int i = 0; i < area.length ; i++) {
    ////                out.println(area[i]);
    ////            }
    ////            while(rs.next ()){
    ////                String temp = rs.getString("location");
    ////                out.println("Location: "+temp);
    ////            }
    //            
    //            out.println("Output"+rs);
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:com.drguildo.bm.TagsSerializer.java

License:Open Source License

@Override
public JsonElement serialize(Tags src, Type typeOfSrc, JsonSerializationContext context) {
    JsonArray fuckThisShit = new JsonArray();
    for (String tag : src.toList()) {
        fuckThisShit.add(new JsonPrimitive(tag));
    }/*from  w  w w.  j  a  v  a  2s. c om*/
    return fuckThisShit;
}

From source file:com.dubic.codesnippets.controllers.NotificationController.java

@RequestMapping(value = "/unread/list")
public @ResponseBody JsonObject getUnread(@RequestParam(value = "start", defaultValue = "0") int start,
        @RequestParam(value = "size", defaultValue = "10") int size) {
    JsonObject resp = new JsonObject();
    List<Notification> unreadNotifications = notifService
            .getUnreadNotifications(idmService.getUserLoggedIn().getId(), start, size);
    JsonArray nArray = new JsonArray();
    for (Notification n : unreadNotifications) {
        JsonObject no = new JsonObject();
        no.addProperty("id", n.getId());
        no.addProperty("msg", n.getMsg());
        no.addProperty("read", n.isSeen());
        no.addProperty("time", n.getCreated().getTime());
        no.addProperty("type", n.getType().toString());
        nArray.add(no);
    }//  w ww . j a  va 2 s. co  m
    resp.add("notifs", nArray);
    notifService.readNotifications(unreadNotifications);
    return resp;
}

From source file:com.dubic.codesnippets.controllers.SearchController.java

@RequestMapping("/results/snippets")
public @ResponseBody JsonObject searchSnippets(@RequestParam("q") String keyword,
        @RequestParam(value = "start", defaultValue = "0") int start,
        @RequestParam(value = "size", defaultValue = "10") int size) {
    JsonObject resp = new JsonObject();
    //search snippets
    String snipsql = "select s.title,s.description,s.id from snippets s where s.title like '%" + keyword + "%'";
    List<Object[]> searchSnippets = db.createNativeQuery(snipsql).setFirstResult(start).setMaxResults(size)
            .getResultList();/*from   www.ja  v  a 2  s  . c  o  m*/
    JsonArray snips = new JsonArray();
    for (Object[] snippet : searchSnippets) {
        JsonObject s = new JsonObject();
        s.addProperty("title", (String) snippet[0]);
        s.addProperty("desc", (String) snippet[1]);
        s.addProperty("id", (Long) snippet[2]);
        snips.add(s);
    }
    resp.add("snippets", snips);
    //count
    String snipcountsql = "select count(s.id) from snippets s where s.title like '%" + keyword + "%'";
    resp.addProperty("snipcount", (Long) db.createNativeQuery(snipcountsql).getSingleResult());
    return resp;
}

From source file:com.dubic.codesnippets.controllers.SearchController.java

@RequestMapping("/results/users")
public @ResponseBody JsonObject searchUsers(@RequestParam("q") String keyword,
        @RequestParam(value = "start", defaultValue = "0") int start,
        @RequestParam(value = "size", defaultValue = "10") int size) {
    JsonObject resp = new JsonObject();
    //search snippets
    String usersql = "select u.id,u.screen_name,u.firstname,u.lastname from users u where\n"
            + " u.screen_name like '%" + keyword + "%' or u.firstname like '%" + keyword
            + "%' or u.lastname like '%" + keyword + "%'";
    List<Object[]> users = db.createNativeQuery(usersql).setFirstResult(start).setMaxResults(size)
            .getResultList();//from  w w  w  .  j  a v  a2  s  .  c  o m
    JsonArray uarray = new JsonArray();
    for (Object[] user : users) {
        JsonObject s = new JsonObject();
        s.addProperty("id", (Long) user[0]);
        s.addProperty("username", (String) user[1]);
        s.addProperty("firstname", (String) user[2]);
        s.addProperty("lastname", (String) user[3]);
        uarray.add(s);
    }
    resp.add("users", uarray);
    //count
    String usercountsql = "select count(u.id) from users u where\n" + " u.screen_name like '%" + keyword
            + "%' or u.firstname like '%" + keyword + "%' or u.lastname like '%" + keyword + "%'";
    resp.addProperty("userscount", (Long) db.createNativeQuery(usercountsql).getSingleResult());
    return resp;
}

From source file:com.dubic.codesnippets.spi.SnippetService.java

public JsonArray loadShared(int start, int size) {
    log.debug(String.format("loadShared(%d,%d)", start, size));
    String sql = "select s.id,s.title,s.lang from snippets s,shared sh where sh.snippet_id=s.id and sh.to_user_id="
            + identityService.getUserLoggedIn().getId();
    List<Object[]> res = db.createNativeQuery(sql).setFirstResult(start).setMaxResults(size).getResultList();
    JsonArray array = new JsonArray();
    for (Object[] o : res) {
        JsonObject jo = new JsonObject();
        jo.addProperty("id", (Long) o[0]);
        //            jo.addProperty("create_dt", IdmUtils.formatDate((Date) o[1]));
        //            jo.addProperty("desc", (String) o[2]);
        jo.addProperty("lang", (String) o[2]);
        jo.addProperty("title", (String) o[1]);
        //            jo.addProperty("screenName", (String) o[5]);
        //            jo.addProperty("picture", (String) o[6]);
        array.add(jo);
    }// w ww  . jav a2 s .  c  o  m
    return array;
}

From source file:com.dubic.codesnippets.spi.SnippetService.java

private JsonArray buildResults(String sql, int start, int size) {
    List<Object[]> res = db.createNativeQuery(sql).setFirstResult(start).setMaxResults(size).getResultList();
    JsonArray array = new JsonArray();
    for (Object[] o : res) {
        JsonObject jo = new JsonObject();
        jo.addProperty("id", (Long) o[0]);
        jo.addProperty("create_dt", IdmUtils.formatDate((Date) o[1]));
        jo.addProperty("desc", (String) o[2]);
        jo.addProperty("lang", (String) o[3]);
        jo.addProperty("title", (String) o[4]);
        jo.addProperty("screenName", (String) o[5]);
        jo.addProperty("picture", (String) o[6]);
        array.add(jo);
    }/*w  w w  . ja va2s . com*/
    return array;
}

From source file:com.dubic.scribbles.admin.controllers.UserController.java

@RequestMapping("/chart")
public @ResponseBody JsonObject usersChart(@RequestParam("m") int month) {
    int sqlMonth = month == -1 ? Util.currentMonth() : month;
    String sql = "select DAY(u.create_dt) as daymonth,count(u.id) as count from users u\n"
            + "where MONTH(u.create_dt)=" + (sqlMonth + 1) + "\n" + "group by DAY(u.create_dt)";
    List<Object[]> users = db.getObjectList(sql, new RowMapper<Object[]>() {
        @Override/*from   w w  w.  j  a  v  a2s. co  m*/
        public Object[] mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new Object[] { rs.getInt("daymonth"), rs.getInt("count") };
        }
    });
    JsonObject resp = new JsonObject();
    JsonArray cats = new JsonArray();
    JsonArray data = new JsonArray();
    for (Object[] o : users) {
        cats.add(new JsonPrimitive((Integer) o[0]));
        data.add(new JsonPrimitive((Integer) o[1]));
    }
    resp.add("categories", cats);
    resp.add("data", data);
    resp.addProperty("month", sqlMonth);

    return resp;
}

From source file:com.edmondapps.utils.android.json.JsonUtils.java

License:Apache License

/**
 * Converts a collection of {@linkplain Jsonable} and insert them in a
 * {@link JsonArray}. Any null elements are skipped.
 * //w  w  w  .j av a  2 s  . c  om
 * @param c
 *            a collection of {@linkplain Jsonable}
 * @return a {@link JsonArray} that contains all the elements.
 */
public static JsonArray arrayOf(Iterable<? extends Jsonable> c) {
    JsonArray array = new JsonArray();
    for (Jsonable j : c) {
        if (j == null) {
            continue;
        }
        array.add(j.toJson());
    }
    return array;
}

From source file:com.ericsson.eiffel.remrem.publish.cli.CLI.java

License:Apache License

/**
 * Handle event from file/*w w  w. jav  a2  s  . c  o m*/
 * @param filePath the path of the file where the messages reside
 */
public void handleContent(String content) {
    String exchangeName = CliOptions.getCommandLine().getOptionValue("en");
    try {
        String msgProtocol = CliOptions.getCommandLine().getOptionValue("mp");
        MsgService msgService = PublishUtils.getMessageService(msgProtocol, msgServices);
        if (msgService != null) {
            rmqHelper.rabbitMqPropertiesInit(msgService.getServiceName());
            SendResult results = messageService.send(content, msgService,
                    CliOptions.getCommandLine().getOptionValue("ud"),
                    CliOptions.getCommandLine().getOptionValue("tag"),
                    CliOptions.getCommandLine().getOptionValue("rk"));
            JsonArray jarray = new JsonArray();
            for (PublishResultItem result : results.getEvents()) {
                jarray.add(result.toJsonObject());
            }
            System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(jarray));
            messageService.cleanUp();
            CliOptions.clearSystemProperties();
        } else {
            throw new Exception();
        }
    } catch (RemRemPublishException e) {
        JsonArray errorResponse = new JsonArray();
        PublishResultItem result = new PublishResultItem(null, 404, null, e.getMessage());
        errorResponse.add(result.toJsonObject());
        System.err.println(new GsonBuilder().setPrettyPrinting().create().toJson(errorResponse));
        CliOptions.exit(CLIExitCodes.HANDLE_CONTENT_FAILED);
    } catch (Exception e) {
        log.debug("Exception: ", e);
        System.err.println("Exception: " + e.getMessage());
        CliOptions.exit(CLIExitCodes.HANDLE_CONTENT_FAILED);
    }
}