kong.unirest.HttpResponse Java Examples

The following examples show how to use kong.unirest.HttpResponse. 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: RetestAuthentication.java    From recheck with GNU Affero General Public License v3.0 7 votes vote down vote up
private Optional<DecodedJWT> refreshAccessToken() {
	final HttpResponse<JsonNode> response = Unirest.post( TOKEN_URL ) //
			.field( OAUTH_GRANT_TYPE, OAUTH_REFRESH_TOKEN ) //
			.field( OAUTH_REFRESH_TOKEN, handler.getOfflineToken() ) //
			.field( OAUTH_CLIENT_ID, client ) //
			.asJson();

	if ( response.isSuccess() ) {
		final JSONObject object = response.getBody().getObject();
		try {
			return Optional.of( verifier.verify( object.getString( OAUTH_ACCESS_TOKEN ) ) );
		} catch ( final Exception e ) {
			log.error( "Error verifying access token: {}", e.getMessage() );
			log.debug( "Details: ", e );
		}
	}
	log.error( "Error retrieving access token: {}", response.getStatusText() );
	return Optional.empty();
}
 
Example #2
Source File: PinataPinningService.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getTracked() {
    log.debug("get pinned files on Pinata");

    try {
        log.trace("GET {}/data/pinList?status=pinned&pageLimit=1000", endpoint);
        HttpResponse<String> response = Unirest.get(endpoint + "/data/pinList?status=pinned&pageLimit=1000")
                .header(HEADER_API_KEY, apiKey)
                .header(HEADER_SECRET_API_KEY, secretApiKey)
                .asString()
                .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.trace("response: {}", response.getBody());

        PinataTrackedResponse result = mapper.readValue(response.getBody(), PinataTrackedResponse.class);
        
        log.debug("get pinned files on Pinata [count: {}]", result.getCount());
        return result.getRows()
                .stream()
                .map(r -> r.getHash())
                .collect(Collectors.toList());

    } catch (UnirestException | IOException ex) {
        log.error("Exception whilst requesting the tracked data", ex);
        throw new TechnicalException("Exception whilst requesting the tracked data", ex);
    }
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: RetestAuthentication.java    From recheck with GNU Affero General Public License v3.0 6 votes vote down vote up
private TokenBundle accessCodeToToken( final String code, final String redirectUri ) {
	final TokenBundle bundle = new TokenBundle();

	final HttpResponse<JsonNode> response = Unirest.post( TOKEN_URL ) //
			.field( OAUTH_GRANT_TYPE, OAUTH_GRANT_TYPE_AUTHORIZATION_CODE ) //
			.field( OAUTH_RESPONSE_TYPE_CODE, code ) //
			.field( OAUTH_CLIENT_ID, client ) //
			.field( OAUTH_REDIRECT_URI, redirectUri ) //
			.asJson();

	if ( response.isSuccess() ) {
		final JSONObject object = response.getBody().getObject();
		bundle.setAccessToken( object.getString( OAUTH_ACCESS_TOKEN ) );
		bundle.setRefreshToken( object.getString( OAUTH_REFRESH_TOKEN ) );
	}

	return bundle;
}
 
Example #11
Source File: RetestAuthentication.java    From recheck with GNU Affero General Public License v3.0 6 votes vote down vote up
public void logout() {
	final String offlineToken = handler.getOfflineToken();
	if ( offlineToken != null ) {
		final HttpResponse<JsonNode> response = Unirest.post( LOGOUT_URL ) //
				.field( OAUTH_REFRESH_TOKEN, handler.getOfflineToken() ) //
				.field( OAUTH_CLIENT_ID, client ) //
				.asJson();

		if ( response.isSuccess() ) {
			handler.logoutPerformed();
		} else {
			handler.logoutFailed( new RuntimeException( response.getStatusText() ) );
		}

	} else {
		log.error( "No offline token provided" );
	}
}
 
Example #12
Source File: IPFSClusterPinningService.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
public static IPFSClusterPinningService connect(String host, Integer port, String protocol) {
    ValidatorUtils.rejectIfEmpty("host", host);
    ValidatorUtils.rejectIfNegative("port", port);
    ValidatorUtils.rejectIfDifferentThan("protocol", protocol, "http", "https");

    try {
        log.trace("call GET {}://{}:{}/id", protocol, host, port);
        HttpResponse<String> response = Unirest.get(String.format(BASE_URI + "/id", protocol, host, port))
                .asString()
                .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.info("Connected to IPFS-Cluster [protocol: {}, host: {}, port: {}]: Info {}", protocol, host, port,
                response.getBody());

        return new IPFSClusterPinningService(host, port, protocol);

    } catch (UnirestException ex) {
        String msg = String.format("Error whilst connecting to IPFS-Cluster [host: %s, port: %s]", host, port);
        log.error(msg, ex);
        throw new ConnectionException(msg, ex);
    }
}
 
Example #13
Source File: IPFSClusterPinningService.java    From Mahuta with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getTracked() {
    log.debug("get pinned files on IPFS-cluster");

    try {
        log.trace("GET {}://{}:{}/pins", protocol, host, port);
        HttpResponse<String> response = Unirest.get(String.format(BASE_URI + "/pins", protocol, host, port))
                .asString()
                .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.debug("response: {}", response);
        IPFSClusterTrackedResponse result = mapper.readValue(response.getBody(), IPFSClusterTrackedResponse.class);

        log.debug("get pinned files on IPFS-cluster");
        return result.getPins();

    } catch (UnirestException | IOException ex) {
        log.error("Exception converting HTTP response to JSON", ex);
        throw new TechnicalException("Exception converting HTTP response to JSON", ex);
    }
}
 
Example #14
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 #15
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 #16
Source File: PinataPinningService.java    From Mahuta with Apache License 2.0 5 votes vote down vote up
@Override
public void unpin(String cid) {
    log.debug("unpin CID {} on Pinata", cid);

    try {
        ValidatorUtils.rejectIfEmpty("cid", cid);
        
        PinataUnpinRequest request = new PinataUnpinRequest(cid);
        log.trace("call POST {}/pinning/removePinFromIPFS {}", endpoint, mapper.writeValueAsString(request));
        
        HttpResponse<String> response = Unirest.post(endpoint + "/pinning/removePinFromIPFS")
            .header(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_VAL)
            .header(HEADER_API_KEY, apiKey)
            .header(HEADER_SECRET_API_KEY, secretApiKey)
            .body(mapper.writeValueAsString(request))
            .asString()
            .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.trace("response: {}", response.getBody());
        
        log.debug("CID {} unpinned on Pinata", cid);
        
    } catch (UnirestException | JsonProcessingException ex) {
        String msg = String.format("Error whilst sending request to Pinata [endpoint: %s/pinning/removePinFromIPFS, cid: %s]", endpoint, cid);
        log.error(msg, ex);
        throw new TechnicalException(msg, ex);
    }
}
 
Example #17
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 #18
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 #19
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 #20
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 #21
Source File: UnirestSample.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post")
            .header("accept", "application/json")
            .queryString("apiKey", "123")
            .field("parameter", "value")
            .field("firstname", "Gary")
            .asJson();
    System.out.println(response.getBody());
    System.out.println(response.isSuccess());
    System.out.println(response.getBody().getObject().get("args"));

    // JsonNode getObject return JSONObject
    // PS : JSONObject IS NOT JSONObject in FastJson
}
 
