Example usage for com.google.gson JsonObject JsonObject

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

Introduction

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

Prototype

JsonObject

Source Link

Usage

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.");
    }/*ww  w  . j  a va2  s  .c  om*/

    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());
        }/*from  ww w.  j a v a2s .  c o  m*/
        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 {//from  w  ww.j  a va 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 {/*  w w w. ja va 2 s  .c  o  m*/
        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.ItemStackGSON.java

License:Open Source License

@Override
public JsonElement serialize(ItemStack src, Type typeOfSrc, JsonSerializationContext context) {
    final JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("name", Item.itemRegistry.getNameForObject(src.getItem()));
    jsonObject.addProperty("meta", src.getItemDamage());
    return jsonObject;
}

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);//from   www . j a  va2s. 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./*from   www  . j a  va2  s.com*/
 * @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;
}

From source file:aopdomotics.storage.GroceryBill.java

/**
 * Return JSON for all food items on bill
 * @return //w w  w .j  av  a  2 s .  co  m
 */
public JsonObject getJson() {
    //Convert food items to json
    JsonObject storage = new JsonObject();

    JsonObject foodItems = new JsonObject();
    for (Food item : foods) {
        JsonElement jsonItem = new JsonObject();
        foodItems.addProperty(item.getClass().getSimpleName().toLowerCase(), item.buyQuantity());
    }

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

From source file:aopdomotics.storage.recipe.Recipe.java

public JsonObject getJson() {
    JsonObject storage = new JsonObject();

    JsonObject foodItems = new JsonObject();

    foodItems.addProperty(component1.getClass().getSimpleName().toLowerCase(), component1.getQuantity());
    foodItems.addProperty(component2.getClass().getSimpleName().toLowerCase(), component2.getQuantity());
    foodItems.addProperty(component3.getClass().getSimpleName().toLowerCase(), component3.getQuantity());

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

From source file:app.abhijit.iter.data.source.remote.IterApi.java

License:Open Source License

public static String fetchStudentId(String registrationNumber) throws Exception {
    JsonObject request = new JsonObject();
    request.addProperty("sid", "validate");
    request.addProperty("instituteID", INSTITUTE_ID);
    request.addProperty("studentrollno", registrationNumber);
    return Http.post(API_ENDPOINT, "jdata=" + request.toString());
}