Java Code Examples for javax.servlet.http.HttpServletResponse.setStatus()

The following are Jave code examples for showing how to use setStatus() of the javax.servlet.http.HttpServletResponse class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: service-hive   File: RateLimitZuulFilter.java   View Source Code Vote up 9 votes
@Override
public Object run() {

    try {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();

        if (!rateLimiter.tryAcquire()) {
            HttpStatus httpStatus = HttpStatus.TOO_MANY_REQUESTS;

            response.setContentType(MediaType.TEXT_PLAIN_VALUE);
            response.setStatus(httpStatus.value());
            ctx.setResponseStatusCode(httpStatus.value());
            ctx.setSendZuulResponse(false);
        }
    } catch (Exception e) {
        ReflectionUtils.rethrowRuntimeException(e);
    }
    return null;
}
 
Example 2
Project: alfresco-remote-api   File: BaseKerberosAuthenticationFilter.java   View Source Code Vote up 9 votes
/**
 * The logon to start again
 *
 * @param context ServletContext
 * @param req HttpServletRequest
 * @param resp HttpServletResponse
 * @param ignoreFallback ignore fallback
 * @throws IOException
 */
private void logonStartAgain(ServletContext context, HttpServletRequest req, HttpServletResponse resp, boolean ignoreFallback) throws IOException
    {
    if (getLogger().isDebugEnabled())
        getLogger().debug("Issuing login challenge to browser.");
    // Force the logon to start again
    resp.setHeader("WWW-Authenticate", "Negotiate");
    
    if (!ignoreFallback && isFallbackEnabled())
    {
        includeFallbackAuth(context, req, resp);
    }
    
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    writeLoginPageLink(context, req, resp);
    resp.flushBuffer();
}
 
Example 3
Project: Monsters_Portal   File: PedidoController.java   View Source Code Vote up 8 votes
@RequestMapping("Admin/RestorePedido")
public void restore(HttpSession session, Long id, HttpServletResponse response) {
	if(Permissoes.checar(session, EnumMetodo.RESTAURAR, entidade)){			//	Consulta a permissão
		dao.restore(id);													//	Ação no banco
		relatorio.gerarRelatorio(session, EnumMetodo.RESTAURAR, entidade);	//	Gera Relatório e armazena no banco
		response.setStatus(200);											//	Indica para a requisição AJAX que tudo ocorreu bem
	}
}
 
Example 4
Project: hauth-java   File: RoleController.java   View Source Code Vote up 7 votes
@RequestMapping(value = "/auth/batch", method = RequestMethod.POST)
public String batchAuth(HttpServletResponse response, HttpServletRequest request) {
    String modifyUserId = JwtService.getConnUser(request).getUserId();
    String json = request.getParameter("JSON");
    List<UserRoleEntity> list = new ParseJson<UserRoleEntity>().toList(json);
    try {
        int size = roleService.batchAuth(list, modifyUserId);
        if (1 == size) {
            return Hret.success(200, "success", null);
        }
        response.setStatus(422);
        return Hret.error(422, "授权失败,用户已经拥有了这个角色", null);
    } catch (Exception e) {
        logger.info(e.getMessage());
        response.setStatus(421);
        return Hret.error(421, "授权失败,用户已经拥有了这个角色", null);
    }
}
 
Example 5
Project: graphouse   File: MetricSearchServlet.java   View Source Code Vote up 6 votes
private void search(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String query = req.getParameter("query");
    final PrintWriter writer = resp.getWriter();

    if (query == null || query.isEmpty()) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        writer.println("Usage:\n" +
            "GET /search?query=<search_query>\n" +
            "POST /search (body: search=<url_encoded_search_query>)");
        return;
    }

    metricSearch.search(query, writer);
}
 
