Example usage for com.google.gson GsonBuilder create

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

Introduction

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

Prototype

public Gson create() 

Source Link

Document

Creates a Gson instance based on the current configuration.

Usage

From source file:com.gazbert.bxbot.exchanges.BitstampExchangeAdapter.java

License:Open Source License

/**
 * Initialises the GSON layer.//w w w  .  j  a v  a  2s.c  om
 */
private void initGson() {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new BitstampDateDeserializer());
    gson = gsonBuilder.create();
}

From source file:com.gazbert.bxbot.exchanges.BtceExchangeAdapter.java

License:Open Source License

/**
 * Initialises the GSON layer.//from   w  ww  .  ja v  a2 s.c o  m
 */
private void initGson() {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(BtceOpenOrders.class, new OpenOrdersDeserializer());
    gson = gsonBuilder.create();
}

From source file:com.gazbert.bxbot.exchanges.HuobiExchangeAdapter.java

License:Open Source License

/**
 * Initialises the GSON layer.//from   w ww .  java 2s  .  co  m
 */
private void initGson() {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(HuobiOpenOrderResponseWrapper.class, new GetHuobiOpenOrdersDeserializer());
    gson = gsonBuilder.create();
}

From source file:com.gazbert.bxbot.exchanges.ItBitExchangeAdapter.java

License:Open Source License

/**
 * Initialises the GSON layer./*w  w w .  j ava 2s. c  om*/
 */
private void initGson() {

    // We need to disable HTML escaping for this adapter else GSON will change = to unicode for query strings, e.g.
    // https://api.itbit.com/v1/wallets?userId=56DA621F --> https://api.itbit.com/v1/wallets?userId\u003d56DA621F
    final GsonBuilder gsonBuilder = new GsonBuilder().disableHtmlEscaping();
    gson = gsonBuilder.create();
}

From source file:com.gazbert.bxbot.exchanges.KrakenExchangeAdapter.java

License:Open Source License

/**
 * Initialises the GSON layer.//from ww w  .j ava  2  s .co  m
 */
private void initGson() {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(KrakenTickerResult.class, new KrakenTickerResultDeserializer());
    gson = gsonBuilder.create();
}

From source file:com.gelakinetic.mtgfam.helpers.tcgp.TcgpApi.java

License:Open Source License

/**
 * This function requests an access token from TCGPlayer.com by providing the private keys.
 * An access token should only be requested if we don't have a valid one stored. When an access
 * token is received, the token and expiration date should be saved for later use.
 *
 * @param publicKey   Supplied by TCGPlayer.com, also referred to as the "client_id"
 * @param privateKey  Supplied by TCGPlayer.com, also referred to as the "client_secret"
 * @param accessToken Supplied by TCGPlayer.com, also referred to as the "X-Tcg-Access-Token"
 * @return An AccessToken object or null if a token is already loaded
 * @throws IOException If something goes wrong with the network
 *///from  w  w w.j  a v a2  s . c  o  m
public AccessToken getAccessToken(String publicKey, String privateKey, String accessToken) throws IOException {

    // Only request an access token if we don't have one already
    if (null == mAccessToken) {
        // Create the connection with default options
        HttpURLConnection conn = (HttpURLConnection) new URL("https://api.tcgplayer.com/token")
                .openConnection();
        setDefaultOptions(conn, HttpMethod.POST);

        // Set the header, special for the token request
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("X-Tcg-Access-Token", accessToken);

        // Set the body and send the POST
        String payload = "grant_type=client_credentials&client_id=" + publicKey + "&client_secret="
                + privateKey;
        conn.getOutputStream().write(payload.getBytes(Charset.forName("UTF-8")));

        // Get the response stream
        InputStream inStream;
        try {
            inStream = conn.getInputStream();
        } catch (FileNotFoundException e) {
            inStream = conn.getErrorStream();
            if (null == inStream) {
                conn.disconnect();
                // Return an empty, not null, object
                return new AccessToken();
            }
        }

        // Parse the json out of the response and save it
        GsonBuilder builder = new GsonBuilder();
        AccessToken.setDateFormat(builder);
        AccessToken token = builder.create().fromJson(new InputStreamReader(inStream), AccessToken.class);
        this.mAccessToken = token.access_token;

        // Clean up
        inStream.close();
        conn.disconnect();

        return token;
    }

    // Return the saved access token
    return null;
}

From source file:com.gelakinetic.mtgfam.helpers.tcgp.TcgpApi.java

License:Open Source License

