Java Code Examples for kong.unirest.HttpResponse#getStatus()

The following examples show how to use kong.unirest.HttpResponse#getStatus() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientAuthenticator.java    From minecraft-world-downloader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Make the authentication request to the Mojang session server. We need to do this as the one sent by the
 * real client will have had our 'fake' public key instead of the server's real one, and as such the server will
 * not accept the connection.
 * @param hash hash based on the server information.
 */
public void makeRequest(String hash) throws UnirestException {
    AuthDetails details = profiles.getAuthDetails();

    Map<String, String> body = new HashMap<>();
    body.put("accessToken", details.getAccessToken());
    body.put("selectedProfile", details.getUuid());
    body.put("serverId", hash);


    HttpResponse<String> str = Unirest.post(AUTH_URL)
        .header("Content-Type", "application/json")
        .body(new Gson().toJson(body))
        .asString();

    if (str.getStatus() != STATUS_SUCCESS) {
        throw new RuntimeException("Client not authenticated! " + str.getBody());
    } else {
        System.out.println("Successfully authenticated user with Mojang session server.");
    }
}
 
Example 2
Source File: GemMetaAnalyzer.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MetaModel analyze(final Component component) {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final MetaModel meta = new MetaModel(component);
    if (component.getPurl() != null) {
        final String url = String.format(baseUrl + API_URL, component.getPurl().getName());
        try {
            final HttpResponse<JsonNode> response = ui.get(url)
                    .header("accept", "application/json")
                    .asJson();
            if (response.getStatus() == 200) {
                if (response.getBody() != null && response.getBody().getObject() != null) {
                    final String latest = response.getBody().getObject().getString("version");
                    meta.setLatestVersion(latest);
                }
            } else {
                handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
            }
        } catch (UnirestException e) {
            handleRequestException(LOGGER, e);
        }
    }
    return meta;
}
 
Example 3
Source File: NugetMetaAnalyzer.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
private boolean performVersionCheck(final MetaModel meta, final Component component) {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final String url = String.format(baseUrl + VERSION_QUERY_URL, component.getPurl().getName().toLowerCase());
    try {
        final HttpResponse<JsonNode> response = ui.get(url)
                .header("accept", "application/json")
                .asJson();
        if (response.getStatus() == 200) {
            if (response.getBody() != null && response.getBody().getObject() != null) {
                final JSONArray versions = response.getBody().getObject().getJSONArray("versions");
                final String latest = versions.getString(versions.length()-1); // get the last version in the array
                meta.setLatestVersion(latest);
            }
            return true;
        } else {
            handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
        }
    } catch (UnirestException e) {
        handleRequestException(LOGGER, e);
    }
    return false;
}
 
Example 4
Source File: NpmAuditAnalysisTask.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
/**
 * Submits the payload to the NPM service
 */
private List<Advisory> submit(final JSONObject payload) throws UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> jsonResponse = ui.post(API_BASE_URL)
            .header("user-agent", "npm/6.1.0 node/v10.5.0 linux x64")
            .header("npm-in-ci", "false")
            .header("npm-scope", "")
            .header("npm-session", generateRandomSession())
            .header("content-type", "application/json")
            .body(payload)
            .asJson();
    if (jsonResponse.getStatus() == 200) {
        final NpmAuditParser parser = new NpmAuditParser();
        return parser.parse(jsonResponse.getBody());
    } else {
        handleUnexpectedHttpResponse(LOGGER, API_BASE_URL, jsonResponse.getStatus(), jsonResponse.getStatusText());
    }
    return new ArrayList<>();
}
 
Example 5
Source File: OssIndexAnalysisTask.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
/**
 * Submits the payload to the Sonatype OSS Index service
 */