Example 6
Project: JAVA-   File: MaliciousRequestInterceptor.java   View Source Code Vote up 6 votes
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
		throws Exception {
	response.setHeader("Access-Control-Allow-Origin", "*");
	response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
	response.setHeader("Access-Control-Allow-Headers",
			"x-requested-with,Access-Control-Allow-Origin,EX-SysAuthToken,EX-JSESSIONID");

	String url = request.getServletPath();
	if (url.endsWith("/unauthorized") || url.endsWith("/forbidden")) {
		return super.preHandle(request, response, handler);
	}
	HttpSession session = request.getSession();
	String preRequest = (String) session.getAttribute(Constants.PREREQUEST);
	Long preRequestTime = (Long) session.getAttribute(Constants.PREREQUEST_TIME);
	if (preRequestTime != null && preRequest != null) { // 过滤频繁操作
		if ((url.equals(preRequest) || allRequest)
				&& System.currentTimeMillis() - preRequestTime < minRequestIntervalTime) {
			Integer maliciousRequestTimes = (Integer) session.getAttribute(Constants.MALICIOUS_REQUEST_TIMES);
			if (maliciousRequestTimes == null) {
				maliciousRequestTimes = 1;
			} else {
				maliciousRequestTimes++;
			}
			session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, maliciousRequestTimes);
			if (maliciousRequestTimes > maxMaliciousTimes) {
				response.setStatus(HttpCode.MULTI_STATUS.value());
				logger.warn("To intercept a malicious request : {}", url);
				return false;
			}
		} else {
			session.setAttribute(Constants.MALICIOUS_REQUEST_TIMES, 0);
		}
	}
	session.setAttribute(Constants.PREREQUEST, url);
	session.setAttribute(Constants.PREREQUEST_TIME, System.currentTimeMillis());
	return super.preHandle(request, response, handler);
}
 
Example 7
Project: NEILREN4J   File: ErrorController.java   View Source Code Vote up 6 votes
@RequestMapping(value = "*")
public ModelAndView error404(HttpServletResponse response) {
    ModelAndView mv = new ModelAndView();
    mv.setViewName("error/404");
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    return mv;
}
 
Example 8
Project: hauth-java   File: OrgController.java   View Source Code Vote up 6 votes
@RequestMapping(method = RequestMethod.PUT)
public String update(HttpServletResponse response, HttpServletRequest request) {
    OrgEntity orgEntity = parse(request);
    RetMsg retMsg = orgService.update(orgEntity);
    if (retMsg.checkCode()) {
        return Hret.success(retMsg);
    }
    response.setStatus(retMsg.getCode());
    return Hret.error(retMsg);
}
 
Example 9
Project: springboot-shiro-cas-mybatis   File: JsonViewUtils.java   View Source Code Vote up 6 votes
/**
 * Render model and view. Sets the response status to OK.
 *
 * @param response the response
 */
