Example usage for com.google.gson JsonArray add

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

Introduction

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

Prototype

public void add(JsonElement element) 

Source Link

Document

Adds the specified element to self.

Usage

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  w  w.  j a  va2s.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.//  w  w w .  j  a  v  a 2s  .  co 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();
        //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. ja  va  2s  .  co 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 ww w. ja va  2  s.co 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.//from   w  w w  . j a va  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.asakusafw.lang.inspection.json.PortReferenceAdapter.java

License:Apache License

@Override
public JsonElement serialize(InspectionNode.PortReference src, Type typeOfSrc,
        JsonSerializationContext context) {
    JsonArray result = new JsonArray();
    result.add(new JsonPrimitive(src.getNodeId()));
    result.add(new JsonPrimitive(src.getPortId()));
    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);
    }/*w w  w  .  j  a va2  s .co  m*/
    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  a2s  .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.asakusafw.yaess.tools.Explain.java

License:Apache License

private static JsonArray toJsonArray(Collection<String> values) {
    assert values != null;
    JsonArray array = new JsonArray();
    for (String value : values) {
        array.add(new JsonPrimitive(value));
    }// w  w w.j  a  va2 s .  c om
    return array;
}

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()));
        }//from   ww w. j a  va2s. c  om
        out.add(key, jsa);
    }
    return out;
}