Java Code Examples for org.springframework.web.client.HttpClientErrorException#getStatusCode()

The following examples show how to use org.springframework.web.client.HttpClientErrorException#getStatusCode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Jira.java    From spring-data-dev-tools with Apache License 2.0 7 votes vote down vote up
private Optional<JiraIssue> getJiraIssue(String ticketId) {

		Map<String, Object> parameters = newUrlTemplateVariables();
		parameters.put("ticketId", ticketId);

		try {
			ResponseEntity<JiraIssue> jiraIssue = operations.getForEntity(ISSUE_TEMPLATE, JiraIssue.class, parameters);

			return Optional.of(jiraIssue.getBody());
		} catch (HttpClientErrorException e) {
			if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
				return Optional.empty();
			}

			throw e;
		}
	}
 
Example 2
Source File: RestResponseHandler.java    From api-layer with Eclipse Public License 2.0 7 votes vote down vote up
private void handleHttpClientError(@NotNull Exception exception, ErrorType errorType, String genericLogErrorMessage, Object... logParameters) {
    HttpClientErrorException hceException = (HttpClientErrorException) exception;
    switch (hceException.getStatusCode()) {
        case UNAUTHORIZED:
            if (errorType != null) {
                if (errorType.equals(ErrorType.BAD_CREDENTIALS)) {
                    throw new BadCredentialsException(errorType.getDefaultMessage(), exception);
                } else if (errorType.equals(ErrorType.TOKEN_NOT_VALID)) {
                    throw new TokenNotValidException(errorType.getDefaultMessage(), exception);
                } else if (errorType.equals(ErrorType.TOKEN_NOT_PROVIDED)) {
                    throw new TokenNotProvidedException(errorType.getDefaultMessage());
                }
            }
            throw new BadCredentialsException(ErrorType.BAD_CREDENTIALS.getDefaultMessage(), exception);
        case BAD_REQUEST:
            throw new AuthenticationCredentialsNotFoundException(ErrorType.AUTH_CREDENTIALS_NOT_FOUND.getDefaultMessage(), exception);
        case METHOD_NOT_ALLOWED:
            throw new AuthMethodNotSupportedException(ErrorType.AUTH_METHOD_NOT_SUPPORTED.getDefaultMessage());
        default:
            addDebugMessage(exception, genericLogErrorMessage, logParameters);
            throw new AuthenticationServiceException(ErrorType.AUTH_GENERAL.getDefaultMessage(), exception);
    }
}
 
Example 3
Source File: RestOperations.java    From bowman with Apache License 2.0 6 votes vote down vote up
public <T> CollectionModel<EntityModel<T>> getResources(URI uri, Class<T> entityType) {
	ObjectNode node;
	
	try {
		node = restTemplate.getForObject(uri, ObjectNode.class);
	}
	catch (HttpClientErrorException exception) {
		if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
			return CollectionModel.wrap(Collections.<T>emptyList());
		}
		
		throw exception;
	}
	
	JavaType innerType = objectMapper.getTypeFactory().constructParametricType(EntityModel.class, entityType);
	JavaType targetType = objectMapper.getTypeFactory().constructParametricType(CollectionModel.class, innerType);
	
	return objectMapper.convertValue(node, targetType);
}
 
Example 4
Source File: RestOperations.java    From bowman with Apache License 2.0 6 votes vote down vote up
public <T> EntityModel<T> getResource(URI uri, Class<T> entityType) {
	ObjectNode node;
	
	try {
		node = restTemplate.getForObject(uri, ObjectNode.class);
	}
	catch (HttpClientErrorException exception) {
		if (exception.getStatusCode() == HttpStatus.NOT_FOUND) {
			return null;
		}
		
		throw exception;
	}
	
	JavaType targetType = objectMapper.getTypeFactory().constructParametricType(EntityModel.class, entityType);
	
	return objectMapper.convertValue(node, targetType);
}
 
Example 5
Source File: AbstractV2RegistryService.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private Manifest getManifest(String name, String reference) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(
            new MediaType("application", "vnd.docker.distribution.manifest.v2+json"),
            new MediaType("application", "vnd.docker.distribution.manifest.v2+prettyjws")
    ));
    HttpEntity entity = new HttpEntity<>(headers);
    URI uri = forName(name).path("/manifests/").path(reference).build().toUri();
    try {
        ResponseEntity<Manifest> exchange = getRestTemplate().exchange(uri, HttpMethod.GET, entity, Manifest.class);
        return exchange.getBody();
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
            return null;
        }
        log.error("can't fetch manifest from {} by {}", uri, e.getMessage());
        throw e;
    }
}
 
Example 6
Source File: SonarServerConfigurationServiceImpl.java    From code-quality-game with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Checks the current status of the server and the version running on it.
 * It also detects if the server is not reachable.
 *
 * @param config The configuration for Sonar Server
 * @return the response from server
 */
