Example usage for org.springframework.http HttpStatus value

List of usage examples for org.springframework.http HttpStatus value

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus value.

Prototype

int value

To view the source code for org.springframework.http HttpStatus value.

Click Source Link

Usage

From source file:com.revolsys.ui.web.rest.interceptor.WebAnnotationMethodHandlerAdapter.java

@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;// w  w w.  j  a v  a 2  s  . co m
    }

    // 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);
    }
}

From source file:com.tasktop.c2c.server.common.service.tests.http.HttpProxyTest.java

private void setupMock(final HttpStatus status) throws IOException {

    proxy.setHttpClient(httpClient);/*from  w w w  .j ava2  s.com*/
    proxy.setHttpMethodProvider(httpMethodProvider);
    proxy.setHeaderFilter(new CookieHeaderFilter());

    ExcludeHeaderFilter excludeHeaders = new ExcludeHeaderFilter();
    excludeHeaders.getExcludedRequestHeaders().addAll(Arrays.asList("Connection", "Accept-Encoding"));
    excludeHeaders.getExcludedResponseHeaders().addAll(Arrays.asList("Connection", "Response-Encoding"));
    proxy.getHeaderFilter().setNext(excludeHeaders);

    final HttpMethod httpMethod = context.mock(HttpMethod.class);

    context.checking(new Expectations() {
        {
            oneOf(httpMethodProvider).getMethod(with(any(String.class)), with(any(String.class)));
            will(returnValue(httpMethod));

            oneOf(httpClient).executeMethod(with(any(HttpMethodBase.class)));
            will(returnValue(status.value()));

            allowing(httpMethod).addRequestHeader(with(any(Header.class)));
            will(new Action() {

                @Override
                public Object invoke(Invocation invocation) throws Throwable {
                    Header header = (Header) invocation.getParameter(0);
                    proxyRequestHeaders.add(header);
                    return null;
                }

                @Override
                public void describeTo(Description arg0) {
                }

            });

            allowing(httpMethod).getRequestHeaders();
            will(new Action() {

                @Override
                public Object invoke(Invocation invocation) throws Throwable {
                    return proxyRequestHeaders.toArray(new Header[] {});
                }

                @Override
                public void describeTo(Description arg0) {
                }

            });

            allowing(httpMethod).getResponseHeaders();
            will(new Action() {

                @Override
                public Object invoke(Invocation invocation) throws Throwable {
                    return proxyResponseHeaders.toArray(new Header[] {});
                }

                @Override
                public void describeTo(Description arg0) {
                }

            });

            allowing(httpMethod).getResponseHeaders(with(any(String.class)));
            will(new Action() {

                @Override
                public Object invoke(Invocation invocation) throws Throwable {
                    String name = (String) invocation.getParameter(0);
                    List<Header> result = new ArrayList<Header>();
                    for (Header h : proxyResponseHeaders) {
                        if (h.getName().equals(name)) {
                            result.add(h);
                        }
                    }
                    return result.toArray(new Header[] {});
                }

                @Override
                public void describeTo(Description arg0) {
                }

            });

            allowing(httpMethod).getResponseBodyAsStream();
            will(returnValue(proxyResponseInputStream));

            allowing(httpMethod);

        }
    });

}

From source file:fi.csc.kapaVirtaAS.VirtaXRoadEndpoint.java

