Example usage for com.google.gson FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES

List of usage examples for com.google.gson FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES

Introduction

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

Prototype

FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES

To view the source code for com.google.gson FieldNamingPolicy LOWER_CASE_WITH_UNDERSCORES.

Click Source Link

Document

Using this naming policy with Gson will modify the Java Field name from its camel cased form to a lower case field name where each word is separated by an underscore (_).

Usage

From source file:net.tradelib.core.Strategy.java

License:Apache License

public JsonObject writeStrategyReport() throws Exception {
    // Annual statistics
    Series annualStats = getAnnualStats();

    JsonObject result = new JsonObject();

    if (annualStats.size() > 0) {

        Average avgPnl = new Average();
        Average avgPnlPct = new Average();
        Average avgDD = new Average();
        Average avgDDPct = new Average();
        JsonArray asa = new JsonArray();

        for (int ii = 0; ii < annualStats.size(); ++ii) {
            JsonObject ajo = new JsonObject();
            ajo.addProperty("year", annualStats.getTimestamp(ii).getYear());
            ajo.addProperty("pnl", Math.round(annualStats.get(ii, 0)));
            ajo.addProperty("pnl_pct", annualStats.get(ii, 1) * 100.0);
            ajo.addProperty("end_equity", Math.round(annualStats.get(ii, 2)));
            ajo.addProperty("maxdd", Math.round(annualStats.get(ii, 3)));
            ajo.addProperty("maxdd_pct", annualStats.get(ii, 4) * 100.0);
            asa.add(ajo);/*w ww .  ja v  a 2 s . com*/

            avgPnl.add(annualStats.get(ii, 0));
            avgPnlPct.add(annualStats.get(ii, 1));
            avgDD.add(annualStats.get(ii, 3));
            avgDDPct.add(annualStats.get(ii, 4));
        }

        result.add("annual_stats", asa);

        result.addProperty("pnl", Math.round(avgPnl.get()));
        result.addProperty("pnl_pct", avgPnlPct.get() * 100.0);
        result.addProperty("avgdd", Math.round(avgDD.get()));
        result.addProperty("avgdd_pct", avgDDPct.get() * 100.0);
        result.addProperty("gain_to_pain", avgPnl.get() / Math.abs(avgDD.get()));
    }

    // Global statistics
    LocalDateTime maxDateTime = LocalDateTime.MIN;
    double maxEndEq = Double.MIN_VALUE;
    double maxDD = Double.MAX_VALUE;
    double maxDDPct = Double.MAX_VALUE;

    Series equity = getEquity();
    for (int ii = 0; ii < equity.size(); ++ii) {
        if (equity.get(ii) > maxEndEq) {
            maxEndEq = equity.get(ii);
            maxDateTime = equity.getTimestamp(ii);
        }
        maxDD = Math.min(maxDD, equity.get(ii) - maxEndEq);
        maxDDPct = Math.min(maxDDPct, equity.get(ii) / maxEndEq - 1);
    }

    double lastDD = equity.get(equity.size() - 1) - maxEndEq;
    double lastDDPct = (lastDD / maxEndEq) * 100;

    JsonObject jo = new JsonObject();
    jo.addProperty("cash", lastDD);
    jo.addProperty("pct", lastDDPct);

    result.add("total_maxdd", jo);

    jo = new JsonObject();
    jo.addProperty("date", maxDateTime.format(DateTimeFormatter.ISO_DATE));
    jo.addProperty("equity", Math.round(maxEndEq));

    result.add("total_peak", jo);

    if (equity.size() > 2) {
        int ii = equity.size() - 1;
        int jj = ii - 1;

        for (; jj >= 0 && equity.getTimestamp(jj).getYear() == equity.getTimestamp(ii).getYear(); --jj) {
        }

        if (jj >= 0 && equity.getTimestamp(jj).getYear() != equity.getTimestamp(ii).getYear()) {
            ++jj;
            maxDateTime = equity.getTimestamp(jj);
            maxEndEq = equity.get(jj);
            for (++jj; jj < equity.size(); ++jj) {
                if (equity.get(jj) > maxEndEq) {
                    maxEndEq = equity.get(jj);
                    maxDateTime = equity.getTimestamp(jj);
                }
            }

            lastDD = equity.get(equity.size() - 1) - maxEndEq;
            lastDDPct = (lastDD / maxEndEq) * 100;

            jo = new JsonObject();
            jo.addProperty("cash", lastDD);
            jo.addProperty("pct", lastDDPct);

            result.add("latest_maxdd", jo);

            jo = new JsonObject();
            jo.addProperty("date", maxDateTime.format(DateTimeFormatter.ISO_DATE));
            jo.addProperty("equity", Math.round(maxEndEq));

            result.add("latest_peak", jo);
        }
    }

    TradeSummary summary = getSummary("TOTAL", "All");
    if (summary != null) {
        result.addProperty("avg_trade_pnl", Math.round(summary.averageTradePnl));
        result.addProperty("maxdd", Math.round(maxDD));
        result.addProperty("maxdd_pct", maxDDPct * 100);
        result.addProperty("num_trades", summary.numTrades);
    } else {
        result.addProperty("avg_trade_pnl", 0);
        result.addProperty("maxdd", 0);
        result.addProperty("maxdd_pct", 0);
        result.addProperty("num_trades", 0);
    }

    Gson gson = new GsonBuilder().setPrettyPrinting()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

    connectIfNecessary();

    String query = " REPLACE INTO strategy_report (strategy_id,last_date,report) " + " VALUES(?,?,?) ";
    PreparedStatement stmt = connection.prepareStatement(query);
    stmt.setLong(1, dbId);
    stmt.setTimestamp(2, Timestamp.valueOf(getLastTimestamp()));
    String jsonString = gson.toJson(result);
    stmt.setString(3, jsonString);
    stmt.executeUpdate();

    connection.commit();

    return result;
}