Example #22
Source File: AbstractRestDao.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
protected Stream<JSONObject> getArray(String url) throws UnirestException {
    HttpResponse<JsonNode> res = Unirest.get(url)
        .asJson();
    if (!res.isSuccess()) {
        throw new UnirestException(res.getStatusText());
    }
    JSONArray array = res
        .getBody()
        .getArray();
    return stream(array.spliterator(), false)
        .map(JSONObject.class::cast);
}
 
Example #23
Source File: PinataPinningService.java    From Mahuta with Apache License 2.0 5 votes vote down vote up
@Override
public void pin(String cid, String name, Map<String, Object> metadata) {
    log.debug("pin CID {} on Pinata [name: {}, metadata: {}]", cid, name, metadata);

    try {
        ValidatorUtils.rejectIfEmpty("cid", cid);
        
        // Transform metadata
        Map<String, String> keyvalues = Optional.ofNullable(metadata).orElseGet(() -> new HashMap<String, Object>())
                .entrySet()
                .stream()
                .limit(MAX_METADATA)
                .collect (Collectors.toMap(Entry::getKey, e->e.getValue().toString()));
        
        PinataPinRequest request = new PinataPinRequest(cid, addresses, 
                new PinataMetadata(name, keyvalues));
        log.trace("call POST {}/pinning/pinHashToIPFS {}", endpoint, mapper.writeValueAsString(request));
        
        HttpResponse<String> response = Unirest.post(endpoint + "/pinning/pinHashToIPFS")
            .header(HEADER_CONTENT_TYPE, HEADER_CONTENT_TYPE_VAL)
            .header(HEADER_API_KEY, apiKey)
            .header(HEADER_SECRET_API_KEY, secretApiKey)
            .body(mapper.writeValueAsString(request))
            .asString()
            .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.trace("response: {}", response.getBody());
        
        log.debug("CID {} pinned on Pinata", cid);
        
    } catch (UnirestException | JsonProcessingException ex) {
        String msg = String.format("Error whilst sending request to Pinata [endpoint: %s/pinning/pinHashToIPFS, cid: %s]", endpoint, cid);
        log.error(msg, ex);
        throw new TechnicalException(msg, ex);
    }
}
 
