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:fr.aliasource.webmail.server.UploadAttachmentsImpl.java

@SuppressWarnings("rawtypes")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    RequestContext ctx = new ServletRequestContext(req);
    String enc = ctx.getCharacterEncoding();
    logger.warn("received encoding is " + enc);
    if (enc == null) {
        enc = "utf-8";
    }/*from www  .  ja v  a2s. c o  m*/
    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory(100 * 1024,
            new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(20 * 1024 * 1024);

    List items = null;
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException e1) {
        logger.error("upload exception", e1);
        return;
    }

    // Process the uploaded items
    String id = null;
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            id = item.getFieldName();
            String fileName = removePathElementsFromFilename(item.getName());
            logger.warn("FileItem: " + item);
            long size = item.getSize();
            logger.warn("pushing upload of " + fileName + " to backend for " + account.getLogin() + "@"
                    + account.getDomain() + " size: " + size + ").");
            AttachmentMetadata meta = new AttachmentMetadata();
            meta.setFileName(fileName);
            meta.setSize(size);
            meta.setMime(item.getContentType());
            try {
                account.uploadAttachement(id, meta, item.getInputStream());
            } catch (Exception e) {
                logger.error("Cannot write uploaded file to disk");
            }
        }
    }
}

From source file:com.dp2345.interceptor.MemberInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    HttpSession session = request.getSession();
    Principal principal = (Principal) session.getAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME);
    if (principal != null) {
        return true;
    } else {//from w  w w  .ja  va 2s . co  m
        // ajax
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
            // ajax
            response.addHeader("loginStatus", "accessDenied");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return false;
        } else {
            //  GET
            if (request.getMethod().equalsIgnoreCase("GET")) {
                String redirectUrl = request.getQueryString() != null
                        ? request.getRequestURI() + "?" + request.getQueryString()
                        : request.getRequestURI();
                response.sendRedirect(request.getContextPath() + loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME
                        + "=" + URLEncoder.encode(redirectUrl, urlEscapingCharset));
            } else {
                //  POST
                response.sendRedirect(request.getContextPath() + loginUrl);
            }
            return false;
        }
    }
}