private List<ComponentReport> submit(final JSONObject payload) throws UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> jsonResponse = ui.post(API_BASE_URL)
            .header(HttpHeaders.ACCEPT, "application/json")
            .header(HttpHeaders.CONTENT_TYPE, "application/json")
            .header(HttpHeaders.USER_AGENT, ManagedHttpClientFactory.getUserAgent())
            .basicAuth(apiUsername, apiToken)
            .body(payload)
            .asJson();
    if (jsonResponse.getStatus() == 200) {
        final OssIndexParser parser = new OssIndexParser();
        return parser.parse(jsonResponse.getBody());
    } else {
        handleUnexpectedHttpResponse(LOGGER, API_BASE_URL, jsonResponse.getStatus(), jsonResponse.getStatusText());
    }
    return new ArrayList<>();
}
 
Example 6
Source File: FortifySscClient.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
public String generateOneTimeUploadToken(final String username, final String password) {
    LOGGER.debug("Generating one-time upload token");
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final JSONObject payload = new JSONObject().put("fileTokenType", "UPLOAD");
    final HttpRequestWithBody request = ui.post(baseURL + "/api/v1/fileTokens");
    final HttpResponse<JsonNode> response = request
            .header("Content-Type", "application/json")
            .basicAuth(username, password)
            .body(payload)
            .asJson();
    if (response.getStatus() == 201) {
        if (response.getBody() != null) {
            final JSONObject root = response.getBody().getObject();
            LOGGER.debug("One-time upload token retrieved");
            return root.getJSONObject("data").getString("token");
        }
    } else {
        LOGGER.warn("Fortify SSC Client did not receive expected response while attempting to generate a "
                + "one-time-use fileupload token. HTTP response code: "
                + response.getStatus() + " - " + response.getStatusText());
        uploader.handleUnexpectedHttpResponse(LOGGER, request.getUrl(), response.getStatus(), response.getStatusText());
    }
    return null;
}
 
Example 7
Source File: FortifySscClient.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
public void uploadDependencyTrackFindings(final String token, final String applicationVersion, final InputStream findingsJson) {
    LOGGER.debug("Uploading Dependency-Track findings to Fortify SSC");
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HashMap<String, Object> params = new HashMap<>();
    params.put("engineType", "DEPENDENCY_TRACK");
    params.put("mat", token);
    params.put("entityId", applicationVersion);
    final HttpRequestWithBody request = ui.post(baseURL + "/upload/resultFileUpload.html");
    final HttpResponse<String> response = request
            .header("accept", "application/xml")
            .queryString(params)
            .field("files[]", findingsJson, "findings.json")
            .asString();
    if (response.getStatus() == 200) {
        LOGGER.debug("Successfully uploaded findings to Fortify SSC");
    } else {
        LOGGER.warn("Fortify SSC Client did not receive expected response while attempting to upload "
                + "Dependency-Track findings. HTTP response code: "
                + response.getStatus() + " - " + response.getStatusText());
        uploader.handleUnexpectedHttpResponse(LOGGER, request.getUrl(), response.getStatus(), response.getStatusText());
    }
}
 
Example 8
Source File: ApiClient.java    From dependency-track with Apache License 2.0 6 votes vote down vote up
public UUID createProject(String name, String version) throws UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> response = ui.put(baseUrl + "/api/v1/project")
            .header("Content-Type", "application/json")
            .header("X-API-Key", apiKey)
            .body(new JSONObject()
                    .put("name", name)
                    .put("version", version)
            )
            .asJson();
    if (response.getStatus() == 201) {
        return UUID.fromString(response.getBody().getObject().getString("uuid"));
    }
    System.out.println("Error creating project " + name + " status: " + response.getStatus());
    return null;
}
 
Example 9
Source File: ServerAuthenticator.java    From minecraft-world-downloader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Verify the user that is connecting to us is actually the user who we just authenticated with Mojang, otherwise
 * we could be giving a malicious user access to our account on the server we are proxying. The user would
 * also have to supply a username matching ours so it should never be accidentally attempted.
 * @param hash hash based on the server information.
 */
