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:net.duckling.ddl.web.controller.LoginController.java

@WebLog(method = "loginToken")
@RequestMapping("/token")
public void dealToken(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Oauth o = new Oauth(config);
    try {// ww  w .ja  v a  2  s . c  o  m
        AccessToken t = o.getAccessTokenByRequest(request);
        String token = t.getAccessToken();
        UserInfo u = t.getUserInfo();
        VWBSession vwbsession = VWBSession.findSession(request);
        LOG.info("token:" + token);
        if (u == null) {
            LOG.info("Failed to authenticate user.");
            vwbsession.setStatus(VWBSession.ANONYMOUS);
            String failURL = policy.getSavedFailURL(request);
            if (failURL != null) {
                response.sendRedirect(failURL);
            } else {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        } else {
            UserPrincipal user = new UserPrincipal(u.getCstnetId(), getUserName(u.getCstnetId(), u),
                    u.getCstnetId(), u.getType());
            List<Principal> set = new ArrayList<Principal>();
            set.add(user);
            vwbsession.setPrincipals(set);
            updateCurrentUserInformation(request);

            request.getSession().setAttribute(Attributes.UMT_ACCESS_TOKEN, token);

            String state = request.getParameter("state");

            //?meepo
            if ("clientcode".equals(state)) {
                request.setAttribute("accessToken", t);
                request.getRequestDispatcher("/system/clientcode").forward(request, response);
            } else if ("clientcode_needteams".equals(state)) { //??
                request.setAttribute("accessToken", t);
                request.getRequestDispatcher("/system/clientcode?need_teams=true").forward(request, response);
            } else if ("syncclient".equals(state)) { //?
                request.setAttribute("accessToken", t);
                request.getRequestDispatcher("/system/syncclient").forward(request, response);
            } else {
                String viewUrl = (String) VWBSession.findSession(request)
                        .removeAttribute(Attributes.REQUEST_URL);
                if (StringUtils.isEmpty(viewUrl)) {
                    viewUrl = state;
                }
                LOG.info("Successfully authenticated user:" + u.getCstnetId() + ";access_token:" + token);
                LOG.info("Redirecting user to " + viewUrl);
                // Redirect!
                redirect(request, response, viewUrl);
            }
        }
    } catch (UMTOauthConnectException e) {
        LOG.error("", e);
    } catch (OAuthProblemException e) {
        LOG.error("", e);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.search.controller.IndexController.java

private void showStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    if (!PolicyHelper.isAuthorizedForActions(req, REQUIRED_ACTIONS)) {
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        resp.getWriter().write("You are not authorized to access this page.");
        return;/*ww w  . ja  v  a  2s .c  o  m*/
    }

    try {
        Map<String, Object> body = new HashMap<>();
        body.put("statusUrl", UrlBuilder.getUrl(PAGE_URL, "status", "true"));
        body.put("rebuildUrl", UrlBuilder.getUrl(PAGE_URL, "rebuild", "true"));
        body.put("status", buildStatusMap(indexer.getStatus()));
        if (history != null) {
            body.put("history", history.toMaps());
        }

        String rendered = FreemarkerProcessingServiceSetup.getService(getServletContext())
                .renderTemplate(STATUS_TEMPLATE_NAME, body, req);
        resp.getWriter().write(rendered);
    } catch (Exception e) {
        resp.setStatus(500);
        resp.getWriter().write(e.toString());
        log.error(e, e);
    }
}

From source file:es.logongas.ix3.web.util.ControllerHelper.java

public void exceptionToHttpResponse(Throwable throwable, HttpServletResponse httpServletResponse) {
    try {//from  www  . ja v a 2 s.co  m
        BusinessException businessException = ExceptionUtil.getBusinessExceptionFromThrowable(throwable);

        if (businessException != null) {

            if (businessException instanceof BusinessSecurityException) {
                BusinessSecurityException businessSecurityException = (BusinessSecurityException) businessException;
                Log log = LogFactory.getLog(ControllerHelper.class);
                log.info(businessSecurityException);

                httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                httpServletResponse.setContentType("text/plain; charset=UTF-8");
                if (businessSecurityException.getBusinessMessages().size() > 0) {
                    httpServletResponse.getWriter()
                            .println(businessSecurityException.getBusinessMessages().get(0).getMessage());
                }
            } else if (businessException instanceof BusinessException) {

                httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                httpServletResponse.setContentType("application/json; charset=UTF-8");
                httpServletResponse.getWriter()
                        .println(jsonFactory.getJsonWriter().toJson(businessException.getBusinessMessages()));
            } else {
                Log log = LogFactory.getLog(ControllerHelper.class);
                log.error("Es un tipo de businessException desconocida:", businessException);

                httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                httpServletResponse.setContentType("text/plain");
                businessException.printStackTrace(httpServletResponse.getWriter());
            }

        } else {
            Log log = LogFactory.getLog(ControllerHelper.class);
            log.error("Fall la llamada al servidor:", throwable);

            httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            httpServletResponse.setContentType("text/plain");
            throwable.printStackTrace(httpServletResponse.getWriter());
        }
    } catch (IOException ioException) {
        Log log = LogFactory.getLog(ControllerHelper.class);
        log.error("Fall al devolver la excepcin por la HttpResponse:", ioException);
        log.error("Excepcion original:", throwable);
        httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:fi.hoski.web.auth.LoginServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    String email = request.getParameter("email");
    String activationKey = request.getParameter("activationKey");
    try {//from ww  w  .j ava  2  s  .  co  m
        if (email != null && activationKey != null) {
            Map<String, Object> user = userDirectory.useActivationKey(email, activationKey);

            if (user != null) {
                HttpSession session = request.getSession(true);
                session.setAttribute(USER, user);
            }

            // redirect always, if user is not logged in,
            // there will be a login screen
            response.sendRedirect("/member"); //TODO target make configurable
        } else {
            HttpSession session = request.getSession(false);
            String etag = request.getHeader("If-None-Match");
            @SuppressWarnings("unchecked")
            Map<String, Object> user = (session != null) ? (Map<String, Object>) session.getAttribute(USER)
                    : null;
            String userEtag = getEtag(user);

            if (etag != null && etag.equals(userEtag)) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            } else {
                response.setHeader("ETag", userEtag);
                response.setHeader("Cache-Control", "private");
                response.setHeader("Vary", "Cookie");

                writeUserJSON(user, response);
            }
        }
    } catch (UnavailableException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    } catch (EmailNotUniqueException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    }
}

From source file:eu.dasish.annotation.backend.rest.NotebookResource.java

/**
 * //from www  .  j ava 2  s  . co  m
 * @param externalIdentifier the external UUID identifier of a notebook.
 * @param accessMode the access mode on which principals must be filtered; 
 * can be "none", "read", "write", "all".
 * @return a {@link ReferenceList} element representing the list of h-references of the
 * principals that have access "accessMode".
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{notebookid: " + BackendConstants.regExpIdentifier + "}/{access}")
@Transactional(readOnly = true)
public JAXBElement<ReferenceList> getPrincipals(@PathParam("notebookid") String externalIdentifier,
        @PathParam("access") String accessMode) throws IOException {
    Number remotePrincipalID = this.getPrincipalID();
    if (remotePrincipalID == null) {
        return new ObjectFactory().createReferenceList(new ReferenceList());
    }
    try {
        Number notebookID = dbDispatcher.getResourceInternalIdentifier(UUID.fromString(externalIdentifier),
                Resource.NOTEBOOK);
        if (dbDispatcher.hasAccess(notebookID, remotePrincipalID, Access.fromValue("read"))) {
            ReferenceList principals = dbDispatcher.getPrincipals(notebookID, accessMode);
            return new ObjectFactory().createReferenceList(principals);
        } else {
            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
            return new ObjectFactory().createReferenceList(new ReferenceList());
        }

    } catch (NotInDataBaseException e) {
        loggerServer.debug(e.toString());
        ;
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.toString());
        return new ObjectFactory().createReferenceList(new ReferenceList());
    }
}

From source file:eu.trentorise.smartcampus.unidataservice.controller.rest.StudentInfoController.java

@RequestMapping(method = RequestMethod.GET, value = "/getstudentexams")
public @ResponseBody StudentInfoExams getStudentExams(HttpServletRequest request, HttpServletResponse response,
        HttpSession session) throws InvocationException {
    try {/*from   w  ww  .ja  va2  s .  co m*/
        User user = getCurrentUser();
        String userId = getUserId(user);
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        String token = getToken(request);
        String idAda = getIdAda(token);
        StudentInfoExams result = getStudentExams(idAda);
        if (result != null) {
            return result;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

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

/**
 * Streams the picture of a gallery.//ww w  . ja v  a  2 s .c o m
 */
@View(pattern = "/picture/${picture.id}-${#type}.${#suffix(picture.image.contentType)}", signature = {
        "picture", "#type" })
@View(pattern = "/picture/${picture.id}.${#suffix(picture.image.contentType)}", signature = { "picture" })
public void pictureView(@PathPart("picture.id") Picture picture, @Optional @PathPart("#type") String type,
        HttpServletRequest req, HttpServletResponse resp) throws ViewException, CillaServiceException {
    // Take measures against deep linking of the pictures. No need to check page
    // permissions, as the picture is not unlocked if the visitor had no access
    // to the page.
    if (!unlockService.isUnlocked(req.getSession(), picture)) {
        throw new ErrorResponseException(HttpServletResponse.SC_FORBIDDEN);
    }

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

    ResourceDataSource ds = pictureService.getImage(picture, ip);
    streamDataSource(ds, req, resp);
}

From source file:org.dasein.cloud.rackspace.AbstractMethod.java

public synchronized @Nullable AuthenticationContext authenticate() throws CloudException, InternalException {
    Logger std = RackspaceCloud.getLogger(RackspaceCloud.class, "std");
    Logger wire = RackspaceCloud.getLogger(RackspaceCloud.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".authenticate()");
    }//from   ww  w .j  a  va  2 s.c om
    if (wire.isDebugEnabled()) {
        wire.debug("--------------------------------------------------------> " + provider.getEndpoint());
        wire.debug("");
    }
    try {
        ProviderContext ctx = provider.getContext();
        HttpClient client = getClient();
        HttpGet get = new HttpGet(provider.getEndpoint());

        try {
            get.addHeader("Content-Type", "application/json");
            get.addHeader("X-Auth-User", new String(ctx.getAccessPublic(), "utf-8"));
            get.addHeader("X-Auth-Key", new String(ctx.getAccessPrivate(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            std.error("authenticate(): Unsupported encoding when building request headers: " + e.getMessage());
            if (std.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new InternalException(e);
        }
        if (wire.isDebugEnabled()) {
            wire.debug(get.getRequestLine().toString());
            for (Header header : get.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            response = client.execute(get);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);
        if (code != HttpServletResponse.SC_NO_CONTENT) {
            if (code == HttpServletResponse.SC_FORBIDDEN || code == HttpServletResponse.SC_UNAUTHORIZED) {
                return null;
            }
            std.error("authenticate(): Expected NO CONTENT for an authentication request, got " + code);
            HttpEntity entity = response.getEntity();
            String json = null;

            if (entity != null) {
                try {
                    json = EntityUtils.toString(entity);

                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                        wire.debug("");
                    }
                } catch (IOException e) {
                    throw new CloudException(e);
                }
            }
            RackspaceException.ExceptionItems items;
            if (json == null) {
                items = RackspaceException.parseException(code, "{}");
            } else {
                items = RackspaceException.parseException(code, json);
            }
            if (items.type.equals(CloudErrorType.AUTHENTICATION)) {
                return null;
            }
            std.error("authenticate(): [" + code + " : " + items.message + "] " + items.details);
            throw new RackspaceException(items);
        } else {
            AuthenticationContext authContext = new AuthenticationContext();

            for (Header h : response.getAllHeaders()) {
                if (h.getName().equalsIgnoreCase("x-auth-token")) {
                    authContext.setAuthToken(h.getValue().trim());
                } else if (h.getName().equalsIgnoreCase("x-server-management-url")) {
                    authContext.setServerUrl(h.getValue().trim());
                } else if (h.getName().equalsIgnoreCase("x-storage-url")) {
                    authContext.setStorageUrl(h.getValue().trim());
                } else if (h.getName().equalsIgnoreCase("x-cdn-management-url")) {
                    authContext.setCdnUrl(h.getValue().trim());
                } else if (h.getName().equalsIgnoreCase("x-storage-token")) {
                    authContext.setStorageToken(h.getValue().trim());
                }
            }
            if (authContext.getAuthToken() == null) {
                std.warn("authenticate(): No authentication token in response");
                throw new CloudException("No authentication token in cloud response");
            }
            return authContext;
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".authenticate()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + provider.getEndpoint());
        }
    }
}

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

private void toogleBan(SuperUserManager superUserManager, String sID, String password,
        HttpServletRequest request, HttpServletResponse response) {
    if (superUserManager == null) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } else {//from   w  w w .  jav  a  2 s . c om
        Admin admin = (Admin) request.getSession().getAttribute(Admin.class.getName());

        if (admin != null) {
            if (sID != null) {
                Integer id = null;

                try {
                    id = Integer.parseInt(sID);
                } catch (Exception e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

                    return;
                }

                SuperDaoUser superUser = superUserManager.getByID(id);

                if (superUser != null) {
                    superUser.setPassword(password);

                    ErrorCode errorCode = superUserManager.update(superUser);

                    if (errorCode.errorNotAccrued()) {
                        response.setStatus(HttpServletResponse.SC_ACCEPTED);
                    } else {
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    }
                } else {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
    }
}

From source file:com.tasktop.c2c.server.scm.web.GitHandler.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final boolean containerSupportsChunkedIO = computeContainerSupportsChunkedIO();

    String pathInfo = request.getPathInfo();
    log.info("Git request: " + request.getMethod() + " " + request.getRequestURI() + " " + pathInfo);

    Repository repository = null;//w ww  .  j  av  a2s.c om
    try {
        // only work on Git requests
        Matcher matcher = pathInfo == null ? null : GIT_COMMAND_PATTERN.matcher(pathInfo);
        if (matcher == null || !matcher.matches()) {
            log.info("Unexpected path: " + pathInfo);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        String requestCommand = matcher.group(1);
        String requestPath = matcher.group(2);

        // sanity check on path, disallow path separator components
        if (requestPath == null || requestPath.contains("/") || requestPath.contains("..")) {
            badPathResponse();
        }

        repository = repositoryResolver.open(request, requestPath);

        InputStream requestInput = request.getInputStream();
        if (!containerSupportsChunkedIO) {
            requestInput = new ChunkedInputStream(requestInput);
        }

        MultiplexingOutputStream mox = createMultiplexingOutputStream(response, containerSupportsChunkedIO);
        // indicate that we're ok to handle the request
        // note that following this there will be a two-way communication with the process
        // that might still encounter errors. That's ok.
        startOkResponse(response, containerSupportsChunkedIO);

        // identify the git command
        GitCommand command = GitCommand.fromCommandName(requestCommand);
        if (command != null) {
            // permissions check
            if (!Security.hasOneOfRoles(command.getRoles())) {
                log.info("Access denied to " + Security.getCurrentUser() + " for " + command.getCommandName()
                        + " on " + TenancyUtil.getCurrentTenantProjectIdentifer() + " " + requestPath);
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            switch (command) {
            case RECEIVE_PACK:
                ReceivePack rp = new ReceivePack(repository);
                rp.setPostReceiveHook(postReceiveHook);
                rp.receive(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            case UPLOAD_PACK:
                UploadPack up = new UploadPack(repository);
                up.upload(requestInput, mox.stream(PacketType.STDOUT), mox.stream(PacketType.STDERR));
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }

        // at this stage we're done with IO
        // send the exit value and closing chunk
        try {
            int exitValue = 0;

            if (exitValue != 0) {
                log.info("Exit value: " + exitValue);
            }
            mox.writeExitCode(exitValue);
            mox.close();
        } catch (IOException e) {
            // ignore
            log.debug("Cannot complete writing exit state", e);
        }

        // clear interrupt status
        Thread.interrupted();

    } catch (ErrorResponseException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotAuthorizedException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } catch (ServiceNotEnabledException e) {
        createGitErrorResponse(response, containerSupportsChunkedIO, e.getMessage());
    } finally {
        log.info("Git request complete");
        if (repository != null) {
            repository.close();
        }
    }
}