Example usage for com.google.gson JsonParser parse

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

Introduction

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

Prototype

@Deprecated
public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException 

Source Link

Usage

From source file:com.blackducksoftware.integration.hub.fod.service.FoDRestConnectionService.java

License:Apache License

public String getFoDImportSessionId(final String releaseId, final long fileLength, final String reportName,
        final String reportNotes) {
    final RestTemplate restTemplate = new RestTemplate();

    final HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + this.getToken());
    headers.setContentType(MediaType.APPLICATION_JSON);

    final JsonObject requestJson = new JsonObject();

    requestJson.addProperty("releaseId", Integer.parseInt(releaseId));
    requestJson.addProperty("fileLength", fileLength);
    requestJson.addProperty("fileExtension", ".pdf");
    requestJson.addProperty("reportName", reportName);
    requestJson.addProperty("reportNotes", reportNotes);

    logger.debug("Requesting Session ID to FoD:" + requestJson.toString());

    final HttpEntity<String> request = new HttpEntity<>(requestJson.toString(), headers);

    // Get the Session ID
    final ResponseEntity<String> response = restTemplate.exchange(
            appProps.getFodAPIBaseURL() + FOD_API_URL_VERSION + REPORT_IMPORT_SESSIONID, HttpMethod.POST,
            request, String.class);

    final JsonParser parser = new JsonParser();
    final JsonObject obj = parser.parse(response.getBody()).getAsJsonObject();

    return obj.get("importReportSessionId").getAsString();
}

From source file:com.blackducksoftware.integration.hub.fod.service.FoDRestConnectionService.java

License:Apache License

public String uploadFoDPDF(final String releaseId, final String sessionId, final String uploadFilePath,
        final long fileLength) throws IOException {
    final RestTemplate restTemplate = new RestTemplate();

    final HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + this.getToken());
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    int fragSize = VulnerabilityReportConstants.FRAG_SIZE;
    byte[] fragBytes = null;
    int totalBytesRead = 0;
    int numberOfFrags = 0;

    // Chunk it up and send to FoD
    try (BufferedInputStream vulnFileStream = new BufferedInputStream(new FileInputStream(uploadFilePath))) {
        ResponseEntity<String> response = null;

        while (totalBytesRead < (int) fileLength) {
            final int bytesRemaining = (int) (fileLength - totalBytesRead);
            // if this is the last frag...
            if (bytesRemaining < fragSize) {
                fragSize = bytesRemaining;
                numberOfFrags = -1;/*from   w  ww.  jav a2  s  . c om*/
            }
            fragBytes = new byte[fragSize];
            final int bytesRead = vulnFileStream.read(fragBytes, 0, fragSize);

            final HttpEntity<byte[]> request = new HttpEntity<>(fragBytes, headers);

            final String importURL = appProps.getFodAPIBaseURL() + FOD_API_URL_VERSION + IMPORT_REPORT
                    + "/?fragNo=" + String.valueOf(numberOfFrags) + "&offset=" + totalBytesRead
                    + "&importReportSessionId=" + sessionId;

            logger.debug("Attempting PUT with: " + importURL);

            response = restTemplate.exchange(importURL, HttpMethod.PUT, request, String.class);

            totalBytesRead += bytesRead;
            numberOfFrags++;
            logger.debug("Total Bytes Read: " + totalBytesRead);
        }

        final JsonParser parser = new JsonParser();
        final JsonObject obj = parser.parse(response.getBody()).getAsJsonObject();

        return obj.get("reportId").getAsString();

    } catch (final Exception e) {
        logger.error("Sending PDF to FoD failed. Please contact Black Duck with this error and stack trace:");
        e.printStackTrace();
        throw e;
    }
}

From source file:com.blackducksoftware.integration.hub.fod.service.FoDRestConnectionService.java

License:Apache License

/**
 * Used for authenticating in the case of a time out using the saved api credentials.
 *
 * @throws Exception/*from   w  w w  .j a v a  2  s . c om*/
 */
