Example usage for com.google.gson JsonParser JsonParser

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

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:com.continusec.client.VerifiableMap.java

License:Apache License

/**
 * Set the value for a given key in the map, conditional on the previous leaf hash value.
 * Calling this has the effect of adding a mutation to the
 * mutation log for the map, which then reflects in the root hash for the map. This occurs asynchronously.
 * @param key the key to set.//from w ww.  ja  v  a  2  s  . c  o  m
 * @param e the entry to set to key to. Typically one of {@link RawDataEntry}, {@link JsonEntry} or {@link RedactableJsonEntry}.
 * @param previousLeafHash the previous leaf hash. Typically one of {@link RawDataEntry} or {@link JsonEntry}.
 * @return add entry response, which includes the Merkle Tree Leaf hash of the mutation log entry added.
 * @throws ContinusecException upon error
 */
public AddEntryResponse update(byte[] key, UploadableEntry e, MerkleTreeLeaf previousLeafHash)
        throws ContinusecException {
    try {
        String[][] headers = { { "X-Previous-LeafHash", Hex.encodeHexString(previousLeafHash.getLeafHash()) } };
        JsonObject j = new JsonParser().parse(new String(
                this.client.makeRequest("PUT", this.path + "/key/h/" + Hex.encodeHexString(key) + e.getFormat(),
                        e.getDataForUpload(), headers).data,
                "UTF-8")).getAsJsonObject();
        return new AddEntryResponse(Base64.decodeBase64(j.get("leaf_hash").getAsString()));
    } catch (UnsupportedEncodingException e1) {
        throw new ContinusecException(e1);
    }
}

From source file:com.continusec.client.VerifiableMap.java

License:Apache License

/**
 * Delete the value for a given key from the map. Calling this has the effect of adding a mutation to the
 * mutation log for the map, which then reflects in the root hash for the map. This occurs asynchronously.
 * @param key the key to delete.//w  w  w  .  j  a  v a  2  s.c om
 * @return add entry response, which includes the Merkle Tree Leaf hash of the mutation log entry added.
 * @throws ContinusecException upon error
 */
public AddEntryResponse delete(byte[] key) throws ContinusecException {
    try {
        JsonObject j = new JsonParser()
                .parse(new String(this.client.makeRequest("DELETE",
                        this.path + "/key/h/" + Hex.encodeHexString(key), null, null).data, "UTF-8"))
                .getAsJsonObject();
        return new AddEntryResponse(Base64.decodeBase64(j.get("leaf_hash").getAsString()));
    } catch (UnsupportedEncodingException e1) {
        throw new ContinusecException(e1);
    }
}

From source file:com.continusec.client.VerifiableMap.java

License:Apache License

/**
 * Get the tree hash for given tree size.
 *
 * @param treeSize the tree size to retrieve the hash for. Pass {@link ContinusecClient#HEAD} to get the
 * latest tree size./*from  w w w  .  j av  a 2  s.  com*/
 * @return the tree hash for the given size (includes the tree size actually used, if unknown before running the query).
 * @throws ContinusecException upon error
 */
public MapTreeHead getTreeHead(int treeSize) throws ContinusecException {
    try {
        JsonObject e = new JsonParser().parse(new String(
                this.client.makeRequest("GET", this.path + "/tree/" + treeSize, null, null).data, "UTF-8"))
                .getAsJsonObject();
        return new MapTreeHead(Base64.decodeBase64(e.get("map_hash").getAsString()),
                LogTreeHead.fromJsonObject(e.getAsJsonObject("mutation_log")));
    } catch (UnsupportedEncodingException e) {
        throw new ContinusecException(e);
    }
}

From source file:com.contrastsecurity.ide.eclipse.core.extended.ExtendedContrastSDK.java

License:Open Source License

