List of usage examples for com.google.gson JsonArray JsonArray
public JsonArray()
From source file:com.adssets.ejb.DataAccess.java
@Override public String buildFeedForMarket(String marketId, String lazyLoad) { JsonArray jsonArray = new JsonArray(); JsonParser parser = new JsonParser(); // Feed feed = feedFacade.find(marketId); Market market = marketFacade.find(Integer.valueOf(marketId)); List<Feed> feeds = em.createNamedQuery("Feed.findByMarketId").setParameter("marketId", market) .getResultList();/*ww w . ja v a 2s . c o m*/ if (feeds.size() > 0) { for (Feed feed : feeds) { JsonObject obj = new JsonObject(); obj.addProperty("id", feed.getId()); obj.addProperty("marketId", feed.getIdmarket().getId()); obj.addProperty("json", feed.getJson()); jsonArray.add(obj); } JsonObject obj = jsonArray.get(0).getAsJsonObject(); String objArray = obj.get("json").getAsString(); JsonArray objArrayParsed = parser.parse(objArray).getAsJsonArray(); JsonArray objData = new JsonArray(); for (JsonElement objId : objArrayParsed) { JsonObject objElmParsed = parser.parse(objId.toString()).getAsJsonObject(); System.out.println(objElmParsed); // try{ // isInteger(objId.getAsString()); String value = objElmParsed.get("type").getAsString(); System.out.println(value); //CHANGE ADPICTURE TO THE PICTURE STORED IN THE DATABASE if (value.equals("object")) { String result = scout24.getApartments(objElmParsed.get("objectid").getAsString()); if (!result.equals("{\"error\":1}")) { JsonObject resultObj = parser.parse(result).getAsJsonObject(); String link = "{\"link\": \"https://www.immobilienscout24.de/expose/" + objElmParsed.get("objectid").getAsInt() + "?referrer=\"}"; JsonObject clickLink = parser.parse(link).getAsJsonObject(); resultObj.add("clickLink", clickLink); resultObj.add("objectId", objElmParsed.get("objectid")); resultObj.add("marketId", parser.parse(marketId)); // Use the selected image as ad image JsonObject objHref = new JsonObject(); objHref.add("href", objElmParsed.get("url")); resultObj.add("adpicture", objHref); //If lazyLoad = yes dont return "allpictures" LazyLoad=yes is the parameter the ad will send so it does not get unneccesary data if (lazyLoad.equals("yes")) { resultObj.remove("allpictures"); } objData.add(resultObj); } } else { objData.add(objId); } // }catch(UnsupportedOperationException ex){ // objData.add(objId); // } } return objData.toString(); } else { return new JsonArray().toString(); } }
From source file:com.afspq.model.Results.java
License:Apache License
/** * Creates the string of words for the cloud visualization. * Also creates a Jsona object of the keywords with the following * structure:// w w w. ja v a2s .c om * { * "words": [ * { * "word": "keyword", * "color": "blue" * } * } * * This Json object can be used in other types of visualizations. * @param search * @param searchResults */ @SuppressWarnings("unchecked") private void createKeywordsCloud(Search search, SearchResults searchResults) { /* * getVisualizations returns an ArrayList containing data for different * visualiztions. The first index in this ArrayList contains data for * that can be used for the keyword cloud. The second index of the list * contains data for the page rank graph and so on. */ ArrayList<?> visualizationList = search.getVisualizations(searchResults); /* * Each element inside the ArrayList contains a HashMap. In this case, * it is a HashMap where the key is the keyword and the value is its * weight, i.e. the popularity of the word in the sample table. */ HashMap<String, Double> keywordsCloudMap = (HashMap<String, Double>) visualizationList.get(0); keywordsCloudJson = new JsonObject(); JsonArray jsonArray = new JsonArray(); SecureRandom sr = new SecureRandom(); // Used to pick a random font. if (keywordsCloudMap == null) { tagCloudWords = tagCloudWords.concat("<ul><li></li></ul>"); return; } /* * The keyword cloud framework requires the words to be contained inside * an HTML unordered list. This is the reason for appending <ul> and * <li> to the string. See http://www.goat1000.com/tagcanvas.php for * more details. */ tagCloudWords = tagCloudWords.concat("<ul>"); String[] fontStyles = { "Times New Roman", "Arial Black", "Sans-Serif" }; int count = 0; for (String s : keywordsCloudMap.keySet()) { // Avoid overcrowding of words and limit to 25 words in the cloud. if (++count == 25) { break; } int i = sr.nextInt(3); JsonObject node = new JsonObject(); node.addProperty("word", s); node.addProperty("color", "#ffffff"); jsonArray.add(node); if (s.equals("[[TOTAL NUM DOCS]]")) { continue; } double weight = keywordsCloudMap.get(s); weight = (weight * 40) + 12; String fontSize = Double.toString(weight); tagCloudWords = tagCloudWords.concat("<li><a style='font-size: " + fontSize + "pt; color: #ffffff; font-family: " + fontStyles[i] + ";'" + "href='ProcessQuery?query=" + s + "&page=1&searchType=web'>" + s + "</a></li>"); } tagCloudWords = tagCloudWords.concat("</ul>"); keywordsCloudJson.add("words", jsonArray); }
From source file:com.afspq.model.Results.java
License:Apache License
/** * Creates the Json object for the keywords space tree visualization. * /* ww w .j a v a 2 s .co m*/ * @param query * @param search * @param searchResults */ @SuppressWarnings("unchecked") private void createKeywordsTree(String query, Search search, SearchResults searchResults) { ArrayList<?> visualizationList = search.getVisualizations(searchResults); HashMap<String, HashSet<String>> keywordsTreeMap = (HashMap<String, HashSet<String>>) visualizationList .get(1); if (keywordsTreeMap == null) { return; } keywordsTreeJson = new JsonObject(); keywordsTreeJson.addProperty("id", "query"); keywordsTreeJson.addProperty("name", query); JsonArray children = new JsonArray(); keywordsTreeJson.add("children", children); int i = 0; for (String title : keywordsTreeMap.keySet()) { if (!keywordsTreeMap.get(title).isEmpty()) { JsonArray grandChildren = new JsonArray(); JsonObject resultTitle = new JsonObject(); String truncatedTitle = ""; // Long titles don't fit nicely in the visualization tree node // so if the title is longer than 20 characters truncate it and // add "..." if (title.length() > 20) { truncatedTitle = title.substring(0, 21).concat("..."); } else { truncatedTitle = title; } resultTitle.addProperty("id", title); resultTitle.addProperty("name", truncatedTitle); resultTitle.add("children", grandChildren); HashSet<String> keywords = keywordsTreeMap.get(title); for (String keyword : keywords) { JsonObject key = new JsonObject(); key.addProperty("id", "k" + i++); key.addProperty("name", keyword); grandChildren.add(key); } children.add(resultTitle); } } }
From source file:com.afspq.model.Results.java
License:Apache License
/** * Creates the Json object for the page rank graph visualizaiton. * //from w ww . j a va2 s . c o m * @param query * @param search * @param searchResults */ @SuppressWarnings("unchecked") private void createPageRankGraph(String query, Search search, SearchResults searchResults) { ArrayList<?> visualizationList = search.getVisualizations(searchResults); HashMap<String, EdgeLinks> pageRankMap = (HashMap<String, EdgeLinks>) visualizationList.get(2); if (pageRankMap == null) { return; } nodesArr = new JsonArray(); // Colors for the nodes. Selected randomly. String[] colorsArr = { "#003DF5", "#B800F5", "#F500B8", "#00B8F5", "#3366FF", "#F5003D", "#00F5B8", "#FFCC33", "#F53D00", "#00F53D", "#B8F500", "#F5B800" }; HashMap<Integer, String> colorMap = new HashMap<Integer, String>(); for (int i = 0; i < colorsArr.length; i++) { colorMap.put(i, colorsArr[i]); } SecureRandom sr = new SecureRandom(); for (Map.Entry<String, EdgeLinks> urlEntry : pageRankMap.entrySet()) { String key = urlEntry.getKey(); EdgeLinks value = urlEntry.getValue(); double dim = value.getPageRank() * 15000 / 23; // Adjusting the diameter of the node. dim = (dim > 70) ? dim / 15 : dim; JsonObject node = new JsonObject(); JsonArray adjArr = new JsonArray(); JsonObject data = new JsonObject(); data.addProperty("$type", "circle"); data.addProperty("$color", colorMap.get(sr.nextInt(colorsArr.length))); data.addProperty("$dim", dim); HashMap<String, Double> assocUrls = value.getEdgeUrls(); int i = 0; int ranAdj = sr.nextInt(15); // Each node should have at least 3 edge connections if possible. ranAdj = (ranAdj < 3) ? 3 : ranAdj; for (Map.Entry<String, Double> urlEdge : assocUrls.entrySet()) { if (i < ranAdj) { i++; JsonObject adj = new JsonObject(); JsonObject empData = new JsonObject(); adj.addProperty("nodeTo", urlEdge.getKey()); adj.addProperty("nodeFrom", key); adj.add("data", empData); adjArr.add(adj); } else break; } node.add("adjacencies", adjArr); node.add("data", data); node.addProperty("id", key); node.addProperty("name", key); nodesArr.add(node); } }
From source file:com.agateau.pixelwheels.stats.JsonGameStatsIO.java
License:Open Source License
private JsonArray createJsonForResults(ArrayList<TrackResult> results) { JsonArray array = new JsonArray(); for (TrackResult result : results) { array.add(mGson.toJsonTree(result)); }//from w w w .j a va 2 s. com return array; }
From source file:com.agwego.common.GsonHelper.java
License:Open Source License
/** * Short hand, check if the object is not null and the key is presence return the result as a JsonArray * * @param jObject the JsonObject in question * @param key the key to lookup/*w ww .java 2s . c o m*/ * @return the JsonArray for this key or a new empty JsonArray */ public static JsonArray getAsArray(final JsonObject jObject, final String key) { if (jObject != null && jObject.has(key)) { try { return jObject.getAsJsonArray(key); } catch (ClassCastException ex) { // fall through } } return new JsonArray(); }
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)); }/* w ww . j a va 2s. com*/ 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//from w w w .j a v a 2 s . c om */ 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.app.json.authenticate.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* ww w . j a v a 2 s. 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()) { /* 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./* w w w.j av a2s . c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * @throws java.sql.SQLException * @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); } } }