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:au.edu.uq.cmm.benny.Benny.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String user = req.getParameter("user");
    String password = req.getParameter("password");
    if (user == null && password == null) {
        String[] credentials = getBasicAuthCredentials(req);
        if (credentials == null) {
            resp.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
            respond(resp, HttpServletResponse.SC_UNAUTHORIZED, "No credentials provided");
            return;
        }//ww w.  ja va 2s  .co m
        user = credentials[0];
        password = credentials[1];
    }
    try {
        LOG.debug("checking user='" + user + "', password='XXXXXX'");
        boolean ok = authenticator.authenticate(user, password, null) != null;
        if (ok) {
            respond(resp, HttpServletResponse.SC_OK, "Credentials accepted");
        } else {
            respond(resp, HttpServletResponse.SC_FORBIDDEN, "Credentials rejected");
        }
    } catch (IOException ex) {
        throw ex;
    } catch (Exception ex) {
        LOG.error("Unexpected exception", ex);
        respond(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Service error");
    }
}

From source file:aiai.ai.launchpad.server.ServerController.java

@GetMapping("/rest-anon/payload/resource/{type}/{code}")
public HttpEntity<AbstractResource> deliverResourceAnon(HttpServletResponse response,
        @PathVariable("type") String typeAsStr, @PathVariable("code") String code) throws IOException {
    log.debug("deliverResourceAnon(), globals.isSecureRestUrl: {}, typeAsStr: {}, code: {}",
            globals.isSecureRestUrl, typeAsStr, code);
    if (globals.isSecureRestUrl) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }//from w  w  w  .  j a v a2  s .com
    return deliverResource(response, typeAsStr, code);
}

From source file:net.duckling.ddl.web.controller.BaseController.java

/**
 * ???
 * @param request
 * @param response
 */
protected void sendForbidden(HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(User user, BindingResult errors, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null) {
        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            return getCancelView();
        } else {/*from w  w  w .  j  a va 2  s  .  c om*/
            return getSuccessView();
        }
    }

    if (validator != null) { // validator is null during testing
        validator.validate(user, errors);

        if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
            return "userform";
        }
    }

    log.debug("entering 'onSubmit' method...");

    Locale locale = request.getLocale();

    if (request.getParameter("delete") != null) {
        getUserManager().removeUser(user.getId().toString());
        saveMessage(request, getText("user.deleted", user.getFullName(), locale));

        return getSuccessView();
    } else {

        // only attempt to change roles if user is admin for other users,
        // showForm() method will handle populating
        if (request.isUserInRole(Constants.ADMIN_ROLE) || request.isUserInRole(Constants.USER_ROLE)) {
            String[] userRoles = request.getParameterValues("userRoles");

            if (userRoles != null) {
                user.getRoles().clear();
                for (String roleName : userRoles) {
                    user.addRole(roleManager.getRole(roleName));
                }
            }
        }

        Integer originalVersion = user.getVersion();

        try {
            getUserManager().saveUser(user);
        } catch (AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
            log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (UserExistsException e) {
            errors.rejectValue("username", "errors.existing.user",
                    new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            // reset the version # to what was passed in
            user.setVersion(originalVersion);

            return "userform";
        }

        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            saveMessage(request, getText("user.saved", user.getFullName(), locale));

            // return to main Menu
            return getCancelView();
        } else {
            if (StringUtils.isBlank(request.getParameter("version"))) {
                saveMessage(request, getText("user.added", user.getFullName(), locale));

                // Send an account information e-mail
                message.setSubject(getText("signup.email.subject", locale));

                try {
                    sendUserMessage(user, getText("newuser.email.message", user.getFullName(), locale),
                            RequestUtil.getAppURL(request));
                } catch (MailException me) {
                    saveError(request, me.getCause().getLocalizedMessage());
                }

                return getSuccessView();
            } else {
                saveMessage(request, getText("user.updated.byAdmin", user.getFullName(), locale));
            }
        }
    }

    return "userform";
}

From source file:com.alfaariss.oa.util.web.SharedSecretFilter.java

