Example usage for com.google.gson JsonObject add

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

Introduction

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

Prototype

public void add(String property, JsonElement value) 

Source Link

Document

Adds a member, which is a name-value pair, to self.

Usage

From source file:adminservlets_Json.Load_BlacklistUsersJson.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w w  w .  jav  a2s  .  com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AdminClass_BlacklistedEmails ab = new AdminClass_BlacklistedEmails();

    ArrayList blacklistedEmails = (ArrayList) ab.getBlacklistedEmails();//loading blacklisted emails
    PrintWriter out = response.getWriter();

    Gson gson = new Gson();
    JsonObject myObj = new JsonObject();

    JsonElement x = gson.toJsonTree(blacklistedEmails);
    myObj.add("blacklistedEmails", x);

    out.write(myObj.toString());
    out.close();
}

From source file:adminservlets_reports.LoadAdReports.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w  w  w.  j a v a  2s  . c o m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AdminClass_ReportedItems art = new AdminClass_ReportedItems();
    ArrayList ReportedItems = art.getItemReports();
    PrintWriter out = response.getWriter();

    Gson gson = new Gson();
    JsonObject myObj = new JsonObject();

    JsonElement x = gson.toJsonTree(ReportedItems);
    myObj.add("ReportedItems", x);

    out.write(myObj.toString());
    out.close();
}

From source file:adminservlets_reports.LoadInquiryReports.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// www  .  j a  v a  2s  .  com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AdminClass_ReportedInquiries ari = new AdminClass_ReportedInquiries();
    ArrayList ReportedInquiries = ari.getInquiryReports();
    PrintWriter out = response.getWriter();

    Gson gson = new Gson();
    JsonObject myObj = new JsonObject();

    JsonElement x = gson.toJsonTree(ReportedInquiries);
    myObj.add("ReportedInquiries", x);

    out.write(myObj.toString());
    out.close();
}

From source file:adminservlets_reports.LoadMessageReports.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w ww .  j a v  a 2  s  . c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AdminClass_ReportedMessages arm = new AdminClass_ReportedMessages();
    ArrayList ReportedMessages = arm.getMessageReports();
    PrintWriter out = response.getWriter();

    Gson gson = new Gson();
    JsonObject myObj = new JsonObject();

    JsonElement x = gson.toJsonTree(ReportedMessages);
    myObj.add("ReportedMessages", x);

    out.write(myObj.toString());
    out.close();
}

From source file:ai.olami.cloudService.SpeechRecognizer.java

License:Apache License

private APIResponse sendGetResultsRequest(CookieSet identifier, String seqType, NLIConfig nliConfig)
        throws IllegalArgumentException, IOException, NoSuchAlgorithmException {

    String cookies = identifier.getContents().toString();
    if (cookies == null) {
        throw new IllegalArgumentException("Invalid contents of the CookieSet.");
    }//from www  .j a  v  a 2s .com

    final Map<String, String> queryParams = new HashMap<String, String>();
    queryParams.put("compress", (mEncodeToSpeex ? "1" : "0"));
    queryParams.put("seq", seqType);

    JsonObject rq = new JsonObject();
    if (seqType.contains(SEQ_TYPE_NLI)) {
        if (nliConfig != null) {
            rq.add("nli_config", nliConfig.toJsonElement());
        }
    }
    queryParams.put("rq", mGson.toJson(rq));

    final URL url = new URL(getConfiguration().getBaseRequestURL(mApiName, queryParams));
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setRequestMethod("GET");
    httpConnection.setRequestProperty("Cookie", cookies);
    httpConnection.setRequestProperty("contentType", "utf-8");
    httpConnection.setConnectTimeout(getTimeout());

    HttpClient httpClient = null;
    String response = null;

    try {
        httpClient = new HttpClient(httpConnection);
        httpClient.normalConnect();
        if (httpClient.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response = httpClient.getResponseContent();
        } else {
            throw new IOException(httpClient.getResponseMessage());
        }
    } finally {
        httpClient.close();
    }

    return APIResponseBuilder.create(response);

}

From source file:ai.olami.cloudService.TextRecognizer.java

License:Apache License

private APIResponse sendRequest(String apiName, String text, NLIConfig nliConfig)
        throws NoSuchAlgorithmException, IOException {

    StringBuffer httpQueryStringBuffer = new StringBuffer();

    if (apiName == APIConfiguration.API_NAME_SEG) {
        httpQueryStringBuffer.append("rq=");
        httpQueryStringBuffer.append(text);
    } else if (apiName == APIConfiguration.API_NAME_NLI) {
        JsonObject data = new JsonObject();
        data.addProperty("input_type", mRqDataInputType);
        data.addProperty("text", text);
        JsonObject rq = new JsonObject();
        rq.addProperty("data_type", "stt");
        rq.add("data", data);
        if (nliConfig != null) {
            rq.add("nli_config", nliConfig.toJsonElement());
        }//ww w.ja v a  2 s . c om
        httpQueryStringBuffer.append("rq=");
        httpQueryStringBuffer.append(mGson.toJson(rq));
    }

    final URL url = new URL(getConfiguration().getBaseRequestURL(apiName));
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("contentType", "utf-8");
    httpConnection.setConnectTimeout(getTimeout());

    HttpClient httpClient = null;
    String response = null;

    try {
        httpClient = new HttpClient(httpConnection);
        httpClient.postQueryConnect(httpQueryStringBuffer.toString());
        if (httpClient.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response = httpClient.getResponseContent();
        } else {
            throw new IOException(httpClient.getResponseMessage());
        }
    } finally {
        httpClient.close();
    }

    return APIResponseBuilder.create(response);
}

