Example usage for com.google.gson GsonBuilder GsonBuilder

List of usage examples for com.google.gson GsonBuilder GsonBuilder

Introduction

In this page you can find the example usage for com.google.gson GsonBuilder GsonBuilder.

Prototype

public GsonBuilder() 

Source Link

Document

Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.

Usage

From source file:com.alexmany.secondstore.restfull.UsersService.java

License:Apache License

/**
 * //from  w  w  w . j a v a2  s  .  c om
 * @param linkProcessor
 * @param uriInfo
 * @return json of anuncis within specific coords. {anunci[path(url
 *         imatge),preu,titol]}
 */
@GET
@Produces({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
@Path("/searchAnuncis")
public String searchAnuncis(@Context LinkBuilders linkProcessor, @Context UriInfo uriInfo) {

    List<AnuncisTOSearch> anuncisTOList = new ArrayList<AnuncisTOSearch>();
    Float lon = Utils.getInfoFromUriInfo(uriInfo, Constants.LONGITUD_KEY, Float.class);
    Float lat = Utils.getInfoFromUriInfo(uriInfo, Constants.LATITUD_KEY, Float.class);
    Integer distance = Utils.getInfoFromUriInfo(uriInfo, Constants.DISTANCE_KEY, Integer.class);
    Integer init = Utils.getInfoFromUriInfo(uriInfo, Constants.INIT_LIST_KEY, Integer.class);

    try {

        List<Anuncis> anuncisList = this.anuncisDao.search(init, distance, lat, lon);

        for (Anuncis anunci : anuncisList) {
            AnuncisTOSearch anunciToSearch = new AnuncisTOSearch(anunci.getId(), anunci.getPreu(),
                    anunci.getEstat(), 0.0, anunci.getTitol(), "", anunci.getDescripcio(), anunci.getCity());

            if (anunci.getImagesAnunci() != null && !anunci.getImagesAnunci().isEmpty()) {
                anunciToSearch.setName("http://" + Constants.server + "/AppStore/images/"
                        + anunci.getImagesAnunci().get(0).getName() + ".jpg");
            }

            anunciToSearch.setDistance(6371 * Math.acos(Math.cos(Math.toRadians(56.467056))
                    * Math.cos(Math.toRadians(anunci.getLatitud()))
                    * Math.cos(Math.toRadians(anunci.getLongitud()) - Math.toRadians(-2.976094))
                    + Math.sin(Math.toRadians(56.467056)) * 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

/**
 * /* ww  w.  j ava  2 s .  com*/
 * @param linkProcessor
 * @param uriInfo
 * @return json of anunci.
 */
@GET
@Produces({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
@Path("/getInfoAnunci")
public String getInfoAnunci(@Context LinkBuilders linkProcessor, @Context UriInfo uriInfo) {

    AnuncisTO anuncisTO = null;
    Long idAnunci = Utils.getInfoFromUriInfo(uriInfo, Constants.IDANUNCI_KEY, Long.class);

    try {

        if (idAnunci == null) {
            throw new RestException("getInfoAnunci :: id of ANUNCI is NULL or Empty");
        }

        Anuncis anunci = this.anuncisDao.load(idAnunci);

        anuncisTO = new AnuncisTO(anunci.getLatitud(), anunci.getLongitud(), anunci.getId(), anunci.getPreu(),
                anunci.getEstat(), 0.0, anunci.getTitol(), "", anunci.getDescripcio(), anunci.getCity(),
                anunci.getUser().getUsername(), this.usersDao.getNumProducts(anunci.getUser().getId()),
                this.usersDao.getNumProductsSold(anunci.getUser().getId()), anunci.getUser().getId());

        anuncisTO = UserUtils.setImagePath(anunci, anuncisTO, Constants.server);

        anuncisTO.setDistance(0.0);
        anuncisTO.setUserId(anunci.getUser().getId());
        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls()
                .excludeFieldsWithoutExposeAnnotation().create();
        String json = gson.toJson(anuncisTO);
        return json;

    } catch (RestException re) {
        re.printStackTrace();
        return "{\"ok\":\"ko\"}";
    } catch (HibernateException e) {
        e.printStackTrace();
        return "{\"ok\":\"ko\"}";
    } catch (Exception e) {
        e.printStackTrace();
        return "{\"ok\":\"ko\"}";
    }
}

From source file:com.alfresco.client.api.common.deserializer.EntryDeserializer.java

License:Apache License

@Override
public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException {
    JsonElement entry = je;//from   w  ww  . j av  a  2s . c o  m
    if (je.getAsJsonObject().has(PublicAPIConstant.ENTRY_VALUE)) {
        entry = je.getAsJsonObject().get(PublicAPIConstant.ENTRY_VALUE);
    }
    return new GsonBuilder().setDateFormat(ISO8601Utils.DATE_ISO_FORMAT).create().fromJson(entry, type);
}

From source file:com.algodefu.yeti.web.ClusterServlet.java

License:Apache License

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    response.setHeader("Cache-Control", "nocache");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    ClusterFormat clusterFormat = new ClusterFormat();

    // for JSON//from w ww . j  av  a2  s  . c  o m
    String errMsg = "";
    String clusterTitle = "";
    List<Cluster> clusterData = new ArrayList<>();
    String symbol = "";

    try {
        symbol = request.getParameter("symbol");
        int count = Integer.parseInt(request.getParameter("count"));
        LocalDateTime beginDt = LocalDateTime.parse(request.getParameter("beginDt"), dtf);
        LocalDateTime endDt = LocalDateTime.parse(request.getParameter("endDt"), dtf);

        ClusterType clusterType = ClusterType.fromName(request.getParameter("cluster-type"));
        clusterFormat.setType(clusterType);
        clusterFormat.setSymbol(symbol);
        clusterFormat.setBeginDt(beginDt);
        clusterFormat.setEndDt(endDt);
        clusterFormat.setCount(count);

        switch (clusterType) {
        case TIMEFRAME:
        case TICKTIME:
            int timeInterval = Integer.parseInt(request.getParameter("time-interval"));
            ChronoUnit chronoUnit = ChronoUnit.valueOf(request.getParameter("chronoUnit"));
            clusterFormat.setTimeInterval(timeInterval);
            clusterFormat.setChronoUnit(chronoUnit);
            break;
        case PRICERANGE:
            double priceRange = Double.parseDouble(request.getParameter("price-range"));
            clusterFormat.setPriceRange(priceRange);
            break;
        case VOLUME:
            long clusterVolume = Long.parseLong(request.getParameter("cluster-volume"));
            clusterFormat.setClusterVolume(clusterVolume);
            break;
        case TRADECOUNT:
            long maxTicksInCluster = Long.parseLong(request.getParameter("maxNumTicksInCluster"));
            clusterFormat.setMaxTicksInCluster(maxTicksInCluster);
            break;
        }

        ClusterSource clusterSource = new ClusterSource(clusterFormat);
        Instant start = Instant.now();
        clusterData = clusterSource.getClusters();
        Instant stop = Instant.now();
        System.out.printf("%d clusters of type %s generated in %d ms. \n", clusterData.size(),
                clusterFormat.getType().toString(), Duration.between(start, stop).toMillis());

        // add clusterType as title
        if (clusterFormat.getType() != null)
            clusterTitle = clusterFormat.getType().toString() + " CLUSTERS";

    } catch (Exception e) {
        errMsg = e.toString().replace("\"", " ");
        e.printStackTrace();
    }

    Hashtable<String, Object> hashtable = new Hashtable<>();
    hashtable.put("errMsg", errMsg);
    hashtable.put("symbol", symbol);
    hashtable.put("clusterTitle", clusterTitle);
    hashtable.put("clusterData", clusterData.toArray());

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Cluster.class, new ClusterTypeAdapter());
    Gson gson = gsonBuilder.create();

    out.println(gson.toJson(hashtable));
    out.flush();
    out.close();
}

From source file:com.algodefu.yeti.web.ShowTradeInPassServlet.java

License:Apache License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String reqTradeId = request.getParameter("tradeId");
    String reqPassId = request.getParameter("passId");
    String reqShowAllTrades = request.getParameter("showAllTrades");
    String reqStartTradeId = request.getParameter("startTradeId");
    String reqEndTradeId = request.getParameter("endTradeId");

    // for JSON/*  w ww .java 2 s.  c  o  m*/
    String errMsg = "";
    String symbol = "";
    String clusterTitle = "";
    List<Cluster> clusterData = new ArrayList<>();

    boolean forwardReq = false;

    if (reqPassId == null || reqPassId.trim().isEmpty())
        forwardReq = true;

    if (forwardReq) {
        // show input passId form
        RequestDispatcher view = request.getRequestDispatcher("/formpassid.html");
        view.forward(request, response);
    } else {
        response.setHeader("Cache-Control", "nocache");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        long singleTradeId = 0;
        long startTradeId = 0;
        long endTradeId = 0;
        int showAllTrades = 0;

        try {
            if (!reqTradeId.equals("undefined") && reqTradeId != null && !reqTradeId.trim().isEmpty())
                singleTradeId = Long.parseLong(reqTradeId);

            if (!reqStartTradeId.equals("undefined") && reqStartTradeId != null
                    && !reqStartTradeId.trim().isEmpty())
                startTradeId = Long.parseLong(reqStartTradeId);

            if (!reqEndTradeId.equals("undefined") && reqEndTradeId != null && !reqEndTradeId.trim().isEmpty())
                endTradeId = Long.parseLong(reqEndTradeId);

            if (!reqShowAllTrades.equals("undefined") && reqShowAllTrades != null
                    && !reqShowAllTrades.trim().isEmpty())
                showAllTrades = Integer.parseInt(reqShowAllTrades);

            TaskStorage taskStorage = TaskStorage.getInstance();

            // find the required trade / trades
            Trade[] trades = taskStorage.getTradesByPassId(reqPassId);

            if (showAllTrades != 1) {
                List<Trade> tradeList = new ArrayList<>();

                for (Trade t : trades) {
                    if (singleTradeId > 0 && t.getTradeID() == singleTradeId) {
                        tradeList.add(t);
                        break;
                    } else if (startTradeId > 0 && endTradeId > 0 && t.getTradeID() >= startTradeId
                            && t.getTradeID() <= endTradeId) {
                        tradeList.add(t);
                    }
                }

                trades = tradeList.toArray(new Trade[0]);
            }

            // get deals for each trade
            List<Deal> deals = new ArrayList<>();
            List<Deal> tempDeals = new ArrayList<>();
            for (Trade t : trades) {
                tempDeals = t.getDeals();
                for (int i = 0; i < tempDeals.size(); i++) {
                    if (tempDeals.get(i).getOrder() != OrderType.CANCELLED)
                        deals.add(tempDeals.get(i));
                }
            }

            ClusterFormat clusterFormat = taskStorage.getStrategyParamSetByPassId(reqPassId).getClusterFormat();
            symbol = clusterFormat.getSymbol();
            ClusterSource clusterSource = new ClusterSource(clusterFormat);
            List<Cluster> clusterList = clusterSource.getClusters();

            int startClusterIndex = 0;
            int endClusterIndex = 0;
            int tempClusterIndex = 0;

            for (Deal deal : deals) {
                Cluster cluster = null;
                for (int i = 0; i < clusterList.size(); i++) {
                    cluster = clusterList.get(i);
                    if (deal.getDateTime().compareTo(cluster.getOpenDateTime()) >= 0
                            && deal.getDateTime().compareTo(cluster.getCloseDateTime()) <= 0) {
                        if (deal.getEntry() == DealEntry.IN) {
                            cluster.addDeal(deal);
                            tempClusterIndex = i - 20;

                            if (tempClusterIndex < 0)
                                tempClusterIndex = 0;

                            if (startClusterIndex == 0)
                                startClusterIndex = tempClusterIndex;

                            if (tempClusterIndex < startClusterIndex)
                                startClusterIndex = tempClusterIndex;

                            //                                if(tempClusterIndex > 0 && (startClusterIndex > 0 && tempClusterIndex < startClusterIndex))
                            //                                    startClusterIndex = tempClusterIndex;

                            break;
                        }

                        if (deal.getEntry() == DealEntry.OUT && deal.getPrice() >= cluster.getLow()
                                && deal.getPrice() <= cluster.getHigh()) {
                            cluster.addDeal(deal);
                            tempClusterIndex = i + 1;

                            if (tempClusterIndex > clusterList.size() - 1)
                                tempClusterIndex = clusterList.size() - 1;

                            if (endClusterIndex == 0)
                                endClusterIndex = tempClusterIndex;

                            if (tempClusterIndex > endClusterIndex)
                                endClusterIndex = tempClusterIndex;

                            //                                if(tempClusterIndex > 0 && tempClusterIndex < clusterList.size() - 1 &&
                            //                                        (endClusterIndex >= 0 && tempClusterIndex > endClusterIndex))
                            //                                    endClusterIndex = tempClusterIndex;

                            break;
                        }
                    }
                } // end for clusterList
            } // end for - deal

            // add clusterType as title
            if (clusterFormat.getType() != null)
                clusterTitle = clusterFormat.getType().toString() + " CLUSTERS";

            // add clusterData
            for (int i = startClusterIndex; i <= endClusterIndex; i++) {
                clusterData.add(clusterList.get(i));
            }

        } catch (Exception e) {
            errMsg = e.toString();
            e.printStackTrace();
        }

        Hashtable<String, Object> hashtable = new Hashtable<>();
        hashtable.put("errMsg", errMsg);
        hashtable.put("symbol", symbol);
        hashtable.put("clusterTitle", clusterTitle);
        hashtable.put("clusterData", clusterData.toArray());

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Cluster.class, new ClusterTypeAdapter());
        Gson gson = gsonBuilder.create();

        out.println(gson.toJson(hashtable));
        out.flush();
        out.close();
    }

}

From source file:com.ali.truyentranh.activity.CategoryActivity.java

License:Apache License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_favorite);
    context = this;

    tvShowsGridView = (MyGridView) findViewById(R.id.gv_tv_shows);

    Intent intent = getIntent();/*ww  w . j a v  a 2s .c o m*/
    String value = intent.getStringExtra("category");
    final GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    api = "http://comicvn.net/truyentranh/apiv2/theloai?id=";
    Category category = gson.fromJson(value, Category.class);
    api = api + category.getId();
    setTitle(category.getName());

    adapter = new GridMangaAdapter(CategoryActivity.context, null, api);
    tvShowsGridView.setAdapter(adapter);
    tvShowsGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            Manga item = (Manga) adapter.getItem(position);
            Intent myIntent = new Intent(CategoryActivity.context, DetailActivity.class);
            myIntent.putExtra("detail", item.toString());
            CategoryActivity.context.startActivity(myIntent);
        }
    });

    scrollView = (ObservableScrollView) findViewById(R.id.scrollview);
    scrollView.setScrollViewListener(this);

    //Get a Tracker (should auto-report)
    Tracker t = ((Analytics) getApplication()).getTracker(Analytics.TrackerName.APP_TRACKER);
    t.setScreenName("Category");
    t.send(new HitBuilders.AppViewBuilder().build());
}

