Search in sources :

Example 96 with HttpStatus

use of org.springframework.http.HttpStatus in project thingsboard by thingsboard.

the class ThingsboardErrorResponseHandler method handleThingsboardException.

private void handleThingsboardException(ThingsboardException thingsboardException, HttpServletResponse response) throws IOException {
    ThingsboardErrorCode errorCode = thingsboardException.getErrorCode();
    HttpStatus status;
    switch(errorCode) {
        case AUTHENTICATION:
            status = HttpStatus.UNAUTHORIZED;
            break;
        case PERMISSION_DENIED:
            status = HttpStatus.FORBIDDEN;
            break;
        case INVALID_ARGUMENTS:
            status = HttpStatus.BAD_REQUEST;
            break;
        case ITEM_NOT_FOUND:
            status = HttpStatus.NOT_FOUND;
            break;
        case BAD_REQUEST_PARAMS:
            status = HttpStatus.BAD_REQUEST;
            break;
        case GENERAL:
            status = HttpStatus.INTERNAL_SERVER_ERROR;
            break;
        default:
            status = HttpStatus.INTERNAL_SERVER_ERROR;
            break;
    }
    response.setStatus(status.value());
    mapper.writeValue(response.getWriter(), ThingsboardErrorResponse.of(thingsboardException.getMessage(), errorCode, status));
}
Also used : HttpStatus(org.springframework.http.HttpStatus)

Example 97 with HttpStatus

use of org.springframework.http.HttpStatus in project elastest-torm by elastest.

the class ElasticsearchService method putCall.

public ResponseEntity<String> putCall(String url, String body) throws IndexAlreadyExistException, RestClientException {
    RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory(5000, 5000));
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> request = new HttpEntity<String>(body, headers);
    try {
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, request, String.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (!HttpStatus.OK.equals(statusCode)) {
            throw new IndexAlreadyExistException();
        }
        return responseEntity;
    } catch (RestClientException e) {
        throw e;
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) HttpStatus(org.springframework.http.HttpStatus) RestTemplate(org.springframework.web.client.RestTemplate) RestClientException(org.springframework.web.client.RestClientException)

Example 98 with HttpStatus

use of org.springframework.http.HttpStatus in project com.revolsys.open by revolsys.

the class WebAnnotationMethodHandlerAdapter method getModelAndView.

@SuppressWarnings({ "unchecked", "rawtypes" })
public ModelAndView getModelAndView(final Method handlerMethod, final Class<?> handlerType, final Object returnValue, final ExtendedModelMap implicitModel, final ServletWebRequest webRequest) throws Exception {
    boolean responseArgumentUsed = false;
    final ResponseStatus responseStatusAnn = AnnotationUtils.findAnnotation(handlerMethod, ResponseStatus.class);
    if (responseStatusAnn != null) {
        final HttpStatus responseStatus = responseStatusAnn.value();
        // to be picked up by the RedirectView
        webRequest.getRequest().setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, responseStatus);
        webRequest.getResponse().setStatus(responseStatus.value());
        responseArgumentUsed = true;
    }
    // Invoke custom resolvers if present...
    if (WebAnnotationMethodHandlerAdapter.this.customModelAndViewResolvers != null) {
        for (final ModelAndViewResolver mavResolver : WebAnnotationMethodHandlerAdapter.this.customModelAndViewResolvers) {
            final ModelAndView mav = mavResolver.resolveModelAndView(handlerMethod, handlerType, returnValue, implicitModel, webRequest);
            if (mav != ModelAndViewResolver.UNRESOLVED) {
                return mav;
            }
        }
    }
    if (returnValue != null && AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) != null) {
        final View view = handleResponseBody(returnValue, webRequest);
        return new ModelAndView(view).addAllObjects(implicitModel);
    }
    if (returnValue instanceof ModelAndView) {
        final ModelAndView mav = (ModelAndView) returnValue;
        mav.getModelMap().mergeAttributes(implicitModel);
        return mav;
    } else if (returnValue instanceof Model) {
        return new ModelAndView().addAllObjects(implicitModel).addAllObjects(((Model) returnValue).asMap());
    } else if (returnValue instanceof View) {
        return new ModelAndView((View) returnValue).addAllObjects(implicitModel);
    } else if (AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class) != null) {
        addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel);
        return new ModelAndView().addAllObjects(implicitModel);
    } else if (returnValue instanceof Map) {
        return new ModelAndView().addAllObjects(implicitModel).addAllObjects((Map) returnValue);
    } else if (returnValue instanceof String) {
        return new ModelAndView((String) returnValue).addAllObjects(implicitModel);
    } else if (returnValue == null) {
        // Either returned null or was 'void' return.
        if (responseArgumentUsed || webRequest.isNotModified()) {
            return null;
        } else {
            // Assuming view name translation...
            return new ModelAndView().addAllObjects(implicitModel);
        }
    } else if (!BeanUtils.isSimpleProperty(returnValue.getClass())) {
        // Assume a single model attribute...
        addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel);
        return new ModelAndView().addAllObjects(implicitModel);
    } else {
        throw new IllegalArgumentException("Invalid handler method return value: " + returnValue);
    }
}
Also used : ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) HttpStatus(org.springframework.http.HttpStatus) ModelAndViewResolver(org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver) ModelAndView(org.springframework.web.servlet.ModelAndView) Model(org.springframework.ui.Model) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ExtendedModelMap(org.springframework.ui.ExtendedModelMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) BindingAwareModelMap(org.springframework.validation.support.BindingAwareModelMap)

