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:com.nagarro.core.resolver.RestHandlerExceptionResolver.java

@Override
protected ModelAndView doResolveException(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler, final Exception ex) {
    if (statusCodeMappings.containsKey(ex.getClass().getSimpleName())) {
        response.setStatus(statusCodeMappings.get(ex.getClass().getSimpleName()).intValue());
    } else {/* ww w.ja  va 2 s .  co m*/
        response.setStatus(DEFAULT_STATUS_CODE);
    }
    logger.warn(
            "Translating exception [" + ex.getClass().getName() + "]: " + YSanitizer.sanitize(ex.getMessage()));
    logger.error(ExceptionUtils.getStackTrace(ex));

    final List<ErrorWsDTO> errorList;
    if (ex instanceof WebserviceValidationException) {
        errorList = getWebserviceErrorFactory()
                .createErrorList(((WebserviceValidationException) ex).getValidationObject());
    } else {
        errorList = getWebserviceErrorFactory().createErrorList(ex);
    }
    final ErrorListWsDTO errorListDto = new ErrorListWsDTO();
    errorListDto.setErrors(errorList);

    final ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(request);
    final ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response);

    try {
        return writeWithMessageConverters(errorListDto, inputMessage, outputMessage);
    } catch (final Exception handlerException) {
        logger.error("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
    }
    return null;
}

From source file:eu.stratosphere.nephele.jobmanager.web.QosStatisticsServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/* www . java2s . c o m*/
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("application/json");

        JSONObject jobs = new JSONObject();
        JobID job;
        long startTimestamp = -1;

        if (req.getParameter("job") != null && !req.getParameter("job").isEmpty())
            job = JobID.fromHexString(req.getParameter("job"));
        else
            job = getLastCreatedJob();

        if (req.getParameter("startTimestamp") != null && !req.getParameter("startTimestamp").isEmpty())
            startTimestamp = Long.parseLong(req.getParameter("startTimestamp"));

        for (JobID id : jobStatistics.keySet()) {
            JSONObject jobDetails = jobStatistics.get(id).getJobMetadata();

            if (job != null && job.equals(id)) {
                if (startTimestamp > 0)
                    jobStatistics.get(id).getStatistics(jobDetails, startTimestamp);
                else
                    jobStatistics.get(id).getStatistics(jobDetails);
            }

            jobs.put(id.toString(), jobDetails);
        }

        JSONObject result = new JSONObject();
        if (job != null && jobStatistics.containsKey(job)) {
            result.put("currentJob", job);
            result.put("refreshInterval", jobStatistics.get(job).getRefreshInterval());
            result.put("maxEntriesCount", jobStatistics.get(job).getMaxEntriesCount());
        } else {
            result.put("refreshInterval", INITIAL_REFRESH_INTERVAL);
            result.put("maxEntriesCount", 0);
        }
        result.put("jobs", jobs);
        result.write(resp.getWriter());

    } catch (JSONException e) {
        LOG.error("JSON Error: " + e.getMessage(), e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.setContentType("application/json");
        resp.getWriter().println("{ status: \"internal error\", message: \"" + e.getMessage() + "\" }");
    }
}

