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.LoginFilter.java

private void denyCall(HttpServletRequest hreq, HttpServletResponse resp) throws IOException {
    hreq.getSession().invalidate();/*from ww w  .  j  ava  2s.  co m*/
    logger.warn("not logged call to '" + computeMyUrl(hreq, resp) + "', denying");
    resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
    resp.getWriter().println("MiniG access not allowed.");
}

From source file:au.org.ala.biocache.web.AbstractSecureController.java

/**
  * Returns true when the operation should be performed.
  * @param apiKey//from w  w w. j  av  a  2  s  . c  o  m
  * @param response
  * @return
  * @throws Exception
  */
public boolean shouldPerformOperation(String apiKey, HttpServletResponse response, boolean checkReadOnly)
        throws Exception {
    if (checkReadOnly && Store.isReadOnly()) {
        response.sendError(HttpServletResponse.SC_CONFLICT, "Server is in read only mode.  Try again later.");
    } else if (apiKey == null || !isValidKey(apiKey)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "An invalid API Key was provided.");
    }
    return !response.isCommitted();
}

From source file:com.bstek.dorado.web.resolver.ErrorPageResolver.java

private void doExcecute(HttpServletRequest request, HttpServletResponse response)
        throws Exception, IOException {
    response.setContentType(HttpConstants.CONTENT_TYPE_HTML);
    response.setCharacterEncoding(Constants.DEFAULT_CHARSET);

    Context velocityContext = new VelocityContext();
    Exception e = (Exception) request.getAttribute(EXCEPTION_ATTRIBUTE);
    if (e != null) {
        logger.error(e, e);/*from   www .  j  a  v a  2s .c  o  m*/

        if (e instanceof PageNotFoundException) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (e instanceof PageAccessDeniedException) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }

        Throwable throwable = e;
        while (throwable.getCause() != null) {
            throwable = throwable.getCause();
        }

        String message = null;
        if (throwable != null) {
            message = throwable.getMessage();
        }
        message = StringUtils.defaultString(message, throwable.getClass().getName());

        velocityContext.put("message", message);
        velocityContext.put(EXCEPTION_ATTRIBUTE, throwable);
    } else {
        velocityContext.put("message", "Can not gain exception information!");
    }
    velocityContext.put("esc", stringEscapeHelper);

    Template template = getVelocityEngine().getTemplate("com/bstek/dorado/web/resolver/ErrorPage.html");

    PrintWriter writer = getWriter(request, response);
    try {
        template.merge(velocityContext, writer);
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:edu.harvard.iq.dataverse.NavigationWrapper.java

public String notAuthorized() {
    if (!session.getUser().isAuthenticated()) {
        return "/loginpage.xhtml" + getRedirectPage();
    } else {//from   www.j  av a 2 s. c om
        return sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:com.haulmont.cuba.core.controllers.FileUploadController.java

private UserSession getSession(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UUID sessionId;//w  w w . ja  v a  2 s.c  om
    try {
        sessionId = UUID.fromString(request.getParameter("s"));
    } catch (Exception e) {
        log.error("Error parsing sessionId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
    UserSession session = userSessions.getAndRefresh(sessionId);
    if (session == null)
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    return session;
}

From source file:com.trsst.ui.AppServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // FLAG: limit access only to local clients
    if (restricted && !request.getRemoteAddr().equals(request.getLocalAddr())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "Non-local clients are not allowed.");
        return;//from w w  w . jav  a  2 s  .com
    }

    // in case of any posted files
    InputStream inStream = null;

    // determine if supported command: pull, push, post
    String path = request.getPathInfo();
    System.err.println(new Date().toString() + " " + path);
    if (path != null) {
        // FLAG: limit only to pull and post
        if (path.startsWith("/pull/") || path.startsWith("/post")) {
            // FLAG: we're sending the user's keystore
            // password over the wire (over SSL)
            List<String> args = new LinkedList<String>();
            if (path.startsWith("/pull/")) {
                path = path.substring("/pull/".length());
                response.setContentType("application/atom+xml; type=feed; charset=utf-8");
                // System.out.println("doPull: " +
                // request.getParameterMap());
                args.add("pull");
                if (request.getParameterMap().size() > 0) {
                    boolean first = true;
                    for (Object name : request.getParameterMap().keySet()) {
                        // FLAG: don't allow "home" (server-abuse)
                        // FLAG: don't allow "attach" (file-system access)
                        if ("decrypt".equals(name) || "pass".equals(name)) {
                            for (String value : request.getParameterValues(name.toString())) {
                                args.add("--" + name.toString());
                                args.add(value);
                            }
                        } else {
                            for (String value : request.getParameterValues(name.toString())) {
                                if (first) {
                                    path = path + '?';
                                    first = false;
                                } else {
                                    path = path + '&';
                                }
                                path = path + name + '=' + value;
                            }
                        }
                    }
                }
                args.add(path);

            } else if (path.startsWith("/post")) {
                // System.out.println("doPost: " +
                // request.getParameterMap());
                args.add("post");

                try { // h/t http://stackoverflow.com/questions/2422468
                    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory())
                            .parseRequest(request);
                    for (FileItem item : items) {
                        if (item.isFormField()) {
                            // process regular form field
                            String name = item.getFieldName();
                            String value = item.getString("UTF-8").trim();
                            // System.out.println("AppServlet: " + name
                            // + " : " + value);
                            if (value.length() > 0) {
                                // FLAG: don't allow "home" (server-abuse)
                                // FLAG: don't allow "attach" (file-system
                                // access)
                                if ("id".equals(name)) {
                                    if (value.startsWith("urn:feed:")) {
                                        value = value.substring("urn:feed:".length());
                                    }
                                    args.add(value);
                                } else if (!"home".equals(name) && !"attach".equals(name)) {
                                    args.add("--" + name);
                                    args.add(value);
                                }
                            } else {
                                log.debug("Empty form value for name: " + name);
                            }
                        } else if (item.getSize() > 0) {
                            // process form file field (input type="file").
                            // String filename = FilenameUtils.getName(item
                            // .getName());
                            if (item.getSize() > 1024 * 1024 * 10) {
                                throw new FileUploadException("Current maximum upload size is 10MB");
                            }
                            String name = item.getFieldName();
                            if ("icon".equals(name) || "logo".equals(name)) {
                                args.add("--" + name);
                                args.add("-");
                            }
                            inStream = item.getInputStream();
                            // NOTE: only handles one file!
                        } else {
                            log.debug("Ignored form field: " + item.getFieldName());
                        }
                    }
                } catch (FileUploadException e) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                            "Could not parse multipart request: " + e);
                    return;
                }
            }

            // send post data if any to command input stream
            if (inStream != null) {
                args.add("--attach");
            }
            //System.out.println(args);

            // make sure we don't create another local server
            args.add("--host");
            args.add(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + "/feed");

            PrintStream outStream = new PrintStream(response.getOutputStream(), false, "UTF-8");
            int result = new Command().doBegin(args.toArray(new String[0]), outStream, inStream);
            if (result != 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Internal error code: " + result);
            } else {
                outStream.flush();
            }
            return;
        }

        // otherwise: determine if static resource request
        if (path.startsWith("/")) {
            path = path.substring(1);
        }

        byte[] result = resources.get(path);
        String mimetype = null;
        if (result == null) {
            // if ("".equals(path) || path.endsWith(".html")) {
            // treat all html requests with index doc
            result = resources.get("index.html");
            mimetype = "text/html";
            // }
        }
        if (result != null) {
            if (mimetype == null) {
                if (path.endsWith(".html")) {
                    mimetype = "text/html";
                } else if (path.endsWith(".css")) {
                    mimetype = "text/css";
                } else if (path.endsWith(".js")) {
                    mimetype = "application/javascript";
                } else if (path.endsWith(".png")) {
                    mimetype = "image/png";
                } else if (path.endsWith(".jpg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".jpeg")) {
                    mimetype = "image/jpeg";
                } else if (path.endsWith(".gif")) {
                    mimetype = "image/gif";
                } else {
                    mimetype = new Tika().detect(result);
                }
            }
            if (request.getHeader("If-None-Match:") != null) {
                // client should always use cached version
                log.info("sending 304");
                response.setStatus(304); // Not Modified
                return;
            }
            // otherwise allow ETag/If-None-Match
            response.setHeader("ETag", Long.toHexString(path.hashCode()));
            if (mimetype != null) {
                response.setContentType(mimetype);
            }
            response.setContentLength(result.length);
            response.getOutputStream().write(result);
            return;
        }

    }

    // // otherwise: 404 Not Found
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:org.shredzone.cilla.view.GalleryView.java

/**
 * Shows a single picture of a gallery.//from  w w w  . j a va  2 s  .  co m
 */
@Framed
@View(pattern = "/show/gallery/${section.id}/picture/${picture.id}.html", signature = { "section", "picture" })
@View(pattern = "/ajax/gallery/${section.id}/picture/${picture.id}.html", signature = { "section",
        "picture" }, qualifier = "ajax")
public String galleryPictureView(@PathPart("section.id") GallerySection section,
        @PathPart("picture.id") Picture picture, @Qualifier String qualifier, HttpServletRequest req,
        HttpServletResponse resp) throws ViewException {
    if (!pageService.isVisible(section.getPage())) {
        throw new ErrorResponseException(HttpServletResponse.SC_FORBIDDEN);
    }

    commentFormHandler.handleComment(picture, req, section.isCommentable());

    List<Picture> pictureList = section.getPictures();
    int size = pictureList.size();
    int current = pictureList.indexOf(picture);

    if (current < 0 || size == 0) {
        // There is such a picture, but not in this gallery!
        throw new PageNotFoundException("No such picture in this gallery.");
    }

    if (redirectRestricted(section.getPage(), req, resp)) {
        return null;
    }

    req.setAttribute("page", section.getPage());
    req.setAttribute("section", section);
    req.setAttribute("picture", picture);
    req.setAttribute("info", new PictureInfoModel(pictureList, current));

    if ("ajax".equals(qualifier)) {
        return "section/gallery/picture-ajax.jsp";
    } else {
        return "section/gallery/picture.jsp";
    }
}

From source file:org.gooru.insights.api.spring.exception.InsightsExceptionResolver.java

public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {/*www.java  2s .com*/
    ResponseParamDTO<Map<Object, Object>> responseDTO = new ResponseParamDTO<Map<Object, Object>>();
    Map<Object, Object> errorMap = new HashMap<Object, Object>();
    Integer statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    String traceId = request.getAttribute("traceId") != null ? request.getAttribute("traceId").toString()
            : DEFAULT_TRACEID;
    if (ex instanceof BadRequestException) {
        statusCode = HttpServletResponse.SC_BAD_REQUEST;
    } else if (ex instanceof AccessDeniedException) {
        statusCode = HttpServletResponse.SC_FORBIDDEN;
    } else if (ex instanceof NotFoundException) {
        statusCode = HttpServletResponse.SC_NOT_FOUND;
    } else {
        statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    if (statusCode.toString().startsWith(Numbers.FOUR.getNumber())) {
        InsightsLogger.debug(traceId, ex);
        errorMap.put(DEVELOPER_MESSAGE, ex.getMessage());
    } else if (statusCode.toString().startsWith(Numbers.FIVE.getNumber())) {
        InsightsLogger.error(traceId, ex);
        errorMap.put(DEVELOPER_MESSAGE, DEFAULT_ERROR);
    } else if (statusCode.equals(HttpServletResponse.SC_NO_CONTENT)) {
        InsightsLogger.error(traceId, ex);
        errorMap.put(DEVELOPER_MESSAGE, CONTENT_UNAVAILABLE);
    }
    errorMap.put(STATUS_CODE, statusCode);
    errorMap.put(MAIL_To, SUPPORT_EMAIL_ID);

    response.setStatus(statusCode);
    responseDTO.setMessage(errorMap);
    return new ModelAndView(modelAttributes.VIEW_NAME.getAttribute(),
            modelAttributes.RETURN_NAME.getAttribute(),
            new JSONSerializer().exclude(ApiConstants.EXCLUDE_CLASSES).deepSerialize(responseDTO));

}

From source file:fr.univrouen.poste.web.ExceptionController.java

@RequestMapping("/denied")
public ModelAndView deniedHandler(HttpServletRequest request, HttpServletResponse response) {
    String ip = request.getRemoteAddr();
    log.warn("Access Denied for " + ip);
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    return new ModelAndView("accessDeniedException");
}