public static void render(final HttpServletResponse response) {
    try {
        final Map<String, Object> map = new HashMap<>();
        response.setStatus(HttpServletResponse.SC_OK);
        render(map, response);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example 10
Project: parabuild-ci   File: ExceptionHandler.java   View Source Code Vote up 6 votes
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    // Allow Jetty RequestRetry exception to propogate to container
    Continuation.rethrowIfContinuation(cause);

    log.warn("Error: " + cause);
    if (cause instanceof SecurityException && log.isDebugEnabled())
    {
        log.debug("- User Agent: " + request.getHeader(HttpConstants.HEADER_USER_AGENT));
        log.debug("- Remote IP:  " + request.getRemoteAddr());
        log.debug("- Request URL:" + request.getRequestURL());
        log.debug("- Query:      " + request.getQueryString());
        log.debug("- Method:     " + request.getMethod());
    }

    // We are going to act on this in engine.js so we are hoping that
    // that SC_NOT_IMPLEMENTED (501) is not something that the servers
    // use that much. I would have used something unassigned like 506+
    // But that could cause future problems and might not get through
    // proxies and the like
    response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    response.setContentType(MimeConstants.MIME_HTML);
    PrintWriter out = response.getWriter();
    out.println(cause.getMessage());

    log.warn("Sent 501", cause);
}
 
Example 11
Project: graphouse   File: MonitoringServlet.java   View Source Code Vote up 6 votes
private void ping(HttpServletResponse resp) throws IOException {
    if (allowColdRun || metricSearch.isMetricTreeLoaded()) {
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.getWriter().print("0;OK");
        return;
    }

    resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    resp.getWriter().println("2;Metric tree not loaded ");
}
 
Example 12
Project: scoold   File: FeedbackController.java   View Source Code Vote up 6 votes
@PostMapping({"/{id}", "/{id}/{title}"})
public String replyAjax(@PathVariable String id, @PathVariable(required = false) String title,
		HttpServletRequest req, HttpServletResponse res, Model model) throws IOException {
	Post showPost = pc.read(id);
	Profile authUser = utils.getAuthUser(req);
	if (showPost != null && !showPost.isClosed() && !showPost.isReply()) {
		//create new answer
		Reply answer = utils.populate(req, new Reply(), "body");
		Map<String, String> error = utils.validate(answer);
		if (!error.containsKey("body")) {
			answer.setTitle(showPost.getTitle());
			answer.setCreatorid(authUser.getId());
			answer.setParentid(showPost.getId());
			answer.create();

			showPost.setAnswercount(showPost.getAnswercount() + 1);
			if (showPost.getAnswercount() >= MAX_REPLIES_PER_POST) {
				showPost.setCloserid("0");
			}
			// update without adding revisions
			pc.update(showPost);
			utils.addBadgeAndUpdate(authUser, Profile.Badge.EUREKA, answer.getCreatorid().equals(showPost.getCreatorid()));
			answer.setAuthor(authUser);
			model.addAttribute("showPost", showPost);
			model.addAttribute("answerslist", Collections.singletonList(answer));
			return "reply";
		}
	}
	if (utils.isAjaxRequest(req)) {
		res.setStatus(200);
		return "base";
	} else {
		return "redirect:" + FEEDBACKLINK + "/" + id;
	}
}
 
Example 13
Project: batch-scheduler   File: UserController.java   View Source Code Vote up 6 votes
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(HttpServletResponse response, HttpServletRequest request) {
    String json = request.getParameter("JSON");
    List<UserEntity> list = new GsonBuilder().create().fromJson(json,
            new TypeToken<List<UserEntity>>() {
            }.getType());
    int size = userService.delete(list);
    if (size == 1) {
        return Hret.success(200, "success", null);
    }
    response.setStatus(421);
    return Hret.error(421, "删除用户信息失败, 请联系管理员", null);
}
 
Example 14
Project: scalable-task-scheduler   File: ControllerExceptionHandler.java   View Source Code Vote up 6 votes
@ExceptionHandler({RequestValidationException.class})
@ResponseBody
public ExceptionResponse handleRequestValidationException(GenericException ex, HttpServletRequest request,
                                                          HttpServletResponse httpResponse) {
    log.error("Request validation exception occurred :", ex);
    ExceptionResponse exception = new ExceptionResponse();
    exception.setCode(ex.getErrCode());
    exception.setMessage(ex.getErrMessage());
    httpResponse.setStatus(400);
    return exception;
}
 
Example 15
Project: ssm-rbac   File: GlobalExceptionHandler.java   View Source Code Vote up 6 votes
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,
                                     Object o, Exception e) {
    //自定义异常拦截
    if (e instanceof RuntimeException) {
        response.setStatus(IConstants.RBAC_AJAX_EXCEPTION);
    }
    //判断是否是ajax
    if (CommonUtils.isAsyncRequest(request)) {
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.write(e.getMessage());
            writer.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        return null;
    } else {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("message", e.getMessage());
        return new ModelAndView("public/errorPage", hashMap);
    }
}
 
