Search in sources :

Example 16 with RestClientException

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

the class BaseLivyInterpreter 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);
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
    headers.add("X-Requested-By", "zeppelin");
    for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
        headers.add(entry.getKey(), entry.getValue());
    }
    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(cause.getResponseBodyAsString() + "\n" + ExceptionUtils.getStackTrace(ExceptionUtils.getRootCause(e)));
        }
        if (e instanceof HttpServerErrorException) {
            HttpServerErrorException errorException = (HttpServerErrorException) e;
            String errorResponse = errorException.getResponseBodyAsString();
            if (errorResponse.contains("Session is in state dead")) {
                throw new SessionDeadException();
            }
            throw new LivyException(errorResponse, e);
        }
        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) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException) ResponseEntity(org.springframework.http.ResponseEntity) RestClientException(org.springframework.web.client.RestClientException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 17 with RestClientException

use of org.springframework.web.client.RestClientException in project java-chassis by ServiceComb.

the class CodeFirstRestTemplateJaxrs method test404.

private void test404(RestTemplate template) {
    HttpClientErrorException exception = null;
    try {
        template.getForEntity("http://127.0.0.1:8080/aPathNotExist", String.class);
    } catch (RestClientException e) {
        if (e instanceof HttpClientErrorException) {
            exception = (HttpClientErrorException) e;
        }
    }
    TestMgr.check(404, exception.getRawStatusCode());
    TestMgr.check("404 Not Found: \"{\"message\":\"Not Found\"}\"", exception.getMessage());
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) RestClientException(org.springframework.web.client.RestClientException)

Example 18 with RestClientException

use of org.springframework.web.client.RestClientException in project kylo by Teradata.

the class AmbariServicesStatusCheck method healthCheck.

/**
 * https://github.com/apache/ambari/blob/trunk/ambari-server/docs/api/v1/host-component-resources.md
 *
 * State 	Description                                                                          <br>
 * INIT 	The initial clean state after the component is first created.                        <br>
 * INSTALLING 	In the process of installing the component.                                  <br>
 * INSTALL_FAILED 	The component install failed.                                                <br>
 * INSTALLED 	The component has been installed successfully but is not currently running.  <br>
 * STARTING 	In the process of starting the component.                                    <br>
 * STARTED 	The component has been installed and started.                                        <br>
 * STOPPING 	In the process of stopping the component.                                    <br>
 * UNINSTALLING 	In the process of uninstalling the component.                                <br>
 * UNINSTALLED 	The component has been successfully uninstalled.                             <br>
 * WIPING_OUT 	In the process of wiping out the installed component.                        <br>
 * UPGRADING 	In the process of upgrading the component.                                   <br>
 * MAINTENANCE 	The component has been marked for maintenance.                               <br>
 * UNKNOWN 	The component state can not be determined.                                           <br>
 */
@Override
public List<ServiceStatusResponse> healthCheck() {
    List<ServiceStatusResponse> serviceStatusResponseList = new ArrayList<>();
    // Get the Map of Services and optional Components we are tracking
    Map<String, List<String>> definedServiceComponentMap = ServiceMonitorCheckUtil.getMapOfServiceAndComponents(services);
    if (definedServiceComponentMap != null && !definedServiceComponentMap.isEmpty()) {
        try {
            AmbariClient client = ambariClient;
            // get the Clusers from ambari
            List<String> clusterNames = client.getAmbariClusterNames();
            // get the Service Status from Ambari
            ServiceComponentInfoSummary response = client.getServiceComponentInfo(clusterNames, services);
            // get alert info for these services as well
            AlertSummary alertSummary = client.getAlerts(clusterNames, services);
            // Convert the Ambari Alerts to the Pipeline Controller Alert
            List<ServiceAlert> serviceAlerts = transformAmbariAlert(alertSummary);
            // Convert the Ambari ServiceComponentInfo objects to Pipeline Controller ServiceComponents
            serviceStatusResponseList = transformAmbariServiceComponents(response, serviceAlerts, definedServiceComponentMap);
        } catch (RestClientException e) {
            Throwable cause;
            if (e.getCause() != null) {
                cause = e.getCause();
            } else {
                cause = e;
            }
            ServiceComponent ambariServiceComponent = new DefaultServiceComponent.Builder("Unknown", "Ambari", "Ambari REST_CLIENT", ServiceComponent.STATE.DOWN).exception(cause).build();
            List<ServiceComponent> ambariComponents = new ArrayList<>();
            ambariComponents.add(ambariServiceComponent);
            ServiceStatusResponse serviceStatusResponse = new DefaultServiceStatusResponse(ambariServiceComponent.getServiceName(), ambariComponents);
            serviceStatusResponseList.add(serviceStatusResponse);
            // add the other services as being Warnings
            addAmbariServiceErrors(cause.getMessage(), serviceStatusResponseList, definedServiceComponentMap);
        }
    }
    return serviceStatusResponseList;
}
Also used : ServiceComponentInfoSummary(com.thinkbiganalytics.servicemonitor.rest.model.ambari.ServiceComponentInfoSummary) DefaultServiceStatusResponse(com.thinkbiganalytics.servicemonitor.model.DefaultServiceStatusResponse) ServiceStatusResponse(com.thinkbiganalytics.servicemonitor.model.ServiceStatusResponse) DefaultServiceComponent(com.thinkbiganalytics.servicemonitor.model.DefaultServiceComponent) ServiceComponent(com.thinkbiganalytics.servicemonitor.model.ServiceComponent) ArrayList(java.util.ArrayList) DefaultServiceStatusResponse(com.thinkbiganalytics.servicemonitor.model.DefaultServiceStatusResponse) DefaultServiceComponent(com.thinkbiganalytics.servicemonitor.model.DefaultServiceComponent) ServiceAlert(com.thinkbiganalytics.servicemonitor.model.ServiceAlert) DefaultServiceAlert(com.thinkbiganalytics.servicemonitor.model.DefaultServiceAlert) RestClientException(org.springframework.web.client.RestClientException) ArrayList(java.util.ArrayList) List(java.util.List) AlertSummary(com.thinkbiganalytics.servicemonitor.rest.model.ambari.AlertSummary) AmbariClient(com.thinkbiganalytics.servicemonitor.rest.client.ambari.AmbariClient)

Example 19 with RestClientException

use of org.springframework.web.client.RestClientException in project plumdo-work by wengwh.

the class RestClient method exchange.

public <T> T exchange(String url, HttpMethod method, MultiValueMap<String, String> queryParams, Object requestBody, Class<T> responseType) {
    T response = null;
    long beginTime = System.currentTimeMillis();
    try {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        builder.queryParams(queryParams);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Token", Authentication.getToken());
        response = restTemplate.exchange(builder.build().toUri(), method, new HttpEntity<>(requestBody, headers), responseType).getBody();
        log.debug("发送Http请求:{},方法:{},参数:{},返回:{},[{}]ms", url, method, requestBody, response, DateUtils.getTimeMillisConsume(beginTime));
    } catch (RestClientException e) {
        log.error("发送http请求:{},方法:{},参数:{},异常:{},[{}]ms", url, method, requestBody, e.getMessage(), DateUtils.getTimeMillisConsume(beginTime));
    }
    return response;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RestClientException(org.springframework.web.client.RestClientException)

Example 20 with RestClientException

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

the class ApplicationRegistratorTest method register_multiple_one_failure.

@SuppressWarnings("rawtypes")
@Test
public void register_multiple_one_failure() {
    adminProps.setRegisterOnce(false);
    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Map.class))).thenReturn(new ResponseEntity<Map>(Collections.singletonMap("id", "-id-"), HttpStatus.CREATED)).thenThrow(new RestClientException("Error"));
    assertTrue(registrator.register());
    assertEquals("-id-", registrator.getRegisteredId());
    verify(restTemplate).postForEntity("http://sba:8080/api/applications", new HttpEntity<>(Application.create("AppName").withHealthUrl("http://localhost:8080/health").withManagementUrl("http://localhost:8080/mgmt").withServiceUrl("http://localhost:8080").build(), headers), Map.class);
    verify(restTemplate).postForEntity("http://sba2:8080/api/applications", new HttpEntity<>(Application.create("AppName").withHealthUrl("http://localhost:8080/health").withManagementUrl("http://localhost:8080/mgmt").withServiceUrl("http://localhost:8080").build(), headers), Map.class);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) RestClientException(org.springframework.web.client.RestClientException) Test(org.junit.Test)

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