public void authenticate() throws Exception {
    try {

        // Build the form body
        final FormBody.Builder formBodyBuilder = new FormBody.Builder().add("scope", "api-tenant");

        // Has username/password
        if (appProps.getFodGrantType().equals(VulnerabilityReportConstants.GRANT_TYPE_PASSWORD)) {
            formBodyBuilder.add("grant_type", VulnerabilityReportConstants.GRANT_TYPE_PASSWORD)
                    .add("username", appProps.getFodTenantId() + "\\" + appProps.getFodUsername())
                    .add("password", appProps.getFodPassword());
        } else // Has api key/secret
        {
            formBodyBuilder.add("grant_type", VulnerabilityReportConstants.GRANT_TYPE_CLIENT_CREDENTIALS)
                    .add("client_id", appProps.getFodClientId())
                    .add("client_secret", appProps.getFodClientSecret());

        }
        final RequestBody formBody = formBodyBuilder.build();

        final Request request = new Request.Builder().url(appProps.getFodAPIBaseURL() + "/oauth/token")
                .post(formBody).build();
        final Response response = client.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.debug(
                    "response::" + response.message() + ", " + response.code() + ", " + response.toString());
            throw new FoDConnectionException("Unexpected code " + response);
        }

        logger.info("Successful connection to Fortify On Demand!");

        final String content = IOUtils.toString(response.body().byteStream(), "utf-8");
        response.body().close();

        // Parse the Response
        final JsonParser parser = new JsonParser();
        final JsonObject obj = parser.parse(content).getAsJsonObject();
        this.token = obj.get("access_token").getAsString();

    } catch (final FoDConnectionException fce) {
        if (fce.getMessage().contains(VulnerabilityReportConstants.FOD_UNAUTORIZED)) {
            logger.error(
                    "FoD CONNECTION FAILED.  Please check the FoD URL, username, tenant, and password and try again.");
            logger.info("FoD URL=" + appProps.getFodAPIBaseURL());
            logger.info("FoD GrantType=" + appProps.getFodGrantType());
            logger.info("FoD client Id=" + appProps.getFodClientId());
            logger.info("FoD username=" + appProps.getFodUsername());
            logger.info("FoD tennant=" + appProps.getFodTenantId());
        } else {
            logger.error("FoD Response was not successful with message: " + fce.getMessage());
        }
        throw fce;
    }

    catch (final UnknownHostException uhe) {
        logger.error("Unknown Host Error.  Are you connected to the internet?");
        uhe.printStackTrace();
        throw uhe;
    }

    catch (final Exception e) {
        logger.error("Authentication to FoD failed. Connection seems OK.");
        e.printStackTrace();
        throw e;
    }
}

From source file:com.blackducksoftware.integration.hub.rest.RestConnection.java

License:Apache License

private <T> T parseResponse(final Class<T> modelClass, final ClientResource resource) throws IOException {
    final String response = readResponseAsString(resource.getResponse());
    final JsonParser parser = new JsonParser();
    final JsonObject json = parser.parse(response).getAsJsonObject();

    final T modelObject = gson.fromJson(json, modelClass);
    return modelObject;
}

From source file:com.bosch.osmi.bdp.access.mock.BdpApiAccessMockImpl.java

License:Open Source License

private JsonObject readJsonFile(Reader jsonReader) {
    // Read from File to String
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonReader);
    return jsonElement.getAsJsonObject();
}

From source file:com.ca.dvs.utilities.raml.JsonUtil.java

License:Open Source License

/**
 * Compare two JSON strings//from  w  ww.  j  av a  2 s.  c o m
 * @param json1 the first of two JSON objects to compare
 * @param json2 the second of two JSON objects to compare
 * @return true when the JSON strings compare favorably, otherwise false
 */
public static boolean equals(String json1, String json2) {

    boolean match = false;

    if (null != json1 && null != json2) {
        JsonParser parser = new JsonParser();

        Object obj1 = parser.parse(json1);
        Object obj2 = parser.parse(json2);

        if (obj1 instanceof JsonObject && obj2 instanceof JsonObject) {
            JsonObject jObj1 = (JsonObject) obj1;
            JsonObject jObj2 = (JsonObject) obj2;
            match = jObj1.equals(jObj2);
        } else if (obj1 instanceof JsonArray && obj2 instanceof JsonArray) {
            JsonArray jAry1 = (JsonArray) obj1;
            JsonArray jAry2 = (JsonArray) obj2;
            match = jAry1.equals(jAry2);
        }
    }
    return match;
}

