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:com.app.json.usage_heatmap.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w  w  .  j a v  a  2s . 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
 * @throws java.sql.SQLException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    response.setContentType("application/JSON");
    Connection conn = null;
    try (PrintWriter out = response.getWriter()) {
        conn = ConnectionManager.getConnection();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        //creats a new json object for printing the desired json output
        JsonObject jsonOutput = new JsonObject();
        JsonArray errorJsonList = new JsonArray();
        //retrieves the user
        String date = request.getParameter("date");
        String floor = request.getParameter("floor");
        String token = request.getParameter("token");
        String time = request.getParameter("time");
        Date dateF = null;
        Date timeF = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);
        SimpleDateFormat timeDf = new SimpleDateFormat("HH:mm:ss");
        timeDf.setLenient(false);
        JsonObject temp = new JsonObject();
        int floorNum = 0;
        if (floor == null) {
            errorJsonList.add(new JsonPrimitive("missing floor"));
        } else if (floor.equals("")) {
            errorJsonList.add(new JsonPrimitive("blank floor"));
        } else {
            try {
                floorNum = Integer.parseInt(floor);
                if (floorNum > 5 || floorNum < 0) {
                    errorJsonList.add(new JsonPrimitive("invalid floor"));
                }
            } catch (NumberFormatException e) {
                errorJsonList.add(new JsonPrimitive("invalid floor"));
            }
        }
        if (date == null) {
            errorJsonList.add(new JsonPrimitive("missing date"));
        } else if (date.equals("")) {
            errorJsonList.add(new JsonPrimitive("blank date"));
        } else {
            try {
                dateF = df.parse(date);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid date"));
            }
        }
        if (time == null) {
            errorJsonList.add(new JsonPrimitive("missing time"));
        } else if (time.equals("")) {
            errorJsonList.add(new JsonPrimitive("blank time"));
        } else {
            try {
                timeF = timeDf.parse(time);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid time"));
            }
        }

        String sharedSecret = "is203g4t6luvjava";
        String username = "";
        if (token == null) {
            errorJsonList.add(new JsonPrimitive("missing token"));
        } else if (token.equals("")) {
            errorJsonList.add(new JsonPrimitive("blank token"));
        } else {
            try {
                username = JWTUtility.verify(token, sharedSecret);
            } catch (JWTException ex) {
                errorJsonList.add(new JsonPrimitive("invalid token"));
            }
        }
        if (errorJsonList.size() > 0) {
            jsonOutput.addProperty("status", "error");
            jsonOutput.add("messages", errorJsonList);
        } else {
            conn = ConnectionManager.getConnection();
            HashMap<Integer, String> floorMap = new HashMap<Integer, String>();
            floorMap.put(0, "B1");
            floorMap.put(1, "L1");
            floorMap.put(2, "L2");
            floorMap.put(3, "L3");
            floorMap.put(4, "L4");
            floorMap.put(5, "L5");
            String level = floorMap.get(floorNum);
            String fullDateFormat = date + " " + time;
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date endDate = null;
            try {
                Date endDateTemp = fmt.parse(fullDateFormat);
                endDate = new Date(endDateTemp.getTime() - 1000);
            } catch (ParseException ex) {
                Logger.getLogger(usage_heatmap.class.getName()).log(Level.SEVERE, null, ex);
            }
            Date startDate = new Date();
            startDate.setTime(endDate.getTime() - 60 * 15 * 1000);

            HashMap<String, ArrayList<Integer>> sematicMap = LocationDAO.retrieveSemanticplaces(level, conn);
            ArrayList<LocationRecord> locationRecordList = LocationRecordDAO
                    .retrieveAllLocationsOnDates(startDate, endDate, conn);
            ArrayList<AppUsage> appUsageList = AppUsageDAO.retrieveAllAppUsageOnDates(startDate, endDate, conn);
            List<String> macAdressList = new ArrayList<String>();
            for (AppUsage a : appUsageList) {
                macAdressList.add(a.getMacAddress());
            }
            Iterator itre = locationRecordList.iterator();
            while (itre.hasNext()) {
                LocationRecord locationRecord = (LocationRecord) itre.next();
                String mac_address = locationRecord.getMacAddress();
                if (!macAdressList.contains(mac_address)) {
                    itre.remove();
                }
            }
            HashMap<String, Integer> locationRecordMap = new HashMap<String, Integer>();
            //remove repeated mac-address
            for (LocationRecord a : locationRecordList) {
                locationRecordMap.put(a.getMacAddress(), a.getLocationId());
            }
            Collection<Integer> locationIds = locationRecordMap.values();
            System.out.println(locationIds.size());
            Set locations = sematicMap.keySet();
            Iterator itr = locations.iterator();
            HashMap<String, Integer> sematicCountMap = new HashMap<String, Integer>();
            while (itr.hasNext()) {
                int count = 0;
                String sematic = (String) itr.next();
                ArrayList<Integer> locationList = sematicMap.get(sematic);
                for (Integer id : locationIds) {
                    if (locationList.contains(id)) {
                        count++;
                    }
                }
                sematicCountMap.put(sematic, count);
            }
            //=========Display==============================//
            JsonArray results = new JsonArray();
            Set sematicCountSet = sematicCountMap.keySet();
            Iterator iter = sematicCountSet.iterator();
            while (iter.hasNext()) {
                JsonObject heatMap = new JsonObject();
                String sematicPlace = (String) iter.next();
                heatMap.add("semantic-place", new JsonPrimitive(sematicPlace));
                int count = sematicCountMap.get(sematicPlace);
                heatMap.add("num-people-using-phone", new JsonPrimitive(count));
                if (count == 0) {
                    heatMap.add("crowd-density", new JsonPrimitive(0));
                } else if (count <= 3) {
                    heatMap.add("crowd-density", new JsonPrimitive(1));
                } else if (count <= 7) {
                    heatMap.add("crowd-density", new JsonPrimitive(2));
                } else if (count <= 13) {
                    heatMap.add("crowd-density", new JsonPrimitive(3));
                } else if (count <= 20) {
                    heatMap.add("crowd-density", new JsonPrimitive(4));
                } else {
                    heatMap.add("crowd-density", new JsonPrimitive(5));
                }
                results.add(heatMap);
            }
            List<JsonObject> jsonValues = new ArrayList<JsonObject>();
            JsonArray sortedJsonArray = new JsonArray();
            for (JsonElement jo : results) {
                jsonValues.add((JsonObject) jo);
            }
            Collections.sort(jsonValues, new Comparator<JsonObject>() {
                //You can change "Name" with "ID" if you want to sort by ID
                private static final String KEY_NAME = "semantic-place";

                @Override
                public int compare(JsonObject a, JsonObject b) {
                    String valA = a.get(KEY_NAME).toString();
                    String valB = b.get(KEY_NAME).toString();

                    return valA.compareTo(valB);
                }
            });
            for (int i = 0; i < results.size(); i++) {
                sortedJsonArray.add(jsonValues.get(i));
            }
            jsonOutput.addProperty("status", "success");
            jsonOutput.add("heatmap", sortedJsonArray);
        }
        //writes the output as a response (but not html)

        out.println(gson.toJson(jsonOutput));
        System.out.println(gson.toJson(jsonOutput));
    } finally {
        ConnectionManager.close(conn);
    }
}