From source file:alexandre.letteridentification.ListAction.java

@Override
public void execute(HttpServletRequest request, PrintWriter out) {
    try {//  ww w . java  2 s  .c o m
        String type = request.getParameter("type");

        JsonArray list = new JsonArray();

        switch (type) {
        case "images_to_be_analyzed":

            String path = ActionServlet.path + "\\Images to be analyzed";

            File[] letters = new File(path).listFiles();

            for (int i = 0; i < letters.length; i++) {
                JsonObject letter_obj = new JsonObject();
                letter_obj.addProperty("letter", letters[i].getName());

                File[] drawings = new File(letters[i].getAbsolutePath() + "\\Drawings").listFiles();

                JsonArray list_drawings = new JsonArray();

                for (int j = 0; j < drawings.length; j++) {
                    BufferedImage im = ImageIO.read(drawings[j]);

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    ImageIO.write(im, "png", baos);
                    baos.flush();
                    byte[] data = baos.toByteArray();

                    baos.close();

                    String encodedImage = "data:image/png;base64," + Base64.getEncoder().encodeToString(data);

                    list_drawings.add(encodedImage);
                }

                letter_obj.add("drawings", list_drawings);

                File[] computer_vision = new File(letters[i].getAbsolutePath() + "\\Computer Vision")
                        .listFiles();

                JsonArray list_computer = new JsonArray();

                for (int j = 0; j < computer_vision.length; j++) {
                    BufferedImage im = ImageIO.read(computer_vision[j]);

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    ImageIO.write(im, "png", baos);
                    baos.flush();
                    byte[] data = baos.toByteArray();

                    baos.close();

                    String encodedImage = "data:image/png;base64," + Base64.getEncoder().encodeToString(data);

                    list_computer.add(encodedImage);
                }

                letter_obj.add("computer_vision", list_computer);

                list.add(letter_obj);
            }

            break;
        }

        JsonObject container = new JsonObject();
        container.add("list", list);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(container);
        out.println(json);
    } catch (IOException ex) {
        Logger.getLogger(ListAction.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:alexandre.letteridentification.LoginAction.java

@Override
public void execute(HttpServletRequest request, PrintWriter out) {
    try {/*from w  w  w  .  j a  va  2  s  . com*/
        HttpSession session = request.getSession();

        String email = request.getParameter("email");
        String password = request.getParameter("password");

        Administrator a = serv.findAdministratorByEmail(email);

        if (a != null) {
            if (password.equals(a.getPassword())) {
                session.setAttribute("administrator", a);

                JsonObject result = new JsonObject();

                result.addProperty("administrator", a.getId());
                result.addProperty("link", "administration.html");

                JsonObject container = new JsonObject();
                container.add("result", result);
                Gson gson = new GsonBuilder().setPrettyPrinting().create();
                String json = gson.toJson(container);
                out.println(json);
            } else {
                session.invalidate();
            }
        } else {
            session.invalidate();
        }
    } catch (Throwable ex) {
        Logger.getLogger(LoginAction.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:allout58.mods.techtree.tree.TechNodeGSON.java

License:Open Source License

@Override
public JsonElement serialize(TechNode src, Type typeOfSrc, JsonSerializationContext context) {
    final JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("id", src.getId());
    jsonObject.addProperty("name", src.getName());
    jsonObject.addProperty("scienceRequired", src.getScienceRequired());
    jsonObject.addProperty("description", src.getDescription());

    final JsonArray jsonParents = new JsonArray();
    for (final TechNode parent : src.getParents()) {
        final JsonPrimitive jsonParent = new JsonPrimitive(parent.getId());
        jsonParents.add(jsonParent);//  w  w w.j  a va  2 s.  c o m
    }

    jsonObject.add("parents", jsonParents);

    final JsonArray jsonItems = new JsonArray();
    for (final ItemStack item : src.getLockedItems()) {
        jsonItems.add(context.serialize(item));
    }

    jsonObject.add("lockedItems", jsonItems);

    return jsonObject;
}

From source file:aopdomotics.storage.FoodStorage.java

/**
 * Return JSON from storage food items.//  w  w w.j  a  v  a 2  s.co m
 * @return 
 */
public JsonObject getStorage() {
    JsonObject storage = new JsonObject();

    JsonObject foodItems = new JsonObject();

    for (Food item : foods) {
        foodItems.addProperty(item.getClass().getSimpleName().toLowerCase(), item.getQuantity());
    }

    storage.add("Storage", foodItems);
    return storage;
}