From source file:com.aliakseipilko.flightdutytracker.dagger.modules.GsonModule.java

License:Open Source License

@Provides
public Gson provideGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
    return gsonBuilder.create();
}

From source file:com.aliakseipilko.flightdutytracker.presenter.impl.CreateFlightPresenter.java

License:Open Source License

public CreateFlightPresenter(CreateFlightFragment view) {
    this.view = view;
    repository = new FlightRepository();
    //This should be injected with Dagger, but its retarded
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
    codeConverter = new AirportCodeConverter(view.getContext().getApplicationContext(), gsonBuilder.create());
}

From source file:com.aliakseipilko.flightdutytracker.presenter.impl.EditFlightPresenter.java

License:Open Source License

public EditFlightPresenter(EditFlightFragment view) {
    this.view = view;
    repository = new FlightRepository();
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY);
    codeConverter = new AirportCodeConverter(view.getContext().getApplicationContext(), gsonBuilder.create());
}

From source file:com.aliakseipilko.flightdutytracker.utils.BackupUtils.java

License:Open Source License

public static File serialiseFlightsRealmToFile(File destFile, RealmResults<Flight> data) throws IOException {
    destFile.createNewFile();//  w  ww.  j a  v  a  2 s . c  o  m
    destFile.setWritable(true);
    if (!destFile.canWrite()) {
        return null;
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.registerTypeAdapter(Flight.class, new FlightSerialiser()).serializeNulls()
            .setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
            .setDateFormat(DateFormat.FULL, DateFormat.FULL).create();

    JsonWriter writer = gson.newJsonWriter(new FileWriter(destFile));

    writer.beginArray();
    for (Flight f : data) {
        //            writer.beginArray();
        gson.toJson(f, Flight.class, writer);
        //            String json = gson.toJson(f, Flight.class);
        //            writer.endArray();
    }
    writer.endArray();
    writer.close();

    return destFile;
}