@Override
public SonarServerStatus checkServerDetails(final SonarServerConfiguration config) {
    log.info("Trying to reach Sonar server at " + config.getUrl() + API_SYSTEM_STATUS);
    try {
        final HttpHeaders authHeaders = ApiHttpUtils.getHeaders(config.getToken());
        HttpEntity<String> request = new HttpEntity<>(authHeaders);
        final ResponseEntity<SonarServerStatus> response = restTemplate
                .exchange(config.getUrl() + API_SYSTEM_STATUS,
                        HttpMethod.GET, request, SonarServerStatus.class);
        log.info("Response received from server: " + response.getBody());
        return response.getBody();
    } catch (final HttpClientErrorException clientErrorException) {
        log.error(clientErrorException);
        if (clientErrorException.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            return new SonarServerStatus(SonarServerStatus.Key.UNAUTHORIZED);
        } else {
            return new SonarServerStatus(SonarServerStatus.Key.UNKNOWN_ERROR, clientErrorException.getMessage());
        }
    } catch (final ResourceAccessException resourceAccessException) {
        log.error(resourceAccessException);
        return new SonarServerStatus(SonarServerStatus.Key.CONNECTION_ERROR, resourceAccessException.getMessage());
    }
}
 
Example 7
Source File: ItemService.java    From apollo with Apache License 2.0 6 votes vote down vote up
private long getNamespaceId(NamespaceIdentifier namespaceIdentifier) {
  String appId = namespaceIdentifier.getAppId();
  String clusterName = namespaceIdentifier.getClusterName();
  String namespaceName = namespaceIdentifier.getNamespaceName();
  Env env = namespaceIdentifier.getEnv();
  NamespaceDTO namespaceDTO = null;
  try {
    namespaceDTO = namespaceAPI.loadNamespace(appId, env, clusterName, namespaceName);
  } catch (HttpClientErrorException e) {
    if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
      throw new BadRequestException(String.format(
          "namespace not exist. appId:%s, env:%s, clusterName:%s, namespaceName:%s", appId, env, clusterName,
          namespaceName));
    }
    throw e;
  }
  return namespaceDTO.getId();
}
 
Example 8
Source File: RestErrorAdvice.java    From sample-boot-hibernate with MIT License 5 votes vote down vote up
/** RestTemplate 例外時のブリッジサポート */
@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<String> handleHttpClientError(HttpClientErrorException e) {
    HttpHeaders headers = new HttpHeaders();
    headers.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(MediaType.APPLICATION_JSON_VALUE));
    return new ResponseEntity<>(e.getResponseBodyAsString(), headers, e.getStatusCode());
}
 
Example 9
Source File: ProductCompositeIntegration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
private RuntimeException handleHttpClientException(HttpClientErrorException ex) {
    switch (ex.getStatusCode()) {

    case NOT_FOUND:
        return new NotFoundException(getErrorMessage(ex));

    case UNPROCESSABLE_ENTITY :
        return new InvalidInputException(getErrorMessage(ex));

    default:
        LOG.warn("Got a unexpected HTTP error: {}, will rethrow it", ex.getStatusCode());
        LOG.warn("Error body: {}", ex.getResponseBodyAsString());
        return ex;
    }
}
 
Example 10
Source File: ErrorHandler.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler({HttpClientErrorException.class})
@ResponseBody
public ResponseEntity<UiError> bindErrorHandler(HttpClientErrorException e) {
    log.error("Can't process request", e);
    HttpStatus statusCode = e.getStatusCode();
    UiError response = createResponse(StringUtils.trimWhitespace(e.getResponseBodyAsString()),
            Throwables.printToString(e), statusCode);
    return new ResponseEntity<>(response, BAD_REQUEST);
}
 
Example 11
Source File: AbstractRestExceptionHandler.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@link HttpClientErrorException}をハンドリングします。
 * @param e {@link HttpClientErrorException}
 * @param headers HTTPヘッダー
 * @return {@link ErrorMessage}
 *         REST Clientで返されたHTTPステータスを返却します。
 */
@ExceptionHandler(HttpClientErrorException.class)
@ResponseBody
@Override
public ResponseEntity<ErrorMessage> handle(HttpClientErrorException e, HttpHeaders headers) {
    if (L.isDebugEnabled()) {
        L.debug(R.getString("D-SPRINGMVC-REST-HANDLER#0014"), e);
    }
    HttpStatus status = e.getStatusCode();
    ErrorMessage error = createServerErrorMessage(status);
    warn(error, e);
    return new ResponseEntity<ErrorMessage>(error, headers, status);
}
 
Example 12
Source File: GlobalExceptionHandler.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler({ HttpClientErrorException.class })
public ResponseEntity<TdpExceptionDto> handleError(HttpClientErrorException e) {

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

    String code = e.getStatusCode().toString();
    String message = e.getMessage();
    String localizedMessage = e.getLocalizedMessage();
    String statusText = e.getStatusText();

    TdpExceptionDto exceptionDto = new TdpExceptionDto(code, null, message, localizedMessage, statusText, null);

    return new ResponseEntity<>(exceptionDto, httpHeaders, e.getStatusCode());
}
 