Example #24
Source File: PinataPinningService.java    From Mahuta with Apache License 2.0 5 votes vote down vote up
public static PinataPinningService connect(String endpoint, String apiKey, String secretApiKey, List<String> addresses) {
    ValidatorUtils.rejectIfEmpty("endpoint", endpoint);
    ValidatorUtils.rejectIfEmpty("apiKey", apiKey);
    ValidatorUtils.rejectIfEmpty("secretApiKey", secretApiKey);
    
    if(addresses != null)
        addresses.forEach(MultiAddress::new); // Validate multiAddress

    try {
        log.trace("call GET {}/data/testAuthentication", endpoint);
        HttpResponse<String> response = Unirest.get(endpoint + "/data/testAuthentication")
                .header(HEADER_API_KEY, apiKey)
                .header(HEADER_SECRET_API_KEY, secretApiKey)
                .asString()
                .ifFailure(r -> { throw new UnirestException(r.getStatus() + " - " + r.getBody()); });
        log.info("Connected to Pinata [endpoint: {}, apiKey: {}, secretApiKey: {}, addresses: {}]: Info {}",
                endpoint, apiKey, obfuscateKey(secretApiKey), addresses,
                response.getBody());

        return new PinataPinningService(endpoint, apiKey, secretApiKey, addresses);

    } catch (UnirestException ex) {
        String msg = String.format("Error whilst connecting to Pinata  [endpoint: %s, apiKey: %s, secretApiKey: %s, addresses: %s]",
                endpoint, apiKey, obfuscateKey(secretApiKey), addresses);
        log.error(msg, ex);
        throw new ConnectionException(msg, ex);
    }
}
 
Example #25
Source File: CloudPersistence.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
private HttpResponse<String> getUploadUrl() {
	final String token = String.format( "Bearer %s", Rehub.getAccessToken() );

	return Unirest.post( SERVICE_ENDPOINT ) //
			.header( "Authorization", token )//
			.asString();
}
 
Example #26
Source File: CloudPersistence.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
private void uploadReport( final ReportUploadContainer metadata ) {
	final long start = System.currentTimeMillis();
	final HttpResponse<?> uploadResponse = Unirest.put( metadata.getUploadUrl() ) //
			.header( "x-amz-meta-report-name", abbreviate( metadata.getReportName(), MAX_REPORT_NAME_LENGTH ) ) //
			.body( metadata.getData() ) //
			.asEmpty();

	if ( uploadResponse.isSuccess() ) {
		final long duration = System.currentTimeMillis() - start;
		log.info( "Successfully uploaded report to rehub in {} ms", duration );
	}
}
 
Example #27
Source File: CloudPersistence.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
private void saveToCloud( final TestReport report, final byte[] data ) {
	final HttpResponse<String> uploadUrlResponse = getUploadUrl();
	if ( uploadUrlResponse.isSuccess() ) {
		final ReportUploadContainer metadata = ReportUploadContainer.builder() //
				.reportName( String.join( ", ", getTestClasses( report ) ) ) //
				.data( data ) //
				.uploadUrl( uploadUrlResponse.getBody() ) //
				.build();
		final boolean hasChanges = report.containsChanges();

		final int maxAttempts = RecheckProperties.getInstance().rehubReportUploadAttempts();
		for ( int remainingAttempts = maxAttempts - 1; remainingAttempts >= 0; remainingAttempts-- ) {
			try {
				uploadReport( metadata );
				break; // Successful, abort retry
			} catch ( final UnirestException e ) {
				if ( !hasChanges ) {
					log.warn(
							"Failed to upload report. Ignoring exception because the report does not have any differences.",
							e );
					break;
				}
				if ( remainingAttempts == 0 ) {
					log.error(
							"Failed to upload report. Aborting, because maximum retries have been reached. If this happens often, consider increasing the property '{}={}'.",
							RecheckProperties.REHUB_REPORT_UPLOAD_ATTEMPTS, maxAttempts, e );
					throw e;
				} else {
					log.warn( "Failed to upload report. Retrying another {} times.", remainingAttempts, e );
				}
			}
		}
	}
}
 
Example #28
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 #29
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 #30
Source File: RegistryLoader.java    From minecraft-world-downloader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Download the correct server.jar for this version.
 * @param url the url, cannot really be guessed so these are read in from a file.
 */
private void downloadServerJar(String url) throws IOException {
    System.out.println("Downloading this version's server.jar (" + url + ")");
    HttpResponse<byte[]> status = Unirest.get(url)
        .asBytes();

    ensureExists(Paths.get(CACHE));
    Files.write(SERVER_PATH, status.getBody());
}