Example usage for org.springframework.web.client HttpClientErrorException getStatusText

List of usage examples for org.springframework.web.client HttpClientErrorException getStatusText

Introduction

In this page you can find the example usage for org.springframework.web.client HttpClientErrorException getStatusText.

Prototype

public String getStatusText() 

Source Link

Document

Return the HTTP status text.

Usage

From source file:org.cloudfoundry.caldecott.client.HttpTunnel.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void close() {
    if (logger.isDebugEnabled()) {
        logger.debug("Deleting tunnel " + this.tunnelInfo.get("path"));
    }/* w w w .  j  a v  a 2  s  .co  m*/
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Auth-Token", auth);
    HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
    try {
        restOperations.exchange(url + this.tunnelInfo.get("path"), HttpMethod.DELETE, requestEntity, null);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().value() == 404) {
            if (logger.isDebugEnabled()) {
                logger.debug("Tunnel not found [" + e.getStatusCode() + "] " + e.getStatusText());
            }
        } else {
            logger.warn("Error while deleting tunnel [" + e.getStatusCode() + "] " + e.getStatusText());
        }
    }
}

From source file:org.trustedanalytics.servicebroker.gearpump.service.CloudFoundryService.java

private String deleteUaaClient(String clientId, String token) {
    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION_HEADER, token);
    headers.add(CONTENT_TYPE_HEADER, "application/json");

    try {/*w  w w .ja v a 2  s .  co  m*/
        LOGGER.debug("Deleting UAA client: {}", clientId);
        return executeWithHeaders(DELETE_UAA_CLIENT_URL, HttpMethod.DELETE, "", headers, uaaApiEndpoint,
                clientId).getBody();
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            LOGGER.debug("Cannot delete UAA client: {}. It is not exists.", clientId);
        } else {
            LOGGER.debug("Cannot delete UAA client: {} Error: {}", clientId, e.getStatusText());
            throw e;
        }
    }
    return null;
}

From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java

/**
 * Handles the authorization grant response
 * /* w w  w .  j  ava  2s  . c o  m*/
 * @param authorizationGrant
 *            The Authorization grant code
 * @param request
 *            The request from which to extract parameters and perform the
 *            authentication
 * @return The authenticated user token, or null if authentication is
 *         incomplete.
 * @throws Exception 
 * @throws UnsupportedEncodingException
 */
protected Authentication handleAuthorizationGrantResponse(String authorizationGrant, HttpServletRequest request,
        OIDCServerConfiguration serverConfig) {

    final boolean debug = logger.isDebugEnabled();

    // Handle Token Endpoint interaction
    HttpClient httpClient = new DefaultHttpClient();

    httpClient.getParams().setParameter("http.socket.timeout", new Integer(httpSocketTimeout));

    //
    // TODO: basic auth is untested (it wasn't working last I
    // tested)
    // UsernamePasswordCredentials credentials = new
    // UsernamePasswordCredentials(serverConfig.getClientId(),
    // serverConfig.getClientSecret());
    // ((DefaultHttpClient)
    // httpClient).getCredentialsProvider().setCredentials(AuthScope.ANY,
    // credentials);
    //

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);

    RestTemplate restTemplate = new RestTemplate(factory);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    form.add("grant_type", "authorization_code");
    form.add("code", authorizationGrant);
    form.add("redirect_uri", AbstractOIDCAuthenticationFilter.buildRedirectURI(request, null));

    // pass clientId and clientSecret in post of request
    form.add("client_id", serverConfig.getClientId());
    form.add("client_secret", serverConfig.getClientSecret());

    if (debug) {
        logger.debug("tokenEndpointURI = " + serverConfig.getTokenEndpointURI());
        logger.debug("form = " + form);
    }
    ;
    String jsonString = null;

    try {
        jsonString = restTemplate.postForObject(serverConfig.getTokenEndpointURI(), form, String.class);
    } catch (HttpClientErrorException httpClientErrorException) {

        // Handle error

        logger.error("Token Endpoint error response:  " + httpClientErrorException.getStatusText() + " : "
                + httpClientErrorException.getMessage());

        throw new AuthenticationServiceException("Unable to obtain Access Token.");
    }

    logger.debug("from TokenEndpoint jsonString = " + jsonString);

    JsonElement jsonRoot = new JsonParser().parse(jsonString);

    if (jsonRoot.getAsJsonObject().get("error") != null) {

        // Handle error

        String error = jsonRoot.getAsJsonObject().get("error").getAsString();

        logger.error("Token Endpoint returned: " + error);

        throw new AuthenticationServiceException(
                "Unable to obtain Access Token.  Token Endpoint returned: " + error);

    } else {

        // Extract the id_token to insert into the
        // OpenIdConnectAuthenticationToken

        IdToken idToken = null;
        JwtSigningAndValidationService jwtValidator = getValidatorForServer(serverConfig);

        if (jsonRoot.getAsJsonObject().get("id_token") != null) {

            try {
                idToken = IdToken.parse(jsonRoot.getAsJsonObject().get("id_token").getAsString());

            } catch (AuthenticationServiceException e) {

                // I suspect this could happen

                logger.error("Problem parsing id_token:  " + e);
                // e.printStackTrace();

                throw new AuthenticationServiceException(
                        "Problem parsing id_token return from Token endpoint: " + e);
            }

            if (jwtValidator
                    .validateSignature(jsonRoot.getAsJsonObject().get("id_token").getAsString()) == false) {
                throw new AuthenticationServiceException("Signature not validated");
            }
            if (idToken.getClaims().getIssuer() == null) {
                throw new AuthenticationServiceException("Issuer is null");
            }
            if (!idToken.getClaims().getIssuer().equals(serverConfig.getIssuer())) {
                throw new AuthenticationServiceException("Issuers do not match");
            }
            if (jwtValidator.isJwtExpired(idToken)) {
                throw new AuthenticationServiceException("Id Token is expired");
            }
            if (jwtValidator.validateIssuedAt(idToken) == false) {
                throw new AuthenticationServiceException("Id Token issuedAt failed");
            }

        } else {

            // An error is unlikely, but it good security to check

            logger.error("Token Endpoint did not return an id_token");

            throw new AuthenticationServiceException("Token Endpoint did not return an id_token");
        }

        // Clients are required to compare nonce claim in ID token to 
        // the nonce sent in the Authorization request.  The client 
        // stores this value as a signed session cookie to detect a 
        // replay by third parties.
        //
        // See: OpenID Connect Messages Section 2.1.1 entitled "ID Token"
        //
        // http://openid.net/specs/openid-connect-messages-1_0.html#id_token
        //

        //String nonce = idToken.getClaims().getClaimAsString("nonce");

        String nonce = idToken.getClaims().getNonce();

        if (StringUtils.isBlank(nonce)) {

            logger.error("ID token did not contain a nonce claim.");

            throw new AuthenticationServiceException("ID token did not contain a nonce claim.");
        }

        Cookie nonceSignatureCookie = WebUtils.getCookie(request, NONCE_SIGNATURE_COOKIE_NAME);

        if (nonceSignatureCookie != null) {

            String sigText = nonceSignatureCookie.getValue();

            if (sigText != null && !sigText.isEmpty()) {

                if (!verify(signer, publicKey, nonce, sigText)) {
                    logger.error("Possible replay attack detected! "
                            + "The comparison of the nonce in the returned " + "ID Token to the signed session "
                            + NONCE_SIGNATURE_COOKIE_NAME + " failed.");

                    throw new AuthenticationServiceException("Possible replay attack detected! "
                            + "The comparison of the nonce in the returned " + "ID Token to the signed session "
                            + NONCE_SIGNATURE_COOKIE_NAME + " failed.");
                }
            } else {
                logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty");
                throw new AuthenticationServiceException(
                        NONCE_SIGNATURE_COOKIE_NAME + " cookie was found but value was null or empty");
            }

        } else {

            logger.error(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found.");

            throw new AuthenticationServiceException(NONCE_SIGNATURE_COOKIE_NAME + " cookie was not found.");
        }

        // pull the user_id out as a claim on the id_token

        String userId = idToken.getTokenClaims().getUserId();

        // construct an OpenIdConnectAuthenticationToken and return 
        // a Authentication object w/the userId and the idToken

        OpenIdConnectAuthenticationToken token = new OpenIdConnectAuthenticationToken(userId, idToken);

        Authentication authentication = this.getAuthenticationManager().authenticate(token);

        return authentication;

    }
}