public StoryResource getStory(String orgUuid, String traceId) throws IOException, UnauthorizedException {
    InputStream is = null;/*from   w w  w .jav  a  2  s.  c  om*/
    InputStreamReader reader = null;
    try {
        String traceUrl = getTraceUrl(orgUuid, traceId);
        is = makeRequest(HttpMethod.GET, traceUrl);
        reader = new InputStreamReader(is);

        String inputString = IOUtils.toString(is, "UTF-8");
        StoryResource story = this.gson.fromJson(inputString, StoryResource.class);
        JsonObject object = (JsonObject) new JsonParser().parse(inputString);
        JsonObject storyObject = (JsonObject) object.get("story");
        if (storyObject != null) {
            JsonArray chaptersArray = (JsonArray) storyObject.get("chapters");
            List<Chapter> chapters = story.getStory().getChapters();
            if (chapters == null) {
                chapters = new ArrayList<>();
            } else {
                chapters.clear();
            }
            for (int i = 0; i < chaptersArray.size(); i++) {
                JsonObject member = (JsonObject) chaptersArray.get(i);
                Chapter chapter = gson.fromJson(member, Chapter.class);
                chapters.add(chapter);
                JsonObject properties = (JsonObject) member.get("properties");
                if (properties != null) {
                    Set<Entry<String, JsonElement>> entries = properties.entrySet();
                    Iterator<Entry<String, JsonElement>> iter = entries.iterator();
                    List<PropertyResource> propertyResources = new ArrayList<>();
                    chapter.setPropertyResources(propertyResources);
                    while (iter.hasNext()) {
                        Entry<String, JsonElement> prop = iter.next();
                        // String key = prop.getKey();
                        JsonElement entryValue = prop.getValue();
                        if (entryValue != null && entryValue.isJsonObject()) {
                            JsonObject obj = (JsonObject) entryValue;
                            JsonElement name = obj.get("name");
                            JsonElement value = obj.get("value");
                            if (name != null && value != null) {
                                PropertyResource propertyResource = new PropertyResource();
                                propertyResource.setName(name.getAsString());
                                propertyResource.setValue(value.getAsString());
                                propertyResources.add(propertyResource);
                            }
                        }
                    }
                }

            }
        }
        return story;
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.coronaide.core.service.impl.DatastoreService.java

License:Open Source License

/**
 * Creates a new data store service instance
 *
 * @since 0.1
 */
public DatastoreService() {
    gson = new Gson();
    jsonParser = new JsonParser();
}

From source file:com.couchbase.plugin.basement.api.Client.java

License:Open Source License

public HashMap<String, Object> parse(String json) {
    JsonParser parser = new JsonParser();
    JsonObject object = (JsonObject) parser.parse(json);

    Set<Map.Entry<String, JsonElement>> set = object.entrySet();
    Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
    HashMap<String, Object> map = new HashMap<String, Object>();
    while (iterator.hasNext()) {
        Map.Entry<String, JsonElement> entry = iterator.next();
        String key = entry.getKey();
        JsonElement value = entry.getValue();

        addJsonElement(key, value, map);

    }/*from w ww  .  jav a 2 s  . c  o  m*/

    return map;
}

From source file:com.createtank.payments.coinbase.CoinbaseApi.java

License:Apache License

private boolean doTokenRequest(Collection<BasicNameValuePair> params) throws IOException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(OAUTH_BASE_URL + "/token");
    List<BasicNameValuePair> paramBody = new ArrayList<BasicNameValuePair>();
    paramBody.add(new BasicNameValuePair("client_id", clientId));
    paramBody.add(new BasicNameValuePair("client_secret", clientSecret));
    paramBody.addAll(params);/*from  ww  w.java 2 s  . c  om*/
    post.setEntity(new UrlEncodedFormEntity(paramBody, "UTF-8"));
    HttpResponse response = client.execute(post);
    int code = response.getStatusLine().getStatusCode();

    if (code == 401) {
        return false;
    } else if (code != 200) {
        throw new IOException("Got HTTP response code " + code);
    }
    String responseString = EntityUtils.toString(response.getEntity());

    JsonParser parser = new JsonParser();
    JsonObject content = (JsonObject) parser.parse(responseString);
    System.out.print("content: " + content.toString());
    accessToken = content.get("access_token").getAsString();
    refreshToken = content.get("refresh_token").getAsString();
    return true;
}

From source file:com.createtank.payments.coinbase.CoinbaseApi.java

License:Apache License

private boolean doTokenRequest(Map<String, String> params) throws IOException {
    Map<String, String> paramsBody = new HashMap<String, String>();
    paramsBody.put("client_id", clientId);
    paramsBody.put("client_secret", clientSecret);
    paramsBody.putAll(params);//from ww  w . j av  a 2 s . com

    String bodyStr = RequestClient.createRequestParams(paramsBody);
    System.out.println(bodyStr);
    HttpURLConnection conn = (HttpsURLConnection) new URL(OAUTH_BASE_URL + "/token").openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(bodyStr);
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();

    if (code == 401) {
        return false;
    } else if (code != 200) {
        throw new IOException("Got HTTP response code " + code);
    }
    String response = RequestClient.getResponseBody(conn.getInputStream());

    JsonParser parser = new JsonParser();
    JsonObject content = (JsonObject) parser.parse(response);
    System.out.print("content: " + content.toString());
    accessToken = content.get("access_token").getAsString();
    refreshToken = content.get("refresh_token").getAsString();
    return true;
}

From source file:com.createtank.payments.coinbase.RequestClient.java

License:Apache License

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry,
        String accessToken) throws IOException, UnsupportedRequestVerbException {

    if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) {
        throw new UnsupportedRequestVerbException();
    }// www .  j  a  v  a  2  s . c o  m
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request;

        switch (verb) {
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        default:
            throw new RuntimeException("RequestVerb not implemented: " + verb);
        }

        ((HttpEntityEnclosingRequestBase) request)
                .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));

        request.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, json, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String url = BASE_URL + method;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());
    conn.addRequestProperty("Content-Type", "application/json");

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(json.toString());
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, json, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:com.createtank.payments.coinbase.RequestClient.java

License:Apache License

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, Map<String, String> params,
        boolean retry, String accessToken) throws IOException {
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request = null;//from w  ww.  j  a va  2  s.com

        if (verb == RequestVerb.POST || verb == RequestVerb.PUT) {
            switch (verb) {
            case POST:
                request = new HttpPost(url);
                break;
            case PUT:
                request = new HttpPut(url);
                break;
            default:
                throw new RuntimeException("RequestVerb not implemented: " + verb);
            }

            List<BasicNameValuePair> paramsBody = new ArrayList<BasicNameValuePair>();

            if (params != null) {
                List<BasicNameValuePair> convertedParams = convertParams(params);
                paramsBody.addAll(convertedParams);
            }

            ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(paramsBody, "UTF-8"));
        } else {
            if (params != null) {
                url = url + "?" + createRequestParams(params);
            }

            if (verb == RequestVerb.GET) {
                request = new HttpGet(url);
            } else if (verb == RequestVerb.DELETE) {
                request = new HttpDelete(url);
            }
        }
        if (request == null)
            return null;

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));
        System.out.println("auth header: " + request.getFirstHeader("Authorization"));
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, params, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String paramStr = createRequestParams(params);
    String url = BASE_URL + method;

    if (paramStr != null && verb == RequestVerb.GET || verb == RequestVerb.DELETE)
        url += "?" + paramStr;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    if (verb != RequestVerb.GET && verb != RequestVerb.DELETE && paramStr != null) {
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(paramStr);
        writer.flush();
        writer.close();
    }

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, params, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}