Search in sources :

Example 21 with RestClientException

use of org.springframework.web.client.RestClientException in project spring-boot-admin by codecentric.

the class ApplicationRegistratorTest method register_retry.

@SuppressWarnings("rawtypes")
@Test
public void register_retry() {
    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Application.class))).thenThrow(new RestClientException("Error"));
    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Map.class))).thenReturn(new ResponseEntity<Map>(Collections.singletonMap("id", "-id-"), HttpStatus.CREATED));
    assertTrue(registrator.register());
    assertEquals("-id-", registrator.getRegisteredId());
}
Also used : HttpEntity(org.springframework.http.HttpEntity) RestClientException(org.springframework.web.client.RestClientException) Application(de.codecentric.boot.admin.client.registration.Application) Map(java.util.Map) Test(org.junit.Test)

Example 22 with RestClientException

use of org.springframework.web.client.RestClientException in project spring-boot-admin by codecentric.

the class ApplicationRegistratorTest method register_failed.

@Test
public void register_failed() {
    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Application.class))).thenThrow(new RestClientException("Error"));
    assertFalse(registrator.register());
    assertEquals(null, registrator.getRegisteredId());
}
Also used : HttpEntity(org.springframework.http.HttpEntity) RestClientException(org.springframework.web.client.RestClientException) Application(de.codecentric.boot.admin.client.registration.Application) Test(org.junit.Test)

Example 23 with RestClientException

use of org.springframework.web.client.RestClientException 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 24 with RestClientException

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

the class OAuth2AccessTokenSupport method retrieveToken.

protected OAuth2AccessToken retrieveToken(AccessTokenRequest request, OAuth2ProtectedResourceDetails resource, MultiValueMap<String, String> form, HttpHeaders headers) throws OAuth2AccessDeniedException {
    try {
        // Prepare headers and form before going into rest template call in case the URI is affected by the result
        authenticationHandler.authenticateTokenRequest(resource, form, headers);
        // Opportunity to customize form and headers
        tokenRequestEnhancer.enhance(request, resource, form, headers);
        final AccessTokenRequest copy = request;
        final ResponseExtractor<OAuth2AccessToken> delegate = getResponseExtractor();
        ResponseExtractor<OAuth2AccessToken> extractor = new ResponseExtractor<OAuth2AccessToken>() {

            @Override
            public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {
                if (response.getHeaders().containsKey("Set-Cookie")) {
                    copy.setCookie(response.getHeaders().getFirst("Set-Cookie"));
                }
                return delegate.extractData(response);
            }
        };
        return getRestTemplate().execute(getAccessTokenUri(resource, form), getHttpMethod(), getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());
    } catch (OAuth2Exception oe) {
        throw new OAuth2AccessDeniedException("Access token denied.", resource, oe);
    } catch (RestClientException rce) {
        throw new OAuth2AccessDeniedException("Error requesting access token.", resource, rce);
    }
}
Also used : OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) RestClientException(org.springframework.web.client.RestClientException) ResponseExtractor(org.springframework.web.client.ResponseExtractor) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 25 with RestClientException

use of org.springframework.web.client.RestClientException in project portal by ixinportal.

the class AuthService method getToken.

// @Autowired
// private static RealNameAuthenticationSerivceImpl authenticationSerivceImpl = new RealNameAuthenticationSerivceImpl();
/**
 * 获得token
 * 访问其他接口的时候 在头信息增加 Authorization :bear+token bear和token之间加个空格
 */
private static String getToken() {
    // client_secret:43b484748d3a936330bc50da70d6ce69e1dfef90
    try {
        // RealNameAuthentication realNameAuthentication =  authenticationSerivceImpl.getRealNameAuthenticationExample(new RealNameAuthenticationExample());
        Long nowDate = System.currentTimeMillis();
        if (ACCESS_TOKEN != null && new Date(nowDate + inDateTime).before(inDate)) {
            return ACCESS_TOKEN;
        }
        List<RealNameAuthentication> list = sqlSession.selectList("com.itrus.portal.db.RealNameAuthenticationMapper.selectByExample", new RealNameAuthenticationExample());
        if (list == null || list.isEmpty()) {
            return null;
        }
        RealNameAuthentication realNameAuthentication = null;
        for (RealNameAuthentication nameAuthentication : list) {
            if (nameAuthentication.getType() == 1)
                realNameAuthentication = nameAuthentication;
        }
        if (realNameAuthentication == null) {
            return null;
        }
        Map params = new HashMap();
        params.put("grant_type", "client_credentials");
        params.put("client_id", realNameAuthentication.getIdCode());
        params.put("client_secret", realNameAuthentication.getKeyCode());
        String rep = HttpClientUtil.postForm(realNameAuthentication.getAccessTokenaddress() + TOKEN, null, params);
        JSONObject data = JSON.parseObject(rep);
        ACCESS_TOKEN = data.getString("access_token");
        inDate = new Date(nowDate + data.getInteger("expires_in") * 1000);
        return ACCESS_TOKEN;
    } catch (RestClientException e) {
        e.printStackTrace();
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : IOException(java.io.IOException) RealNameAuthentication(com.itrus.portal.db.RealNameAuthentication) JsonParseException(com.fasterxml.jackson.core.JsonParseException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) RestClientException(org.springframework.web.client.RestClientException) IOException(java.io.IOException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) RealNameAuthenticationExample(com.itrus.portal.db.RealNameAuthenticationExample) JSONObject(com.alibaba.fastjson.JSONObject) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) RestClientException(org.springframework.web.client.RestClientException)

Aggregations

RestClientException (org.springframework.web.client.RestClientException)43 HttpHeaders (org.springframework.http.HttpHeaders)12 HttpEntity (org.springframework.http.HttpEntity)11 IOException (java.io.IOException)9 RestTemplate (org.springframework.web.client.RestTemplate)9 HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)8 Test (org.junit.Test)5 JsonParseException (com.fasterxml.jackson.core.JsonParseException)4 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)4 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)4 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)4 URI (java.net.URI)3 List (java.util.List)3 Test (org.junit.jupiter.api.Test)3 JSONObject (com.alibaba.fastjson.JSONObject)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2 RealNameAuthentication (com.itrus.portal.db.RealNameAuthentication)2 RealNameAuthenticationExample (com.itrus.portal.db.RealNameAuthenticationExample)2 GitHubDTO (com.nixmash.blog.jpa.dto.GitHubDTO)2