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:org.activiti.rest.api.identity.LoginPost.java

/**
 * Authenticates username and password and prepares the response for the webscript template.
 *
 * @param req The webscripts request/*  ww  w. j a  v  a  2  s .  co  m*/
 * @param status The webscripts status
 * @param cache The webscript cache
 * @param model The webscripts template model
 */
@Override
protected void executeWebScript(WebScriptRequest req, Status status, Cache cache, Map<String, Object> model) {
    // Extract user and password from JSON POST
    Content c = req.getContent();
    if (c == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing POST body.");
    }

    try {
        JSONObject json = new JSONObject(c.getContent());
        String userId = json.getString("userId");
        String password = json.getString("password");
        if (userId == null || userId.length() == 0) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Username not specified");
        }
        if (password == null) {
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Password not specified");
        }
        String engineName = config.getEngine();
        ProcessEngine pe = ProcessEngines.getProcessEngine(engineName);
        if (pe != null) {
            if (!pe.getIdentityService().checkPassword(userId, password)) {
                throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN,
                        "Username and password does not match.");
            }
            // Login successful ...
        } else {
            String message;
            ProcessEngineInfo pei = ProcessEngines.getProcessEngineInfo(engineName);
            if (pei != null) {
                message = pei.getException();
            } else {
                message = "Can't find process engine named '" + engineName
                        + "' which is needed to authenticate username and password.";
                List<ProcessEngineInfo> processEngineInfos = ProcessEngines.getProcessEngineInfos();
                if (processEngineInfos.size() > 0) {
                    message += "\nHowever " + processEngineInfos.size()
                            + " other process engine(s) was found: ";
                }
                for (ProcessEngineInfo processEngineInfo : processEngineInfos) {
                    message += "Process engine '" + processEngineInfo.getName() + "' ("
                            + processEngineInfo.getResourceUrl() + "):";
                    if (processEngineInfo.getException() != null) {
                        message += processEngineInfo.getException();
                    } else {
                        message += "OK";
                    }
                }
            }
            throw new WebScriptException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        }
    } catch (JSONException e) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST,
                "Unable to parse JSON POST body: " + e.getMessage());
    } catch (IOException e) {
        throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,
                "Unable to retrieve POST body: " + e.getMessage());
    }
}

From source file:ee.pri.rl.blog.web.servlet.FileDownloadServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    WebApplicationContext context = WebApplicationContextUtils
            .getRequiredWebApplicationContext(getServletContext());
    BlogService blogService = (BlogService) context.getBean("blogService");

    String path = req.getRequestURI().substring(req.getContextPath().length());
    log.debug("Requested file " + path);

    if (path.startsWith("/")) {
        path = path.substring(1);//from  w w w . ja va 2  s. c o m
    }
    if (path.startsWith("files/")) {
        path = path.substring("files/".length());
    }

    int slashIndex = path.indexOf('/');
    if (slashIndex > 0) {
        String entryName = path.substring(0, slashIndex);
        log.debug("Entry name: " + entryName);
        boolean authenticated = Session.exists() && ((BlogSession) Session.get()).isAuthenticated();
        if (blogService.isPrivateEntry(entryName) && !authenticated) {
            log.warn("Tried to access private files");
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }

    File directory = new File(blogService.getSetting(SettingName.UPLOAD_PATH).getValue());
    File file = new File(directory, path);

    if (!file.exists()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        log.warn("File " + file + " does not exist");
        return;
    }

    // Check if the requested file is still inside the upload dir.
    if (!FileUtil.insideDirectory(file, directory)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        log.warn("File " + file + " is not inside upload dir");
        return;
    }

    try {
        String calculatedTag = blogService.getUploadedFileTag(path);
        String tag = req.getHeader("If-None-Match");

        if (tag == null) {
            log.debug("Tag not found, sending file");
            sendFile(path, calculatedTag, directory, resp);
        } else if (tag.equals(calculatedTag)) {
            log.debug("Tag matches, sending 304");
            sendNotModified(calculatedTag, resp);
        } else {
            log.debug("Tag does not match, sending file");
            sendFile(path, calculatedTag, directory, resp);
        }
    } catch (NoSuchFileException e) {
        log.warn("File " + file + " does not exist");
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.AjaxAwareAccessDeniedHandler.java

/**
 * {@inheritDoc}/*from  ww  w  . j a  v a  2s  . c  o  m*/
 * @see org.springframework.security.web.access.AccessDeniedHandler#handle(
 *    javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
 *    org.springframework.security.access.AccessDeniedException)
 */
public void handle(final HttpServletRequest request, final HttpServletResponse response,
        final AccessDeniedException e) throws IOException, ServletException {

    if (e != null && isLoggedIn() && authenticationTrustResolver.isRememberMe(getAuthentication())) {
        // user has a cookie but is getting bounced because of IS_AUTHENTICATED_FULLY,
        // so Acegi won't save the original request
        request.getSession().setAttribute(WebAttributes.SAVED_REQUEST,
                new DefaultSavedRequest(request, portResolver));
    }

    if (response.isCommitted()) {
        return;
    }

    boolean ajaxError = ajaxErrorPage != null && SpringSecurityUtils.isAjax(request);
    if (errorPage == null && !ajaxError) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        return;
    }

    boolean includePort = true;
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = portResolver.getServerPort(request);
    String contextPath = request.getContextPath();
    boolean inHttp = "http".equals(scheme.toLowerCase());
    boolean inHttps = "https".equals(scheme.toLowerCase());

    if (inHttp && (serverPort == 80)) {
        includePort = false;
    } else if (inHttps && (serverPort == 443)) {
        includePort = false;
    }

    String redirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "") + contextPath;
    if (ajaxError) {
        redirectUrl += ajaxErrorPage;
    } else if (errorPage != null) {
        redirectUrl += errorPage;
    }
    response.sendRedirect(response.encodeRedirectURL(redirectUrl));
}

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

