Example usage for javax.servlet.http HttpServletResponse setStatus

List of usage examples for javax.servlet.http HttpServletResponse setStatus

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setStatus.

Prototype

public void setStatus(int sc);

Source Link

Document

Sets the status code for this response.

Usage

From source file:pdl.web.filter.JsonBasicAuthenticationEP.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\"");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    PrintWriter writer = response.getWriter();
    writer.printf("Error(%s) - %s", HttpServletResponse.SC_UNAUTHORIZED, "Bad credentials");
}

From source file:de.yaio.services.webshot.server.controller.WebshotController.java

@ExceptionHandler(value = { Exception.class, RuntimeException.class, IOException.class })
public void handleAllException(final HttpServletRequest request, final Exception e,
        final HttpServletResponse response) {
    LOGGER.info("Exception while running request:" + createRequestLogMessage(request), e);
    response.setStatus(SC_INTERNAL_SERVER_ERROR);
    try {//  w  w  w .  j a  v a  2  s . c  o  m
        response.getWriter().append("exception while webshoting for requested resource");
    } catch (IOException ex) {
        LOGGER.warn("exception while exceptionhandling", ex);
    }
}

From source file:no.dusken.momus.exceptions.ExceptionHandler.java

@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response,
        Object o, Exception e) {

    if (e instanceof RestException) { // If it's our exception, we know how to handle it and has set a status
        response.setStatus(((RestException) e).getStatus());
    } else if (e instanceof AccessDeniedException) { // let Spring handle it by throwing it again
        throw (AccessDeniedException) e;
    } else if (e instanceof AuthenticationException) { // let Spring handle it, is a failed login
        throw (AuthenticationException) e;
    } else { // Something else, log it and set status to internal server error
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        logException(e);/*from   w w  w . j  a va2 s  .c  o  m*/
    }

    ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
    mav.addObject("error", e.getMessage());

    return mav;
}

From source file:org.magnum.mobilecloud.video.AppController.java

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}", method = RequestMethod.GET)
public @ResponseBody Video getVideo(@PathVariable("id") Long id, HttpServletResponse response) {

    Video v = videos.findOne(id);//  w  ww  . j  a  v  a 2  s.co m
    if (null == v) {
        response.setStatus(404);
        return null;
    }

    response.setStatus(200);
    return v;
}

From source file:org.ngrinder.infra.spring.Redirect404DispatcherServlet.java

/**
 * Redirect to error 404 when the /svn/ is not included in the path.
 *
 * @param request  current HTTP requests
 * @param response current HTTP response
 * @throws Exception if preparing the response failed
 *//*  ww  w  .  j  ava2s.  co m*/
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (!request.getPathInfo().startsWith("/svn/")) {
        if (request.getPathInfo().contains("/api")) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setContentType("application/json; charset=UTF-8");
            String requestUri = urlPathHelper.getRequestUri(request);
            JsonObject object = new JsonObject();

            object.addProperty(JSON_SUCCESS, false);
            object.addProperty(JSON_CAUSE,
                    "API URL " + requestUri + " [" + request.getMethod() + "] does not exist.");
            response.getWriter().write(gson.toJson(object));
            response.flushBuffer();
        } else {
            if (pageNotFoundLogger.isWarnEnabled()) {
                String requestUri = urlPathHelper.getRequestUri(request);
                pageNotFoundLogger.warn("No mapping found for HTTP request with URI [" + requestUri
                        + "] in DispatcherServlet with name '" + getServletName() + "'");
            }
            response.sendRedirect("/error_404");
        }
    }
}

From source file:org.smigo.species.SpeciesController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/rest/species/{id:\\d+}", method = RequestMethod.PUT)
@ResponseBody//from  w ww. jav  a2s.c om
public Object updateSpecies(@Valid @RequestBody Species species, BindingResult result, @PathVariable int id,
        @AuthenticationPrincipal AuthenticatedUser user, HttpServletResponse response, Locale locale) {
    log.info("Updating species. Species:" + species);
    if (result.hasErrors()) {
        response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
        return result.getAllErrors();
    }
    Review review = speciesHandler.updateSpecies(id, species, user);
    if (review == Review.MODERATOR) {
        response.setStatus(HttpStatus.ACCEPTED.value());
    }
    return speciesHandler.getSpecies(id);
}

From source file:org.vbossica.springbox.metrics.MetricsController.java

@RequestMapping(value = "/metrics/metrics", method = RequestMethod.GET)
public void process(
        @RequestParam(value = "pretty", required = false, defaultValue = "true") boolean prettyPrint,
        HttpServletResponse resp) throws IOException {
    resp.setContentType("application/json");
    resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
    resp.setStatus(HttpServletResponse.SC_OK);

    final OutputStream output = resp.getOutputStream();
    try {/*from   ww  w.j ava 2  s. co m*/
        (prettyPrint ? mapper.writerWithDefaultPrettyPrinter() : mapper.writer()).writeValue(output, registry);
    } finally {
        output.close();
    }
}

From source file:ar.com.zauber.commons.spring.servlet.view.PermanentlyRedirectView.java

/** @see RedirectView#sendRedirect() */
@Override//from ww  w  .  java  2  s  .c  o m
protected final void sendRedirect(final HttpServletRequest request, final HttpServletResponse response,
        final String targetUrl, final boolean http10Compatible) throws IOException {

    if (request.getMethod().toLowerCase().equals("get")) {
        response.setStatus(301);
        response.setHeader("Location", response.encodeRedirectURL(targetUrl));
    } else {
        super.sendRedirect(request, response, targetUrl, http10Compatible);
    }
}

From source file:com.thoughtworks.go.server.newsecurity.filters.AccessTokenAuthenticationFilter.java

private void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        String errorMessage) throws IOException {
    response.setStatus(SC_UNAUTHORIZED);
    ContentTypeAwareResponse contentTypeAwareResponse = new ContentTypeNegotiationMessageRenderer()
            .getResponse(request);//from   w w  w  .  j a v a 2  s  .  c o m
    response.setCharacterEncoding("utf-8");
    response.setContentType(contentTypeAwareResponse.getContentType().toString());
    response.getOutputStream().print(contentTypeAwareResponse.getFormattedMessage(errorMessage));
}

From source file:de.devbliss.apitester.dummyserver.DummyRequestHandler.java

private void handleGet(String path, HttpServletResponse response) throws IOException {

    try {//from   w ww  .  j  a v  a2s . c  om
        int desiredResponseCode = parseDesiredResponseCode(path);
        response.setStatus(desiredResponseCode);
        response.setContentType(CONTENT_TYPE);

        if (desiredResponseCode == HttpServletResponse.SC_OK) {
            response.getWriter().write(gson.toJson(DummyDto.createSampleInstance()));
        }
    } catch (Exception e) {
        handleException(e, response);
    }
}