Example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN

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

Introduction

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

Prototype

int SC_FORBIDDEN

To view the source code for javax.servlet.http HttpServletResponse SC_FORBIDDEN.

Click Source Link

Document

Status code (403) indicating the server understood the request but refused to fulfill it.

Usage

From source file:com.acc.storefront.util.CSRFHandlerInterceptor.java

@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) throws Exception {

    if (shouldCheckCSRFTokenForRequest(request)) {
        // This is a POST request - need to check the CSRF token
        final String sessionToken = CSRFTokenManager.getTokenForSession(request.getSession());
        final String requestToken = CSRFTokenManager.getTokenFromRequest(request);
        if (sessionToken.equals(requestToken)) {
            return true;
        } else {/*from  w w  w  .j ava2 s.  c om*/
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Bad or missing CSRF value");
            return false;
        }
    } else {
        {
            // Not a POST - allow the request
            return true;
        }
    }
}

From source file:com.epam.cme.storefront.util.CSRFHandlerInterceptor.java

@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
        final Object handler) throws Exception {
    if (shouldCheckCSRFTokenForRequest(request)) {
        // This is a POST request - need to check the CSRF token
        final String sessionToken = CSRFTokenManager.getTokenForSession(request.getSession());
        final String requestToken = CSRFTokenManager.getTokenFromRequest(request);
        if (sessionToken.equals(requestToken)) {
            return true;
        } else {/*from  w  ww .  j  ava  2 s.  c  o  m*/
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Bad or missing CSRF value");
            return false;
        }
    } else {
        // Not a POST - allow the request
        return true;
    }
}

From source file:com.taobao.diamond.server.interceptor.FlowControlInterceptor.java

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    boolean handlerOk = super.preHandle(request, response, handler);
    if (handlerOk) {
        boolean fcAccess = doACLAndFlowControl(request, response);
        if (!fcAccess) {
            String remoteIp = getRemoteIP(request);
            String msg = remoteIp + ":trigger flow control:invoke per second:" + getCurrentCount(remoteIp);
            log.warn(msg);//w w  w .  j a  va 2 s.c  o m
            System.out.println(msg);
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "over_flow_control");
            return false;
        }
        return true;
    }
    return false;
}

From source file:fr.aliasource.webmail.server.invitation.GetInvitationInfoProxyImpl.java

@SuppressWarnings("unchecked")
@Override//from   w ww.j a v a  2s  .  c  o m
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    IAccount ac = (IAccount) req.getSession().getAttribute("account");

    if (ac == null) {
        GWT.log("Account not found in session", null);
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    PostMethod pm = new PostMethod(backendUrl);
    if (req.getQueryString() != null) {
        pm.setQueryString(req.getQueryString());
    }
    Map<String, String[]> params = req.getParameterMap();
    for (String p : params.keySet()) {
        String[] val = params.get(p);
        pm.setParameter(p, val[0]);
    }

    synchronized (hc) {
        try {
            int ret = hc.executeMethod(pm);
            if (ret != HttpStatus.SC_OK) {
                log("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
                resp.setStatus(ret);
            } else {
                InputStream is = pm.getResponseBodyAsStream();
                transfer(is, resp.getOutputStream(), false);
            }

        } catch (Exception e) {
            log("error occured on call proxyfication", e);
        } finally {
            pm.releaseConnection();
        }
    }
}

From source file:net.groupbuy.interceptor.TokenInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String token = WebUtils.getCookie(request, TOKEN_COOKIE_NAME);
    if (request.getMethod().equalsIgnoreCase("POST")) {
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
            if (token != null && token.equals(request.getHeader(TOKEN_PARAMETER_NAME))) {
                return true;
            } else {
                response.addHeader("tokenStatus", "accessDenied");
            }/*from   www  . java2 s. co  m*/
        } else {
            if (token != null && token.equals(request.getParameter(TOKEN_PARAMETER_NAME))) {
                return true;
            }
        }
        if (token == null) {
            token = UUID.randomUUID().toString();
            WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME, token);
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ERROR_MESSAGE);
        return false;
    } else {
        if (token == null) {
            token = UUID.randomUUID().toString();
            WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME, token);
        }
        request.setAttribute(TOKEN_ATTRIBUTE_NAME, token);
        return true;
    }
}