From source file:com.daon.identityx.controller.SimpleController.java

/**
 * The a web method throws an exception with a http status, then we controller will pass this detail
 * back to the client.// w w  w. ja v a2 s . co m
 * 
 * @param ex
 * @return
 */
@ExceptionHandler(HttpClientErrorException.class)
@ResponseBody
public Error handleHttpExceptions(HttpClientErrorException ex, HttpServletResponse response) {
    logger.error("An unexpected exception occurred while attempting to process the request. Exception: "
            + ex.getMessage());
    response.setStatus(ex.getStatusCode().value());
    return new Error(ex.getStatusCode().value(), ex.getStatusText());
}

From source file:org.springframework.data.keyvalue.riak.client.RiakRestClient.java

private <T> ResponseEntity<T> execute(String path, HttpMethod method, Object value, RiakParameter[] parameters,
        Class<T> clazz, String... pathParams) throws RiakException {
    try {//  w w  w .  j a v a 2 s  .  c  o  m
        if (value == null)
            return restTemplate.exchange(getUrl(path, parameters, pathParams), method,
                    new HttpEntity<Object>(getHeadersMap(parameters)), clazz);
        else
            return restTemplate.exchange(getUrl(path, parameters, pathParams), method,
                    new HttpEntity<Object>(value, getHeadersMap(parameters)), clazz);
    } catch (RestClientException e) {
        if (e instanceof HttpClientErrorException) {
            // 400 error
            HttpClientErrorException ex = (HttpClientErrorException) e;
            if (ex.getStatusCode().equals(HttpStatus.NOT_FOUND))
                throw new RiakObjectNotFoundException(HttpStatus.NOT_FOUND.toString());

            throw new RiakUncategorizedClientErrorException(ex.getStatusText());
        } else if (e instanceof HttpServerErrorException) {
            // 500 error
            HttpServerErrorException ex = (HttpServerErrorException) e;
            throw new RiakServerErrorException(ex.getStatusText());
        }

        throw new RiakUncategorizedException("Uncategorized exception thrown", e);
    }
}

From source file:org.springframework.web.client.RestTemplateIntegrationTests.java

@Test
public void notFound() {
    try {//from  w  w  w .  j ava  2s  .c om
        template.execute(baseUrl + "/status/notfound", HttpMethod.GET, null, null);
        fail("HttpClientErrorException expected");
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
        assertNotNull(ex.getStatusText());
        assertNotNull(ex.getResponseBodyAsString());
    }
}