/**
 * Given an array of productIds, request and return all of the product's non-price details
 *
 * @param productIds The productId of the card to query
 * @return All the non-price details//from   w ww.  j  ava 2s.  c  o  m
 * @throws IOException If something goes wrong with the network
 */
public ProductDetails getProductDetails(long[] productIds) throws IOException {
    // Make sure we have an access token first
    if (null != mAccessToken) {

        // Concatenate all the product IDs into one string
        StringBuilder stringIds = new StringBuilder();
        for (long id : productIds) {
            if (stringIds.length() == 0) {
                stringIds = new StringBuilder(Long.toString(id));
            } else {
                stringIds.append(',').append(Long.toString(id));
            }
        }

        // Create the connection with default options and headers
        HttpURLConnection conn = (HttpURLConnection) new URL(
                "https://api.tcgplayer.com/" + TCGP_VERSION + "/catalog/products/" + stringIds.toString())
                        .openConnection();
        setDefaultOptions(conn, HttpMethod.GET);
        addHeaders(conn);

        // Get the response stream. This opens the connection
        InputStream inStream;
        try {
            inStream = conn.getInputStream();
        } catch (FileNotFoundException e) {
            inStream = conn.getErrorStream();
            if (null == inStream) {
                conn.disconnect();
                // Return an empty, not null, object
                return new ProductDetails();
            }
        }

        // Parse the json out of the response and save it
        GsonBuilder builder = new GsonBuilder();
        CatalogData.CatalogDataItem.setDateFormat(builder);
        ProductDetails details = builder.create().fromJson(new InputStreamReader(inStream),
                ProductDetails.class);

        // Clean up
        inStream.close();
        conn.disconnect();
        return details;
    }
    // No access token
    return null;
}

From source file:com.gemini.httpclienttest.HttpClientTestMain.java

public static void main(String[] args) {
    //authenticate with the server
    URL url;//w  w w .j a  va2 s  .c om
    try {
        url = new URL("http://198.11.209.34:5000/v2.0/tokens");
    } catch (MalformedURLException ex) {
        System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0");
        return;
    }
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    try {
        HttpPost httpPost = new HttpPost(url.toString());
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity strEntity = new StringEntity(
                "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}");
        httpPost.setEntity(strEntity);
        //System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            //get the response status code 
            String respStatus = response.getStatusLine().getReasonPhrase();

            //get the response body
            int bytes = response.getEntity().getContent().available();
            InputStream body = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(body));
            String line;
            StringBuffer sbJSON = new StringBuffer();
            while ((line = in.readLine()) != null) {
                sbJSON.append(line);
            }
            String json = sbJSON.toString();
            EntityUtils.consume(response.getEntity());

            GsonBuilder gsonBuilder = new GsonBuilder();
            Object parsedJson = gsonBuilder.create().fromJson(json, Object.class);
            System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString());
            if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) {
                com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson;
                if (treeJson.containsKey("id")) {
                    String s = (String) treeJson.getOrDefault("id", "no key provided");
                    System.out.printf("\n\ntree contained id %s\n", s);
                } else {
                    System.out.printf("\n\ntree does not contain key id\n");
                }
            }
        } catch (IOException ex) {
            System.out.print(ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        System.out.print(ex);
    } finally {
        //lots of exceptions, just the connection and exit
        try {
            httpclient.close();
        } catch (IOException | NoSuchMethodError ex) {
            System.out.print(ex);
            return;
        }
    }
}

From source file:com.ghjansen.cas.ui.desktop.manager.EventManager.java

License:Open Source License

public EventManager(Main main) {
    this.main = main;
    this.skipRuleNumberEvent = false;
    this.invalidFieldColor = Color.red;
    this.validator = new GUIValidator(main, invalidFieldColor);
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(UnidimensionalSimulationParameter.class,
            new SimulationParameterJsonAdapter<UnidimensionalSimulationParameter>());
    gsonBuilder.setPrettyPrinting();/*from  w  ww  .  j  a v a2  s. c o m*/
    this.gson = gsonBuilder.create();
    this.notification = new Notification(this);
}

From source file:com.gitblit.manager.FilestoreManager.java

License:Apache License

private static Gson gson(ExclusionStrategy... strategies) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Date.class, new GmtDateTypeAdapter());
    if (!ArrayUtils.isEmpty(strategies)) {
        builder.setExclusionStrategies(strategies);
    }//from  w  w w .  j  a  v  a  2s. c  om
    return builder.create();
}