public void makeRequest(String hash) throws UnirestException {
    HttpResponse<JsonNode> str = Unirest.get(AUTH_URL)
        .queryString("username", username)
        .queryString("serverId", hash)
        .asJson();

    if (str.getStatus() != 200) {
        System.out.println("WARNING: Connection attempt by using pretending to be you! Closing connection.");
        throw new RuntimeException("Server could not authenticate client! " + str.getBody());
    } else {
        System.out.println("User identity confirmed with Mojang.");
    }
}
 
Example 10
Source File: UnirestService.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse executeRequest(String url) {
    HttpResponse<String> response = Unirest.get(url)
            .header(HEADER_KEY_CLIENT_TYPE, getClientType().getValue())
            .asString();

    return new ClientResponse(response.getBody(), response.getStatus());
}
 
Example 11
Source File: NpmMetaAnalyzer.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MetaModel analyze(final Component component) {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final MetaModel meta = new MetaModel(component);
    if (component.getPurl() != null) {

        final String packageName;
        if (component.getPurl().getNamespace() != null) {
            packageName = component.getPurl().getNamespace().replace("@", "%40") + "%2F" + component.getPurl().getName();
        } else {
            packageName = component.getPurl().getName();
        }

        final String url = String.format(baseUrl + API_URL, packageName);
        try {
            final HttpResponse<JsonNode> response = ui.get(url)
                    .header("accept", "application/json")
                    .asJson();
            if (response.getStatus() == 200) {
                if (response.getBody() != null && response.getBody().getObject() != null) {
                    final String latest = response.getBody().getObject().getString("latest");
                    meta.setLatestVersion(latest);
                }
            } else {
                handleUnexpectedHttpResponse(LOGGER, url, response.getStatus(), response.getStatusText(), component);
            }
        } catch (UnirestException e) {
            handleRequestException(LOGGER, e);
        }
    }
    return meta;
}
 
Example 12
Source File: KennaSecurityUploader.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
@Override
public void upload(final InputStream payload) {
    LOGGER.debug("Uploading payload to KennaSecurity");
    final ConfigProperty tokenProperty = qm.getConfigProperty(KENNA_TOKEN.getGroupName(), KENNA_TOKEN.getPropertyName());
    try {
        final UnirestInstance ui = UnirestFactory.getUnirestInstance();
        final String token = DataEncryption.decryptAsString(tokenProperty.getPropertyValue());
        final HttpRequestWithBody request = ui.post(String.format(CONNECTOR_UPLOAD_URL, connectorId));
        final HttpResponse<JsonNode> response = request
                .header("X-Risk-Token", token)
                .header("accept", "application/json")
                .field("file", payload, ContentType.APPLICATION_JSON, "findings.json")
                .field("run", "true")
                .asJson();
        if (response.getStatus() == 200 && response.getBody() != null) {
            final JSONObject root = response.getBody().getObject();
            if (root.getString("success").equals("true")) {
                LOGGER.debug("Successfully uploaded KDI");
                return;
            }
            LOGGER.warn("An unexpected response was received uploading findings to Kenna Security");
        } else {
            LOGGER.warn("Kenna uploader did not receive expected response while attempting to upload "
                    + "Dependency-Track findings. HTTP response code: "
                    + response.getStatus() + " - " + response.getStatusText());
            handleUnexpectedHttpResponse(LOGGER, request.getUrl(), response.getStatus(), response.getStatusText());
        }
    } catch (Exception e) {
        LOGGER.error("An error occurred attempting to upload findings to Kenna Security", e);
    }
}
 
Example 13
Source File: AbstractWebhookPublisher.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
public void publish(final String publisherName, final PebbleTemplate template, final Notification notification, final JsonObject config) {
    final Logger logger = Logger.getLogger(this.getClass());
    logger.debug("Preparing to publish notification");
    if (config == null) {
        logger.warn("No configuration found. Skipping notification.");
        return;
    }
    final String destination = config.getString("destination");
    final String content = prepareTemplate(notification, template);
    if (destination == null || content == null) {
        logger.warn("A destination or template was not found. Skipping notification");
        return;
    }

    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> response = ui.post(destination)
            .header("content-type", "application/json")
            .header("accept", "application/json")
            .body(content)
            .asJson();

    if (response.getStatus() < 200 || response.getStatus() > 299) {
        logger.error("An error was encountered publishing notification to " + publisherName);
        logger.error("HTTP Status : " + response.getStatus() + " " + response.getStatusText());
        logger.error("Destination: " + destination);
        logger.debug(content);
    }
}
 
