List of usage examples for com.google.gson JsonArray add
public void add(JsonElement element)
From source file:com.adssets.ejb.DataAccess.java
@Override public String getObjectsByMarket(String marketId) { JsonArray jsonArray = new JsonArray(); // Feed feed = feedFacade.find(marketId); Market market = marketFacade.find(Integer.valueOf(marketId)); List<Feed> feeds = em.createNamedQuery("Feed.findByMarketId").setParameter("marketId", market) .getResultList();/*from w w w . j av a 2 s . co m*/ 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); } return jsonArray.toString(); }
From source file:com.adssets.ejb.DataAccess.java
@Override public String createFeed(String obj) { JsonObject jsonObject = (new JsonParser()).parse(obj).getAsJsonObject(); Market marketId = marketFacade.find(jsonObject.get("marketId").getAsInt()); // Feed feedCheck = feedFacade.find(marketId); List<Feed> feeds = em.createNamedQuery("Feed.findByMarketId").setParameter("marketId", marketId) .getResultList();/* ww w .ja va 2 s .co m*/ Integer feedCheck = null; if (feeds.size() > 0) { feedCheck = feeds.get(0).getId(); } Feed feed = new Feed(); feed.setIdmarket(marketId); feed.setJson(jsonObject.get("json").getAsJsonArray().toString()); JsonArray jsonArray = new JsonArray(); JsonObject jsonObj = new JsonObject(); if (feedCheck == null) { feedFacade.create(feed); jsonObj.addProperty("id", feed.getId()); jsonObj.addProperty("marketId", feed.getIdmarket().getId()); jsonObj.addProperty("json", feed.getJson()); jsonArray.add(jsonObj); return jsonArray.toString(); } else { feed.setId(feedCheck); feedFacade.edit(feed); jsonObj.addProperty("id", feed.getId()); jsonObj.addProperty("marketId", feed.getIdmarket().getId()); jsonObj.addProperty("json", feed.getJson()); jsonArray.add(jsonObj); return jsonArray.toString(); } }
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();/*from ww w .j a v a 2 s .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:/*from w ww. j av a2 s. co m*/ * { * "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. * /*from www.java2 s . c o 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 w w . j a va 2s .co 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 .java 2 s .c o m return array; }
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)); }/* www . j ava 2 s. co 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/*ww w . j a v a 2 s. co 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.app.json.authenticate.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww 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()) { /* 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); } } }