From source file:com.ca.dvs.utilities.raml.JsonUtil.java

License:Open Source License

/**
 * Get a JSON representation of the Raml example, whether it is inline or included.
 * <p>//from   www. j  a va2 s .co  m
 * @param example the Raml example text
 * @param resourceDir a folder to search for imported Raml elements
 * @return Raml example data in JSON format
 */
public static String getJsonFromExample(String example, File resourceDir) {

    String json = example;

    // Example is not JSON.  Is it a string containing the path to a file?
    File includeFile = null;

    includeFile = resourceDir == null ? new File(example.trim()) : new File(resourceDir, example.trim());

    logger.debug(String.format("Potential include file: %s", includeFile.getAbsolutePath()));

    String includedContent = null;

    if (includeFile.canRead()) { // First check to see if example is actually an existing file path (RAML parser include bug workaround)

        Scanner scanner = null;

        try {

            scanner = new Scanner(includeFile);

            includedContent = scanner.useDelimiter("\\Z").next();

            JsonParser parser = new JsonParser();

            try {

                parser.parse(includedContent);

                json = includedContent;

            } catch (JsonSyntaxException jse) {

                String msg = String.format("Processing included example %s - %s\nContent follows...\n%s",
                        includeFile.getPath(), jse.getMessage(), includedContent);
                throw new JsonSyntaxException(msg, jse.getCause());

            }

        } catch (FileNotFoundException e1) {

            // If resolving the example content as a file lands us here, it's apparently not a file
            // validate the content by parsing as JSON

            try {

                JsonParser parser = new JsonParser();
                parser.parse(example);

                // If we get this far without an exception, the example is truly JSON
                json = example;

            } catch (JsonSyntaxException e) {

                String msg = String.format("Processing example - %s\nContent follows...\n%s", e.getMessage(),
                        example);
                throw new JsonSyntaxException(msg, e.getCause());

            }

        } finally {

            if (null != scanner) {
                scanner.close();
            }

        }

    } else {

        try {
            JsonParser parser = new JsonParser();
            parser.parse(example);

            // If we get this far without an exception, the example is truly JSON
            json = example;

        } catch (JsonSyntaxException e) {

            String msg = String.format("Processing example - %s\nContent follows...\n%s", e.getMessage(),
                    example);
            throw new JsonSyntaxException(msg, e.getCause());

        }
    }

    return json;
}

From source file:com.ca.dvs.utilities.raml.RamlUtil.java

License:Open Source License

/**
 * @param jsonString/*from www. ja  v a  2 s. c o m*/
 * @return the appropriate JsonElement object from the parsed jsonString
 */
private static Object getJsonElementValue(String jsonString) {

    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(jsonString);

    if (jsonElement.isJsonObject()) {

        return jsonElement.getAsJsonObject();

    } else if (jsonElement.isJsonArray()) {

        return jsonElement.getAsJsonArray();

    } else if (jsonElement.isJsonNull()) {

        return jsonElement.getAsJsonNull();

    } else if (jsonElement.isJsonPrimitive()) {

        return jsonElement.getAsJsonPrimitive();

    } else {

        return null;

    }
}

From source file:com.caihan.scframe.utils.json.gson.GsonConvertUtils.java

License:Apache License

public static String formatJson(String json) {
    try {/*  w w w.j  av a  2  s .  co  m*/
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(json);
        return new GsonBuilder().setPrettyPrinting()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .registerTypeAdapter(Date.class, new DateTypeAdapter()).create().toJson(je);
    } catch (Exception e) {
        return json;
    }
}

From source file:com.caihan.scframe.utils.json.gson.GsonConvertUtils.java

License:Apache License

public static String formatJson(Object src) {
    try {/*  w  w w. j a  va 2  s.c o  m*/
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(toJson(src));
        return new GsonBuilder().setPrettyPrinting()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .registerTypeAdapter(Date.class, new DateTypeAdapter()).create().toJson(je);
    } catch (Exception e) {
        return e.getMessage();
    }
}