Example usage for com.google.gson JsonObject addProperty

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

Introduction

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

Prototype

public void addProperty(String property, Character value) 

Source Link

Document

Convenience method to add a char member.

Usage

From source file:alexandre.letteridentification.ListAction.java

@Override
public void execute(HttpServletRequest request, PrintWriter out) {
    try {/*from www  .  j a  va  2 s  . co 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  v  a2s  . 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.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  ww  w.j a v a 2s . 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 va2  s  .c  o  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;
}

From source file:aopdomotics.storage.GroceryBill.java

/**
 * Return JSON for all food items on bill
 * @return //from w  ww .ja  v a2 s. c  o  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:apim.restful.importexport.utils.APIImportUtil.java

License:Open Source License

/**
 * This method imports an API//from   w  w w .j a  v  a 2s  .c  o  m
 *
 * @param pathToArchive            location of the extracted folder of the API
 * @param currentUser              the current logged in user
 * @param isDefaultProviderAllowed decision to keep or replace the provider
 * @throws APIImportException     if there is an error in importing an API
 */
public static void importAPI(String pathToArchive, String currentUser, boolean isDefaultProviderAllowed)
        throws APIImportException {

    API importedApi;

    // If the original provider is preserved,
    if (isDefaultProviderAllowed) {

        FileInputStream inputStream = null;
        BufferedReader bufferedReader = null;

        try {
            inputStream = new FileInputStream(pathToArchive + APIImportExportConstants.JSON_FILE_LOCATION);
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            importedApi = new Gson().fromJson(bufferedReader, API.class);
        } catch (FileNotFoundException e) {
            log.error("Error in locating api.json file. ", e);
            throw new APIImportException("Error in locating api.json file. " + e.getMessage());
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(bufferedReader);
        }
    } else {

        String pathToJSONFile = pathToArchive + APIImportExportConstants.JSON_FILE_LOCATION;

        try {
            String jsonContent = FileUtils.readFileToString(new File(pathToJSONFile));
            JsonElement configElement = new JsonParser().parse(jsonContent);
            JsonObject configObject = configElement.getAsJsonObject();

            //locate the "providerName" within the "id" and set it as the current user
            JsonObject apiId = configObject.getAsJsonObject(APIImportExportConstants.ID_ELEMENT);
            apiId.addProperty(APIImportExportConstants.PROVIDER_ELEMENT,
                    APIUtil.replaceEmailDomain(currentUser));
            importedApi = new Gson().fromJson(configElement, API.class);

        } catch (IOException e) {
            log.error("Error in setting API provider to logged in user. ", e);
            throw new APIImportException("Error in setting API provider to logged in user. " + e.getMessage());
        }
    }

    Set<Tier> allowedTiers;
    Set<Tier> unsupportedTiersList;

    try {
        allowedTiers = provider.getTiers();
    } catch (APIManagementException e) {
        log.error("Error in retrieving tiers of the provider. ", e);
        throw new APIImportException("Error in retrieving tiers of the provider. " + e.getMessage());
    }

    if (!(allowedTiers.isEmpty())) {
        unsupportedTiersList = Sets.difference(importedApi.getAvailableTiers(), allowedTiers);

        //If at least one unsupported tier is found, it should be removed before adding API
        if (!(unsupportedTiersList.isEmpty())) {
            for (Tier unsupportedTier : unsupportedTiersList) {

                //Process is continued with a warning and only supported tiers are added to the importer API
                log.warn("Tier name : " + unsupportedTier.getName() + " is not supported.");
            }

            //Remove the unsupported tiers before adding the API
            importedApi.removeAvailableTiers(unsupportedTiersList);
        }
    }

    try {
        int tenantId = APIUtil.getTenantId(currentUser);
        provider.addAPI(importedApi);
        addSwaggerDefinition(importedApi, pathToArchive, tenantId);
    } catch (APIManagementException e) {
        //Error is logged and APIImportException is thrown because adding API and swagger are mandatory steps
        log.error("Error in adding API to the provider. ", e);
        throw new APIImportException("Error in adding API to the provider. " + e.getMessage());
    }
    //Since Image, documents, sequences and WSDL are optional, exceptions are logged and ignored in implementation
    addAPIImage(pathToArchive, importedApi);
    addAPIDocuments(pathToArchive, importedApi);
    addAPISequences(pathToArchive, importedApi, currentUser);
    addAPIWsdl(pathToArchive, importedApi, currentUser);

}

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());
}

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

License:Open Source License

public static String fetchStudentDetails(String studentId) throws Exception {
    JsonObject request = new JsonObject();
    request.addProperty("sid", "studentdetails");
    request.addProperty("instituteid", INSTITUTE_ID);
    request.addProperty("studentid", studentId);
    return Http.post(API_ENDPOINT, "jdata=" + request.toString());
}