Example 14
Source File: ApiClient.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
public boolean uploadBom(UUID uuid, File bom) throws IOException, UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> response = ui.put(baseUrl + "/api/v1/bom")
            .header("Content-Type", "application/json")
            .header("X-API-Key", apiKey)
            .body(new JSONObject()
                    .put("project", uuid.toString())
                    .put("bom", Base64.encode(FileUtils.readFileToByteArray(bom)))
            )
            .asJson();
    return (response.getStatus() == 200);
}
 
Example 15
Source File: ApiClient.java    From dependency-track with Apache License 2.0 5 votes vote down vote up
public boolean uploadScan(UUID uuid, File scan) throws IOException, UnirestException {
    final UnirestInstance ui = UnirestFactory.getUnirestInstance();
    final HttpResponse<JsonNode> response = ui.put(baseUrl + "/api/v1/scan")
            .header("Content-Type", "application/json")
            .header("X-API-Key", apiKey)
            .body(new JSONObject()
                    .put("project", uuid.toString())
                    .put("scan", Base64.encode(FileUtils.readFileToByteArray(scan)))
            )
            .asJson();
    return (response.getStatus() == 200);
}
 
Example 16
Source File: NpmAdvisoryMirrorTask.java    From dependency-track with Apache License 2.0 4 votes vote down vote up
/**
 * Performs an incremental mirror (using pagination) of the NPM public advisory database.
 */
private void getAdvisories() {
    final Date currentDate = new Date();
    LOGGER.info("Retrieving NPM advisories at " + currentDate);

    try {
        final UnirestInstance ui = UnirestFactory.getUnirestInstance();

        boolean more = true;

        String url = NPM_BASE_URL + NPM_ADVISORY_START;
        while (more) {
            LOGGER.info("Retrieving NPM advisories from " + url);
            final HttpResponse<JsonNode> jsonResponse = ui.get(url)
                    .header("accept", "application/json")
                    .asJson();

            if (jsonResponse.getStatus() == 200) {
                final NpmAdvisoriesParser parser = new NpmAdvisoriesParser();
                final AdvisoryResults results = parser.parse(jsonResponse.getBody());
                updateDatasource(results);
                more = results.getNext() != null;
                // Workaround for breaking changes made to NPM Advisories API documented in:
                // https://github.com/DependencyTrack/dependency-track/issues/676
                if (more) {
                    final String queryString = results.getNext().substring(results.getNext().indexOf("?"));
                    url = NPM_BASE_URL + NPM_ADVISORY_START + queryString;
                }
                //url = NPM_BASE_URL + results.getNext(); // No longer works
            } else {
                final String error = "An unexpected response received from NPM while performing mirror. Response: "
                        + jsonResponse.getStatus() + " " + jsonResponse.getStatusText() + " - Aborting";
                LOGGER.warn(error);
                Notification.dispatch(new Notification()
                        .scope(NotificationScope.SYSTEM)
                        .group(NotificationGroup.DATASOURCE_MIRRORING)
                        .title(NotificationConstants.Title.NPM_ADVISORY_MIRROR)
                        .content(error)
                        .level(NotificationLevel.ERROR)
                );
                return;
            }
        }
    } catch (UnirestException e) {
        LOGGER.error("An error occurred while retrieving NPM advisory", e);
        successful = false;
        Notification.dispatch(new Notification()
                .scope(NotificationScope.SYSTEM)
                .group(NotificationGroup.DATASOURCE_MIRRORING)
                .title(NotificationConstants.Title.NPM_ADVISORY_MIRROR)
                .content("An error occurred while retrieving NPM advisory. Check log for details. " + e.getMessage())
                .level(NotificationLevel.ERROR)
        );
    }
}