From source file:com.arangodb.entity.EntityFactory.java

License:Apache License

public static <T> String toJsonString(T obj, boolean includeNullValue) {
    if (obj != null && obj.getClass().equals(BaseDocument.class)) {
        String tmp = includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj);
        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(tmp);
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        JsonObject result = jsonObject.getAsJsonObject("properties");
        JsonElement keyObject = jsonObject.get("_key");
        if (keyObject != null && keyObject.getClass() != JsonNull.class) {
            result.add("_key", jsonObject.get("_key"));
        }/*from w ww  . ja  va2 s.c  o m*/
        JsonElement handleObject = jsonObject.get("_id");
        if (handleObject != null && handleObject.getClass() != JsonNull.class) {
            result.add("_id", jsonObject.get("_id"));
        }
        // JsonElement revisionValue = jsonObject.get("documentRevision");
        // result.add("_rev", revisionValue);
        return result.toString();
    }
    return includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj);
}

From source file:com.arcbees.vcs.util.PolymorphicTypeAdapter.java

License:Apache License

@Override
public JsonElement serialize(T src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject retValue = new JsonObject();

    String className = src.getClass().getCanonicalName();
    retValue.addProperty(CLASSNAME, className);

    JsonElement jsonElement = context.serialize(src);
    retValue.add(VALUE, jsonElement);

    return retValue;
}

