Java Code Examples for org.springframework.http.HttpStatus#resolve()

The following examples show how to use org.springframework.http.HttpStatus#resolve() . 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: DefaultWebClient.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private <T extends Publisher<?>> T handleBody(ClientResponse response,
		T bodyPublisher, Function<Mono<? extends Throwable>, T> errorFunction) {

	if (HttpStatus.resolve(response.rawStatusCode()) != null) {
		for (StatusHandler handler : this.statusHandlers) {
			if (handler.test(response.statusCode())) {
				HttpRequest request = this.requestSupplier.get();
				Mono<? extends Throwable> exMono = handler.apply(response, request);
				exMono = exMono.flatMap(ex -> drainBody(response, ex));
				exMono = exMono.onErrorResume(ex -> drainBody(response, ex));
				T result = errorFunction.apply(exMono);
				return insertCheckpoint(result, response.statusCode(), request);
			}
		}
		return bodyPublisher;
	}
	else {
		return errorFunction.apply(createResponseException(response, this.requestSupplier.get()));
	}
}
 
Example 2
Source File: NettyRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void setResponseStatus(HttpClientResponse clientResponse,
		ServerHttpResponse response) {
	HttpStatus status = HttpStatus.resolve(clientResponse.status().code());
	if (status != null) {
		response.setStatusCode(status);
	}
	else {
		while (response instanceof ServerHttpResponseDecorator) {
			response = ((ServerHttpResponseDecorator) response).getDelegate();
		}
		if (response instanceof AbstractServerHttpResponse) {
			((AbstractServerHttpResponse) response)
					.setStatusCodeValue(clientResponse.status().code());
		}
		else {
			// TODO: log warning here, not throw error?
			throw new IllegalStateException("Unable to set status code "
					+ clientResponse.status().code() + " on response of type "
					+ response.getClass().getName());
		}
	}
}
 
Example 3
Source File: BackstopperSpringWebFluxComponentTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@GetMapping(path = RESPONSE_STATUS_EX_FOR_SPECIFIC_STATUS_CODE_ENDPOINT)
@ResponseBody
public String responseStatusExForSpecificStatusCodeEndpoint(ServerHttpRequest request) {
    int desiredStatusCode = Integer.parseInt(
        request.getHeaders().getFirst("desired-status-code")
    );
    throw new ResponseStatusException(
        HttpStatus.resolve(desiredStatusCode),
        "Synthetic ResponseStatusException with specific desired status code: " + desiredStatusCode
    );
}
 
Example 4
Source File: LogInterceptor.java    From spring-microservice-boilerplate with MIT License 5 votes vote down vote up
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
    Object handler, Exception ex) {
  if (!(HttpMethod.GET.matches(request.getMethod())
      || HttpMethod.DELETE.matches(request.getMethod()))) {
    String path = request.getRequestURI();
    HttpStatus status = HttpStatus.resolve(response.getStatus());
    if (!path.contains(ResourcePath.OPEN) && status != null && !status.isError()) {
      logHelper.log(HttpMethod.resolve(request.getMethod()), path);
    }
  }
}
 
Example 5
Source File: DefaultServerResponseBuilder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void writeStatusAndHeaders(ServerHttpResponse response) {
	if (response instanceof AbstractServerHttpResponse) {
		((AbstractServerHttpResponse) response).setStatusCodeValue(this.statusCode);
	}
	else {
		HttpStatus status = HttpStatus.resolve(this.statusCode);
		if (status == null) {
			throw new IllegalStateException(
					"Unresolvable HttpStatus for general ServerHttpResponse: " + this.statusCode);
		}
		response.setStatusCode(status);
	}
	copy(this.headers, response.getHeaders());
	copy(this.cookies, response.getCookies());
}
 
Example 6
Source File: ServerWebExchangeUtils.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public static HttpStatus parse(String statusString) {
	HttpStatus httpStatus;

	try {
		int status = Integer.parseInt(statusString);
		httpStatus = HttpStatus.resolve(status);
	}
	catch (NumberFormatException e) {
		// try the enum string
		httpStatus = HttpStatus.valueOf(statusString.toUpperCase());
	}
	return httpStatus;
}
 
