List of usage examples for com.google.gson JsonPrimitive JsonPrimitive
public JsonPrimitive(Character c)
From source file:com.cognifide.aet.vs.metadata.TimestampSerializer.java
License:Apache License
@Override public JsonElement serialize(Suite.Timestamp src, Type typeOfSrc, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(src.get()); }
From source file:com.continuuity.loom.macro.Expander.java
License:Apache License
/** * Given a JSON tree, find the element specified by the path (or the root if path is null). In that subtree, * recursively traverse all elements, and expand all String typed right hand side values. If a macro cannot be * expanded due to the cluster object missing certain data, that macro will be left unexpanded. * * @param json A JSON tree/*from www . jav a 2 s . c o m*/ * @param path the path to expand under * @param cluster the cluster to use for expanding macros. * @param nodes the cluster nodes to use for expanding macros. * @param node the cluster node to use for expanding macros. * @return a new JSON tree if any expansion took place, and the original JSON tree otherwise. * @throws SyntaxException if a macro expression is ill-formed. * @throws IncompleteClusterException if the cluster does not have the meta data to expand all macros. */ public static JsonElement expand(JsonElement json, @Nullable java.util.List<String> path, Cluster cluster, Set<Node> nodes, Node node) throws SyntaxException, IncompleteClusterException { // if path is given, if (path != null && !path.isEmpty()) { String first = path.get(0); if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); JsonElement json1 = object.get(first); if (json1 != null) { JsonElement expanded = expand(json1, path.subList(1, path.size()), cluster, nodes, node); if (expanded != json1) { // only construct new json object if actual expansion happened JsonObject object1 = new JsonObject(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { object1.add(entry.getKey(), entry.getKey().equals(first) ? expanded : entry.getValue()); } return object1; } } } // path was given, but either no corresponding subtree was found or no expansion happened... return json; } if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { String value = primitive.getAsString(); String expanded = expand(value, cluster, nodes, node); if (!expanded.equals(value)) { // only return a new json element if actual expansion happened return new JsonPrimitive(expanded); } } } if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); JsonArray array1 = new JsonArray(); boolean expansionHappened = false; for (JsonElement element : array) { JsonElement expanded = expand(element, path, cluster, nodes, node); if (expanded != element) { expansionHappened = true; } array1.add(expanded); } // only return a new json array if actual expansion happened if (expansionHappened) { return array1; } } if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); JsonObject object1 = new JsonObject(); boolean expansionHappened = false; for (Map.Entry<String, JsonElement> entry : object.entrySet()) { JsonElement expanded = expand(entry.getValue(), path, cluster, nodes, node); if (expanded != entry.getValue()) { expansionHappened = true; } object1.add(entry.getKey(), expand(entry.getValue(), path, cluster, nodes, node)); } if (expansionHappened) { return object1; } } return json; }
From source file:com.controller.webServices.JsonAutoDetect.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); JsonObject jsonResult = new JsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonArray errorArray = new JsonArray(); String date = request.getParameter("date"); String token = request.getParameter("token"); //validation - date if (date == null) { errorArray.add(new JsonPrimitive("missing date")); } else {/* w w w . jav a 2 s. c o m*/ try { DateTime ts2 = new DateTime(date); } catch (IllegalArgumentException e) { errorArray.add(new JsonPrimitive("invalid date")); } } //validation - token if (token == null) { errorArray.add(new JsonPrimitive("missing token")); } else if (token.equals("")) { errorArray.add(new JsonPrimitive("blank token")); } else { try { JWTUtility.verify(token, "ylleeg4t8"); } catch (JWTException e) { errorArray.add(new JsonPrimitive("invalid token")); } } if (errorArray.size() > 0) { jsonResult.add("message", errorArray); out.println(gson.toJson(jsonResult)); return; } if (errorArray.size() == 0) { String date1 = date.substring(0, date.indexOf("T")); String time = date.substring(date.indexOf("T") + 1, date.length()); try { LocalTime after = new LocalTime(Timestamp.valueOf(date1 + " " + time)); int hour = Integer.parseInt(time.substring(0, time.indexOf(":"))); int minute = Integer.parseInt(time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"))); int second = Integer.parseInt(time.substring(time.lastIndexOf(":") + 1, time.length())); if (hour >= 24 || minute >= 60 || second >= 60) { throw new Exception(); } Timestamp tsAfter = Timestamp.valueOf(date1 + " " + after); Timestamp tsBefore = new Timestamp(tsAfter.getTime() - 900000); ArrayList<Group> groupList = new ArrayList<Group>(); AutoGroupDetectController ac = new AutoGroupDetectController(); System.out.println(tsBefore.toString() + " " + tsAfter.toString()); groupList = ac.getFullGroups(tsBefore.toString(), tsAfter.toString()); jsonResult.addProperty("status", "success"); int count = 0; HashSet set = new HashSet(); for (Group g : groupList) { set.addAll(g.getIndivSet()); } count = set.size(); jsonResult.addProperty("total-groups", groupList.size()); jsonResult.addProperty("total-users", count); JsonArray groupArray = new JsonArray(); JsonArraySorter sorter = new JsonArraySorter(); for (Group g : groupList) { JsonObject groupObject = new JsonObject(); groupObject.addProperty("size", g.getIndivSet().size()); groupObject.addProperty("total-time-spent", g.getFullCount()); JsonArray memberArray = new JsonArray(); HashSet<FullUser> userSet = g.getIndivSet(); Iterator i = userSet.iterator(); while (i.hasNext()) { FullUser fullUser = (FullUser) i.next(); JsonObject memberObj = new JsonObject(); memberObj.addProperty("email", fullUser.getEmail()); memberObj.addProperty("mac-address", fullUser.getMacAddress()); memberArray.add(memberObj); } memberArray = sorter.sortAGDMembers(memberArray); groupObject.add("members", memberArray); // Add location objects JsonArray locationArray = new JsonArray(); HashMap<String, Integer> locationMapping = g.getLocTimeMap(); for (String s : locationMapping.keySet()) { JsonObject locationObject = new JsonObject(); locationObject.addProperty("location", s); locationObject.addProperty("time-spent", locationMapping.get(s)); locationArray.add(locationObject); } locationArray = sorter.sortAGDlocation(locationArray); groupObject.add("locations", locationArray); groupArray.add(groupObject); } groupArray = sorter.sortAGDGroup(groupArray); jsonResult.add("groups", groupArray); out.println(gson.toJson(jsonResult)); } catch (Exception e) { e.printStackTrace(); } } else { } // ======= End of Json Codes ======= }
From source file:com.controller.webServices.JsonTopKGroupNextPlaces.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); System.out.println("====== Group Next Places ======== "); JsonObject jsonResult = new JsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonArray errorArray = new JsonArray(); String date = request.getParameter("date"); String token = request.getParameter("token"); Timestamp ts = null;/* w w w . j a v a 2s . c o m*/ Timestamp tsBefore = null; Timestamp tsAfter = null; HashMap<String, Integer> finalMap = null; ArrayList<String[]> personCount = null; //validation - date if (date == null) { errorArray.add(new JsonPrimitive("missing date")); } else { try { DateTime ts2 = new DateTime(date); } catch (IllegalArgumentException e) { errorArray.add(new JsonPrimitive("invalid date")); } } //validation - token if (token == null) { errorArray.add(new JsonPrimitive("missing token")); } // } else if (token.equals("")) { // errorArray.add(new JsonPrimitive("blank token")); // } else { // try { // JWTUtility.verify(token, "ylleeg4t8"); // } catch (JWTException e) { // errorArray.add(new JsonPrimitive("invalid token")); // } // } // Validation: Semantic Places String place = request.getParameter("origin"); if (place == null) { errorArray.add(new JsonPrimitive("missing origin")); } else if (place.equals("")) { errorArray.add(new JsonPrimitive("blank origin")); } if (errorArray.size() > 0) { jsonResult.add("message", errorArray); out.println(gson.toJson(jsonResult)); return; } ArrayList<Group> finalGroup = null; if (errorArray.size() == 0) { String date1 = date.substring(0, date.indexOf("T")); String time = date.substring(date.indexOf("T") + 1, date.length()); try { LocalTime after = new LocalTime(Timestamp.valueOf(date1 + " " + time)); int hour = Integer.parseInt(time.substring(0, time.indexOf(":"))); int minute = Integer.parseInt(time.substring(time.indexOf(":") + 1, time.lastIndexOf(":"))); int second = Integer.parseInt(time.substring(time.lastIndexOf(":") + 1, time.length())); if (hour >= 24 || minute >= 60 || second >= 60) { throw new Exception(); } ts = Timestamp.valueOf(date1 + " " + time); tsBefore = new Timestamp(ts.getTime() - 900000); tsAfter = new Timestamp(ts.getTime() + 900000); ArrayList<Group> groupList = new ArrayList<Group>(); finalMap = new HashMap<String, Integer>(); personCount = new ArrayList<String[]>(); AutoGroupDetectController agd = new AutoGroupDetectController(); System.out.println("Group next places: " + tsBefore.toString() + " " + ts.toString()); LocationLookupDAO llDAO = new LocationLookupDAO(); HashMap<String, String> referMap = llDAO.retrieveAll(); ArrayList<Group> firstGroup = agd.getFullGroups(tsBefore.toString(), ts.toString()); // if (firstGroup.size() == 0) { // request.setAttribute("results", personCount); // RequestDispatcher rd = request.getRequestDispatcher("group_next.jsp"); // rd.forward(request, response); // return; // } System.out.println("List size for group next places: " + firstGroup.size()); ArrayList<Group> midGroup = new ArrayList<Group>(); for (Group g : firstGroup) { String s = referMap.get(g.getLastPlace()); System.out.println(s); if (s.equals(place)) { midGroup.add(g); } } System.out.println("Mid list size for group next places: " + midGroup.size()); finalGroup = agd.getMatchingGroups(ts.toString(), tsAfter.toString(), midGroup); System.out.println("Final list size for group next places: " + finalGroup.size()); LocationLookupDAO lookupDAO = new LocationLookupDAO(); HashMap<String, String> lookupMap = lookupDAO.retrieveAll(); for (Group g : finalGroup) { ArrayList<Interval> groupInterList = new ArrayList<Interval>(); HashMap<Interval, Integer> tempMap = new HashMap<Interval, Integer>(); HashMap<String, ArrayList<Interval>> overlapMap = g.getLocOverlapMap(); for (String s : overlapMap.keySet()) { ArrayList<Interval> interList = overlapMap.get(s); groupInterList.addAll(interList); for (Interval in : interList) { Integer i = Integer.parseInt(s); tempMap.put(in, i); } } Collections.sort(groupInterList, new IntervalEndComparator(groupInterList)); for (Interval in : groupInterList) { if (Seconds.secondsIn(in).getSeconds() >= 300) { Integer i = tempMap.get(in); String semPlace = lookupMap.get(String.valueOf(i)); Integer groupCount = finalMap.get(semPlace); if (groupCount != null) { finalMap.put(semPlace, (groupCount + 1)); } else { finalMap.put(semPlace, 1); } break; } } } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } for (Entry<String, Integer> entry : finalMap.entrySet()) { String[] countArray = new String[] { entry.getKey(), entry.getValue().toString() }; personCount.add(countArray); } Collections.sort(personCount, new ValueComparator(personCount)); jsonResult.addProperty("status", "success"); jsonResult.addProperty("total-groups", finalGroup.size()); jsonResult.addProperty("total-next-place-groups", personCount.size()); JsonArray results = new JsonArray(); for (int i = 0; i < personCount.size(); i++) { String[] arr = personCount.get(i); JsonObject nextPlaceObject = new JsonObject(); nextPlaceObject.addProperty("rank", i + 1); nextPlaceObject.addProperty("semantic-place", arr[0]); nextPlaceObject.addProperty("num-groups", Integer.parseInt(arr[1])); results.add(nextPlaceObject); } jsonResult.add("results", results); out.println(gson.toJson(jsonResult)); // request.setAttribute("results", personCount); // RequestDispatcher rd = request.getRequestDispatcher("group_next.jsp"); // rd.forward(request, response); } }
From source file:com.dardenestates.code.src.Servlets.JsonServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from ww w .j a v a2s . 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); BufferedReader reader = request.getReader(); List<String> message = new ArrayList(); JsonObject jsonObject; if (reader.ready()) { JsonParser jsonParser = new JsonParser(); try { jsonObject = jsonParser.parse(reader).getAsJsonObject(); } catch (Exception e) { System.out.println(e.getMessage()); System.out.println(e.getStackTrace()); jsonObject = new JsonObject(); jsonObject.add("Exception_Code", new JsonPrimitive("malformed request structure")); } } else { jsonObject = new JsonObject(); jsonObject.add("Exception_Code", new JsonPrimitive("Empty Request")); System.out.println(" Empty Request "); } try (PrintWriter out = response.getWriter()) { out.write(jsonObject.toString()); } //extract the commandkey String commandKey = jsonObject.get("COMMANDKEY").getAsString(); // route the command RoutingEnum routingEnum = RoutingEnum.valueOf(commandKey); ControllerInterface command = routingEnum.getExecutable(); String urlLocation = routingEnum.getResponseURL(); if (command.validate(jsonObject, message, makeDataSource())) { MysqlDataSource dataSource = new MysqlDataSource(); if (command.processRequest(jsonObject, message, dataSource)) { response.sendRedirect(urlLocation); } } //get the value of command //match it with the enum }
From source file:com.darkfalcon.java.gson.ByteArrayToBase64TypeAdapter.java
@Override public JsonElement serialize(byte[] src, Type type, JsonSerializationContext jsc) { Base64 base = new Base64(); return new JsonPrimitive(base.encodeToString(src)); }
From source file:com.daxstudio.sa.base.model.jsr310.ZonedDateTimeJsonConverter.java
License:Open Source License
/** * Gson invokes this call-back method during serialization when it encounters a field of the * specified type. <p>/*from www . j a v a 2 s . com*/ * * In the implementation of this call-back method, you should consider invoking * {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for * any * non-trivial field of the {@code src} object. However, you should never invoke it on the * {@code src} object itself since that will cause an infinite loop (Gson will call your * call-back method again). * * @param src the object that needs to be converted to Json. * @param typeOfSrc the actual type (fully genericized version) of the source object. * @return a JsonElement corresponding to the specified object. */ @Override public JsonElement serialize(final ZonedDateTime src, final Type typeOfSrc, final JsonSerializationContext context) { return new JsonPrimitive(mDateTimeFormatter.format(src)); }
From source file:com.denimgroup.threadfix.remote.response.ByteToStringSerializer.java
License:Mozilla Public License
@Override public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(new String(src)); }
From source file:com.denimgroup.threadfix.remote.response.CalendarSerializer.java
License:Mozilla Public License
@Override public JsonElement serialize(Calendar src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getTimeInMillis()); }
From source file:com.denimgroup.threadfix.remote.response.DateSerializer.java
License:Mozilla Public License
@Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getTime()); }