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.blackducksoftware.integration.hub.detect.detector.packagist.PackagistParser.java

License:Apache License

public PackagistParseResult getDependencyGraphFromProject(final String sourcePath,
        final String composerJsonText, final String composerLockText) {
    final LazyExternalIdDependencyGraphBuilder builder = new LazyExternalIdDependencyGraphBuilder();

    final JsonObject composerJsonObject = new JsonParser().parse(composerJsonText).getAsJsonObject();
    final NameVersion projectNameVersion = parseNameVersionFromJson(composerJsonObject);

    final JsonObject composerLockObject = new JsonParser().parse(composerLockText).getAsJsonObject();
    final List<PackagistPackage> models = convertJsonToModel(composerLockObject,
            detectConfiguration.getBooleanProperty(DetectProperty.DETECT_PACKAGIST_INCLUDE_DEV_DEPENDENCIES,
                    PropertyAuthority.None));
    final List<NameVersion> rootPackages = parseDependencies(composerJsonObject,
            detectConfiguration.getBooleanProperty(DetectProperty.DETECT_PACKAGIST_INCLUDE_DEV_DEPENDENCIES,
                    PropertyAuthority.None));

    models.forEach(it -> {/*www .  j  a  v a2s . c o m*/
        final ExternalId id = externalIdFactory.createNameVersionExternalId(Forge.PACKAGIST,
                it.getNameVersion().getName(), it.getNameVersion().getVersion());
        final NameDependencyId dependencyId = new NameDependencyId(it.getNameVersion().getName());
        builder.setDependencyInfo(dependencyId, it.getNameVersion().getName(), it.getNameVersion().getVersion(),
                id);
        if (isRootPackage(it.getNameVersion(), rootPackages)) {
            builder.addChildToRoot(dependencyId);
        }
        it.getDependencies().forEach(child -> {
            if (existsInPackages(child, models)) {
                final NameDependencyId childId = new NameDependencyId(child.getName());
                builder.addChildWithParent(childId, dependencyId);
            } else {
                logger.warn("Dependency was not found in packages list but found a require that used it: "
                        + child.getName());
            }
        });
    });

    ExternalId projectExternalId;
    if (projectNameVersion.getName() == null || projectNameVersion.getVersion() == null) {
        projectExternalId = externalIdFactory.createPathExternalId(Forge.PACKAGIST, sourcePath);
    } else {
        projectExternalId = externalIdFactory.createNameVersionExternalId(Forge.PACKAGIST,
                projectNameVersion.getName(), projectNameVersion.getVersion());
    }

    final DependencyGraph graph = builder.build();
    final DetectCodeLocation codeLocation = new DetectCodeLocation.Builder(DetectCodeLocationType.PACKAGIST,
            sourcePath, projectExternalId, graph).build();

    return new PackagistParseResult(projectNameVersion.getName(), projectNameVersion.getVersion(),
            codeLocation);
}

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;/*  ww  w . j  a  v  a2s . co  m*/
            }
            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/*w  w  w .  jav a 2 s  .  c o m*/
 */
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.fod.utils.HubFoDJsonParser.java

License:Apache License

public static String getVulnerableComponentsURL(final String projectVersionJson) {

    final JsonObject jsonObject = new JsonParser().parse(projectVersionJson).getAsJsonObject();
    final JsonArray linksArray = jsonObject.get(JSON_META_LABEL).getAsJsonObject().get(JSON_META_LINKS)
            .getAsJsonArray();/*from w  ww .jav  a  2s .  c om*/
    for (final JsonElement link : linksArray) {
        final JsonObject linkObj = link.getAsJsonObject();
        if (linkObj.get(JSON_META_REL).getAsString().equalsIgnoreCase(JSON_META_VULNERABLE_COMPONENTS)) {
            return linkObj.get(JSON_HREF).getAsString();
        }
    }

    return null;

}

From source file:com.blackducksoftware.integration.hub.fod.utils.HubFoDJsonParser.java

License:Apache License

public static String getProjectHubUIURL(final String projectJson) {
    final JsonObject jsonObject = new JsonParser().parse(projectJson).getAsJsonObject();
    final String projectApiLink = jsonObject.get(JSON_META_LABEL).getAsJsonObject().get(JSON_HREF)
            .getAsString();//from  w ww .  j av  a 2 s . co  m

    return projectApiLink.replace(HUB_API_PROJECTS, HUB_UI_PROJECTS);

}

From source file:com.blackducksoftware.integration.hub.fod.utils.HubFoDJsonParser.java

License:Apache License

public static String getProjectVersionHubUIURL(final String projectVersionJson) {
    final JsonObject jsonObject = new JsonParser().parse(projectVersionJson).getAsJsonObject();
    final String projectVersionApiLink = jsonObject.get(JSON_META_LABEL).getAsJsonObject().get(JSON_HREF)
            .getAsString();/*from   w  w  w.  j  a v a2s. c  o  m*/

    return projectVersionApiLink.substring(0, projectVersionApiLink.indexOf(HUB_API_PROJECTS))
            .concat(projectVersionApiLink.substring(projectVersionApiLink.indexOf(HUB_API_VERSIONS)))
            .replace(HUB_API_VERSIONS, HUB_UI_VERSIONS);

}

From source file:com.blackducksoftware.integration.hub.fod.utils.HubFoDJsonParser.java

License:Apache License

public static String getProjectVersionRestURL(final String projectVersionJson) {
    final JsonObject jsonObject = new JsonParser().parse(projectVersionJson).getAsJsonObject();
    return jsonObject.get(JSON_META_LABEL).getAsJsonObject().get(JSON_HREF).getAsString();

}

From source file:com.blackducksoftware.integration.hub.fod.utils.HubFoDJsonParser.java

License:Apache License

public static HashMap<String, String> getVulnerableComponentLicense(final String vulnComponentJson) {
    final HashMap<String, String> licenseMap = new HashMap<>();

    final JsonObject jsonObject = new JsonParser().parse(vulnComponentJson).getAsJsonObject();
    final JsonArray licenseArray = jsonObject.get(JSON_LICENSE).getAsJsonObject().get(JSON_LICENSES)
            .getAsJsonArray();/*  w ww.  ja v  a2s  .c  om*/

    for (final JsonElement license : licenseArray) {
        final JsonObject licenseObj = license.getAsJsonObject();
        licenseMap.put(licenseObj.get(JSON_NAME).getAsString(),
                licenseObj.get(JSON_CODE_SHARING).getAsString());
    }

    return licenseMap;
}

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;
}