Example usage for com.google.gson JsonArray size

List of usage examples for com.google.gson JsonArray size

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

From source file:com.android.tools.idea.gradle.structure.model.repositories.search.JCenterRepository.java

License:Apache License

SearchResult parse(@NotNull Reader response) {
    /*//from  w  w  w.  ja  va 2s .  c o  m
      Sample response:
      [
        {
          "name": "com.atlassian.guava:guava",
          "repo": "jcenter",
          "owner": "bintray",
          "desc": null,
          "system_ids": [
    "com.atlassian.guava:guava"
          ],
          "versions": [
    "15.0"
          ],
          "latest_version": "15.0"
        },
        {
          "name": "com.atlassian.bundles:guava",
          "repo": "jcenter",
          "owner": "bintray",
          "desc": null,
          "system_ids": [
    "com.atlassian.bundles:guava"
          ],
          "versions": [
    "8.1",
    "8.0",
    "1.0-actually-8.1"
          ],
          "latest_version": "8.1"
        },
        {
          "name": "io.janusproject.guava:guava",
          "repo": "jcenter",
          "owner": "bintray",
          "desc": null,
          "system_ids": [
    "io.janusproject.guava:guava"
          ],
          "versions": [
    "19.0.0",
    "17.0.2",
    "17.0"
          ],
          "latest_version": "19.0.0"
        },
        {
          "name": "com.google.guava:guava",
          "repo": "jcenter",
          "owner": "bintray",
          "desc": "Guava is a suite of core and expanded libraries that include\n    utility classes, google's collections, io classes, and much\n    much more.\n\n    Guava has two code dependencies - javax.annotation\n    per the JSR-305 spec and javax.inject per the JSR-330 spec.",
          "system_ids": [
    "com.google.guava:guava"
          ],
          "versions": [
    "19.0",
    "19.0-rc3",
    "19.0-rc2",
    "19.0-rc1",
    "18.0",
    "18.0-rc2",
    "18.0-rc1",
    "11.0.2-atlassian-02",
    "17.0",
    "17.0-rc2",
    "17.0-rc1",
    "16.0.1",
    "16.0",
    "16.0-rc1",
    "15.0",
    "15.0-rc1",
    "14.0.1",
    "14.0",
    "14.0-rc3",
    "14.0-rc2",
    "14.0-rc1",
    "13.0.1",
    "13.0",
    "13.0-final",
    "13.0-rc2",
    "13.0-rc1",
    "12.0.1",
    "12.0",
    "12.0-rc2",
    "12.0-rc1",
    "11.0.2-atlassian-01",
    "11.0.2",
    "11.0.1",
    "11.0",
    "11.0-rc1",
    "10.0.1",
    "10.0",
    "10.0-rc3",
    "10.0-rc2",
    "10.0-rc1",
    "r09",
    "r08",
    "r07",
    "r06",
    "r05",
    "r03"
          ],
          "latest_version": "19.0"
        }
      ]
     */

    JsonParser parser = new JsonParser();
    JsonArray array = parser.parse(response).getAsJsonArray();

    int totalFound = array.size();
    List<FoundArtifact> artifacts = Lists.newArrayListWithExpectedSize(totalFound);

    for (int i = 0; i < totalFound; i++) {
        JsonObject root = array.get(i).getAsJsonObject();
        String name = root.getAsJsonPrimitive("name").getAsString();

        List<GradleVersion> availableVersions = Lists.newArrayList();
        JsonArray versions = root.getAsJsonArray("versions");
        versions.forEach(element -> {
            String version = element.getAsString();
            availableVersions.add(GradleVersion.parse(version));
        });

        List<String> coordinate = Splitter.on(GRADLE_PATH_SEPARATOR).splitToList(name);
        assert coordinate.size() == 2;

        artifacts.add(new FoundArtifact(getName(), coordinate.get(0), coordinate.get(1), availableVersions));
    }

    return new SearchResult(getName(), artifacts, totalFound);
}

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.// ww  w.j av a 2 s .c o m
 */
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));
        }/*from  www . j a  v  a 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.app.json.overuse_report.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w . j  a v a 2 s . 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
 * @throws java.text.ParseException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, ParseException {
    response.setContentType("application/JSON");
    Connection conn = null;
    try (PrintWriter out = response.getWriter()) {
        conn = ConnectionManager.getConnection();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonObject jsonOutput = new JsonObject();
        JsonArray errorJsonList = new JsonArray();
        String startdate = request.getParameter("startdate");
        String enddate = request.getParameter("enddate");
        String token = request.getParameter("token");
        String macAdd = request.getParameter("macaddress");
        Date startDateFmt = new Date();
        Date endDateFmt = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);

        if (macAdd == null) {
            errorJsonList.add(new JsonPrimitive("missing macaddress"));
        } else if (macAdd.equals("")) {
            errorJsonList.add(new JsonPrimitive("blank macaddress"));
        } else {
            if (UserDAO.retrieveUserByMacAddress(macAdd, conn) == null) {
                errorJsonList.add(new JsonPrimitive("invalid macaddress"));
            }
        }

        if (startdate == null) {
            errorJsonList.add(new JsonPrimitive("missing startdate"));
        } else if (startdate.equals("")) {
            errorJsonList.add(new JsonPrimitive("blank startdate"));
        } else {
            try {
                startDateFmt = df.parse(startdate);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid startdate"));
            }
        }

        if (enddate == null) {
            errorJsonList.add(new JsonPrimitive("missing enddate"));
        } else if (enddate.equals("")) {
            errorJsonList.add(new JsonPrimitive("blank enddate"));
        } else {
            try {
                endDateFmt = df.parse(enddate);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid enddate"));
            }
        }
        if (startDateFmt != null && endDateFmt != null && startDateFmt.after(endDateFmt)) {
            errorJsonList.add(new JsonPrimitive("invalid startdate"));
        }
        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 {
            ArrayList<String> macaddress = new ArrayList<>();
            macaddress.add(macAdd);
            ArrayList<AppUsage> usages = AppUsageDAO.retrieve(macaddress, startdate, enddate, conn);
            char duration;
            char gameDuration;
            char frequency;
            long days = 0;
            float totalDuration = 0;
            days = SmartphoneOveruseUtility.getDays(startdate, enddate);
            totalDuration = (float) SmartphoneOveruseUtility.getDuration(usages, enddate);

            float durationValue = totalDuration / days;
            int durationValueSecs = Math.round(durationValue);
            if (durationValue >= 5 * 3600) {
                duration = 'S';
            } else if (durationValue >= 3 * 3600) {
                duration = 'M';
            } else {
                duration = 'L';
            }

            ArrayList<Integer> gameID = AppDAO.retrieveID("games", conn);
            ArrayList<AppUsage> gameUsage = AppUsageDAO.retrieve(macaddress.get(0), startdate, enddate, gameID,
                    conn);
            float totalGameDuration = 0;
            int gameDurationValueSec = 0;
            try {
                totalGameDuration = (float) SmartphoneOveruseUtility.getDuration(gameUsage, enddate);

            } catch (ParseException e) {

            }
            float gameDurationValue = totalGameDuration / days;
            gameDurationValueSec = Math.round(gameDurationValue);
            if (gameDurationValue >= 2 * 3600) {
                gameDuration = 'S';
            } else if (gameDurationValue >= 1 * 3600) {
                gameDuration = 'M';
            } else {
                gameDuration = 'L';
            }

            float frequencyValue = 0;
            float frequencyFormatValue = 0;

            frequencyValue = SmartphoneOveruseUtility.getFrequency(usages, enddate, days);
            frequencyFormatValue = Math.round(frequencyValue * 10) / 10;

            if (frequencyValue >= 5) {
                frequency = 'S';
            } else if (frequencyValue >= 3) {
                frequency = 'M';
            } else {
                frequency = 'L';
            }
            JsonObject result = new JsonObject();

            HashMap<Character, String> metrics = new HashMap<Character, String>();
            metrics.put('S', "Severe");
            metrics.put('L', "Light");
            metrics.put('M', "Moderate");
            if (!(duration != 'S' && gameDuration != 'S' && frequency != 'S')) {
                JsonObject usage = new JsonObject();
                JsonObject gaming = new JsonObject();
                JsonObject accessF = new JsonObject();
                JsonArray metricsArr = new JsonArray();
                result.addProperty("overuse-index", "Overusing");
                String usageCat = metrics.get(duration);
                usage.addProperty("usage-category", usageCat);
                usage.addProperty("usage-duration", durationValueSecs);
                metricsArr.add(usage);
                String gamingCat = metrics.get(gameDuration);
                gaming.addProperty("gaming-category", gamingCat);
                gaming.addProperty("gaming-duration", gameDurationValueSec);
                metricsArr.add(gaming);
                String accessFrequencyCat = metrics.get(frequency);
                accessF.addProperty("accessfrequency-category", accessFrequencyCat);
                accessF.addProperty("accessfrequency", frequencyFormatValue);
                metricsArr.add(accessF);
                result.add("metrics", metricsArr);
            } else if (duration == 'L' && gameDuration == 'L' && frequency == 'L') {
                JsonObject usage = new JsonObject();
                JsonObject gaming = new JsonObject();
                JsonObject accessF = new JsonObject();
                JsonArray metricsArr = new JsonArray();
                result.addProperty("overuse-index", "Normal");
                String usageCat = metrics.get(duration);
                usage.addProperty("usage-category", usageCat);
                usage.addProperty("usage-duration", durationValueSecs);
                metricsArr.add(usage);
                String gamingCat = metrics.get(gameDuration);
                gaming.addProperty("gaming-category", gamingCat);
                gaming.addProperty("gaming-duration", gameDurationValueSec);
                metricsArr.add(gaming);
                String accessFrequencyCat = metrics.get(frequency);
                accessF.addProperty("accessfrequency-category", accessFrequencyCat);
                accessF.addProperty("accessfrequency", frequencyFormatValue);
                metricsArr.add(accessF);
                result.add("metrics", metricsArr);
            } else {
                JsonObject usage = new JsonObject();
                JsonObject gaming = new JsonObject();
                JsonObject accessF = new JsonObject();
                JsonArray metricsArr = new JsonArray();
                result.addProperty("overuse-index", "ToBeCautious");
                String usageCat = metrics.get(duration);
                usage.addProperty("usage-category", usageCat);
                usage.addProperty("usage-duration", durationValueSecs);
                metricsArr.add(usage);
                String gamingCat = metrics.get(gameDuration);
                gaming.addProperty("gaming-category", gamingCat);
                gaming.addProperty("gaming-duration", gameDurationValueSec);
                metricsArr.add(gaming);
                String accessFrequencyCat = metrics.get(frequency);
                accessF.addProperty("accessfrequency-category", accessFrequencyCat);
                accessF.addProperty("accessfrequency", frequencyFormatValue);
                metricsArr.add(accessF);
                result.add("metrics", metricsArr);
            }
            jsonOutput.addProperty("status", "success");
            jsonOutput.add("results", result);
        }
        try {
            out.println(gson.toJson(jsonOutput));
        } finally {
            out.close();
            ConnectionManager.close(conn);
        }
    }
}

From source file:com.app.json.top_k_most_used_apps.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from ww w . ja  v  a2s .c om*/
 *
 * @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();
        JsonObject jsonOutput = new JsonObject();
        JsonArray errorJsonList = new JsonArray();
        //retrieves the user
        String[] schools = { "sis", "economics", "socsc", "law", "accountancy", "business" };
        List<String> schoolList = (List<String>) Arrays.asList(schools);
        String startdate = request.getParameter("startdate");
        String enddate = request.getParameter("enddate");
        String token = request.getParameter("token");
        String k = request.getParameter("k");
        String school = request.getParameter("school");
        Date startDateFmt = null;
        Date endDateFmt = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);
        JsonObject temp = new JsonObject();
        if (startdate == null || startdate.equals("")) {
            errorJsonList.add(new JsonPrimitive("invalid startdate"));
        } else {
            try {
                startDateFmt = df.parse(startdate);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid startdate"));
            }
        }
        if (enddate == null || enddate.equals("")) {
            errorJsonList.add(new JsonPrimitive("invalid enddate"));
        } else {
            try {
                endDateFmt = df.parse(enddate);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid enddate"));
            }
        }
        if (startDateFmt != null && endDateFmt != null && startDateFmt.after(endDateFmt)) {
            errorJsonList.add(new JsonPrimitive("invalid startdate"));
        }
        int kInt = 0;
        if (k == null || k.equals("")) {
            kInt = 3;
        } else {
            try {
                kInt = Integer.parseInt(k);
                if (kInt < 1 || kInt > 10) {
                    errorJsonList.add(new JsonPrimitive("invalid k"));
                }
            } catch (NumberFormatException e) {
                errorJsonList.add(new JsonPrimitive("invalid k"));
            }
        }
        String sharedSecret = "is203g4t6luvjava";
        String username = "";
        try {
            username = JWTUtility.verify(token, sharedSecret);
        } catch (JWTException ex) {
            errorJsonList.add(new JsonPrimitive("invalid token"));
        }
        if (!schoolList.contains(school)) {
            errorJsonList.add(new JsonPrimitive("invalid school"));
        }
        if (errorJsonList.size() > 0) {
            jsonOutput.addProperty("status", "error");
            jsonOutput.add("messages", errorJsonList);
        } else {
            JsonArray results = new JsonArray();
            ArrayList<String> macList = UserDAO.retrieveMacAddress(school, conn);
            ArrayList<AppUsage> usages = AppUsageDAO.retrieve(macList, startdate, enddate, conn);
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            HashMap<String, TreeMap<Long, Integer>> usageMap = new HashMap<>();
            for (AppUsage usage : usages) {
                String mac = usage.getMacAddress();
                String timestamp = usage.getTimestamp();
                Date date = new Date();
                try {
                    date = fmt.parse(timestamp);
                } catch (ParseException ex) {
                    Logger.getLogger(top_k_most_used_apps.class.getName()).log(Level.SEVERE, null, ex);
                }
                int appid = usage.getId();
                if (usageMap.get(mac) == null) {
                    TreeMap<Long, Integer> tm = new TreeMap<>();
                    tm.put(date.getTime(), appid);
                    usageMap.put(mac, tm);
                } else {
                    TreeMap<Long, Integer> tm = usageMap.get(mac);
                    tm.put(date.getTime(), appid);
                    usageMap.put(mac, tm);
                }
            }
            HashMap<Integer, Long> appDuMap = new HashMap<>();
            Set<String> macSet = usageMap.keySet();
            Iterator ite = macSet.iterator();
            while (ite.hasNext()) {
                String mac = (String) ite.next();
                TreeMap<Long, Integer> tm = usageMap.get(mac);
                Set<Long> timeSet = tm.keySet();
                Iterator timeIte = timeSet.iterator();
                long time1 = (long) timeIte.next();
                long time2;
                int id1 = tm.get(time1);
                int id2;
                long duration = 0;
                if (!timeIte.hasNext()) {//the last record

                    Date end = new Date();
                    try {
                        end = fmt.parse(enddate + " 23:59:59");
                    } catch (ParseException ex) {
                        Logger.getLogger(top_k_most_used_apps.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    long lastDif = (end.getTime() - time1) / 1000;
                    if (lastDif > 120) {
                        lastDif = 10;
                    }
                    duration += lastDif;
                    if (appDuMap.get(id1) == null) {
                        appDuMap.put(id1, duration);
                    } else {
                        long d = appDuMap.get(id1) + duration;
                        appDuMap.put(id1, d);
                    }
                } else {
                    while (timeIte.hasNext()) {//go through the treemap<date, appid> of one mac address
                        time2 = (long) timeIte.next();
                        id2 = tm.get(time2);
                        long dif = (time2 - time1) / 1000; // seconds
                        if (dif > 120) {
                            dif = 10;
                        }
                        duration += dif;
                        if (id1 != id2) {
                            if (appDuMap.get(id1) == null) {
                                appDuMap.put(id1, duration);
                            } else {
                                long d = appDuMap.get(id1) + duration;
                                appDuMap.put(id1, d);
                            }
                            duration = 0;
                        }
                        if (!timeIte.hasNext()) {//the last record

                            Date end = new Date();
                            try {
                                end = fmt.parse(enddate + " 23:59:59");
                            } catch (ParseException ex) {
                                Logger.getLogger(top_k_most_used_apps.class.getName()).log(Level.SEVERE, null,
                                        ex);
                            }

                            long lastDif = (end.getTime() - time2) / 1000;
                            if (lastDif > 120) {
                                lastDif = 10;
                            }
                            duration += lastDif;
                            if (appDuMap.get(id2) == null) {
                                appDuMap.put(id2, duration);
                            } else {
                                long d = appDuMap.get(id2) + duration;
                                appDuMap.put(id2, d);
                            }
                        }
                        id1 = id2;
                        time1 = time2;
                    }
                }
            }
            TreeMap<Long, ArrayList<String>> duAppMap = new TreeMap<>();
            Set<Integer> aSet = appDuMap.keySet();
            Iterator iter = aSet.iterator();
            while (iter.hasNext()) {
                int id = (int) iter.next();
                String name = AppDAO.retrieveName(id, conn);
                long dur = appDuMap.get(id);
                if (duAppMap.get(dur) == null) {
                    ArrayList<String> iList = new ArrayList<>();
                    iList.add(name);
                    duAppMap.put(dur, iList);
                } else {
                    ArrayList<String> iList = duAppMap.get(dur);
                    iList.add(name);
                    duAppMap.put(dur, iList);
                }
            }
            NavigableMap<Long, ArrayList<String>> map1 = null;
            TreeMap<Long, ArrayList<String>> treemap1 = duAppMap;
            if (treemap1 != null) {
                map1 = treemap1.descendingMap();
            }
            if (map1 != null && !map1.isEmpty()) {
                Set<Long> durSet = map1.keySet();
                Iterator it = durSet.iterator();
                int kCount = kInt;
                int rank = 1;
                while (it.hasNext() && rank <= kCount) {
                    Long usage = (Long) it.next();
                    ArrayList<String> apps = map1.get(usage);
                    Collections.sort(apps);
                    int count = 0;
                    for (int i = 0; i < apps.size(); i++) {
                        JsonObject obj = new JsonObject();
                        obj.addProperty("rank", rank);
                        obj.addProperty("app-name", apps.get(i));
                        obj.addProperty("duration", usage);
                        results.add(obj);
                        count++;
                    }
                    rank += count;
                }
            }

            jsonOutput.addProperty("status", "success");
            jsonOutput.add("results", results);
        }
        try {
            out.println(gson.toJson(jsonOutput));
        } finally {
            out.close();
            ConnectionManager.close(conn);
        }
    }
}

