List of usage examples for com.google.gson JsonObject add
public void add(String property, JsonElement value)
From source file:com.aliakseipilko.flightdutytracker.utils.FlightSerialiser.java
License:Open Source License
@Override public JsonElement serialize(final Flight src, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); jsonObject.add("id", context.serialize(src.getId())); jsonObject.addProperty("departureIATACode", src.getDepartureIATACode()); jsonObject.addProperty("departureICAOCode", src.getDepartureICAOCode()); jsonObject.addProperty("arrivalIATACode", src.getArrivalIATACode()); jsonObject.addProperty("arrivalICAOCode", src.getArrivalICAOCode()); jsonObject.add("startDutyTime", context.serialize(src.getStartDutyTime())); jsonObject.add("endDutyTime", context.serialize(src.getEndDutyTime())); jsonObject.add("startFlightTime", context.serialize(src.getStartFlightTime())); jsonObject.add("endFlightTime", context.serialize(src.getEndFlightTime())); jsonObject.addProperty("acType", src.getAcType()); jsonObject.addProperty("flightNumber", src.getFlightNumber()); return jsonObject; }
From source file:com.aliyun.odps.udf.utils.CounterUtils.java
License:Apache License
private static JsonObject toJson(Counters counters) { JsonObject obj = new JsonObject(); for (CounterGroup group : counters) { obj.add(group.getName(), toJson(group)); }//from w ww .java 2 s. c o m return obj; }
From source file:com.aliyun.odps.udf.utils.CounterUtils.java
License:Apache License
private static JsonObject toJson(CounterGroup counterGroup) { JsonObject obj = new JsonObject(); obj.addProperty("name", counterGroup.getName()); JsonArray counterArray = new JsonArray(); for (Counter entry : counterGroup) { counterArray.add(toJson(entry)); }//from w w w . jav a 2 s. c o m obj.add("counters", counterArray); return obj; }
From source file:com.amsterdam.marktbureau.makkelijkemarkt.DagvergunningFragment.java
License:Mozilla Public License
/** * Create a json object from the dagvergunning values * @return json object/* w ww .jav a 2 s . c o m*/ */ private JsonObject dagvergunningToJson() { JsonObject dagvergunningPayload = new JsonObject(); dagvergunningPayload.addProperty( getString(R.string.makkelijkemarkt_api_dagvergunning_payload_erkenningsnummer), mErkenningsnummer); dagvergunningPayload.addProperty(getString(R.string.makkelijkemarkt_api_dagvergunning_payload_markt_id), mMarktId); dagvergunningPayload.addProperty(getString(R.string.makkelijkemarkt_api_dagvergunning_payload_dag), mDagToday); dagvergunningPayload.addProperty(getString(R.string.makkelijkemarkt_api_dagvergunning_payload_aanwezig), mKoopmanAanwezig); // get product values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (int i = 0; i < productParams.length; i++) { if (mProducten.get(productParams[i]) > 0) { dagvergunningPayload.addProperty(productParams[i], mProducten.get(productParams[i])); } } if (mErkenningsnummerInvoerMethode != null) { dagvergunningPayload.addProperty( getString(R.string.makkelijkemarkt_api_dagvergunning_payload_erkenningsnummer_invoer_methode), mErkenningsnummerInvoerMethode); } if (mNotitie != null) { dagvergunningPayload.addProperty(getString(R.string.makkelijkemarkt_api_dagvergunning_payload_notitie), mNotitie); } DateFormat datumtijdFormat = new SimpleDateFormat(getString(R.string.date_format_datumtijd)); dagvergunningPayload.addProperty( getString(R.string.makkelijkemarkt_api_dagvergunning_payload_registratie_datumtijd), String.valueOf(datumtijdFormat.format(new Date()))); // add the location from gps if (mRegistratieGeolocatieLatitude != -1 && mRegistratieGeolocatieLongitude != -1) { JsonArray geolocation = new JsonArray(); geolocation.add(mRegistratieGeolocatieLatitude); geolocation.add(mRegistratieGeolocatieLongitude); dagvergunningPayload.add( getString(R.string.makkelijkemarkt_api_dagvergunning_payload_registratie_geolocatie), geolocation); } // if set, add vervanger erkenningsnummer if (mVervangerErkenningsnummer != null) { dagvergunningPayload.addProperty( getString(R.string.makkelijkemarkt_api_dagvergunning_payload_vervanger_erkenningsnummer), mVervangerErkenningsnummer); } return dagvergunningPayload; }
From source file:com.android.cloudfiles.cloudfilesforandroid.CloudFiles.java
License:Apache License
private String generateToken(String userName, String apiKey) throws IOException { JsonObject cred = new JsonObject(); cred.addProperty("username", userName); cred.addProperty("apiKey", apiKey); JsonObject rax = new JsonObject(); rax.add("RAX-KSKEY:apiKeyCredentials", cred); JsonObject obj = new JsonObject(); obj.add("auth", rax); String json = obj.toString(); RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder().url(tokenURL).post(body).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); return response.body().string(); }
From source file:com.app.json.authenticate.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . java2s . 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()) { /* TODO output your page here. You may use following sample code. */ Gson gson = new GsonBuilder().setPrettyPrinting().create(); conn = ConnectionManager.getConnection(); //creats a new json object for printing the desired json output JsonObject jsonOutput = new JsonObject(); //retrieves the user String username = request.getParameter("username"); String password = request.getParameter("password"); String errorMsg = "invalid username/password"; JsonArray errorArray = new JsonArray(); errorArray.add(new JsonPrimitive(errorMsg)); User currentUser = UserDAO.retrieveUser(username, conn); Admin admin = AdminDAO.retrieveAdmin(username); if (admin != null) { if (!admin.getPassword().equals(password) || password == null) { jsonOutput.addProperty("status", "error"); jsonOutput.add("messages", errorArray); try { out.println(gson.toJson(jsonOutput)); } finally { out.close(); ConnectionManager.close(conn); } } else { jsonOutput.addProperty("status", "success"); String sharedSecret = "is203g4t6luvjava"; String token = JWTUtility.sign(sharedSecret, username); jsonOutput.addProperty("token", token); try { out.println(gson.toJson(jsonOutput)); } finally { out.close(); ConnectionManager.close(conn); } } return; } if (username.equals("")) { // error output jsonOutput.addProperty("status", "error"); errorArray.add(new JsonPrimitive("blank username")); jsonOutput.add("messages", errorArray); } if (password.equals("")) { // error output jsonOutput.addProperty("status", "error"); errorArray.add(new JsonPrimitive("blank password")); jsonOutput.add("messages", errorArray); } if (currentUser == null) { // error output jsonOutput.addProperty("status", "error"); jsonOutput.add("messages", errorArray); } else { if (currentUser.getPassword().equals(password)) { // success output jsonOutput.addProperty("status", "success"); String sharedSecret = "is203g4t6luvjava"; String token = JWTUtility.sign(sharedSecret, username); jsonOutput.addProperty("token", token); } else { // error output jsonOutput.addProperty("status", "error"); jsonOutput.add("messages", errorArray); } } //writes the output as a response (but not html) try { out.println(gson.toJson(jsonOutput)); } finally { out.close(); ConnectionManager.close(conn); } } }
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 .ja v a2s. 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 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(); //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.//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./*w ww. j a va2s . 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(); 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); } } }