Example 7
Source File: MessageBodyClientHttpResponseWrapper.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Indicates whether the response has a message body.
 * <p>Implementation returns {@code false} for:
 * <ul>
 * <li>a response status of {@code 1XX}, {@code 204} or {@code 304}</li>
 * <li>a {@code Content-Length} header of {@code 0}</li>
 * </ul>
 * @return {@code true} if the response has a message body, {@code false} otherwise
 * @throws IOException in case of I/O errors
 */
public boolean hasMessageBody() throws IOException {
	HttpStatus status = HttpStatus.resolve(getRawStatusCode());
	if (status != null && (status.is1xxInformational() || status == HttpStatus.NO_CONTENT ||
			status == HttpStatus.NOT_MODIFIED)) {
		return false;
	}
	if (getHeaders().getContentLength() == 0) {
		return false;
	}
	return true;
}
 
Example 8
Source File: DefaultServerResponseBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void writeStatusAndHeaders(ServerHttpResponse response) {
	if (response instanceof AbstractServerHttpResponse) {
		((AbstractServerHttpResponse) response).setStatusCodeValue(this.statusCode);
	}
	else {
		HttpStatus status = HttpStatus.resolve(this.statusCode);
		if (status == null) {
			throw new IllegalStateException(
					"Unresolvable HttpStatus for general ServerHttpResponse: " + this.statusCode);
		}
		response.setStatusCode(status);
	}
	copy(this.headers, response.getHeaders());
	copy(this.cookies, response.getCookies());
}
 
Example 9
Source File: RestResponseErrorHandler.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
    if (statusCode == null) {
        throw new KmssServiceException("errors.unkown", new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),response.getHeaders(), getResponseBody(response), getCharset(response)));
    }
    handleError(response, statusCode);
}
 
Example 10
Source File: DefaultResponseErrorHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Delegates to {@link #handleError(ClientHttpResponse, HttpStatus)} with the
 * response status code.
 * @throws UnknownHttpStatusCodeException in case of an unresolvable status code
 * @see #handleError(ClientHttpResponse, HttpStatus)
 */
@Override
public void handleError(ClientHttpResponse response) throws IOException {
	HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
	if (statusCode == null) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
				response.getHeaders(), getResponseBody(response), getCharset(response));
	}
	handleError(response, statusCode);
}
 
Example 11
Source File: SynchronousQueryProcessor.java    From kayenta with Apache License 2.0 5 votes vote down vote up
private boolean isRetryable(RetrofitError e) {
  if (isNetworkError(e)) {
    // retry in case of network errors
    return true;
  }
  HttpStatus responseStatus = HttpStatus.resolve(e.getResponse().getStatus());
  if (responseStatus == null) {
    return false;
  }
  return retryConfiguration.getStatuses().contains(responseStatus)
      || retryConfiguration.getSeries().contains(responseStatus.series());
}
 
Example 12
Source File: WebClientResponseException.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Create {@code WebClientResponseException} or an HTTP status specific subclass.
 * @since 5.1.4
 */
public static WebClientResponseException create(
		int statusCode, String statusText, HttpHeaders headers, byte[] body,
		@Nullable Charset charset, @Nullable HttpRequest request) {

	HttpStatus httpStatus = HttpStatus.resolve(statusCode);
	if (httpStatus != null) {
		switch (httpStatus) {
			case BAD_REQUEST:
				return new WebClientResponseException.BadRequest(statusText, headers, body, charset, request);
			case UNAUTHORIZED:
				return new WebClientResponseException.Unauthorized(statusText, headers, body, charset, request);
			case FORBIDDEN:
				return new WebClientResponseException.Forbidden(statusText, headers, body, charset, request);
			case NOT_FOUND:
				return new WebClientResponseException.NotFound(statusText, headers, body, charset, request);
			case METHOD_NOT_ALLOWED:
				return new WebClientResponseException.MethodNotAllowed(statusText, headers, body, charset, request);
			case NOT_ACCEPTABLE:
				return new WebClientResponseException.NotAcceptable(statusText, headers, body, charset, request);
			case CONFLICT:
				return new WebClientResponseException.Conflict(statusText, headers, body, charset, request);
			case GONE:
				return new WebClientResponseException.Gone(statusText, headers, body, charset, request);
			case UNSUPPORTED_MEDIA_TYPE:
				return new WebClientResponseException.UnsupportedMediaType(statusText, headers, body, charset, request);
			case TOO_MANY_REQUESTS:
				return new WebClientResponseException.TooManyRequests(statusText, headers, body, charset, request);
			case UNPROCESSABLE_ENTITY:
				return new WebClientResponseException.UnprocessableEntity(statusText, headers, body, charset, request);
			case INTERNAL_SERVER_ERROR:
				return new WebClientResponseException.InternalServerError(statusText, headers, body, charset, request);
			case NOT_IMPLEMENTED:
				return new WebClientResponseException.NotImplemented(statusText, headers, body, charset, request);
			case BAD_GATEWAY:
				return new WebClientResponseException.BadGateway(statusText, headers, body, charset, request);
			case SERVICE_UNAVAILABLE:
				return new WebClientResponseException.ServiceUnavailable(statusText, headers, body, charset, request);
			case GATEWAY_TIMEOUT:
				return new WebClientResponseException.GatewayTimeout(statusText, headers, body, charset, request);
		}
	}
	return new WebClientResponseException(statusCode, statusText, headers, body, charset, request);
}
 