@RequestMapping(value = "/ws", method = RequestMethod.POST)
public ResponseEntity<String> getVirtaResponse(@RequestBody String XRoadRequestMessage) throws Exception {
    FaultMessageService faultMessageService = new FaultMessageService();
    MessageTransformer messageTransformer = new MessageTransformer(conf, faultMessageService);
    VirtaClient virtaClient = new VirtaClient(conf);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(new MediaType("text", "xml", Charsets.UTF_8));
    HttpResponse virtaResponse;/*from w ww .j  a v  a 2s.co m*/

    try {
        String virtaRequestMessage = messageTransformer.transform(XRoadRequestMessage,
                MessageTransformer.MessageDirection.XRoadToVirta);
        //Send transformed SOAP-request to Virta
        virtaResponse = virtaClient.getVirtaWS(virtaRequestMessage,
                messageTransformer.createAuthenticationString(XRoadRequestMessage));
    } catch (Exception e) {
        log.error(e.toString());
        HttpStatus errorStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        String errorMessage = ERROR_MESSAGE;
        if (e instanceof DOMException) {
            errorStatus = HttpStatus.BAD_REQUEST;
            errorMessage = "Request SOAP-headers did not contain client identifiers (http://x-road.eu/xsd/identifiers)";
        }
        return new ResponseEntity<>(faultMessageService.generateSOAPFault(errorMessage,
                faultMessageService.getReqValidFail(), messageTransformer.getXroadHeaderElement()), httpHeaders,
                errorStatus);
    }

    try {
        if (virtaResponse.getStatusLine().getStatusCode() != 200) {
            log.error(virtaResponse.getStatusLine().getReasonPhrase());
            throw new HttpResponseException(virtaResponse.getStatusLine().getStatusCode(),
                    virtaResponse.getStatusLine().getReasonPhrase());
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(virtaResponse.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        String virtaResponseMessage = result.toString();

        return new ResponseEntity<>(messageTransformer.transform(virtaResponseMessage,
                MessageTransformer.MessageDirection.VirtaToXRoad), httpHeaders, HttpStatus.OK);
    } catch (Exception e) {
        log.error(e.toString());
        HttpStatus status = HttpStatus.valueOf(virtaResponse.getStatusLine().getStatusCode());
        if (status.value() == 200) {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
        } else if (IOUtils.toString(virtaResponse.getEntity().getContent()).toLowerCase()
                .contains("access denied")) {
            status = HttpStatus.FORBIDDEN;
        }
        return new ResponseEntity<>(
                faultMessageService.generateSOAPFault(ERROR_MESSAGE + status.name(),
                        faultMessageService.getResValidFail(), messageTransformer.getXroadHeaderElement()),
                httpHeaders, status);
    }
}

From source file:it.infn.mw.iam.api.scim.controller.ScimExceptionHandler.java

private ScimErrorResponse buildErrorResponse(HttpStatus status, String message) {

    return new ScimErrorResponse(status.value(), message);
}

From source file:it.infn.mw.iam.core.web.IamErrorController.java

@RequestMapping(PATH)
public ModelAndView error(HttpServletRequest request) {

    ModelAndView errorPage = new ModelAndView(IAM_ERROR_VIEW);

    HttpStatus status = HttpStatus.valueOf(getErrorCode(request));

    errorPage.addObject("errorMessage", String.format("%d. %s", status.value(), status.getReasonPhrase()));

    Exception exception = getRequestException(request);

    if (exception != null) {
        errorPage.addObject("exceptionMessage", exception.getMessage());
        errorPage.addObject("exceptionStackTrace", ExceptionUtils.getStackTrace(exception).trim());
    }/*www . ja v  a2s  . co  m*/
    return errorPage;
}

From source file:org.apache.metron.rest.controller.RestExceptionHandler.java

@ExceptionHandler(RestException.class)
@ResponseBody//  www  . j ava  2s  .c om
ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
    HttpStatus status = getStatus(request);
    LOG.error("Encountered error: " + ex.getMessage(), ex);
    return new ResponseEntity<>(
            new RestError(status.value(), ex.getMessage(), ExceptionUtils.getRootCauseMessage(ex)), status);
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimGroupEndpointsMockMvcTests.java

private ResultActions[] addAndDeleteMemberstoZoneManagementGroups(String displayName, HttpStatus create,
        HttpStatus delete) throws Exception {
    ResultActions[] result = new ResultActions[2];
    IdentityZone zone = utils().createZoneUsingWebRequest(getMockMvc(), identityClientToken);
    ScimGroupMember member = new ScimGroupMember(scimUser.getId());
    ScimGroup group = new ScimGroup(String.format(displayName, zone.getId()));
    group.setMembers(Arrays.asList(member));

    result[0] = createZoneScope(group);//ww  w . j  a  va  2  s . c om
    result[0].andExpect(status().is(create.value()));

    if (delete != null) {
        result[1] = deleteZoneScope(zone, group);
        result[1].andExpect(status().is(delete.value()));
    }
    return result;
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimGroupEndpointsTests.java

private void validateView(View view, HttpStatus status) {
    MockHttpServletResponse response = new MockHttpServletResponse();
    try {//from  www. j  a v  a 2 s.  com
        view.render(new HashMap<String, Object>(), new MockHttpServletRequest(), response);
        assertNotNull(response.getContentAsString());
    } catch (Exception e) {
        fail("view should render correct status and body");
    }
    assertEquals(status.value(), response.getStatus());
}

From source file:org.fao.geonet.api.userfeedback.UserFeedbackAPI.java

/**
 * Prints the output message.// w ww  .j  a va  2 s. c om
 *
 * @param response the response
 * @param code the code
 * @param message the message
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void printOutputMessage(final HttpServletResponse response, final HttpStatus code, final String message)
        throws IOException {
    response.setStatus(code.value());
    final PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    out.println(message);
    response.flushBuffer();
}

From source file:org.finra.dm.service.helper.DmErrorInformationExceptionHandler.java

/**
 * Gets a new error information based on the specified message and sets the HTTP status on the HTTP response.
 *
 * @param httpStatus the status of the error.
 * @param exception the exception whose message will be used.
 * @param response the optional HTTP response that will have its status set from the specified httpStatus.
 *
 * @return the error information.//w  w w . j  a  v  a2  s. c o  m
 */
private ErrorInformation getErrorInformationAndSetStatus(HttpStatus httpStatus, Throwable exception,
        HttpServletResponse response) {
    // Set the status one response if one was passed in.
    if (response != null) {
        response.setStatus(httpStatus.value());
    }

    // Get the error information based on the status and error message.
    return getErrorInformation(httpStatus, exception);
}