List of usage examples for com.google.gson GsonBuilder GsonBuilder
public GsonBuilder()
From source file:com.adobe.acs.commons.json.JsonObjectUtil.java
License:Apache License
public static JsonObject toJsonObject(Object source) { if (source instanceof String) { return toJsonObject((String) source); } else if (source instanceof Resource) { return toJsonObject((Resource) source); } else {// w w w . j a va 2 s . c o m Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Node.class, new JcrJsonAdapter()).create(); return gson.toJsonTree(source).getAsJsonObject(); } }
From source file:com.adobe.acs.commons.oak.sql2scorer.impl.servlets.ExplainScoreServlet.java
License:Apache License
@Override protected void doPost(@Nonnull final SlingHttpServletRequest request, @Nonnull final SlingHttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=utf-8"); final long limit = ofNullable(request.getParameter(P_LIMIT)).map(Long::valueOf).orElse(10L); final long offset = ofNullable(request.getParameter(P_OFFSET)).map(Long::valueOf).orElse(0L); // require a query statement final String rawStatement = request.getParameter(P_STATEMENT); if (rawStatement == null) { JsonObject obj = new JsonObject(); obj.addProperty(KEY_ERROR, "please submit a valid JCR-SQL2 query in the `statement` parameter."); response.getWriter().write(obj.toString()); return;//from w w w .ja va 2s . c o m } try { final Session session = request.getResourceResolver().adaptTo(Session.class); if (session == null || !session.isLive()) { throw new RepositoryException("failed to get a live JCR session from the request"); } final QueryManager qm = session.getWorkspace().getQueryManager(); // validate the syntax of the raw statement. Query rawQuery = qm.createQuery(rawStatement, Query.JCR_SQL2); rawQuery.setLimit(1L); rawQuery.execute(); // we can then expect the first SELECT to exist and be the instance we want to replace. (case-insensitive) final String statement = rawStatement.replaceFirst("(?i)SELECT", "SELECT [oak:scoreExplanation],"); // create a new query using our enhanced statement final Query query = qm.createQuery(statement, Query.JCR_SQL2); // set limit and offset query.setLimit(limit); query.setOffset(offset); // prepare Gson with QueryExecutingTypeAdapter Gson json = new GsonBuilder() .registerTypeHierarchyAdapter(Query.class, new QueryExecutingTypeAdapter(qm)).create(); // execute the query and write the response. response.getWriter().write(json.toJson(query)); } catch (final InvalidQueryException e) { JsonObject obj = new JsonObject(); obj.addProperty(KEY_ERROR, "please submit a valid JCR-SQL2 query in the `statement` parameter: " + e.getMessage()); response.getWriter().write(obj.toString()); } catch (final RepositoryException e) { JsonObject obj = new JsonObject(); obj.addProperty(KEY_ERROR, e.getMessage()); response.getWriter().write(obj.toString()); } }
From source file:com.aelitis.azureus.util.JSONUtilsGSON.java
License:Open Source License
private static Gson getGson() { if (gson == null) { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapterFactory(ObjectTypeAdapterLong.FACTORY); gson = builder.create();//from w w w. j a va2s . c o m } return gson; }
From source file:com.afis.jx.ckfinder.connector.handlers.command.QuickUploadCommand.java
License:Open Source License
/** * Writes JSON object into response stream after uploading file which was * dragged and dropped in to CKEditor 4.5 or higher. * * @param out the response stream/*from w ww . j av a 2 s. c o m*/ * @param errorMsg string representing error message which indicates that * there was an error during upload or uploaded file was renamed * @param path path to uploaded file */ private void handleJSONResponse(final OutputStream out, final String errorMsg, final String path) throws IOException { Gson gson = new GsonBuilder().serializeNulls().create(); Map<String, Object> jsonObj = new HashMap<String, Object>(); jsonObj.put("fileName", this.newFileName); jsonObj.put("uploaded", this.uploaded ? new Integer(1) : new Integer(0)); if (uploaded) { if (path != null && !path.equals("")) { jsonObj.put("url", path + FileUtils.backupWithBackSlash(FileUtils.encodeURIComponent(this.newFileName), "'")); } else { jsonObj.put("url", configuration.getTypes().get(this.type).getUrl() + this.currentFolder + FileUtils.backupWithBackSlash(FileUtils.encodeURIComponent(this.newFileName), "'")); } } if (errorMsg != null && !errorMsg.equals("")) { Map<String, Object> jsonErrObj = new HashMap<String, Object>(); jsonErrObj.put("number", this.errorCode); jsonErrObj.put("message", errorMsg); jsonObj.put("error", jsonErrObj); } out.write((gson.toJson(jsonObj)).getBytes("UTF-8")); }
From source file:com.afpa.dahouet.Dahouet.java
/** * @param args the command line arguments */// w w w . j a va 2 s . c o m public static void main(String[] args) { /* UI */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(Dahouet.class.getName()).log(Level.SEVERE, null, ex); } VoilierForm win = new VoilierForm(); win.setVisible(true); /* CONSOLE */ System.out.println(Color.ANSI_PURPLE + "****RESULTATS ALGORITHMIE & OBJECT****" + Color.ANSI_RESET); System.out.println(Color.ANSI_PURPLE + "----Creation d'une liste de personnes----" + Color.ANSI_RESET); List<Personne> personnes = new ArrayList<>(); Licencie lic1 = new Licencie(100, 100, 2016, "Nagepas", "Jean-Michel", "jmng@plouf.fr", 1980); personnes.add(lic1); Licencie lic2 = new Licencie(100, 150, 2017, "Le Gall", "Nicolas", "jmng@plouf.fr", 1995); personnes.add(lic2); Licencie lic3 = new Licencie(100, 200, 2017, "Le Floc\'h", "Nicolas", "jmng@plouf.fr", 1995); personnes.add(lic3); Commissaire comi1 = new Commissaire("Sud-Bretagne", "Goff", "Erwann", "ccc@ccc.com", 1970); personnes.add(comi1); Proprietaire pro1 = new Proprietaire("Le Hire", "Dd", "sfggf@gsr.fr", 1965); personnes.add(pro1); Proprietaire pro2 = new Proprietaire("Le Gronec", "Gwen", "sdfgdsfg@sdfg.com", 1975); personnes.add(pro2); Date date = new Date(); System.out.println(Color.ANSI_YELLOW + "Longueur de la liste : " + Color.ANSI_RESET + personnes.size()); System.out.println(Color.ANSI_PURPLE + "----Calcul de la moyenne et de la mdiane----" + Color.ANSI_RESET); System.out .println(Color.ANSI_YELLOW + "Moyenne d\'ge : " + Color.ANSI_RESET + Utils.averageAge(personnes)); System.out .println(Color.ANSI_YELLOW + "Valeur mdiane : " + Color.ANSI_RESET + Utils.medianAge(personnes)); System.out.println(Color.ANSI_PURPLE + "----Affichage des personnes----" + Color.ANSI_RESET); System.out.print(Utils.toStringList(personnes)); System.out.println(Color.ANSI_PURPLE + "----Ajout d'une personne----" + Color.ANSI_RESET); personnes.add(new Commissaire("Normadie", "Jacq", "Daniel", "Blo@fgf.fr", 1985)); System.out.println(Color.ANSI_YELLOW + "Longueur de la liste : " + Color.ANSI_RESET + personnes.size()); System.out.println(Color.ANSI_BLUE + personnes.get(personnes.size() - 1).toString()); System.out.println(Color.ANSI_PURPLE + "----Calcul de la moyenne et de la mdiane----" + Color.ANSI_RESET); System.out .println(Color.ANSI_YELLOW + "Moyenne d\'ge : " + Color.ANSI_RESET + Utils.averageAge(personnes)); System.out .println(Color.ANSI_YELLOW + "Valeur mdiane : " + Color.ANSI_RESET + Utils.medianAge(personnes)); System.out .println(Color.ANSI_PURPLE + "----Test de la mthode de calcul de points----" + Color.ANSI_RESET); try { double pts = lic1.calculPoints(date, 20.5); System.out.print(Color.ANSI_YELLOW + "Nombre de pts : " + Color.ANSI_RESET + pts); } catch (MismatchYearsException e) { System.err.println("ERREUR : " + e.getClass() + " : " + e.getMessage()); } try { double pts = lic2.calculPoints(date, 20.5); System.out.println(Color.ANSI_YELLOW + "Nombre de pts : " + Color.ANSI_RESET + pts); } catch (MismatchYearsException e) { System.err.println("ERREUR : " + e.getClass() + " : " + e.getMessage()); } try { double pts = lic3.calculPoints(date, 20.5); System.out.println(Color.ANSI_YELLOW + "Nombre de pts : " + Color.ANSI_RESET + pts); } catch (MismatchYearsException e) { System.err.println("ERREUR : " + e.getClass() + " : " + e.getMessage()); } System.out.println(Color.ANSI_PURPLE + "****FIN RESULTATS ALGORITHMIE & POO****" + Color.ANSI_RESET); /* FIN CONSOLE */ get("/hello", (Request req, Response res) -> { List<Challenge> cs = ChallengeDAO.findAll(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); String json = gson.toJson(cs); res.type("application/json; charset=utf-8"); return json; }); /** * Return current Challenge based on local date */ get("/currentChallenge", (Request req, Response res) -> { Challenge challenge = ChallengeDAO.getCurrentChallenge(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create(); String json = gson.toJson(challenge); res.type("application/json; charset=utf-8"); return json; }); get("/currentRegates", (Request req, Response res) -> { Challenge challenge = ChallengeDAO.getCurrentChallenge(); List<Regate> regates = RegateDAO.findByChallenge(challenge); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create(); res.type("application/json; charset=utf-8"); return gson.toJson(regates); }); get("/participation", (Request req, Response res) -> { Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssz").create(); Challenge challenge = ChallengeDAO.getCurrentChallenge(); List<Regate> regates = RegateDAO.findByChallenge(challenge); List<Participation> participations = new ArrayList<>(); for (Regate regate : regates) { participations.addAll(ParticipationDAO.findFromRegateWithResults(regate)); } res.type("application/json; charset=utf-8"); gson.toJson(participations); return gson.toJson(participations); }); get("/participations_without_result/:id", (req, res) -> { String id = req.params(":id"); Regate regate = RegateDAO.findById(id); List<Participation> participations = ParticipationDAO.findFromRegateWithoutResult(regate); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssz").create(); String json = gson.toJson(participations); res.type("application/json; charset=utf-8"); return json; }); get("/participations_with_result/:id", (req, res) -> { String id = req.params(":id"); Regate regate = RegateDAO.findById(id); List<Participation> participations = ParticipationDAO.findFromRegateWithResults(regate); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssz").create(); String json = gson.toJson(participations); res.type("application/json; charset=utf-8"); return json; }); }
From source file:com.agwego.fuzz.FuzzTestCase.java
License:Open Source License
@SuppressWarnings("unchecked method invocation: <T>fromJson(com.google.gson.JsonElement,java.lang.Class<T>) in com.google.gson.Gson is applied to (com.google.gson.Jon: <T>fromJson(com.google.gson.JsonElement,java.lang.Class<T>) in com.google.gson.Gson is applied to (com.google.gson.J") protected static Object createArg(JsonElement jarg, Class argClass) { Gson consumer = new GsonBuilder().setPrettyPrinting().create(); // TODO perhaps, provide better error messaging here. if (argClass == StringBuilder.class) { return consumer.fromJson(jarg, String.class) == null ? null : new StringBuilder(consumer.fromJson(jarg, String.class)); } else if (argClass == Integer.class) { return consumer.fromJson(jarg, Integer.class) == null ? null : consumer.fromJson(jarg, Integer.class); } else {//from ww w.j a va 2 s . c o m return consumer.fromJson(jarg, argClass == Object.class ? String.class : argClass); } }
From source file:com.ahmadrosid.lib.baseapp.core.BasePresenter.java
License:Apache License
public BasePresenter(T mvpView) { this.mvpView = mvpView; gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setPrettyPrinting().registerTypeAdapter(Date.class, new DateTypeAdapter()).create(); }
From source file:com.ai2020lab.aiutils.common.JsonUtils.java
License:Apache License
private static void initGson(ParserType type) { if (type == ParserType.EXCLUDE) { gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); } else if (type == ParserType.NORMAL) { gson = new GsonBuilder().create(); }/*from www . ja v a2 s . com*/ }
From source file:com.alexmany.secondstore.restfull.UsersService.java
License:Apache License
/** * //from w w w. j a va 2s.c om * @param linkProcessor * @param uriInfo * @return json of anuncis. {anunci[path(url imatge),preu,titol]} */ @GET @Produces({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) @Path("/getAnuncis") public String getAnuncis(@Context LinkBuilders linkProcessor, @Context UriInfo uriInfo) { List<AnuncisTOSearch> anuncisTOList = new ArrayList<AnuncisTOSearch>(); String init = Utils.getInfoFromUriInfo(uriInfo, Constants.INIT_LIST_KEY, String.class); Double lat = Utils.getInfoFromUriInfo(uriInfo, Constants.LATITUD_KEY, Double.class); Double lon = Utils.getInfoFromUriInfo(uriInfo, Constants.LONGITUD_KEY, Double.class); try { List<Anuncis> anuncisList = this.anuncisDao.getAll(Integer.parseInt(init)); for (Anuncis anunci : anuncisList) { AnuncisTOSearch anunciToSearch = new AnuncisTOSearch(anunci.getId(), anunci.getPreu(), anunci.getEstat(), 0.0, anunci.getTitol(), "", anunci.getDescripcio(), anunci.getCity()); anunciToSearch = UserUtils.setImagePath(anunci, anunciToSearch, Constants.server); if (lat == null || lon == null || anunci.getLatitud() == null || anunci.getLongitud() == null) { anunciToSearch.setDistance(0.0); } else { anunciToSearch.setDistance(6371 * Math.acos(Math.cos(Math.toRadians(lat)) * Math.cos(Math.toRadians(anunci.getLatitud())) * Math.cos(Math.toRadians(anunci.getLongitud()) - Math.toRadians(lon)) + Math.sin(Math.toRadians(lat)) * Math.sin(Math.toRadians(anunci.getLatitud())))); } anuncisTOList.add(anunciToSearch); } Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls() .excludeFieldsWithoutExposeAnnotation().create(); String json = gson.toJson(anuncisTOList); return json; } catch (HibernateException e) { e.printStackTrace(); return "{\"ok\":\"ko\"}"; } catch (Exception e) { e.printStackTrace(); return "{\"ok\":\"ko\"}"; } }
From source file:com.alexmany.secondstore.restfull.UsersService.java
License:Apache License
/** * //from www . ja v a2s . com * @param linkProcessor * @param uriInfo * @return json of anuncis. {anunci[path(url imatge),preu,titol]} */ @GET @Produces({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON }) @Path("/getListUserAnuncis") public String getListUserAnuncis(@Context LinkBuilders linkProcessor, @Context UriInfo uriInfo) { List<AnuncisTOSearch> anuncisTOList = new ArrayList<AnuncisTOSearch>(); Long userId = Utils.getInfoFromUriInfo(uriInfo, Constants.USERID_KEY, Long.class); try { List<Anuncis> anuncisList = this.anuncisDao.searchBy(userId); for (Anuncis anunci : anuncisList) { AnuncisTOSearch anunciToSearch = new AnuncisTOSearch(anunci.getId(), anunci.getPreu(), anunci.getEstat(), 0.0, anunci.getTitol(), "", anunci.getDescripcio(), anunci.getCity()); anunciToSearch = UserUtils.setImagePath(anunci, anunciToSearch, Constants.server); anuncisTOList.add(anunciToSearch); } Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls() .excludeFieldsWithoutExposeAnnotation().create(); String json = gson.toJson(anuncisTOList); return json; } catch (HibernateException e) { e.printStackTrace(); return "{\"ok\":\"ko\"}"; } catch (Exception e) { e.printStackTrace(); return "{\"ok\":\"ko\"}"; } }