Example 16
Project: logistimo-web-service   File: DashboardServlet.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
private static void getMonthlyUsageStatsForDomain(HttpServletRequest request,
                                                  HttpServletResponse response,
                                                  ResourceBundle backendMessages,
                                                  ResourceBundle messages) throws IOException {
  xLogger.fine("Entered getMonthlyUsageStatsForDomain");
  // Get the domain ID
  String domainIdStr = request.getParameter("domainid");
  String offsetStr = request.getParameter("offset");
  String sizeStr = request.getParameter("size");
  String startDateStr = request.getParameter("startdate");
  if (sizeStr == null || sizeStr.isEmpty() || startDateStr == null || startDateStr.isEmpty()
      || domainIdStr == null || domainIdStr.isEmpty()) {
    xLogger.severe(
        "One or more manadatory parameters or null or empty. offsetStr: {0}, sizeStr: {1}, startDateStr: {2}, domainIdStr: {3}",
        offsetStr, sizeStr, startDateStr, domainIdStr);
    response.setStatus(500);
    return;
  }
  Long domainId = null;
  Date startDate = null;
  int offset = 0;
  try {
    domainId = Long.parseLong(domainIdStr);
    SimpleDateFormat df = new SimpleDateFormat(Constants.DATE_FORMAT);
    startDate = df.parse(startDateStr);
    int size = Integer.parseInt(sizeStr);
    if (offsetStr != null) {
      offset = Integer.parseInt(offsetStr);
    }

    // Proceed only if the mandatory attributes are present.
    ReportsService rs = Services.getService("reports");
    PageParams pageParams = new PageParams(null, offset, size);
    Results results = rs.getMonthlyUsageStatsForDomain(domainId, startDate, pageParams);
    List<IMonthSlice> resultsList = results.getResults();
    if (resultsList != null && !resultsList.isEmpty()) {
      // From the List<MonthSlice> get UsageStats object
      UsageStats usageStats = new UsageStats(results);
      xLogger.info("usageStats: " + usageStats.toJSONString());
      // Convert the usageStats object to JSON and return it.
      writeText(response, usageStats.toJSONString());
    } else {
      xLogger.info("No results: {0}", resultsList);
      writeText(response, "{\"msg\": \"No results\" }");
    }
  } catch (Exception e) {
    xLogger.severe("{0} when trying to get monthly usage stats for domain {1}. Message: {2}",
        e.getClass().getName(), domainId, e.getMessage());
    response.setStatus(500);
  }
  xLogger.fine("Exiting getMonthlyUsageStatsForDomain");
}
 
Example 17
Project: appinventor-extensions   File: OdeAuthFilter.java   View Source Code Vote up 5 votes
/**
   * Filters using Google Accounts
   */
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest && response instanceof HttpServletResponse)) {
      throw new ServletException("Unsupported request type.");
    }

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    // Use Local Authentication
    // String userid = (String) httpRequest.getSession().getAttribute("userid");
    // Object isReadOnlyObject = httpRequest.getSession().getAttribute("readonly");
    // boolean isReadOnly = false;
    // if (isReadOnlyObject != null) {
    //   isReadOnly = (boolean) isReadOnlyObject;
    // }
    // LOG.info("isReadOnly = " + isReadOnly);
    // if (userid == null) {        // Invalid Login
    //   LOG.info("userid is null on login.");
    //   httpResponse.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
    //   return;
    // }

    // Use Local Authentication
    UserInfo userInfo = getUserInfo(httpRequest);
    if (userInfo == null) {        // Invalid Login
      if (DEBUG) {
        LOG.info("uinfo is null on login.");
      }
      // If the URI starts with /ode, then we are being invoked through
      // the App Inventor client. In that case we are in an XMLHttpRequest
      // (aka ajax) so we cannot send a redirect to the login page
      // instead we return SC_PRECONDITION_FAILED which tips off the
      // client that it needs to reload itself to the login page.
      String uri = httpRequest.getRequestURI();
      if (DEBUG) {
        LOG.info("Not Logged In: uri = " + uri);
      }
      if (uri.startsWith("/ode")) {
        httpResponse.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
      } else {
        httpResponse.sendRedirect("/login?redirect=" + uri);
      }
      return;
    }

    String userId = userInfo.userId;
    boolean isAdmin = userInfo.isAdmin;
    boolean isReadOnly = userInfo.isReadOnly;

//    Object oIsAdmin = httpRequest.getSession().getAttribute("isadmin");
//    if (oIsAdmin != null) {
//      isAdmin = (boolean) oIsAdmin;
//    }

    doMyFilter(userInfo, isAdmin, isReadOnly, httpRequest, httpResponse, chain);
  }
 
Example 18
Project: sporticus   File: HttpLogoutSuccessHandler.java   View Source Code Vote up 5 votes
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
		throws IOException {
	response.setStatus(HttpServletResponse.SC_OK);
	response.getWriter().flush();
}
 
Example 19
Project: lams   File: SAPI.java   View Source Code Vote up 5 votes
public static void status(HttpServletResponse res,
                          int sc)
{
    res.setStatus(sc);
}
 
Example 20
Project: springboot-shiro-cas-mybatis   File: JsonViewUtils.java   View Source Code Vote up 3 votes
/**
 * Render exceptions. Sets the response status accordingly to note bad requests.
 *
 * @param model the model
 * @param response the response
 */
private static void renderException(final Map model, final HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    model.put("status", HttpServletResponse.SC_BAD_REQUEST);
    render(model, response);
}