/**
 * Streams a medium of the given page.//from  w  ww.  j  a v a 2  s . co m
 */
@View(pattern = "/page/${page.id}/${#type}/${#name}", signature = { "page", "#type", "#name" })
@View(pattern = "/page/${page.id}/${#name}", signature = { "page", "#name" })
public void mediumView(@PathPart("page.id") Page page, @Optional @PathPart("#type") String type,
        @PathPart("#name") String name, HttpServletRequest req, HttpServletResponse resp)
        throws ViewException, CillaServiceException {
    if (!pageService.isVisible(page)) {
        throw new ErrorResponseException(HttpServletResponse.SC_FORBIDDEN);
    }

    Medium media = mediaDao.fetchByName(page, name);
    if (media == null) {
        throw new PageNotFoundException();
    }

    ImageProcessing ip = null;
    if (type != null) {
        ip = imageProcessingManager.createImageProcessing(type);
        if (ip == null) {
            throw new ErrorResponseException(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    ResourceDataSource ds = pageService.getMediumImage(media, ip);
    streamDataSource(ds, req, resp);
}

From source file:com.rockagen.gnext.service.spring.security.extension.ExAuthenticationHandler.java

/**
 * Authentication success handler/*  w w  w . j a  v a2 s. com*/
 *
 * @param request        request
 * @param response       response
 * @param authentication {@link org.springframework.security.core.Authentication}
 */
public void successHandler(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) {

    String uid = authentication.getName();
    successRegister(uid, request);
    // Response Token
    String token = exTokenAuthentication.newToken(uid);
    if (CommUtil.isNotBlank(token)) {
        response.setHeader(tokenName, token);
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:it.marcoberri.mbfasturl.cron.QuartzInitServlet.java

/**
 * //from w  w w. j  a  va 2  s .co m
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.FileDownload.java

@Override
public ActionForward execute(final ActionMapping mapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final String oid = request.getParameter("oid");
    final File file = FenixFramework.getDomainObject(oid);
    if (file == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();//from w  w  w .j ava 2s  . c  om
    } else {
        final Person person = AccessControl.getPerson();
        if (!file.isPrivate() || file.isPersonAllowedToAccess(person)) {
            response.setContentType(file.getContentType());
            response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename());
            response.setContentLength(file.getSize().intValue());
            final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
            dos.write(file.getContents());
            dos.close();
        } else if (file.isPrivate() && person == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED));
            response.getWriter().close();
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN));
            response.getWriter().close();
        }
    }
    return null;
}

From source file:net.big_oh.common.web.servlets.mime.MimeServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logger.info(getServletConfig().getServletName() + " invoked.  Requested mime resource: "
            + req.getParameter(REQUESTED_RESOURCE_NAME));

    // Get the name of the requested resource
    String requestedResourceName = req.getParameter(REQUESTED_RESOURCE_NAME);

    if (requestedResourceName == null || requestedResourceName.equals("")) {
        logger.error("Called " + getServletConfig().getServletName() + " without providing a parameter for '"
                + REQUESTED_RESOURCE_NAME + "'");
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return;// www  .  j  av a 2  s .co m
    }

    // Ensure that the user is allowed to access the requested resource
    if (!isCanUserAccessRequestedResource(requestedResourceName, req.getSession(true))) {
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Get a byte array representation of the resource to be returned in the
    // response
    byte[] resourceBytes = getMimeResourceBytes(requestedResourceName);

    if (resourceBytes == null || resourceBytes.length == 0) {
        logger.error("No resource found under the name \"" + requestedResourceName + "\"");
        resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Set content length for the response
    resp.setContentLength(resourceBytes.length);

    // Get the MIME type for the resource
    String mimeType = getMimeType(requestedResourceName);

    if (mimeType == null || mimeType.equals("")) {
        logger.error("Failed to get MIME type for the requested resource.");
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    // Set the content type for the response
    resp.setContentType(mimeType);

    // Control the HTTP caching of the response
    // This setting controls how frequently the cached resource is
    // revalidated (which is not necessarily the same as reloaded)
    resp.setHeader("Cache-Control", "max-age=" + getMaxAgeInSeconds(requestedResourceName));

    // Use streams to return the requested resource
    ByteArrayInputStream in = new ByteArrayInputStream(resourceBytes);
    OutputStream out = resp.getOutputStream();

    byte[] buf = new byte[1024];
    int count = 0;
    while ((count = in.read(buf)) >= 0) {
        out.write(buf, 0, count);
    }

    in.close();
    out.close();

}

From source file:com.jaspersoft.jasperserver.remote.handlers.RepositoryResourceHandler.java

/**
 * Perform a validation of the passed in resource and save it if validation is passed, otherwise it throws a ServiceException
 *
 * @param repository/*ww  w  .java2 s.  c o m*/
 * @param resource
 * @param serviceContext
 * @throws ServiceException
 */
protected void saveValidated(RepositoryService repository, Resource resource,
        RepositoryRemoteServiceContext serviceContext) throws ServiceException {
    ValidationErrorFilter filter = resource.isNew() ? UniversalValidationErrorFilter.getInstance() : null; // getting exception when doing new file resource
    ValidationErrors errors = repository.validateResource(null, resource, filter);

    if (errors.isError()) {
        throw new ServiceException(HttpServletResponse.SC_FORBIDDEN, errors.toString());
    }

    repository.saveResource(null, resource);
}