From source file:com.app.json.top_k_most_used_schools.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w  w  w  .j  a v a2 s.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();
        JsonObject jsonOutput = new JsonObject();
        JsonArray errorJsonList = new JsonArray();
        ArrayList<String> categories = AppDAO.retrieveAllAppCategory(conn);

        String startdate = request.getParameter("startdate");
        String enddate = request.getParameter("enddate");
        String token = request.getParameter("token");
        String k = request.getParameter("k");
        String appcategory = request.getParameter("appcategory");

        Date startDateFmt = null;
        Date endDateFmt = null;

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);
        if (startdate == null || startdate.equals("")) {
            errorJsonList.add(new JsonPrimitive("invalid startdate"));
        } else {
            try {
                startDateFmt = df.parse(startdate);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid startdate"));
            }
        }
        if (enddate == null || enddate.equals("")) {
            errorJsonList.add(new JsonPrimitive("invalid enddate"));
        } else {
            try {
                endDateFmt = df.parse(enddate);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid enddate"));
            }
        }
        if (startDateFmt != null && endDateFmt != null && startDateFmt.after(endDateFmt)) {
            errorJsonList.add(new JsonPrimitive("invalid startdate"));
        }
        int kValue = 0;
        if (k == null || k.equals("")) {
            kValue = 3;
        } else {
            try {
                kValue = Integer.parseInt(k);
                if (kValue < 1 || kValue > 10) {
                    errorJsonList.add(new JsonPrimitive("invalid k"));
                }
            } catch (NumberFormatException e) {
                errorJsonList.add(new JsonPrimitive("invalid k"));
            }
        }
        if (!categories.contains(appcategory)) {
            errorJsonList.add(new JsonPrimitive("invalid app category"));
        }
        String sharedSecret = "is203g4t6luvjava";
        String username = "";
        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 {
            JsonArray results = new JsonArray();

            if (!k.equals("")) {
                ArrayList<Integer> idList = AppDAO.retrieveID(appcategory, conn);
                ArrayList<AppUsage> usages = AppUsageDAO.retrieve(startdate, enddate, conn);
                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                HashMap<String, TreeMap<Long, Integer>> usageMap = new HashMap<>();
                //HashMap<macaddress, TreeMap<date, appid>>
                for (AppUsage usage : usages) {
                    String mac = usage.getMacAddress();
                    String timestamp = usage.getTimestamp();
                    Date date = new Date();
                    try {
                        date = fmt.parse(timestamp);
                    } catch (ParseException ex) {
                        Logger.getLogger(top_k_most_used_schools.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    int appid = usage.getId();
                    if (usageMap.get(mac) == null) {//this mac address hasn't been put into the hashmap
                        TreeMap<Long, Integer> tm = new TreeMap<>();
                        tm.put(date.getTime(), appid);
                        usageMap.put(mac, tm);
                    } else {//this mac address already exists in the hashmap
                        TreeMap<Long, Integer> tm = usageMap.get(mac);
                        tm.put(date.getTime(), appid);
                        usageMap.put(mac, tm);
                    }
                }
                HashMap<String, Long> macDuMap = new HashMap<>();
                //<MacAddress, Duration>
                Set<String> macSet = usageMap.keySet();
                Iterator ite = macSet.iterator();
                while (ite.hasNext()) {//for a mac address:
                    HashMap<Integer, Long> appDuMap = new HashMap<>();
                    //<appid, duration>
                    String mac = (String) ite.next();
                    TreeMap<Long, Integer> tm = usageMap.get(mac);
                    //<date, appid>
                    Set<Long> timeSet = tm.keySet();
                    Iterator timeIte = timeSet.iterator();
                    long time1 = (long) timeIte.next();
                    long time2;
                    int id1 = tm.get(time1);
                    int id2;
                    long duration = 0;
                    if (!timeIte.hasNext()) {
                        Date end = new Date();
                        try {
                            end = fmt.parse(enddate + " 23:59:59");
                        } catch (ParseException ex) {
                            Logger.getLogger(top_k_most_used_schools.class.getName()).log(Level.SEVERE, null,
                                    ex);
                        }
                        long lastDif = (end.getTime() - time1) / 1000;
                        if (lastDif > 120) {
                            lastDif = 10;
                        }
                        duration += lastDif;
                        if (idList.contains(id1)) {
                            if (appDuMap.get(id1) == null) {
                                appDuMap.put(id1, duration);
                            } else {
                                long d = appDuMap.get(id1) + duration;
                                appDuMap.put(id1, d);
                            }
                        }
                    } else {
                        while (timeIte.hasNext()) {//go through the treemap<date, appid> of one mac address
                            time2 = (long) timeIte.next();
                            id2 = tm.get(time2);
                            long dif = (time2 - time1) / 1000; // seconds
                            if (dif > 120) {
                                dif = 10;
                            }
                            duration += dif;
                            if (id1 != id2) {
                                if (idList.contains(id1)) {
                                    if (appDuMap.get(id1) == null) {
                                        appDuMap.put(id1, duration);
                                    } else {
                                        long d = appDuMap.get(id1) + duration;
                                        appDuMap.put(id1, d);
                                    }
                                    duration = 0;
                                }
                            }
                            if (!timeIte.hasNext()) {//the last record
                                Date end = new Date();
                                try {
                                    end = fmt.parse(enddate + " 23:59:59");
                                } catch (ParseException ex) {
                                    Logger.getLogger(top_k_most_used_schools.class.getName()).log(Level.SEVERE,
                                            null, ex);
                                }
                                long lastDif = (end.getTime() - time2) / 1000;
                                if (lastDif > 120) {
                                    lastDif = 10;
                                }
                                duration += lastDif;
                                if (idList.contains(id2)) {
                                    if (appDuMap.get(id2) == null) {
                                        appDuMap.put(id2, duration);
                                    } else {
                                        long d = appDuMap.get(id2) + duration;
                                        appDuMap.put(id2, d);
                                    }
                                }
                            }
                            id1 = id2;
                            time1 = time2;
                        }
                    }
                    Collection<Long> duCollect = appDuMap.values();
                    Iterator duIte = duCollect.iterator();
                    long totalDu = 0;
                    while (duIte.hasNext()) {
                        long dur = (long) duIte.next();
                        totalDu += dur;
                    }
                    macDuMap.put(mac, totalDu);

                }
                //convert the mac-duration map into school-duration hashmap
                Set<String> mSet = macDuMap.keySet();
                Iterator iter = mSet.iterator();
                HashMap<String, Long> schoolDuMap = new HashMap<>();//<school, duration>
                while (iter.hasNext()) {
                    String macAdr = (String) iter.next();
                    long dur = macDuMap.get(macAdr);
                    String school = UserDAO.retrieveSchool(macAdr, conn);
                    if (schoolDuMap.get(school) == null) {
                        schoolDuMap.put(school, dur);
                    } else {
                        long d = schoolDuMap.get(school);
                        schoolDuMap.put(school, dur + d);
                    }
                }
                //convert school-duration map into duration-school treemap
                TreeMap<Long, ArrayList<String>> duSchoolMap = new TreeMap<>();
                Set<String> schSet = schoolDuMap.keySet();
                Iterator schIte = schSet.iterator();
                while (schIte.hasNext()) {
                    String school = (String) schIte.next();
                    long dur = schoolDuMap.get(school);
                    ArrayList<String> schools = new ArrayList<>();
                    if (duSchoolMap.get(dur) == null) {
                        schools.add(school);
                        duSchoolMap.put(dur, schools);
                    } else {
                        schools = duSchoolMap.get(dur);
                        schools.add(school);
                        duSchoolMap.put(dur, schools);
                    }
                }
                TreeMap<Long, ArrayList<String>> treemap3 = duSchoolMap;
                NavigableMap<Long, ArrayList<String>> map3 = null;
                if (treemap3 != null) {
                    map3 = treemap3.descendingMap();
                }
                if (map3 != null && !map3.isEmpty()) {
                    Set<Long> durSet = map3.keySet();
                    Iterator iterator = durSet.iterator();
                    int kCount = kValue;
                    int rank = 1;
                    while (iterator.hasNext() && rank <= kCount) {
                        Long usage = (Long) iterator.next();
                        ArrayList<String> schoolList = map3.get(usage);
                        int count = 0;
                        Collections.sort(schoolList);
                        for (int i = 0; i < schoolList.size(); i++) {
                            JsonObject obj = new JsonObject();
                            obj.addProperty("rank", rank);
                            String school = schoolList.get(i);
                            obj.addProperty("school", school);
                            obj.addProperty("duration", usage);
                            results.add(obj);
                            count++;
                        }
                        rank += count;
                    }
                    jsonOutput.addProperty("status", "success");
                    jsonOutput.add("results", results);
                }
            }
        }
        try {
            out.println(gson.toJson(jsonOutput));
        } finally {
            out.close();
            ConnectionManager.close(conn);
        }
    }
}

