Example usage for com.google.gson JsonObject get

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

Introduction

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

Prototype

public JsonElement get(String memberName) 

Source Link

Document

Returns the member with the specified name.

Usage

From source file:com.android.tools.lint.checks.AppLinksAutoVerifyDetector.java

License:Apache License

/**
 * Gets the package names of all the apps from the Digital Asset Links JSON file.
 *
 * @param element The JsonElement of the json file.
 * @return All the package names.// w ww . j a v  a2s  .c  om
 */
private static List<String> getPackageNameFromJson(JsonElement element) {
    List<String> packageNames = Lists.newArrayList();
    if (element instanceof JsonArray) {
        JsonArray jsonArray = (JsonArray) element;
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonElement app = jsonArray.get(i);
            if (app instanceof JsonObject) {
                JsonObject target = ((JsonObject) app).getAsJsonObject("target");
                if (target != null) {
                    // Checks namespace to ensure it is an app statement.
                    JsonElement namespace = target.get("namespace");
                    JsonElement packageName = target.get("package_name");
                    if (namespace != null && namespace.getAsString().equals("android_app")
                            && packageName != null) {
                        packageNames.add(packageName.getAsString());
                    }
                }
            }
        }
    }
    return packageNames;
}

From source file:com.apcb.utils.utils.HtmlTemplateReader.java

private SectionMatch readJson(JsonElement jsonElement, String from, SectionMatch sectionMatch) {
    //log.info(jsonElement.toString());
    //SectionMatch sectionMatchChild = new SectionMatch(from);
    if (jsonElement.isJsonArray()) {
        //log.info("JsonArray");
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            SectionMatch sectionMatchArrayLevel = new SectionMatch(sectionMatch.getName());
            sectionMatchArrayLevel.setIndex(i);
            sectionMatch.putChildens(readJson(jsonArray.get(i), from + "[" + i + "]", sectionMatchArrayLevel));
        }/*w ww .j a va 2  s .  c o m*/
    } else if (jsonElement.isJsonObject()) {
        //log.info("JsonObject");
        JsonObject jsonObject = jsonElement.getAsJsonObject(); //since you know it's a JsonObject
        Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();//will return members of your object
        for (Map.Entry<String, JsonElement> entry : entries) {
            //log.info(entry.getKey());
            sectionMatch.putChildens(readJson(jsonObject.get(entry.getKey()), from + "." + entry.getKey(),
                    new SectionMatch(entry.getKey())));
        }
    } else if (jsonElement.isJsonNull()) {
        log.info("JsonNull");
    } else if (jsonElement.isJsonPrimitive()) {
        //log.info("JsonPrimitive");
        String jsonVal = jsonElement.getAsString();
        //from+= "."+entry.getKey(); 
        sectionMatch.setValue(jsonVal);
        log.info(from + "=" + jsonVal);
    }

    return sectionMatch;
}

From source file:com.apifest.AccessTokenValidator.java

License:Apache License

protected static String extractTokenScope(String tokenContent) {
    String scope = null;/*from w w  w  .jav  a 2 s. co m*/
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = parser.parse(tokenContent).getAsJsonObject();
    JsonElement scopeElement = jsonObject.get("scope");
    String rs = (scopeElement != null && !scopeElement.isJsonNull()) ? scopeElement.getAsString() : null;
    if (rs != null && !rs.toString().equals("null")) {
        scope = rs;
    }
    return scope;
}

From source file:com.apifest.api.BasicAction.java

License:Apache License

/**
 * Extracts userId from tokenValidationResponse.
 * @param response the response received after access token is validate
 * @return userId associated with a token
 *///w ww.j a  v a2  s.  c  o m
public static String getUserId(HttpResponse tokenValidationResponse) {
    String userId = null;
    if (tokenValidationResponse != null) {
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(tokenValidationResponse.getContent().toString(CharsetUtil.UTF_8))
                .getAsJsonObject();
        JsonElement userIdElement = json.get("userId");
        userId = (userIdElement != null && !userIdElement.isJsonNull()) ? userIdElement.getAsString() : null;
    }
    return userId;
}

From source file:com.apifest.oauth20.MongoDBManager.java

License:Apache License

protected String constructDbId(Object object) {
    Gson gson = new Gson();
    String json = gson.toJson(object);
    JsonParser parser = new JsonParser();
    JsonObject jsonObj = parser.parse(json).getAsJsonObject();
    if (jsonObj.has("id")) {
        String id = jsonObj.get("id").getAsString();
        jsonObj.remove("id");
        jsonObj.addProperty(ID_NAME, id);
    }//from   ww  w  . j  a v a2 s .  co  m
    return jsonObj.toString();
}

From source file:com.apifest.oauth20.persistence.mongodb.MongoDBManager.java

License:Apache License

protected String constructDbId(Object object) {
    Gson gson = new Gson();
    String json = gson.toJson(object);
    JsonParser parser = new JsonParser();
    JsonObject jsonObj = parser.parse(json).getAsJsonObject();
    if (jsonObj.has("id")) {
        String id = jsonObj.get("id").getAsString();
        jsonObj.remove("id");
        jsonObj.addProperty(CLIENTS_ID, id);
    }/*  ww  w .  ja v  a  2  s .c  o m*/
    return jsonObj.toString();
}

From source file:com.apifest.oauth20.RevokeTokenRequest.java

License:Apache License

public RevokeTokenRequest(HttpRequest request) {
    String content = request.getContent().toString(CharsetUtil.UTF_8);
    JsonParser parser = new JsonParser();
    try {//  ww  w.j av  a  2s  .co m
        JsonObject jsonObj = parser.parse(content).getAsJsonObject();
        this.accessToken = (jsonObj.get(ACCESS_TOKEN) != null) ? jsonObj.get(ACCESS_TOKEN).getAsString() : null;
        this.clientId = (jsonObj.get(CLIENT_ID) != null) ? jsonObj.get(CLIENT_ID).getAsString() : null;
    } catch (JsonSyntaxException e) {
        // do nothing
    }
}

From source file:com.apifest.oauth20.RevokeUserTokensRequest.java

License:Apache License

public RevokeUserTokensRequest(HttpRequest request) {
    String content = request.getContent().toString(CharsetUtil.UTF_8);
    JsonParser parser = new JsonParser();
    try {//  w w w  .jav  a2 s  . c  om
        JsonObject jsonObj = parser.parse(content).getAsJsonObject();
        this.userId = (jsonObj.get(USER_ID) != null) ? jsonObj.get(USER_ID).getAsString() : null;
    } catch (JsonSyntaxException e) {
        // do nothing
    }
}

From source file:com.apothesource.pillfill.service.drug.impl.DefaultDrugAlertServiceImpl.java

License:Open Source License

private List<DrugAlertType> deserializeDrugAlerts(Collection<PrescriptionType> rxs, String msg) {
    try {//from  w w w.  j  av a  2s  .  co  m
        JsonObject returnValue = new JsonParser().parse(msg).getAsJsonObject();
        if (!returnValue.has("fullInteractionTypeGroup")) {
            return Collections.emptyList();
        } else {
            Gson gson = new Gson();
            TypeToken<List<FullInteractionTypeGroup>> interactionGroupListType = new TypeToken<List<FullInteractionTypeGroup>>() {
            };
            List<FullInteractionTypeGroup> group = gson.fromJson(returnValue.get("fullInteractionTypeGroup"),
                    interactionGroupListType.getType());
            ArrayList<DrugAlertType> alerts = processDrugInteractions(rxs, group);
            return alerts;

        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Invalid drug interaction alert response.", e);
        throw new RuntimeException(e);
    }
}

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