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.bhira.sample.api.controller.CompanyController.java

/**
 * Fetch all the companies in the system. It will return a light weight version of
 * {@link net.bhira.sample.model.Company} model without the address and contactInfo objects.
 * /* w w w  .j  a va 2 s.c om*/
 * @param response
 *            the http response to which the results will be written.
 * @return an array of {@link net.bhira.sample.model.Company} instances as JSON.
 */
@RequestMapping(value = "/company", method = RequestMethod.GET)
@ResponseBody
public Callable<String> getAll(HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            String body = "";
            try {
                LOG.debug("servicing GET company/");
                List<Company> list = companyService.loadAll();
                int count = (list == null) ? 0 : list.size();
                LOG.debug("GET company/ count = {}", count);
                body = JsonUtil.createGson().toJson(list);
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error loading companies. {}", body);
                LOG.debug("Load error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:com.sonicle.webtop.core.app.shiro.filter.JWTSignatureVerifier.java

@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
        throws Exception {
    // Retrieve signing key
    SecretKey signingKey = getSigningKey(request);
    if (signingKey == null) {
        logger.warn("Missing JWT secret. Please check '{}' context attribute.", SECRET_CONTEXT_ATTRIBUTE);
        return true;
    }/*from  ww w .j  a  v a2s  . c  om*/

    // Extracts the JWT string
    String authz = getAuthzHeader(request);
    if (!StringUtils.startsWith(authz, AUTHORIZATION_SCHEME_BEARER)) {
        if (logger.isTraceEnabled()) {
            logger.trace("Authorization header is missing or malformed");
            logger.trace("{}: {}", AUTHORIZATION_HEADER, authz);
        }
        WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN,
                "Authorization header is missing or malformed");
        return false;
    }
    String jwts = authz.substring(authz.indexOf(" ") + 1).trim();

    try {
        Jwts.parser().setSigningKey(signingKey).parseClaimsJws(jwts);
        return true;

    } catch (JwtException ex) {
        logger.trace("Unable to parse JWT string [{}]", ex, jwts);
        WebUtils.toHttp(response).sendError(HttpServletResponse.SC_FORBIDDEN, "JWT token not signed correctly");
        return false;
    }
}

From source file:org.jboss.as.test.integration.web.response.DefaultResponseCodeAtRootTestCase.java

@Test
public void testNormalOpMode() throws Exception {
    deployer.deploy("test");
    try {// w w  w.  jav  a 2s.  com
        HttpGet httpget = new HttpGet(url.toString());
        HttpResponse response = this.httpclient.execute(httpget);
        //403 apparently
        Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatusLine().getStatusCode());
        httpget = new HttpGet(url.toString() + URL_PATTERN + "xxx");
        response = this.httpclient.execute(httpget);
        Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
    } finally {
        deployer.undeploy("test");
    }
}

From source file:org.jboss.as.test.integration.web.security.servlet.methods.DenyUncoveredHttpMethodsTestCase.java

@Test
public void testPostMethod() throws Exception {
    HttpPost httpPost = new HttpPost(getURL());
    HttpResponse response = getHttpResponse(httpPost);

    assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN));
}

From source file:com.formtek.dashlets.sitetaskmgr.SiteWorkflowInstanceDelete.java

@Override
protected Map<String, Object> buildModel(WorkflowModelBuilder modelBuilder, WebScriptRequest req, Status status,
        Cache cache) {//  ww w  . j ava 2s  .  c om
    Map<String, String> params = req.getServiceMatch().getTemplateVars();

    // getting workflow instance id from request parameters
    String workflowInstanceId = params.get("workflow_instance_id");
    logger.debug("Workflow should be associated with workflow instance: " + workflowInstanceId);

    // determine if instance should be cancelled or deleted
    boolean forced = getForced(req);
    logger.debug("Forced flag is set to: " + forced);

    // get the name of the site the workflow should be associated with
    String site = getSite(req);
    logger.debug("Workflow should be associated with site: " + site);

    // get the workflow path from the incoming workflow Id
    // for site task manager workflows, there will be a single path
    WorkflowPath wfPath = SiteWFUtil.getWorkflowPath(workflowInstanceId, workflowService);

    if (SiteWFUtil.canUserChangeWorkflow(wfPath, site, workflowService, nodeService, authenticationService,
            authorityService)) {
        if (forced) {
            workflowService.deleteWorkflow(workflowInstanceId);
        } else {
            workflowService.cancelWorkflow(workflowInstanceId);
        }

        return null;
    } else {
        throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "Failed to "
                + (forced ? "delete" : "cancel") + " workflow instance with id: " + workflowInstanceId);
    }
}