From source file:com.thinkberg.moxo.dav.MkColHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (request.getReader().readLine() != null) {
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        return;/*from   w  w  w  .  j  ava2  s  . c  o  m*/
    }

    FileObject object = getResourceManager().getFileObject(request.getPathInfo());

    try {
        LockManager.getInstance().checkCondition(object, getIf(request));
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    if (object.exists()) {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    if (!object.getParent().exists() || !FileType.FOLDER.equals(object.getParent().getType())) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }

    try {
        object.createFolder();
        response.setStatus(HttpServletResponse.SC_CREATED);
    } catch (FileSystemException e) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:nl.surfnet.spring.security.opensaml.AuthenticationFailureHandlerImpl.java

public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authenticationException) throws IOException, ServletException {

    SavedRequest savedRequest = requestCache.getRequest(request, response);

    logger.debug("saved Request: {}", savedRequest);

    if (authenticationException instanceof IdentityProviderAuthenticationException && savedRequest != null) {

        logger.warn("Authn Failure reported by the IDP.", authenticationException);
        logger.debug("Retry original request of {}", savedRequest.getRedirectUrl());
        response.sendRedirect(savedRequest.getRedirectUrl());
    } else {/*from  w  w w  .ja  v  a2s .  c  o  m*/
        logger.warn("Unrecoverable authn failure. Sending to Forbidden", authenticationException);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:com.adanac.module.blog.filter.DynamicFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    String requestUri = StringUtil.replaceSlants(((HttpServletRequest) request).getRequestURI());
    try {//  w  w w  .java  2s . c o m
        Map<String, Object> data = FreemarkerHelper
                .buildCommonDataMap(FreemarkerHelper.getNamespace(requestUri), ViewMode.DYNAMIC);
        boolean forbidden = loginFilter(data, requestUri, request);
        if (forbidden) {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        String template = putCustomData(data, requestUri, request, response);
        response.setCharacterEncoding("UTF-8");
        FreemarkerHelper.generateByTemplatePath(template + ".ftl", response.getWriter(), data);
    } catch (Exception e) {
        throw new RuntimeException(requestUri, e);
    }
}

From source file:net.solarnetwork.central.dras.web.ControllerSupport.java

/**
 * SecurityException handler./* www. ja va  2 s .  c o  m*/
 * 
 * <p>Logs a WARN log and returns HTTP 403 (Forbidden).</p>
 * 
 * @param e the security exception
 * @param res the servlet response
 */
@ExceptionHandler(SecurityException.class)
public void handleSecurityException(SecurityException e, HttpServletResponse res) {
    if (log.isWarnEnabled()) {
        log.warn("Security exception: " + e.getMessage());
    }
    res.setStatus(HttpServletResponse.SC_FORBIDDEN);
}

From source file:org.openmrs.module.hl7query.web.controller.BaseHL7QueryController.java

@ExceptionHandler(APIAuthenticationException.class)
@ResponseBody/*from w  w  w. j  a v  a 2s  .co  m*/
public AuthenticationErrorObject apiAuthenticationExceptionHandler(Exception ex, HttpServletResponse response)
        throws Exception {
    if (Context.isAuthenticated()) {
        // user is logged in but doesn't have the relevant privilege -> 403 FORBIDDEN
        errorCode = HttpServletResponse.SC_FORBIDDEN;
        errorDetail = "User is logged in but doesn't have the relevant privilege";
    } else {
        // user is not logged in -> 401 UNAUTHORIZED
        errorCode = HttpServletResponse.SC_UNAUTHORIZED;
        errorDetail = "User is not logged in";
        response.addHeader("WWW-Authenticate", "Basic realm=\"OpenMRS at " + HL7QueryConstants.URI_PREFIX);
    }
    response.setStatus(errorCode);
    return ExceptionUtil.wrapErrorResponse(ex, errorDetail);
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from www.j  a  v  a2  s  .  com*/
 *
 * @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("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        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();
            response.setContentType("application/json");
            return;
        }
        Integer userId = Integer.parseInt(session.getAttribute("UID").toString());
        List<Map<String, Object>> requestBodyList = AppConstants.GSON
                .fromJson(new BufferedReader(request.getReader()), List.class);
        if (requestBodyList == null || requestBodyList.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "Request body is missing");
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        List<String> errorMessages = validateRequestBodyList(requestBodyList);
        if (!errorMessages.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMessages);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }

        for (Map<String, Object> requestBodyMap : requestBodyList) {
            String tokenDataString = requestBodyMap.get("token_data").toString();
            String type = requestBodyMap.get("type").toString();
            errorMessages.addAll(validateTokenData(tokenDataString, type));
            String metadataString = requestBodyMap.get("metadata").toString();
            errorMessages.addAll(validateMetadata(metadataString, type));
        }

        if (!errorMessages.isEmpty()) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", errorMessages);
            response.getWriter().write(AppConstants.GSON.toJson(error));
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().flush();
            return;
        }
        List<Map<String, Integer>> daoResponseList = new ArrayList<>();
        try (Connection conn = ConnectionManager.getInstance().getConnection()) {
            conn.setAutoCommit(false);
            try {
                for (Map<String, Object> requestBodyMap : requestBodyList) {
                    String tokenDataString = requestBodyMap.get("token_data").toString();
                    String metadataString = requestBodyMap.get("metadata").toString();
                    String schedule_id = (String) requestBodyMap.get("schedule_id");
                    Map<String, Integer> daoResponse = ScheduleSocialPostDAO.updateActionsToScheduleSocialPost(
                            userId, Integer.parseInt(schedule_id), requestBodyMap.get("image_name").toString(),
                            AppConstants.GSON.fromJson(tokenDataString, Map.class),
                            AppConstants.GSON.fromJson(metadataString, Map.class),
                            requestBodyMap.get("type").toString(), TemplateStatus.template_saved.toString(),
                            conn);
                    daoResponseList.add(daoResponse);
                }
                conn.commit();
            } catch (SQLException ex) {
                conn.rollback();
                throw ex;
            }
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().write(AppConstants.GSON.toJson(daoResponseList));
            response.getWriter().flush();

        } catch (SQLException ex) {
            Logger.getLogger(ScheduleSocialPostServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (Exception e) {
        Logger.getLogger(ScheduleSocialPostServlet.class.getName()).log(Level.SEVERE, null, e);
        out.println(e);
    }
}

From source file:org.owasp.dependencytrack.controller.token.TokenHandlerInterceptor.java

/**
 * Intercepts an incoming requests, determines if method was POST and enforces token policy.
 * @param request The HttpServletRequest to intercept
 * @param response The HttpServletResponse
 * @param handler not-used but required for interface definition
 * @return a Boolean indicating if the request should be further processed.
 * @throws Exception Required by interface
 *//*from  w w  w  .  j a v a2  s.c o m*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    if ("POST".equalsIgnoreCase(request.getMethod())) {
        if (!TokenManager.isTokenValid(request)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Incorrect token value");
            return false;
        }
    }
    return true;
}

From source file:egovframework.rte.tex.com.EgovAccessDeniedHandlerImpl.java

public void handle(ServletRequest request, ServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {

    if (errorPage != null) {
        // Put exception into request scope (perhaps of use to a view)
        ((HttpServletRequest) request).setAttribute(SPRING_SECURITY_ACCESS_DENIED_EXCEPTION_KEY,
                accessDeniedException);/*w w w  .  j av  a2  s .c o m*/

        // Perform RequestDispatcher "forward"
        //RequestDispatcher rd = request.getRequestDispatcher(errorPage);
        //rd.forward(request, response);

        ((HttpServletResponse) response).sendRedirect(errorPage);

    }

    if (!response.isCommitted()) {
        // Send 403 (we do this after response has been written)
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
                accessDeniedException.getMessage());
    }
}