From source file:com.app.json.top_k_most_used_students.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w  w  . j a v  a 2 s  . 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();
        JsonObject jsonOutput = new JsonObject();
        JsonArray errorJsonList = new JsonArray();
        String startdate = request.getParameter("startdate");
        String enddate = request.getParameter("enddate");
        String token = request.getParameter("token");
        String k = request.getParameter("k");
        if (k == null || k.length() == 0) {
            k = "3";
        }
        int kValue = Integer.parseInt(k);
        String appcategory = request.getParameter("appcategory");
        Date startDateFmt = null;
        Date endDateFmt = null;
        if (appcategory == null || appcategory.length() == 0) {
            errorJsonList.add(new JsonPrimitive("invalid app category"));
        } else {
            ArrayList<String> appCategories = AppDAO.retrieveAllAppCategory(conn);
            boolean appCategoryExist = false;
            for (String a : appCategories) {
                if (a.equals(appcategory)) {
                    appCategoryExist = true;
                }
            }
            if (!appCategoryExist) {
                errorJsonList.add(new JsonPrimitive("invalid app category"));
            }
        }
        if (kValue > 10 || kValue < 1) {
            errorJsonList.add(new JsonPrimitive("invalid k"));
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        df.setLenient(false);
        if (startdate == null || startdate.equals("")) {
            errorJsonList.add(new JsonPrimitive("invalid startdate"));
        } else {
            try {
                startDateFmt = df.parse(startdate);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid startdate"));
            }
        }
        if (enddate == null || enddate.equals("")) {
            errorJsonList.add(new JsonPrimitive("invalid enddate"));
        } else {
            try {
                endDateFmt = df.parse(enddate);
            } catch (ParseException ex) {
                errorJsonList.add(new JsonPrimitive("invalid enddate"));
            }
        }
        if (startDateFmt.after(endDateFmt)) {
            errorJsonList.add(new JsonPrimitive("invalid startdate"));
        }
        String sharedSecret = "is203g4t6luvjava";
        String username = "";
        if (token == null) {
            token = "";
        }
        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 {
            try {
                ArrayList<Integer> idList = AppDAO.retrieveID(appcategory, conn);
                ArrayList<AppUsage> usages = AppUsageDAO.retrieve(startdate, enddate, idList, conn);
                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                HashMap<String, TreeMap<Long, Integer>> usageMap = new HashMap<>();

                for (AppUsage usage : usages) {
                    String mac = usage.getMacAddress();
                    String timestamp = usage.getTimestamp();
                    Date date = fmt.parse(timestamp);
                    int appid = usage.getId();
                    if (usageMap.get(mac) == null) {//this mac address hasn't been put into the hashmap
                        TreeMap<Long, Integer> tm = new TreeMap<>();
                        tm.put(date.getTime(), appid);
                        usageMap.put(mac, tm);
                    } else {//this mac address already exists in the hashmap
                        TreeMap<Long, Integer> tm = usageMap.get(mac);
                        tm.put(date.getTime(), appid);
                        usageMap.put(mac, tm);
                    }
                }
                HashMap<String, Long> macDuMap = new HashMap<>();
                //<MacAddress, Duration>
                Set<String> macSet = usageMap.keySet();
                Iterator ite = macSet.iterator();
                while (ite.hasNext()) {//for a mac address:
                    HashMap<Integer, Long> appDuMap = new HashMap<>();
                    //<appid, duration>
                    String mac = (String) ite.next();
                    TreeMap<Long, Integer> tm = usageMap.get(mac);
                    //<date, appid>
                    Set<Long> timeSet = tm.keySet();
                    Iterator timeIte = timeSet.iterator();
                    long time1 = (long) timeIte.next();
                    long time2;
                    int id1 = tm.get(time1);
                    int id2;
                    long duration = 0;
                    if (!timeIte.hasNext()) {//the last record
                        Date end = fmt.parse(enddate + " 23:59:59");
                        long lastDif = (end.getTime() - time1) / 1000;
                        if (lastDif > 120) {
                            lastDif = 10;
                        }
                        duration += lastDif;
                        if (appDuMap.get(id1) == null) {
                            appDuMap.put(id1, duration);
                        } else {
                            long d = appDuMap.get(id1) + duration;
                            appDuMap.put(id1, d);
                        }
                    } else {
                        while (timeIte.hasNext()) {//go through the treemap<date, appid> of one mac address
                            time2 = (long) timeIte.next();
                            id2 = tm.get(time2);
                            long dif = (time2 - time1) / 1000; // seconds
                            if (dif > 120) {
                                dif = 10;
                            }
                            duration += dif;
                            if (id1 != id2) {
                                if (appDuMap.get(id1) == null) {
                                    appDuMap.put(id1, duration);
                                } else {
                                    long d = appDuMap.get(id1) + duration;
                                    appDuMap.put(id1, d);
                                }
                                duration = 0;
                            }
                            if (!timeIte.hasNext()) {//the last record
                                Date end = fmt.parse(enddate + " 23:59:59");
                                long lastDif = (end.getTime() - time2) / 1000;
                                if (lastDif > 120) {
                                    lastDif = 10;
                                }
                                duration += lastDif;
                                if (appDuMap.get(id2) == null) {
                                    appDuMap.put(id2, duration);
                                } else {
                                    long d = appDuMap.get(id2) + duration;
                                    appDuMap.put(id2, d);
                                }
                            }
                            id1 = id2;
                            time1 = time2;
                        }
                    }
                    Collection<Long> duCollect = appDuMap.values();
                    Iterator duIte = duCollect.iterator();
                    long totalDu = 0;
                    while (duIte.hasNext()) {
                        long dur = (long) duIte.next();
                        totalDu += dur;
                    }
                    macDuMap.put(mac, totalDu);

                }

                TreeMap<Long, ArrayList<HashMap<String, String>>> duNameMap = new TreeMap<>();
                Set<String> mSet = macDuMap.keySet();
                Iterator iter = mSet.iterator();
                JsonArray results = new JsonArray();
                while (iter.hasNext()) {
                    String macAdr = (String) iter.next();
                    String name = UserDAO.retrieveName(macAdr, conn);
                    long dur = macDuMap.get(macAdr);
                    if (duNameMap.get(dur) == null) {
                        ArrayList<HashMap<String, String>> nList = new ArrayList<>();
                        HashMap<String, String> nameMacMap = new HashMap<>();
                        nameMacMap.put(name, macAdr);
                        nList.add(nameMacMap);
                        duNameMap.put(dur, nList);
                    } else {
                        ArrayList<HashMap<String, String>> nList = duNameMap.get(dur);
                        HashMap<String, String> nameMacMap = new HashMap<>();
                        nameMacMap.put(name, macAdr);
                        nList.add(nameMacMap);
                        duNameMap.put(dur, nList);
                    }
                }
                NavigableMap<Long, ArrayList<HashMap<String, String>>> map2 = duNameMap.descendingMap();
                Set<Long> durSet = map2.keySet();
                Iterator iter1 = durSet.iterator();
                int rank1 = 1;
                while (iter1.hasNext() && rank1 <= kValue) {
                    Long usage = (Long) iter1.next();
                    ArrayList<HashMap<String, String>> nameMacList = map2.get(usage);
                    int count = 0;
                    for (int i = 0; i < nameMacList.size(); i++) {
                        JsonObject rank = new JsonObject();
                        rank.addProperty("rank", rank1);
                        HashMap<String, String> nameMac = nameMacList.get(i);
                        Set<String> nameSet = nameMac.keySet();
                        Iterator nameIte = nameSet.iterator();
                        while (nameIte.hasNext()) {
                            String n = (String) nameIte.next();
                            String m = nameMac.get(n);
                            rank.addProperty("name", n);
                            rank.addProperty("mac-address", m);
                            rank.addProperty("duration", usage);
                            count++;
                        }
                        results.add(rank);
                    }
                    rank1 += count;
                }
                jsonOutput.addProperty("status", "success");
                jsonOutput.add("results", results);
            } catch (ParseException ex) {
                Logger.getLogger(TopKAppReport.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            out.println(gson.toJson(jsonOutput));
        } finally {
            out.close();
            ConnectionManager.close(conn);
        }
    }
}

From source file:com.app.json.usage_heatmap.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  ww.j  av a 2 s. 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.appdynamics.monitors.boundary.BoundaryWrapper.java

License:Apache License

/**
 * Constructs a metrics map based on the Json response data retrieved from the REST API
 * @param   responseData    The extracted 'data' field from the Json response
 * @param   metricsMap      Map that is to be populated with metrics parsed from the responseData
 * @param    meterName       Name of the Boundary application node
 */// w w  w . java2  s .c o  m
private void populateMetricsMap(JsonArray responseData, Map metricsMap, String meterName) throws Exception {
    for (int i = 0; i < responseData.size(); i++) {
        JsonArray ipMetricsArray = responseData.get(i).getAsJsonArray();
        HashMap<String, Long> ipMetrics = new HashMap<String, Long>();
        for (int j = 1; j < ipMetricsArray.size(); j++) {
            ipMetrics.put(metricNames.get(j - 1), ipMetricsArray.get(j).getAsLong());
        }
        metricsMap.put(meterName, ipMetrics);
    }
}

From source file:com.appdynamics.monitors.boundary.BoundaryWrapper.java

License:Apache License

/**
 * Retrieves observation domain ids from the /meters REST request
 * @return  Map       A map containing the name of the meter and it's corresponding observationDomainId
 *///from ww w  . java 2s . c om
private void populateObservationDomainIds() throws Exception {
    HttpGet httpGet = new HttpGet(constructMetersURL());
    httpGet.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(apiKey, ""), "UTF-8", false));

    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    BufferedReader bufferedReader2 = new BufferedReader(new InputStreamReader(entity.getContent()));
    StringBuilder responseString = new StringBuilder();
    String line = "";
    while ((line = bufferedReader2.readLine()) != null) {
        responseString.append(line);
    }

    JsonArray responseArray = new JsonParser().parse(responseString.toString()).getAsJsonArray();

    for (int i = 0; i < responseArray.size(); i++) {
        JsonObject obj = responseArray.get(i).getAsJsonObject();
        meterIds.put(obj.get("name").getAsString(), obj.get("obs_domain_id").getAsString());
    }
}