Example 13
Source File: UserServiceClient.java    From spring-microservice-sample with GNU General Public License v3.0 5 votes vote down vote up
public void handleSignup(SignupForm form) {
    try {
        ResponseEntity<Void> response = this.restTemplate.postForEntity(userServiceUrl + "/users", form, Void.class);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode() == CONFLICT) {
            Map map = null;
            try {
                map = objectMapper.readValue(e.getResponseBodyAsByteArray(), Map.class);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new SignupConflictException((String) map.get("message"));
        }
    }
}
 
Example 14
Source File: SpecialRoutesFilter.java    From spring-microservices-in-action with Apache License 2.0 5 votes vote down vote up
/**
 * Call the SpecialRoutes service to see if there is any alternate 
 * endpoint for the service being called by Zuul.
 * 
 * @param  serviceName
 *         The Eureka service ID for the service being called by Zuul.
 *         
 * @return  The {@code AbTestingRoute} object which contains the alternate 
 *          end-point address and the percentage of calls (weight number) 
 *          to be sent to new versus old service.
 */
private AbTestingRoute getAbRoutingInfo(String serviceName){
    ResponseEntity<AbTestingRoute> restExchange = null;
    try {
        restExchange = restTemplate.exchange("http://specialroutesservice/v1/route/abtesting/{serviceName}", HttpMethod.GET, null, AbTestingRoute.class, serviceName);
    } catch(HttpClientErrorException ex){
        if (ex.getStatusCode() == HttpStatus.NOT_FOUND) {
        		return null;
        }
        throw ex;
    }
    return restExchange.getBody();
}
 
Example 15
Source File: FootballEcosystem.java    From football-events with MIT License 5 votes vote down vote up
public HttpStatus command(String url, HttpMethod method, String json) {
    logger.trace(json);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    try {
        return rest.exchange(url, method, new HttpEntity<>(json, headers), String.class).getStatusCode();
    } catch (HttpClientErrorException e) {
        return e.getStatusCode();
    }
}
 
Example 16
Source File: RabbitMQHttpClient.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
private void deleteIgnoring404(URI uri) {
    try {
        this.rt.delete(uri);
    } catch (final HttpClientErrorException ce) {
        if(!(ce.getStatusCode() == HttpStatus.NOT_FOUND)) {
            throw ce;
        }
    }
}
 
Example 17
Source File: RabbitMQHttpClient.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
private <T> T getForObjectReturningNullOn404(final URI uri, final Class<T> klass) {
    try {
        return this.rt.getForObject(uri, klass);
    } catch (final HttpClientErrorException ce) {
        if(ce.getStatusCode() == HttpStatus.NOT_FOUND) {
            return null;
        } else {
            throw ce;
        }
    }
}
 
Example 18
Source File: ProductCompositeIntegration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
public Product getProduct(int productId) {

        try {
            String url = productServiceUrl + productId;
            LOG.debug("Will call getProduct API on URL: {}", url);

            Product product = restTemplate.getForObject(url, Product.class);
            LOG.debug("Found a product with id: {}", product.getProductId());

            return product;

        } catch (HttpClientErrorException ex) {

            switch (ex.getStatusCode()) {

            case NOT_FOUND:
                throw new NotFoundException(getErrorMessage(ex));

            case UNPROCESSABLE_ENTITY :
                throw new InvalidInputException(getErrorMessage(ex));

            default:
                LOG.warn("Got a unexpected HTTP error: {}, will rethrow it", ex.getStatusCode());
                LOG.warn("Error body: {}", ex.getResponseBodyAsString());
                throw ex;
            }
        }
    }
 
Example 19
Source File: ProductCompositeIntegration.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 5 votes vote down vote up
public Product getProduct(int productId) {

        try {
            String url = productServiceUrl + productId;
            LOG.debug("Will call getProduct API on URL: {}", url);

            Product product = restTemplate.getForObject(url, Product.class);
            LOG.debug("Found a product with id: {}", product.getProductId());

            return product;

        } catch (HttpClientErrorException ex) {

            switch (ex.getStatusCode()) {

            case NOT_FOUND:
                throw new NotFoundException(getErrorMessage(ex));

            case UNPROCESSABLE_ENTITY :
                throw new InvalidInputException(getErrorMessage(ex));

            default:
                LOG.warn("Got a unexpected HTTP error: {}, will rethrow it", ex.getStatusCode());
                LOG.warn("Error body: {}", ex.getResponseBodyAsString());
                throw ex;
            }
        }
    }
 
Example 20
Source File: ValidationLibException.java    From CheckPoint with Apache License 2.0 2 votes vote down vote up
/**
 * Instantiates a new Validation lib exception.
 *
 * @param e the e
 */
public ValidationLibException(HttpClientErrorException e) {
    super(e.getMessage());
    this.statusCode = e.getStatusCode();
}