/**
 * This method only passes on the request to the chain if the shared secret
 * parameter matches the configured shared secret.
 * /*w w  w.jav  a  2 s  . com*/
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest oRequest, ServletResponse oResponse, FilterChain oChain)
        throws IOException, ServletException {
    HttpServletRequest oHttpRequest = null;
    HttpServletResponse oHttpResponse = null;

    try {
        // try to create Http servlet request/response
        if (oRequest instanceof HttpServletRequest)
            oHttpRequest = (HttpServletRequest) oRequest;
        else {
            _logger.warn("received a non HTTP request");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }
        if (oResponse instanceof HttpServletResponse)
            oHttpResponse = (HttpServletResponse) oResponse;
        else {
            _logger.warn("received a non HTTP response");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        String sharedSecret = oHttpRequest.getParameter("shared_secret");
        if (sharedSecret != null && sharedSecret.length() > 0) {
            if (_sharedSecret.equals(sharedSecret)) {

                _logger.debug("Request accepted. Shared secret credentials accepted: " + sharedSecret);
                //Continue with chain
                oChain.doFilter(oRequest, oResponse);
            } else {
                _logger.warn("Request not accepted. Shared secret credentials NOT accepted: " + sharedSecret);
                oHttpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
            }
        } else //FORBIDDEN
        {
            _logger.warn("Request not accepted. No Shared secret credentials supplied");
            oHttpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);

        }
    } catch (OAException e) {
        _logger.error("Could not process request", e);
        throw new ServletException();
    } catch (Exception e) {
        _logger.fatal("Could not process request, due to internal error", e);
        throw new ServletException();
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.web.template.SelectStudySegmentController.java

@SuppressWarnings({ "unchecked" })
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    int id = ServletRequestUtils.getRequiredIntParameter(request, "studySegment");
    StudySegment studySegment = studySegmentDao.getById(id);

    Integer amendId = ServletRequestUtils.getIntParameter(request, "amendment");
    Amendment amendment = null;/*from  w w  w. j  a  va 2  s . c  om*/
    if (amendId != null) {
        amendment = amendmentDao.getById(amendId);
    }

    boolean isDevelopmentRequest = !StringUtils.isBlank(request.getParameter("development"));

    studySegment = (amendment != null && !isDevelopmentRequest)
            ? amendmentService.getAmendedNode(studySegment, amendment)
            : studySegment;

    Study study = templateService.findStudy(studySegment);

    UserTemplateRelationship utr = new UserTemplateRelationship(applicationSecurityManager.getUser(), study,
            configuration);

    StudyWorkflowStatus workflow = workflowService.build(study, applicationSecurityManager.getUser());
    model.put("studyWorkflowMessages", workflow.getMessages());

    if ((isDevelopmentRequest && utr.getCanSeeDevelopmentVersion())
            || (!isDevelopmentRequest && utr.getCanSeeReleasedVersions())) {
        if (study.getDevelopmentAmendment() != null && isDevelopmentRequest) {
            studySegment = deltaService.revise(studySegment);
            model.put("developmentRevision", study.getDevelopmentAmendment());
            model.put("canEdit", utr.getCanDevelop());
        } else {
            model.put("canEdit", false);
        }
        controllerTools.addHierarchyToModel(studySegment, model);

        model.put("studySegment", new StudySegmentTemplate(studySegment));
        return new ModelAndView("template/ajax/selectStudySegment", model);
    } else {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }
}

From source file:com.openmeap.admin.web.servlet.WebViewServlet.java

@SuppressWarnings("unchecked")
@Override/*  w w w.j ava2 s  .c  om*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    logger.trace("in service");

    ModelManager mgr = getModelManager();
    GlobalSettings settings = mgr.getGlobalSettings();
    String validTempPath = settings.validateTemporaryStoragePath();
    if (validTempPath != null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, validTempPath);
    }

    String pathInfo = request.getPathInfo();
    String[] pathParts = pathInfo.split("[/]");
    if (pathParts.length < 4) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    String remove = pathParts[1] + "/" + pathParts[2] + "/" + pathParts[3];
    String fileRelative = pathInfo.replace(remove, "");

    String applicationNameString = URLDecoder.decode(pathParts[APP_NAME_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    String archiveHash = URLDecoder.decode(pathParts[APP_VER_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    Application app = mgr.getModelService().findApplicationByName(applicationNameString);
    ApplicationArchive arch = mgr.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archiveHash,
            "MD5");

    String authSalt = app.getProxyAuthSalt();
    String authToken = URLDecoder.decode(pathParts[AUTH_TOKEN_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    try {
        if (!AuthTokenProvider.validateAuthToken(authSalt, authToken)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (DigestException e1) {
        throw new GenericRuntimeException(e1);
    }

    File fileFull = new File(
            arch.getExplodedPath(settings.getTemporaryStoragePath()).getAbsolutePath() + "/" + fileRelative);
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(fileFull.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(fileFull.length()).intValue());

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //response.setStatus(HttpServletResponse.SC_FOUND);
            inputStream = new FileInputStream(fileFull);
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.codenvy.ide.git.VFSPermissionsFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    int tokenPlace;
    String lastTokenBeforePath = "/" + gitServerUriPrefix + "/";
    if ((tokenPlace = req.getRequestURL().indexOf(lastTokenBeforePath)) != -1) {
        //get path to project
        String url = req.getRequestURL().substring(tokenPlace + lastTokenBeforePath.length());
        url = url.replaceFirst("/info/refs", "");
        url = url.replaceFirst("/git-upload-pack", "");
        //adaptation to fs
        url = url.replaceAll("/", Matcher.quoteReplacement(File.separator));
        //search for dotVFS directory
        File projectDirectory = Paths.get(vfsRoot, url).toFile();
        String auth;//from  w  w w .  j av  a  2 s  . c  o  m
        String userName = "";
        String password = "";
        if ((auth = req.getHeader("authorization")) != null) {
            //get encoded password phrase
            String userAndPasswordEncoded = auth.substring(6);
            // decode Base64 user:password
            String userAndPasswordDecoded = new String(Base64.decodeBase64(userAndPasswordEncoded));
            //get username and password separator ':'
            int betweenUserAndPassword = userAndPasswordDecoded.indexOf(':');
            //get username - it is before first ':'
            userName = userAndPasswordDecoded.substring(0, betweenUserAndPassword);
            //get password - it is after first ':'
            password = userAndPasswordDecoded.substring(betweenUserAndPassword + 1);
        }

        // Check if user authenticated and has permissions to project, or send response code 403
        boolean needLogout = false;
        String token = null;
        User user;
        try {
            if (!userName.isEmpty()) {
                if (password.equals("x-che")) { // internal SSO
                    token = userName;
                } else {
                    token = getToken(userName, password);
                    if (token == null) {
                        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                        return;
                    }
                    needLogout = true;
                }
                user = getUserBySSO(token);
                EnvironmentContext.getCurrent().setUser(user);
            }

            if (!hasAccessToItem(projectDirectory.getParentFile().getName(), projectDirectory.getName())) {
                if (!userName.isEmpty()) {
                    // Authenticated but no access
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                } else {
                    // Not authenticated, try again with credentials
                    ((HttpServletResponse) response).addHeader("Cache-Control", "private");
                    ((HttpServletResponse) response).addHeader("WWW-Authenticate", "Basic");
                    ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return;
                }
            }
        } finally {
            if (needLogout) {
                logout();
            }
            EnvironmentContext.reset();
        }
    }
    chain.doFilter(req, response);
}

From source file:com.janrain.backplane2.server.Token.java

public static @NotNull Token fromRequest(DAOFactory daoFactory, HttpServletRequest request, String tokenString,
        String authorizationHeader) throws TokenException {

    Pair<String, EnumSet<TokenSource>> tokenAndSource = extractToken(request.getQueryString(), tokenString,
            authorizationHeader);/* ww  w .j  av a2 s . c  om*/

    if (!Token.looksLikeOurToken(tokenAndSource.getLeft())) {
        throw new TokenException("invalid token", HttpServletResponse.SC_FORBIDDEN);
    }

    Token token;
    try {
        token = daoFactory.getTokenDao().get(tokenAndSource.getLeft());
    } catch (BackplaneServerException e) {
        logger.error("Error looking up token: " + tokenAndSource.getLeft(), e);
        throw new TokenException(OAuth2.OAUTH2_TOKEN_SERVER_ERROR, "error loading token",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    if (token == null) {
        logger.warn("token not found: " + tokenAndSource.getLeft());
        throw new TokenException("invalid token", HttpServletResponse.SC_FORBIDDEN);
    }

    if (token.isExpired()) {
        throw new TokenException("expired token", HttpServletResponse.SC_FORBIDDEN);
    }

    token.checkAllowedSources(tokenAndSource.getRight());

    return token;
}

From source file:mitm.djigzo.web.utils.IPFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("HttpServletResponse expected.");
    }//  w  w w.j ava 2s .  c  om

    HttpServletResponse httpResponse = (HttpServletResponse) response;

    String servletPath = null;

    if (request instanceof HttpServletRequest) {
        servletPath = ((HttpServletRequest) request).getServletPath();
    }

    String remoteAddress = request.getRemoteAddr();

    if (filter.isAccepted(remoteAddress) || isServletPathExcluded(servletPath)) {
        chain.doFilter(request, response);
    } else {
        logger.warn("Request from " + remoteAddress + " to " + request.toString() + " is blocked.");

        httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Access denied (" + remoteAddress + " is not allowed to connect)");
    }
}