Search in sources :

Example 51 with HttpClientErrorException

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

use of org.springframework.web.client.HttpClientErrorException in project uPortal by Jasig.

the class DefaultTinCanAPIProvider method init.

/**
 * Initialize the API. Just sends an initialization event to the LRS provider. This uses the
 * activities/state API to do the initial test.
 */
@Override
public void init() {
    loadConfig();
    if (!isEnabled()) {
        return;
    }
    try {
        String actorStr = format(ACTOR_FORMAT, actorName, actorEmail);
        // Setup GET params...
        List<BasicNameValuePair> getParams = new ArrayList<>();
        getParams.add(new BasicNameValuePair(PARAM_ACTIVITY_ID, activityId));
        getParams.add(new BasicNameValuePair(PARAM_AGENT, actorStr));
        getParams.add(new BasicNameValuePair(PARAM_STATE_ID, stateId));
        Object body = null;
        if (formEncodeActivityData) {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            String json = format(STATE_FORMAT, STATE_KEY_STATUS, STATE_VALUE_STARTED);
            map.add(activitiesFormParamName, json);
            body = map;
        } else {
            // just post a simple:  {"status": "started"} record to the states API to verify
            // the service is up.
            Map<String, String> data = new HashMap<String, String>();
            data.put(STATE_KEY_STATUS, STATE_VALUE_STARTED);
            body = data;
        }
        ResponseEntity<Object> response = sendRequest(STATES_REST_ENDPOINT, HttpMethod.POST, getParams, body, Object.class);
        if (response.getStatusCode().series() != Series.SUCCESSFUL) {
            logger.error("LRS provider for URL " + LRSUrl + " it not configured properly, or is offline.  Disabling provider.");
        }
    // todo: Need to think through a strategy for handling errors submitting
    // to the LRS.
    } catch (HttpClientErrorException e) {
        // log some additional info in this case...
        logger.error("LRS provider for URL " + LRSUrl + " failed to contact LRS for initialization.  Disabling provider.", e);
        logger.error("  Status: {}, Response: {}", e.getStatusCode(), e.getResponseBodyAsString());
        enabled = false;
    } catch (Exception e) {
        logger.error("LRS provider for URL " + LRSUrl + " failed to contact LRS for initialization.  Disabling provider", e);
        enabled = false;
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HashMap(java.util.HashMap) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException)

Example 53 with HttpClientErrorException

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

the class Consumer method testErrorCode.

@SuppressWarnings({ "rawtypes" })
protected void testErrorCode() {
    String url = edgePrefix + "/v2/error/add";
    int response = template.getForObject(url + "?x=2&y=3", Integer.class);
    Assert.isTrue(response == 5, "not get 5.");
    try {
        Map raw = template.getForObject(url + "?x=99&y=3", Map.class);
    } catch (HttpServerErrorException e) {
        Assert.isTrue(e.getRawStatusCode() == 500, "x99");
        Assert.isTrue(e.getResponseBodyAsString().contains("Unexpected exception when processing the request"), "x99");
    }
    try {
        template.getForObject(url + "?x=88&y=3", Map.class);
        Assert.isTrue(false, "x88");
    } catch (HttpClientErrorException e) {
        Assert.isTrue(e.getRawStatusCode() == 403, "x88");
        Assert.isTrue(e.getResponseBodyAsString().equals("{\"id\":12,\"message\":\"not allowed id.\"}"), "x88");
    }
    try {
        template.getForObject(url + "?x=77&y=3", Map.class);
        Assert.isTrue(false, "x77");
    } catch (HttpServerErrorException e) {
        Assert.isTrue(e.getRawStatusCode() == 500, "x77");
        Assert.isTrue(e.getResponseBodyAsString().equals("{\"id\":500,\"message\":\"77\",\"state\":\"77\"}"), "x77");
    }
}
Also used : HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HttpServerErrorException(org.springframework.web.client.HttpServerErrorException)

Example 54 with HttpClientErrorException

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

use of org.springframework.web.client.HttpClientErrorException in project metacat by Netflix.

the class DruidConnectorTableService method get.

/**
 * {@inheritDoc}
 */
@Override
public TableInfo get(@Nonnull final ConnectorRequestContext context, @Nonnull final QualifiedName name) {
    log.debug("Get table metadata for qualified name {} for request {}", name, context);
    try {
        final ObjectNode node = this.druidClient.getLatestDataByName(name.getTableName());
        final DataSource dataSource = DruidConverterUtil.getDatasourceFromLatestSegmentJsonObject(node);
        return this.druidConnectorInfoConverter.getTableInfoFromDatasource(dataSource);
    } catch (MetacatException e) {
        log.error(String.format("Table %s not found.", name), e);
        throw new TableNotFoundException(name);
    } catch (HttpClientErrorException e) {
        log.error(String.format("Failed getting table %s.", name), e);
        if (HttpStatus.NOT_FOUND.equals(e.getStatusCode())) {
            throw new TableNotFoundException(name);
        } else {
            throw new InvalidMetadataException(String.format("Invalid table %s. %s", name, e.getMessage()));
        }
    }
}
Also used : TableNotFoundException(com.netflix.metacat.common.server.connectors.exception.TableNotFoundException) HttpClientErrorException(org.springframework.web.client.HttpClientErrorException) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) MetacatException(com.netflix.metacat.common.exception.MetacatException) InvalidMetadataException(com.netflix.metacat.common.server.connectors.exception.InvalidMetadataException) DataSource(com.netflix.metacat.connector.druid.converter.DataSource)

Aggregations

HttpClientErrorException (org.springframework.web.client.HttpClientErrorException)109 HttpHeaders (org.springframework.http.HttpHeaders)31 Test (org.junit.Test)25 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)24 HashMap (java.util.HashMap)21 HttpServerErrorException (org.springframework.web.client.HttpServerErrorException)21 MediaType (org.springframework.http.MediaType)19 RestTemplate (org.springframework.web.client.RestTemplate)19 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)18 HttpEntity (org.springframework.http.HttpEntity)16 URI (java.net.URI)15 Map (java.util.Map)8 HttpStatus (org.springframework.http.HttpStatus)8 RestClientException (org.springframework.web.client.RestClientException)8 ResourceAccessException (org.springframework.web.client.ResourceAccessException)7 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)6 Date (java.util.Date)5 List (java.util.List)5 OpenAppNamespaceDTO (com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO)4 ArrayList (java.util.ArrayList)4