From source file:nl.binaryimpact.showcase.util.module.ApiModule.java

License:Apache License

public Gson provideJsonParser() {
    return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setExclusionStrategies(new GsonIgnoreExclusionStrategy(), new GeneratedIdExclusionStrategy())
            .registerTypeAdapter(Date.class, new DateTypeAdapter())
            // TODO optimization: replace GSON's DateTypeAdapter with custom adapter
            // Gson standard DateTypeAdapter is very sub-optimal. It (1) uses SimpleDateFormat
            // which needs to be synchronized because it is not thread safe. And (2) it handles
            // error cases very poorly, repeatedly trying two date formats before ending up with
            // the usual ISO8601. We can optimize issue (1) by wrapping a the DateFormat in a
            // ThreadLocal subclass and we can optimize issue (2) by specifying one date format
            // rather than defaulting to three different date format patterns.
            .create();//from w w  w .  j ava  2 s . co m
}

From source file:nl.ivonet.io.GsonFactory.java

License:Apache License

public Gson gson() {
    return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
}

From source file:ooo.oxo.moments.InstaApplication.java

License:Open Source License

@Override
public void onCreate() {
    super.onCreate();

    //noinspection ConstantConditions
    if (TextUtils.isEmpty(BuildConfig.CLIENT_ID) || TextUtils.isEmpty(BuildConfig.CLIENT_SECRET)) {
        throw new IllegalStateException("Please create a \"client.properties\" in the same"
                + " directory of this module to specify your CLIENT_ID and CLIENT_SECRET.");
    }/*from   w  w  w .j av  a2s .  c  o m*/

    InstaSharedState.createInstance(this);

    httpClient = new OkHttpClient();
    httpClient.interceptors().add(chain -> {
        Request request = chain.request();
        Log.d("OkHttp", request.toString());
        Response response = chain.proceed(request);
        Log.d("OkHttp", response.toString());
        return response;
    });

    InstaSharedState.getInstance().applyProxy();

    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .registerTypeAdapter(Date.class, new TimestampTypeAdapter()).create();

    retrofit = new Retrofit.Builder().client(httpClient).addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).baseUrl("https://api.instagram.com/")
            .build();
}

From source file:ooo.oxo.mr.MrApplication.java

License:Open Source License

@Override
public void onCreate() {
    super.onCreate();

    LeakCanary.install(this);

    MrSharedState.createInstance();//from  w w w .  j  a v  a2s  .  c o  m

    httpClient = new OkHttpClient();

    httpClient.networkInterceptors().add(chain -> chain.proceed(chain.request().newBuilder()
            .header("Accept-Language", buildAcceptLanguage()).header("User-Agent", buildUserAgent()).build()));

    if (BuildConfig.DEBUG) {
        httpClient.networkInterceptors().add(new LoggingInterceptor());
    }

    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setDateFormat(Image.DATE_FORMAT_PATTERN).registerTypeAdapter(Color.class, new ColorTypeAdapter())
            .create();

    retrofit = new Retrofit.Builder().client(httpClient).addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).baseUrl("http://119.29.45.113:1024/api/")
            .build();
}

From source file:org.apache.cloudstack.network.opendaylight.api.resources.NeutronNetworksNorthboundAction.java

License:Apache License

public NeutronNetworksNorthboundAction(final URL url, final String username, final String password) {
    super(url, username, password);
    gsonNeutronNetwork = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();//from   w w w . j av  a 2s  .c  o m
}

From source file:org.apache.cloudstack.network.opendaylight.api.resources.NeutronNodesNorthboundAction.java

License:Apache License

public NeutronNodesNorthboundAction(final URL url, final String username, final String password) {
    super(url, username, password);
    gsonNeutronNode = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();/*from ww  w.j a v  a  2 s . co m*/
}

From source file:org.apache.cloudstack.network.opendaylight.api.resources.NeutronPortsNorthboundAction.java

License:Apache License

public NeutronPortsNorthboundAction(final URL url, final String username, final String password) {
    super(url, username, password);
    gsonNeutronPort = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();//from www .j ava 2  s . co  m
}

From source file:org.apache.fluo.core.util.ScanUtil.java

License:Apache License

/**
 * Generate JSON format as result of the scan.
 *
 * @since 1.2/* w  ww  .j a  v  a  2  s  .  c o m*/
 */
private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder, PrintStream out)
        throws JsonIOException {
    Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG)
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0).create();

    Map<String, String> json = new LinkedHashMap<>();
    for (RowColumnValue rcv : cellScanner) {
        json.put(FLUO_ROW, encoder.apply(rcv.getRow()));
        json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily()));
        json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier()));
        json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility()));
        json.put(FLUO_VALUE, encoder.apply(rcv.getValue()));
        gson.toJson(json, out);
        out.append("\n");

        if (out.checkError()) {
            break;
        }
    }
    out.flush();
}

From source file:org.apache.sling.auth.xing.login.XingLoginUtil.java

License:Apache License

public static XingUser fromJson(final String json) {
    final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();//from   w w w  . j  a v  a 2s  .com
    return gson.fromJson(json, XingUser.class);
}