From source file:nl.surfnet.mujina.saml.SSOSuccessAuthnResponder.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AuthnRequestInfo info = (AuthnRequestInfo) request.getSession()
            .getAttribute(AuthnRequestInfo.class.getName());

    if (info == null) {
        logger.warn("Could not find AuthnRequest on the request.  Responding with SC_FORBIDDEN.");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;// w  w w  . j a  v  a 2s.c o m
    }

    logger.debug("AuthnRequestInfo: {}", info);

    SimpleAuthentication authToken = (SimpleAuthentication) SecurityContextHolder.getContext()
            .getAuthentication();
    DateTime authnInstant = new DateTime(request.getSession().getCreationTime());

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(idpConfiguration.getEntityID()));
    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    Credential signingCredential = null;
    try {
        signingCredential = credentialResolver.resolveSingle(criteriaSet);
    } catch (org.opensaml.xml.security.SecurityException e) {
        logger.warn("Unable to resolve EntityID while signing", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    Validate.notNull(signingCredential);

    AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator(signingCredential,
            idpConfiguration.getEntityID(), timeService, idService, idpConfiguration);
    EndpointGenerator endpointGenerator = new EndpointGenerator();

    final String remoteIP = request.getRemoteAddr();
    String attributeJson = null;

    if (null != request.getCookies()) {
        for (Cookie current : request.getCookies()) {
            if (current.getName().equalsIgnoreCase("mujina-attr")) {
                logger.info("Found a attribute cookie, this is used for the assertion response");
                attributeJson = URLDecoder.decode(current.getValue(), "UTF-8");
            }
        }
    }
    String acsEndpointURL = info.getAssertionConsumerURL();
    if (idpConfiguration.getAcsEndpoint() != null) {
        acsEndpointURL = idpConfiguration.getAcsEndpoint().getUrl();
    }
    Response authResponse = authnResponseGenerator.generateAuthnResponse(remoteIP, authToken, acsEndpointURL,
            responseValidityTimeInSeconds, info.getAuthnRequestID(), authnInstant, attributeJson,
            info.getEntityId());
    Endpoint endpoint = endpointGenerator.generateEndpoint(
            org.opensaml.saml2.metadata.AssertionConsumerService.DEFAULT_ELEMENT_NAME, acsEndpointURL, null);

    request.getSession().removeAttribute(AuthnRequestInfo.class.getName());

    String relayState = request.getParameter("RelayState");

    //we could use a different adapter to send the response based on request issuer...
    try {
        adapter.sendSAMLMessage(authResponse, endpoint, response, relayState, signingCredential);
    } catch (MessageEncodingException mee) {
        logger.error("Exception encoding SAML message", mee);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
}

From source file:contestWebsite.Data.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets, html/templates");
    ve.init();//from  w ww.  j  av a 2 s.  c o m
    VelocityContext context = new VelocityContext();
    String template = null;

    Pair<Entity, UserCookie> infoAndCookie = init(context, req);

    UserCookie userCookie = infoAndCookie.y;
    boolean loggedIn = (boolean) context.get("loggedIn");

    Entity contestInfo = infoAndCookie.x;

    if (!loggedIn || !userCookie.isAdmin()) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    } else {
        String choice = req.getPathInfo();
        if (choice == null) {
            resp.sendRedirect("/data/overview");
            return;
        } else if (choice.equals("/overview")) {
            template = "data.html";
        } else if (choice.equals("/registrations")) {
            template = "dataRegistrations.html";
            context.put("updated", req.getParameter("updated"));
            context.put("price", contestInfo.getProperty("price"));
            context.put("classificationQuestion", contestInfo.getProperty("classificationQuestion"));
            context.put("dateFormat", new SimpleDateFormat("MMM dd, yyyy hh:mm aa"));
            context.put("Test", Test.class);
            context.put("subjects", Subject.values());
            context.put("levels", Level.values());
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

            Map<Level, List<Entity>> registrations = new HashMap<Level, List<Entity>>();
            for (Level level : Level.values()) {
                Query query = new Query("registration")
                        .setFilter(new FilterPredicate("schoolLevel", FilterOperator.EQUAL, level.toString()));
                List<Entity> regs = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
                if (regs != null) {
                    registrations.put(level, regs);
                }
            }

            context.put("registrations", registrations);

            context.put("regJSONtoList", new Function<Text, List<Map<String, Object>>>() {
                @Override
                public List<Map<String, Object>> apply(Text textJSON) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

                    String rawJSON = unescapeHtml4(textJSON.getValue());
                    try {
                        JSONArray arrayJSON = new JSONArray(rawJSON);
                        for (int i = 0; i < arrayJSON.length(); i++) {
                            JSONObject objectJSON = arrayJSON.getJSONObject(i);

                            Iterator<String> objectKeys = objectJSON.keys();
                            Map<String, Object> map = new HashMap<String, Object>();
                            while (objectKeys.hasNext()) {
                                String objectKey = objectKeys.next();
                                map.put(objectKey, objectJSON.get(objectKey));
                            }

                            list.add(map);
                        }

                        return list;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    return null;
                }
            });

            context.put("esc", new EscapeTool());
        } else if (choice.equals("/questions")) {
            template = "dataQuestions.html";
            context.put("updated", req.getParameter("updated"));
            DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
            Query query = new Query("feedback")
                    .setFilter(new FilterPredicate("resolved", FilterOperator.EQUAL, true));
            List<Entity> resolvedQs = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
            query = new Query("feedback")
                    .setFilter(new FilterPredicate("resolved", FilterOperator.NOT_EQUAL, true));
            List<Entity> unresolvedQs = datastore.prepare(query).asList(FetchOptions.Builder.withDefaults());
            context.put("resolvedQs", resolvedQs);
            context.put("unresolvedQs", unresolvedQs);
        } else if (choice.equals("/scores")) {
            template = "dataScores.html";

            Map<String, Integer> awardCriteria = Retrieve.awardCriteria(contestInfo);

            String type = req.getParameter("type");
            if (type != null) {
                context.put("type", type);
                String[] types = type.split("_");

                String levelString = req.getParameter("level");
                Level level;
                try {
                    level = Level.fromString(levelString);
                } catch (IllegalArgumentException e) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid level: " + levelString);
                    return;
                }

                context.put("level", level.toString());
                context.put("tests", Test.getTests(level));
                context.put("Test", Test.class);

                if (type.equals("students")) {
                    context.put("subjects", Subject.values());
                    context.put("students", Retrieve.allStudents(level));
                } else if (type.startsWith("qualifying_")) {
                    context.put("School", School.class);
                    Pair<School, List<Student>> schoolAndStudents = Retrieve.schoolStudents(types[1], level);
                    context.put("school", schoolAndStudents.x);
                    context.put("students", schoolAndStudents.y);
                } else if (type.startsWith("school_")) {
                    Pair<School, Map<Test, Statistics>> schoolAndStats = Retrieve.schoolOverview(types[1],
                            level);
                    context.put("school", schoolAndStats.x);
                    context.put("statistics", schoolAndStats.y);
                } else if (type.startsWith("category_")) {
                    context.put("test", Test.fromString(types[1]));
                    context.put("trophy", awardCriteria.get("category_" + level + "_trophy"));
                    context.put("medal", awardCriteria.get("category_" + level + "_medal"));
                    context.put("winners", Retrieve.categoryWinners(types[1], level));
                } else if (type.startsWith("categorySweep")) {
                    context.put("trophy", awardCriteria.get("categorySweep_" + level));
                    context.put("winners", Retrieve.categorySweepstakesWinners(level));
                } else if (type.equals("sweep")) {
                    context.put("trophy", awardCriteria.get("sweepstakes_" + level));
                    context.put("winners", Retrieve.sweepstakesWinners(level));
                } else if (type.equals("visualizations")) {
                    Map<Test, Statistics> statistics;
                    try {
                        statistics = Retrieve.visualizations(level);
                    } catch (JSONException e) {
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                        e.printStackTrace();
                        return;
                    }

                    context.put("statistics", statistics);
                } else {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid type: " + type);
                    return;
                }
            } else {
                context.put("type", "overview");
                context.put("testsGradedNums",
                        contestInfo.hasProperty("testsGradedNums")
                                && contestInfo.getProperty("testsGradedNums") != null
                                        ? ((Text) contestInfo.getProperty("testsGradedNums")).getValue()
                                        : "{}");
                if (contestInfo.hasProperty("testsGraded") && contestInfo.getProperty("testsGraded") != null) {
                    context.put("testsGraded", contestInfo.getProperty("testsGraded"));
                }
            }

            Map<Level, List<String>> schools = new HashMap<Level, List<String>>();
            for (Level level : Level.values()) {
                schools.put(level, Retrieve.schoolNames(level));
            }
            context.put("schools", schools);

            context.put("qualifyingCriteria", Retrieve.qualifyingCriteria(contestInfo));
            context.put("hideFullNames", false);
            context.put("subjects", Subject.values());
            context.put("Level", Level.class);
            context.put("levels", Level.values());
            context.put("date", contestInfo.getProperty("updated"));
            context.put("esc", new EscapeTool());
        } else {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid choice: " + choice);
            return;
        }

        close(context, ve.getTemplate(template, "UTF-8"), resp);
    }
}

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