From source file:com.asakusafw.lang.inspection.json.NodeAdapter.java

License:Apache License

@Override
public JsonElement serialize(InspectionNode src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    result.add(KEY_ID, new JsonPrimitive(src.getId()));
    result.add(KEY_TITLE, new JsonPrimitive(src.getTitle()));
    result.add(KEY_INPUTS, context.serialize(extract(src.getInputs()), TYPE_PORTS));
    result.add(KEY_OUTPUTS, context.serialize(extract(src.getOutputs()), TYPE_PORTS));
    result.add(KEY_PROPERTIES, context.serialize(src.getProperties(), TYPE_PROPERTIES));
    result.add(KEY_ELEMENTS, context.serialize(extract(src.getElements()), TYPE_NODES));
    return result;
}

From source file:com.asakusafw.lang.inspection.json.PortAdapter.java

License:Apache License

@Override
public JsonElement serialize(InspectionNode.Port src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject result = new JsonObject();
    result.add(KEY_ID, new JsonPrimitive(src.getId()));
    result.add(KEY_PROPERTIES, context.serialize(src.getProperties(), TYPE_PROPERTIES));
    result.add(KEY_OPPOSITES, context.serialize(src.getOpposites(), TYPE_REFERENCES));
    return result;
}

From source file:com.asakusafw.yaess.tools.Explain.java

License:Apache License

private static JsonObject analyzeBatch(BatchScript script) {
    assert script != null;
    JsonArray jobflows = new JsonArray();
    for (FlowScript flowScript : script.getAllFlows()) {
        JsonObject jobflow = analyzeJobflow(flowScript);
        jobflows.add(jobflow);/*from w  w w. j av a 2 s.com*/
    }
    JsonObject batch = new JsonObject();
    batch.addProperty("id", script.getId());
    batch.add("jobflows", jobflows);
    return batch;
}

From source file:com.asakusafw.yaess.tools.Explain.java

License:Apache License

private static JsonObject analyzeJobflow(FlowScript flowScript) {
    assert flowScript != null;
    JsonArray phases = new JsonArray();
    for (Map.Entry<ExecutionPhase, Set<ExecutionScript>> entry : flowScript.getScripts().entrySet()) {
        ExecutionPhase phase = entry.getKey();
        if (entry.getValue().isEmpty() == false || phase == ExecutionPhase.SETUP
                || phase == ExecutionPhase.CLEANUP) {
            phases.add(new JsonPrimitive(phase.getSymbol()));
        }//from w  w w. j av  a  2s  .  c  o m
    }
    JsonObject jobflow = new JsonObject();
    jobflow.addProperty("id", flowScript.getId());
    jobflow.add("blockers", toJsonArray(flowScript.getBlockerIds()));
    jobflow.add("phases", phases);
    return jobflow;
}

From source file:com.atlauncher.data.mojang.PropertyMapSerializer.java

License:Open Source License

@Override
public JsonElement serialize(PropertyMap src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject out = new JsonObject();
    for (String key : src.keySet()) {
        JsonArray jsa = new JsonArray();
        for (com.mojang.authlib.properties.Property p : src.get(key)) {
            jsa.add(new JsonPrimitive(p.getValue()));
        }//w w w.ja v a 2  s .  co m
        out.add(key, jsa);
    }
    return out;
}