Example 13
Source File: SpringAnnotationScanner.java    From smallrye-open-api with Apache License 2.0 4 votes vote down vote up
@Override
public String getReasonPhrase(int statusCode) {
    HttpStatus status = HttpStatus.resolve(statusCode);
    return status != null ? status.getReasonPhrase() : null;
}
 
Example 14
Source File: UndertowServerHttpResponse.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public HttpStatus getStatusCode() {
	HttpStatus httpStatus = super.getStatusCode();
	return httpStatus != null ? httpStatus : HttpStatus.resolve(this.exchange.getStatusCode());
}
 
Example 15
Source File: AbstractServerHttpResponse.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
@Nullable
public HttpStatus getStatusCode() {
	return this.statusCode != null ? HttpStatus.resolve(this.statusCode) : null;
}
 
Example 16
Source File: DefaultClientResponse.java    From java-technology-stack with MIT License 4 votes vote down vote up
private <T> ResponseEntity<T> createEntity(T body, HttpHeaders headers, int status) {
	HttpStatus resolvedStatus = HttpStatus.resolve(status);
	return resolvedStatus != null
			? new ResponseEntity<>(body, headers, resolvedStatus)
			: ResponseEntity.status(status).headers(headers).body(body);
}
 
Example 17
Source File: DefaultClientResponse.java    From java-technology-stack with MIT License 4 votes vote down vote up
private <T> ResponseEntity<T> createEntity(HttpHeaders headers, int status) {
	HttpStatus resolvedStatus = HttpStatus.resolve(status);
	return resolvedStatus != null
			? new ResponseEntity<>(headers, resolvedStatus)
			: ResponseEntity.status(status).headers(headers).build();
}
 
Example 18
Source File: RestTemplateXhrTransport.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
	if (httpStatus == null) {
		throw new UnknownHttpStatusCodeException(
				response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
	}
	if (httpStatus != HttpStatus.OK) {
		throw new HttpServerErrorException(
				httpStatus, response.getStatusText(), response.getHeaders(), null, null);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();

	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
Example 19
Source File: RestTemplateXhrTransport.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
	if (httpStatus == null) {
		throw new UnknownHttpStatusCodeException(
				response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
	}
	if (httpStatus != HttpStatus.OK) {
		throw new HttpServerErrorException(
				httpStatus, response.getStatusText(), response.getHeaders(), null, null);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();

	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
Example 20
Source File: DefaultResponseErrorHandler.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Determine the HTTP status of the given response.
 * @param response the response to inspect
 * @return the associated HTTP status
 * @throws IOException in case of I/O errors
 * @throws UnknownHttpStatusCodeException in case of an unknown status code
 * that cannot be represented with the {@link HttpStatus} enum
 * @since 4.3.8
 * @deprecated as of 5.0, in favor of {@link #handleError(ClientHttpResponse, HttpStatus)}
 */
@Deprecated
protected HttpStatus getHttpStatusCode(ClientHttpResponse response) throws IOException {
	HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
	if (statusCode == null) {
		throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(),
				response.getHeaders(), getResponseBody(response), getCharset(response));
	}
	return statusCode;
}