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

The following examples show how to use kong.unirest.HttpResponse#isSuccess() . 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: 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 3
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 4
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 5
Source File: AbstractRestDao.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 5 votes vote down vote up
protected void deleteObject(String url) throws UnirestException {
    HttpResponse res = Unirest.delete(url)
        .asEmpty();
    if (!res.isSuccess()) {
        throw new UnirestException(res.getStatusText());
    }
}
 
Example 6
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 7
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 8
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 9
Source File: DefaultTranslator.java    From pom-manipulation-ext with Apache License 2.0 4 votes vote down vote up
@Override
public List<ProjectVersionRef> findBlacklisted( ProjectRef ga ) throws RestException
{
    final String blacklistEndpointUrl = endpointUrl + LISTING_BLACKLIST_GA;
    final AtomicReference<List<ProjectVersionRef>> result = new AtomicReference<>();
    final String[] errorString = new String[1];
    final HttpResponse<List<ProjectVersionRef>> r;

    logger.debug( "Called findBlacklisted to {} with {} and custom headers {}", blacklistEndpointUrl, ga, restHeaders );

    try
    {
        r = Unirest.get( blacklistEndpointUrl )
                   .header( "accept", "application/json" )
                   .header( "Content-Type", "application/json" )
                   .headers( restHeaders )
                   .connectTimeout(restConnectionTimeout * 1000)
                   .socketTimeout(restSocketTimeout * 1000)
                   .queryString( "groupid", ga.getGroupId() )
                   .queryString( "artifactid", ga.getArtifactId() )
                   .asObject( pvrTyoe )
                   .ifSuccess( successResponse -> result.set( successResponse.getBody() ) )
                   .ifFailure( failedResponse -> {
                       if ( !failedResponse.getParsingError().isPresent() )
                       {
                           logger.debug( "Parsing error but no message. Status text {}", failedResponse.getStatusText() );
                           throw new ManipulationUncheckedException( failedResponse.getStatusText() );
                       }
                       else
                       {
                           String originalBody = failedResponse.getParsingError().get().getOriginalBody();

                           if ( originalBody.length() == 0 )
                           {
                               errorString[0] = "No content to read.";
                           }
                           else if ( originalBody.startsWith( "<" ) )
                           {
                               // Read an HTML string.
                               String stripped = originalBody.replaceAll( "<.*?>", "" ).replaceAll( "\n", " " ).trim();
                               logger.debug( "Read HTML string '{}' rather than a JSON stream; stripping message to '{}'",
                                             originalBody, stripped );
                               errorString[0] = stripped;
                           }
                           else if ( originalBody.startsWith( "{\"" ) )
                           {
                               errorString[0] = failedResponse.mapError( ErrorMessage.class ).toString();

                               logger.debug( "Read message string {}, processed to {} ", originalBody, errorString );
                           }
                           else
                           {
                               throw new ManipulationUncheckedException( "Problem in HTTP communication with status code {} and message {}",
                                                                         failedResponse.getStatus(), failedResponse.getStatusText() );
                           }
                       }
                   } );

        if ( !r.isSuccess() )
        {
            throw new RestException( "Failed to establish blacklist calling {} with error {}", endpointUrl, errorString[0] );
        }
    }
    catch ( ManipulationUncheckedException | UnirestException e )
    {
        throw new RestException( "Unable to contact DA", e );
    }

    return result.get();
}