Search in sources :

Example 11 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project zeppelin by apache.

the class BaseLivyInterprereter method callRestAPI.

private String callRestAPI(String targetURL, String method, String jsonData) throws LivyException {
    targetURL = livyURL + targetURL;
    LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData);
    RestTemplate restTemplate = getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.add("X-Requested-By", "zeppelin");
    ResponseEntity<String> response = null;
    try {
        if (method.equals("POST")) {
            HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
            response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class);
        } else if (method.equals("GET")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class);
        } else if (method.equals("DELETE")) {
            HttpEntity<String> entity = new HttpEntity<>(headers);
            response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class);
        }
    } catch (HttpClientErrorException e) {
        response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode());
        LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), e.getResponseBodyAsString()));
    } catch (RestClientException e) {
        // Exception happens when kerberos is enabled.
        if (e.getCause() instanceof HttpClientErrorException) {
            HttpClientErrorException cause = (HttpClientErrorException) e.getCause();
            if (cause.getResponseBodyAsString().matches(SESSION_NOT_FOUND_PATTERN)) {
                throw new SessionNotFoundException(cause.getResponseBodyAsString());
            }
        }
        throw new LivyException(e);
    }
    if (response == null) {
        throw new LivyException("No http response returned");
    }
    LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(), response.getBody());
    if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201) {
        return response.getBody();
    } else if (response.getStatusCode().value() == 404) {
        if (response.getBody().matches(SESSION_NOT_FOUND_PATTERN)) {
            throw new SessionNotFoundException(response.getBody());
        } else {
            throw new APINotFoundException("No rest api found for " + targetURL + ", " + response.getStatusCode());
        }
    } else {
        String responseString = response.getBody();
        if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) {
            return responseString;
        }
        throw new LivyException(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HttpEntity(org.springframework.http.HttpEntity) ResponseEntity(org.springframework.http.ResponseEntity) KerberosRestTemplate(org.springframework.security.kerberos.client.KerberosRestTemplate) RestTemplate(org.springframework.web.client.RestTemplate) RestClientException(org.springframework.web.client.RestClientException)

Example 12 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project spring-framework by spring-projects.

the class SimpleUrlHandlerMappingIntegrationTests method testHandlerNotFound.

@Test
public void testHandlerNotFound() throws Exception {
    URI url = new URI("http://localhost:" + this.port + "/oops");
    RequestEntity<Void> request = RequestEntity.get(url).build();
    try {
        new RestTemplate().exchange(request, byte[].class);
    } catch (HttpClientErrorException ex) {
        assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) RestTemplate(org.springframework.web.client.RestTemplate) URI(java.net.URI) Test(org.junit.Test)

Example 13 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project spring-boot by spring-projects.

the class CloudFoundrySecurityService method getAccessLevel.

/**
	 * Return the access level that should be granted to the given token.
	 * @param token the token
	 * @param applicationId the cloud foundry application ID
	 * @return the access level that should be granted
	 * @throws CloudFoundryAuthorizationException if the token is not authorized
	 */
public AccessLevel getAccessLevel(String token, String applicationId) throws CloudFoundryAuthorizationException {
    try {
        URI uri = getPermissionsUri(applicationId);
        RequestEntity<?> request = RequestEntity.get(uri).header("Authorization", "bearer " + token).build();
        Map<?, ?> body = this.restTemplate.exchange(request, Map.class).getBody();
        if (Boolean.TRUE.equals(body.get("read_sensitive_data"))) {
            return AccessLevel.FULL;
        }
        return AccessLevel.RESTRICTED;
    } catch (HttpClientErrorException ex) {
        if (ex.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
            throw new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied");
        }
        throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Invalid token", ex);
    } catch (HttpServerErrorException ex) {
        throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Cloud controller not reachable");
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) URI(java.net.URI) HashMap(java.util.HashMap) Map(java.util.Map) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException)

Example 14 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project goci by EBISPOT.

the class EnsemblController method getAncestors.

public Map<String, String> getAncestors(String efoTerm) throws IOException {
    Map<String, String> result = new HashMap<>();
    String uri = olsServer.concat(olsEfoTerms);
    if (efoTerm.contains("http")) {
        uri = uri.concat("?").concat(efoTerm);
    } else {
        uri = uri.concat(olsShortForm).concat(efoTerm);
    }
    RestTemplate restTemplate = new RestTemplate();
    String efoObject = null;
    try {
        efoObject = restTemplate.getForObject(uri, String.class);
    } catch (HttpClientErrorException ex) {
        result.put("error", "Term ".concat(efoTerm).concat(" not found in EFO"));
    }
    if (efoObject != null) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(efoObject);
        JsonNode responseNode = node.get("_embedded").get("terms").get(0);
        String ancestors_link = responseNode.get("_links").get("hierarchicalAncestors").get("href").asText().trim();
        ancestors_link = java.net.URLDecoder.decode(ancestors_link, "UTF-8");
        String label = responseNode.get("label").asText().trim();
        String iri = responseNode.get("iri").asText().trim();
        String ancestorsObject = restTemplate.getForObject(ancestors_link, String.class);
        result.put("iri", iri);
        result.put("label", label);
        result.put("ancestors", ancestorsObject);
    }
    return result;
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) HashMap(java.util.HashMap) RestTemplate(org.springframework.web.client.RestTemplate) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 15 with HttpClientErrorException

use of org.springframework.web.client.HttpClientErrorException in project spring-security-oauth by spring-projects.

the class AbstractAuthorizationCodeProviderTests method testUnauthenticatedAuthorizationRespondsUnauthorized.

@Test
@OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false)
public void testUnauthenticatedAuthorizationRespondsUnauthorized() throws Exception {
    AccessTokenRequest request = context.getAccessTokenRequest();
    request.setCurrentUri("http://anywhere");
    request.add(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    try {
        String code = accessTokenProvider.obtainAuthorizationCode(context.getResource(), request);
        assertNotNull(code);
        fail("Expected UserRedirectRequiredException");
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode());
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Aggregations

HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)19 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)8 RestTemplate (org.springframework.web.client.RestTemplate)6 HashMap (java.util.HashMap)4 HttpEntity (org.springframework.http.HttpEntity)4 HttpHeaders (org.springframework.http.HttpHeaders)4 HttpStatus (org.springframework.http.HttpStatus)4 ResourceAccessException (org.springframework.web.client.ResourceAccessException)4 URI (java.net.URI)3 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 AccountExpiredException (javax.security.auth.login.AccountExpiredException)2 AccountLockedException (javax.security.auth.login.AccountLockedException)2 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)2 FailedLoginException (javax.security.auth.login.FailedLoginException)2 AccountDisabledException (org.apereo.cas.authentication.exceptions.AccountDisabledException)2 AccountPasswordMustChangeException (org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException)2 Principal (org.apereo.cas.authentication.principal.Principal)2 Configuration (org.hisp.dhis.configuration.Configuration)2 ImportSummariesResponseExtractor (org.hisp.dhis.dxf2.common.ImportSummariesResponseExtractor)2