From source file:com.google.gwt.benchmark.dashboard.server.servlets.AddBenchmarkResultServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String auth = req.getHeader("auth");
    if (!authController.validateAuth(auth)) {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;//w w w  . ja v  a  2  s . c om
    }

    BenchmarkRunJson benchmarkRunJSON = null;
    String json = null;
    try {
        json = IOUtils.toString(req.getInputStream(), "UTF-8");
        AutoBean<BenchmarkRunJson> bean = AutoBeanCodex.decode(JsonFactory.get(), BenchmarkRunJson.class, json);
        benchmarkRunJSON = bean.as();
    } catch (Exception e) {
        logger.log(Level.WARNING, "Can not deserialize JSON", e);
        if (json != null) {
            logger.warning(json);
        }
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Can't parse JSON, see App Engine log for details.");
        return;
    }

    try {

        benchmarkController.addBenchmarkResult(benchmarkRunJSON);
        resp.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        logger.log(Level.WARNING, "Can not add benchmark results", e);
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

private void handlePostPatchPut(String target, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    try {/*from w ww  .  ja  va  2s .c om*/
        int desiredResponseCode = parseDesiredResponseCode(target);
        response.setStatus(desiredResponseCode);
        response.setContentType(CONTENT_TYPE);

        if (desiredResponseCode == HttpServletResponse.SC_OK) {
            String requestBody = IOUtils.toString(request.getInputStream());
            response.getWriter().write(requestBody);
        }
    } catch (Exception e) {
        handleException(e, response);
    }
}

From source file:com.github.dbourdette.otto.web.controller.api.ApiController.java

@RequestMapping(value = "/api/sources/{name}/events", method = RequestMethod.POST)
public void post(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) {
    remoteEventsFacade.post(name, copyParams(request));

    response.setStatus(200);
}

From source file:com.okta.scim.UsersController.java

/**
 * Creates new {@link User} with given attributes
 *
 * @param params JSON {@link Map} of {@link User} attributes
 * @param response HTTP response//from   www . j av  a  2  s. com
 * @return JSON {@link Map} of {@link User}
 */
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Map usersPost(@RequestBody Map<String, Object> params, HttpServletResponse response) {

    User newUser = new User(params);
    newUser.id = UUID.randomUUID().toString();
    db.save(newUser);
    response.setStatus(201);
    return newUser.toScimResource();
}

From source file:jp.eisbahn.oauth2.server.spi.servlet.ProtectedResourceFilter.java

/**
 * Check the request for whether can access or not to APIs to access the protected
 * resource.//from   www  . j  a  va 2s  .co m
 * 
 * @param req The request object.
 * @param resp The response object.
 * @param chain The chain object to chain some filters.
 * @exception IOException When the error regarding I/O occurred.
 * @exception ServletException When the first argument is not a HttpServletRequest
 * instance.
 */
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (req instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) req;
        HttpServletRequestAdapter adapter = new HttpServletRequestAdapter(httpRequest);
        try {
            Response response = protectedResource.handleRequest(adapter);
            req.setAttribute("client_id", response.getClientId());
            req.setAttribute("remote_user", response.getRemoteUser());
            req.setAttribute("scope", response.getScope());
            chain.doFilter(req, resp);
        } catch (OAuthError e) {
            if (resp instanceof HttpServletResponse) {
                HttpServletResponse httpResponse = (HttpServletResponse) resp;
                httpResponse.setStatus(e.getCode());
                List<String> params = new ArrayList<String>();
                params.add("error=\"" + e.getType() + "\"");
                if (StringUtils.isNotBlank(e.getDescription())) {
                    params.add("error_description=\"" + e.getDescription() + "\"");
                }
                String error = StringUtils.join(params, ", ");
                httpResponse.setHeader("WWW-Authenticate", "Bearer " + error);
            } else {
                throw new ServletException("This filter is available under HTTP Servlet container.");
            }
        }
    } else {
        throw new ServletException("This filter is available under HTTP Servlet container.");
    }
}

From source file:tachyon.metrics.sink.MetricsServlet.java

private HttpServlet createServlet() {
    return new HttpServlet() {
        @Override/*from   w w  w  . j  a v  a 2  s .co  m*/
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType(String.format("text/json;charset=utf-8"));
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            String result = mObjectMapper.writeValueAsString(mMetricsRegistry);
            response.getWriter().println(result);
        }
    };
}

From source file:com.thinkberg.webdav.LockHandler.java

private void sendLockAcquiredResponse(HttpServletResponse response, Lock lock) throws IOException {
    if (!lock.getObject().exists()) {
        response.setStatus(SC_CREATED);
    }//from  w  ww .j  ava  2 s .  co m
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");
    response.setHeader(HEADER_LOCK_TOKEN, "<" + lock.getToken() + ">");

    Document propDoc = DocumentHelper.createDocument();
    Element propEl = propDoc.addElement(TAG_PROP, "DAV:");
    Element lockdiscoveryEl = propEl.addElement(TAG_LOCKDISCOVERY);

    lock.serializeToXml(lockdiscoveryEl);

    XMLWriter xmlWriter = new XMLWriter(response.getWriter());
    xmlWriter.write(propDoc);

    logXml(propDoc);
}

From source file:de.perdoctus.synology.jdadapter.controller.JdAdapter.java

@RequestMapping(value = "/flash", method = RequestMethod.GET)
public void enableFlashButton(final HttpServletResponse resp) throws IOException {
    LOG.info("Got Request from flash click'n'load button.");
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().print("JDownloader");
}