Example 99 with HttpStatus

use of org.springframework.http.HttpStatus in project spring-integration by spring-projects.

the class HttpRequestHandlingEndpointSupport method setupResponseAndConvertReply.

/**
 * Converts the reply message to the appropriate HTTP reply object and
 * sets up the {@link ServletServerHttpResponse}.
 * @param response     The ServletServerHttpResponse.
 * @param replyMessage The reply message.
 * @return The message payload (if {@link #extractReplyPayload}) otherwise the message.
 */
protected final Object setupResponseAndConvertReply(ServletServerHttpResponse response, Message<?> replyMessage) {
    getHeaderMapper().fromHeaders(replyMessage.getHeaders(), response.getHeaders());
    HttpStatus httpStatus = this.resolveHttpStatusFromHeaders(replyMessage.getHeaders());
    if (httpStatus != null) {
        response.setStatusCode(httpStatus);
    }
    Object reply = replyMessage;
    if (getExtractReplyPayload()) {
        reply = replyMessage.getPayload();
    }
    return reply;
}
Also used : HttpStatus(org.springframework.http.HttpStatus)

Example 100 with HttpStatus

use of org.springframework.http.HttpStatus in project spring-integration by spring-projects.

the class HttpRequestHandlingMessagingGateway method handleRequest.

/**
 * Handles the HTTP request by generating a Message and sending it to the request channel. If this gateway's
 * 'expectReply' property is true, it will also generate a response from the reply Message once received. That
 * response will be written by the {@link HttpMessageConverter}s.
 */
public final void handleRequest(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException {
    Object responseContent = null;
    Message<?> responseMessage;
    final ServletServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
    final ServletServerHttpResponse response = new ServletServerHttpResponse(servletResponse);
    try {
        responseMessage = super.doHandleRequest(servletRequest, servletResponse);
        if (responseMessage != null) {
            responseContent = setupResponseAndConvertReply(response, responseMessage);
        }
    } catch (Exception e) {
        responseContent = handleExceptionInternal(e);
    }
    if (responseContent != null) {
        if (responseContent instanceof HttpStatus) {
            response.setStatusCode((HttpStatus) responseContent);
        } else {
            if (responseContent instanceof ResponseEntity) {
                ResponseEntity<?> responseEntity = (ResponseEntity<?>) responseContent;
                responseContent = responseEntity.getBody();
                response.setStatusCode(responseEntity.getStatusCode());
                HttpHeaders outputHeaders = response.getHeaders();
                HttpHeaders entityHeaders = responseEntity.getHeaders();
                if (!entityHeaders.isEmpty()) {
                    entityHeaders.entrySet().stream().filter(entry -> !outputHeaders.containsKey(entry.getKey())).forEach(entry -> outputHeaders.put(entry.getKey(), entry.getValue()));
                }
            }
            if (responseContent != null) {
                writeResponse(responseContent, response, request.getHeaders().getAccept());
            } else {
                response.flush();
            }
        }
    } else {
        setStatusCodeIfNeeded(response);
    }
}
Also used : MessagingException(org.springframework.messaging.MessagingException) ServletException(javax.servlet.ServletException) HttpHeaders(org.springframework.http.HttpHeaders) MediaType(org.springframework.http.MediaType) HttpServletResponse(javax.servlet.http.HttpServletResponse) MultiValueMap(org.springframework.util.MultiValueMap) IOException(java.io.IOException) HttpStatus(org.springframework.http.HttpStatus) List(java.util.List) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletServerHttpResponse(org.springframework.http.server.ServletServerHttpResponse) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) CollectionUtils(org.springframework.util.CollectionUtils) MultipartAwareFormHttpMessageConverter(org.springframework.integration.http.converter.MultipartAwareFormHttpMessageConverter) ResponseEntity(org.springframework.http.ResponseEntity) Message(org.springframework.messaging.Message) Collections(java.util.Collections) HttpRequestHandler(org.springframework.web.HttpRequestHandler) ServletServerHttpRequest(org.springframework.http.server.ServletServerHttpRequest) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) HttpStatus(org.springframework.http.HttpStatus) ServletServerHttpResponse(org.springframework.http.server.ServletServerHttpResponse) MessagingException(org.springframework.messaging.MessagingException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Aggregations

HttpStatus (org.springframework.http.HttpStatus)165 ResponseEntity (org.springframework.http.ResponseEntity)43 HttpHeaders (org.springframework.http.HttpHeaders)38 Test (org.junit.jupiter.api.Test)26 MediaType (org.springframework.http.MediaType)17 Mono (reactor.core.publisher.Mono)17 IOException (java.io.IOException)16 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)15 Collections (java.util.Collections)13 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)13 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)13 URI (java.net.URI)12 List (java.util.List)11 Optional (java.util.Optional)11 Test (org.junit.Test)11 Map (java.util.Map)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 ClassPathResource (org.springframework.core.io.ClassPathResource)9 Resource (org.springframework.core.io.Resource)9 HashMap (java.util.HashMap)8