From source file:com.att.pirates.controller.ProjectController.java

@RequestMapping(value = "/pid/{prismId}/getProjectNotesJson", method = RequestMethod.GET)
public @ResponseBody String getCompanies(@PathVariable("prismId") String prismId, HttpServletRequest request) {
    // logger.error(msgHeader + " getCompanies prismId: " + prismId);
    JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);

    String sEcho = param.sEcho;//from w  ww .ja  v  a 2s . co m
    int iTotalRecords; // total number of records (unfiltered)
    int iTotalDisplayRecords; //value will be set when code filters companies by keyword
    List<Company> allNotes = GlobalDataController.GetCompanies(prismId);

    iTotalRecords = allNotes.size();
    List<Company> companies = new LinkedList<Company>();
    for (Company c : allNotes) {
        if (c.getName().toLowerCase().contains(param.sSearch.toLowerCase())
                || c.getAddress().toLowerCase().contains(param.sSearch.toLowerCase())
                || c.getTown().toLowerCase().contains(param.sSearch.toLowerCase())
                || c.getDateCreated().toLowerCase().contains(param.sSearch.toLowerCase())) {
            companies.add(c); // add company that matches given search criterion
        }
    }
    iTotalDisplayRecords = companies.size();// number of companies that match search criterion should be returned

    final int sortColumnIndex = param.iSortColumnIndex;
    final int sortDirection = param.sSortDirection.equals("asc") ? -1 : 1;

    Collections.sort(companies, new Comparator<Company>() {
        @Override
        public int compare(Company c1, Company c2) {
            switch (sortColumnIndex) {
            case 0:
                return 0; // sort by id is not allowed
            case 1:
                return c1.getName().compareTo(c2.getName()) * sortDirection;
            case 2:
                return c1.getAddress().compareTo(c2.getAddress()) * sortDirection;
            case 3:
                return c1.getTown().compareTo(c2.getTown()) * sortDirection;
            case 4:
                SimpleDateFormat yFormat = new SimpleDateFormat("MM/dd/yyyy");
                try {
                    Date c1d = yFormat.parse(c1.getDateCreated());
                    Date c2d = yFormat.parse(c2.getDateCreated());

                    return c1d.compareTo(c2d) * sortDirection;
                } catch (ParseException ex) {
                    logger.error(ex.getMessage());
                }
            }
            return 0;
        }
    });

    if (companies.size() < param.iDisplayStart + param.iDisplayLength) {
        companies = companies.subList(param.iDisplayStart, companies.size());
    } else {
        companies = companies.subList(param.iDisplayStart, param.iDisplayStart + param.iDisplayLength);
    }

    try {
        JsonObject jsonResponse = new JsonObject();
        jsonResponse.addProperty("sEcho", sEcho);
        jsonResponse.addProperty("iTotalRecords", iTotalRecords);
        jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
        Gson gson = new Gson();
        jsonResponse.add("aaData", gson.toJsonTree(companies));

        String tmp = jsonResponse.toString();
        // logger.error(msgHeader + ".. json string: " + tmp);
        return jsonResponse.toString();
    } catch (JsonIOException e) {
        logger.error(msgHeader + e.getMessage());
    }
    return null;
}

From source file:com.autoclavestudios.jbower.config.internal.JsonRegistryTranslator.java

License:Apache License

@Override
public JsonElement serialize(Registry src, Type typeOfSrc, JsonSerializationContext context) {

    JsonElement jsonElement = null;//from  w w  w  . j  a va 2 s. c  o  m
    if (src.isSimple()) {
        if (src.search().size() == 1) {
            jsonElement = new JsonPrimitive(src.search().get(0).toString());
        }
    } else {
        JsonObject jsonObject = new JsonObject();
        jsonObject.add("register", ConvertToJsonArray(src.register()));
        jsonObject.add("search", ConvertToJsonArray(src.search()));
        jsonObject.add("publish", ConvertToJsonArray(src.publish()));
        jsonElement = jsonObject;
    }

    return jsonElement;
}