/**
 * Page renderer.//w w  w  .  j  ava  2 s. co m
 *
 * @param page
 *            {@link Page} to be rendered
 * @param req
 *            {@link HttpServletRequest}
 * @return view to render
 */
private String renderPage(Page page, HttpServletRequest req, HttpServletResponse resp)
        throws ViewException, CillaServiceException {
    if (!pageService.isVisible(page)) {
        throw new ErrorResponseException(HttpServletResponse.SC_FORBIDDEN);
    }

    if (handleRestricted(page, req)) {
        req.setAttribute("page", page);
        req.setAttribute("turner",
                new PageTurnerModel(pageDao.fetchPreviousPage(page), pageDao.fetchNextPage(page)));
        return "view/pageUnlock.jsp";
    }

    addHeadersIfRestricted(page, req, resp);

    commentFormHandler.handleComment(page, req);

    List<Page> sameSubject = pageDao.fetchSameSubject(page);
    if (sameSubject != null && sameSubject.size() > 1) {
        // only set if there is at least a second page with the same subject
        req.setAttribute("sameSubject", sameSubject);
    }

    DateRange dr = new DateRange();
    Date orderDate = DateUtils.getOrderDate(page, pageOrder);
    if (orderDate != null) {
        dr.setDate(orderDate);
    }

    FilterModel filter = new FilterModel();
    filter.setDate(dr);
    SearchResult result = searchService.search(filter);
    req.setAttribute("result", result);

    req.setAttribute("page", page);
    req.setAttribute("turner",
            new PageTurnerModel(pageDao.fetchPreviousPage(page), pageDao.fetchNextPage(page)));

    return "view/page.jsp";
}

From source file:com.br.helpdesk.controller.UserGroupController.java

@ExceptionHandler(DataIntegrityViolationException.class)
public void handleDataIntegrityViolationException(DataIntegrityViolationException ex,
        HttpServletResponse response) throws IOException {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
}