From source file:com.controller.email.GetEmailTagsServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w  ww .  ja  v  a  2s . c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    List<Map<String, Object>> tagsFromMandrill = MandrillApiHandler.getTags();
    List<Map<String, Object>> tagsFromMandrillForUser = new ArrayList<>();

    HttpSession session = request.getSession();
    if (session.getAttribute("UID") == null || StringUtils.isEmpty(session.getAttribute("UID").toString())) {
        Map<String, String> responseMap = new HashMap<>();
        responseMap.put("error", "user is not logged in");
        response.getWriter().write(new Gson().toJson(responseMap));
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    int userId = Integer.parseInt(session.getAttribute("UID").toString());
    Set<String> tagsForUser = EmailHistoryDAO.getTagsForUser(userId);
    for (Map<String, Object> mTag : tagsFromMandrill) {
        if (mTag.get("tag") != null) {
            if (tagsForUser.contains(mTag.get("tag").toString())) {
                tagsFromMandrillForUser.add(mTag);
            }
        }
    }
    response.getWriter().write(new Gson().toJson(tagsFromMandrillForUser));

    response.getWriter().flush();
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.controller.schedule.GetScheduledEmailDetailServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from www  .jav  a2  s.c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    HttpSession session = request.getSession();
    if (session.getAttribute("UID") == null) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "User is not logged in");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.getWriter().flush();
        return;
    }
    Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
    if (StringUtils.isEmpty(request.getParameter("schedule_id"))) {
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Schedule id is missing");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
        return;
    }

    try {
        Integer scheduleEmailId = Integer.parseInt(request.getParameter("schedule_id"));
        Map<String, Object> scheduleEmailDetails = ScheduleDAO.getScheduleEmailDetails(userId, scheduleEmailId);
        response.getWriter().write(AppConstants.GSON.toJson(scheduleEmailDetails));
        response.getWriter().flush();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (ParseException parse) {
        logger.log(Level.SEVERE, null, parse);
    } catch (NumberFormatException ex) {
        logger.log(Level.SEVERE, null, ex);
        Map<String, Object> error = new HashMap<>();
        error.put("error", "Schedule id cannot be parsed to integer");
        response.getWriter().write(AppConstants.GSON.toJson(error));
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().flush();
    } catch (SQLException ex) {
        Logger.getLogger(GetScheduledEmailDetailServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.craftercms.security.authorization.impl.AccessDeniedHandlerImplTest.java

@Test
public void testForwardToErrorPage() throws Exception {
    handler.setErrorPageUrl(ERROR_PAGE_URL);

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);

    handler.handle(context, new AccessDeniedException(""));

    assertEquals(ERROR_PAGE_URL, response.getForwardedUrl());
    assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatus());
}

From source file:ge.taxistgela.servlet.AdminServlet.java

public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    Admin admin = new Admin();

    if (admin.checkLogin(username, password)) {
        request.getSession().setAttribute(Admin.class.getName(), admin);

        response.setStatus(HttpServletResponse.SC_OK);
        response.sendRedirect("/admin.jsp");

        return;/*from ww  w. j  a  v a2 s .  c om*/
    }

    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}

From source file:net.shopxx.interceptor.TokenInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String token = WebUtils.getCookie(request, TOKEN_COOKIE_NAME);
    if (StringUtils.equalsIgnoreCase(request.getMethod(), "POST")) {
        if (StringUtils.isNotEmpty(token)) {
            String requestType = request.getHeader("X-Requested-With");
            if (StringUtils.equalsIgnoreCase(requestType, "XMLHttpRequest")) {
                if (StringUtils.equals(token, request.getHeader(TOKEN_PARAMETER_NAME))) {
                    return true;
                } else {
                    response.addHeader("tokenStatus", "accessDenied");
                }/*from  w ww.  j av  a  2s .  com*/
            } else {
                if (StringUtils.equals(token, request.getParameter(TOKEN_PARAMETER_NAME))) {
                    return true;
                }
            }
        } else {
            WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME,
                    DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30)));
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ERROR_MESSAGE);
        return false;
    } else {
        if (StringUtils.isEmpty(token)) {
            token = DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30));
            WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME, token);
        }
        request.setAttribute(TOKEN_ATTRIBUTE_NAME, token);
        return true;
    }
}