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:com.imaginary.home.cloud.api.call.RelayCall.java

@Override
public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path,
        @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp,
        @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters)
        throws RestException, IOException {
    try {/*w  ww  .j  a  v a2  s .c o  m*/
        if (path.length < 2) {
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No PUT on /relay");
        }
        ControllerRelay relay = ControllerRelay.getRelay(path[1]);

        if (relay == null) {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT,
                    "Relay " + path[1] + " not found");
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
        StringBuilder source = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            source.append(line);
            source.append(" ");
        }
        JSONObject object = new JSONObject(source.toString());
        String action;

        if (object.has("action") && !object.isNull("action")) {
            action = object.getString("action");
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "An invalid action was specified (or not specified) in the PUT");
        }
        if (action.equalsIgnoreCase("update")) {
            if (userId != null) {
                throw new RestException(HttpServletResponse.SC_FORBIDDEN, RestException.USER_NOT_ALLOWED,
                        "This API call may be called only by controller relays");
            }
            update(relay, object, resp);
        } else if (action.equalsIgnoreCase("modify")) {
            if (object.has("relay")) {
                object = object.getJSONObject("relay");
            } else {
                object = null;
            }
            if (object == null) {
                throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PUT,
                        "No location was specified in the PUT");
            }
            String name;

            if (object.has("name") && !object.isNull("name")) {
                name = object.getString("name");
            } else {
                name = relay.getName();
            }
            relay.modify(name);
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION,
                    "The action " + action + " is not a valid action.");
        }
    } catch (JSONException e) {
        throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON,
                "Invalid JSON in body");
    } catch (PersistenceException e) {
        e.printStackTrace();
        throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR,
                "Internal database error");
    }
}

From source file:alpha.portal.webapp.controller.UserFormController.java

/**
 * On submit.//from ww w  . j  a  v a 2 s. com
 * 
 * @param user
 *            the user
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @param response
 *            the response
 * @param model
 *            the model
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final User user, final BindingResult errors, final HttpServletRequest request,
        final HttpServletResponse response, final Model model) throws Exception {
    if (request.getParameter("cancel") != null) {
        if (!StringUtils.equals(request.getParameter("from"), "list"))
            return this.getCancelView();
        else
            return this.getSuccessView();
    }

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

        if (errors.hasErrors() && (request.getParameter("delete") == null)) {
            model.addAttribute("contributorRoles", this.contributorRoleManager.getAll());
            return "userform";
        }
    }

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

    final Locale locale = request.getLocale();

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

        return this.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)) {
            final String[] userRoles = request.getParameterValues("userRoles");

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

        final Integer originalVersion = user.getVersion();

        try {
            this.getUserManager().saveUser(user);
        } catch (final AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor
            // userManagerSecurity
            this.log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (final 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);

            model.addAttribute("contributorRoles", this.contributorRoleManager.getAll());
            return "userform";
        }

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

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

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

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

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

    return "redirect:/mainMenu";
}

From source file:ch.entwine.weblounge.kernel.site.SiteServlet.java

/**
 * Depending on whether a call to a jsp is made or not, delegates to the
 * jasper servlet with a controlled context class loader or tries to load the
 * requested file from the bundle as a static resource.
 * // w  w w .  j  a va2 s. c o m
 * @see HttpServlet#service(HttpServletRequest, HttpServletResponse)
 */
@Override
public void service(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    String filename = FilenameUtils.getName(request.getPathInfo());

    // Don't allow listing the root directory?
    if (StringUtils.isBlank(filename)) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Check the requested format. In case of a JSP, this can either be
    // processed (default) or raw, in which case the file contents are
    // returned rather than Jasper's output of it.
    Format format = Format.Processed;
    String f = request.getParameter(PARAM_FORMAT);
    if (StringUtils.isNotBlank(f)) {
        try {
            format = Format.valueOf(StringUtils.capitalize(f.toLowerCase()));
        } catch (IllegalArgumentException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
    }

    if (Format.Processed.equals(format) && filename.endsWith(".jsp")) {
        serviceJavaServerPage(request, response);
    } else {
        serviceResource(request, response);
    }
}

From source file:jipdbs.web.processors.PlayerPenaltyProcessor.java

/**
 * //ww w .  j ava2 s  . c  o  m
 * @param req
 * @param redirect
 * @param player
 * @param server
 * @param penalty
 * @return
 * @throws HttpError
 */
private String removePenalty(HttpServletRequest req, String redirect, Player player, Server server,
        Penalty penalty) throws HttpError {
    if (!penalty.getPlayer().equals(player.getKey())) {
        log.debug("Penalty is not associated to this player");
        Flash.error(req, MessageResource.getMessage("forbidden"));
        throw new HttpError(HttpServletResponse.SC_FORBIDDEN);
    }
    if (penalty.getType().equals(Penalty.BAN)) {
        if (!UserServiceFactory.getUserService().hasPermission(server.getKey(),
                server.getPermission(RemotePermissions.REMOVE_BAN))) {
            log.debug("Cannot remove ban");
            Flash.error(req, MessageResource.getMessage("forbidden"));
            throw new HttpError(HttpServletResponse.SC_FORBIDDEN);
        }
        if (!((server.getRemotePermission() & RemotePermissions.REMOVE_BAN) == RemotePermissions.REMOVE_BAN)) {
            Flash.error(req, MessageResource.getMessage("remote_action_not_available"));
            return redirect;
        }
        Flash.info(req, MessageResource.getMessage("local_action_pending"));
        penalty.setSynced(false);
    } else {
        if (!UserServiceFactory.getUserService().hasPermission(server.getKey(),
                server.getPermission(RemotePermissions.REMOVE_NOTICE))) {
            log.debug("Cannot remove notice");
            Flash.error(req, MessageResource.getMessage("forbidden"));
            throw new HttpError(HttpServletResponse.SC_FORBIDDEN);
        }
        if (!((server.getRemotePermission()
                & RemotePermissions.REMOVE_NOTICE) == RemotePermissions.REMOVE_NOTICE)) {
            Flash.warn(req, MessageResource.getMessage("local_action_only"));
            penalty.setSynced(true);
            penalty.setActive(false);
        } else {
            Flash.info(req, MessageResource.getMessage("local_action_pending"));
            penalty.setSynced(false);
        }
    }
    return null;
}

From source file:com.paladin.mvc.RequestContext.java

public void forbidden() throws IOException {
    error(HttpServletResponse.SC_FORBIDDEN);
}

From source file:com.haulmont.cuba.restapi.DataServiceController.java

@RequestMapping(value = "/api/query.{type}", method = RequestMethod.GET)
public void queryByGet(@PathVariable String type, @RequestParam(value = "e") String entityName,
        @RequestParam(value = "q") String queryStr,
        @RequestParam(value = "view", required = false) String viewName,
        @RequestParam(value = "first", required = false) Integer firstResult,
        @RequestParam(value = "max", required = false) Integer maxResults,
        @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "dynamicAttributes", required = false) Boolean dynamicAttributes,
        HttpServletRequest request, HttpServletResponse response)
        throws IOException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {

    if (!connect(sessionId, response))
        return;//from ww  w.jav  a 2  s  .  c  om

    try {
        MetaClass metaClass = metadata.getClass(entityName);
        if (metaClass == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Persistent entity " + entityName + " does not exist");
            return;
        }

        if (!entityOpPermitted(metaClass, EntityOp.READ)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        Map<String, String[]> queryParams = new HashMap<>(request.getParameterMap());
        queryParams.remove("e");
        queryParams.remove("q");
        queryParams.remove("view");
        queryParams.remove("first");
        queryParams.remove("s");
        queryParams.remove("max");
        queryParams.remove("dynamicAttributes");

        LoadContext loadCtx = new LoadContext(metaClass);
        loadCtx.setLoadDynamicAttributes(Boolean.TRUE.equals(dynamicAttributes));
        LoadContext.Query query = new LoadContext.Query(queryStr);
        loadCtx.setQuery(query);
        if (firstResult != null)
            query.setFirstResult(firstResult);
        if (maxResults != null)
            query.setMaxResults(maxResults);

        for (Map.Entry<String, String[]> entry : queryParams.entrySet()) {
            String paramKey = entry.getKey();
            if (paramKey.endsWith("_type"))
                continue;

            if (entry.getValue().length != 1) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            String paramValue = entry.getValue()[0];
            Object parsedParam = parseQueryParameter(paramKey, paramValue, queryParams);
            query.setParameter(paramKey, parsedParam);
        }

        if (viewName == null) {
            View view = metadata.getViewRepository().getView(metaClass, View.LOCAL);
            loadCtx.setView(new View(view, "local-with-system-props", true));
        } else {
            loadCtx.setView(viewName);
        }
        List<Entity> entities = dataService.loadList(loadCtx);
        Converter converter = conversionFactory.getConverter(type);
        String result = converter.process(entities, metaClass, loadCtx.getView());
        writeResponse(response, result, converter.getMimeType());
    } catch (Throwable e) {
        sendError(request, response, e);
    } finally {
        authentication.end();
    }
}

From source file:org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler.java

/**
 * Authenticates an HTTP client request.
 * <p>/*ww  w .  j  av a 2s .  co m*/
 * It extracts the {@link PseudoAuthenticator#USER_NAME} parameter from the query string and creates
 * an {@link AuthenticationToken} with it.
 * <p>
 * If the HTTP client request does not contain the {@link PseudoAuthenticator#USER_NAME} parameter and
 * the handler is configured to allow anonymous users it returns the {@link AuthenticationToken#ANONYMOUS}
 * token.
 * <p>
 * If the HTTP client request does not contain the {@link PseudoAuthenticator#USER_NAME} parameter and
 * the handler is configured to disallow anonymous users it throws an {@link AuthenticationException}.
 *
 * @param request the HTTP client request.
 * @param response the HTTP client response.
 *
 * @return an authentication token if the HTTP client request is accepted and credentials are valid.
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws AuthenticationException thrown if HTTP client request was not accepted as an authentication request.
 */
@Override
public AuthenticationToken authenticate(HttpServletRequest request, HttpServletResponse response)
        throws IOException, AuthenticationException {
    AuthenticationToken token;
    String userName = getUserName(request);
    if (userName == null) {
        if (getAcceptAnonymous()) {
            token = AuthenticationToken.ANONYMOUS;
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setHeader(WWW_AUTHENTICATE, PSEUDO_AUTH);
            token = null;
        }
    } else {
        token = new AuthenticationToken(userName, userName, getType());
    }
    return token;
}

From source file:TestHTTPSource.java

private void doTestForbidden(HttpRequestBase request) throws Exception {
    HttpResponse response = httpClient.execute(request);
    Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatusLine().getStatusCode());
}

From source file:edu.vt.middleware.servlet.filter.SessionAttributeFilter.java

/**
 * Handle all requests sent to this filter.
 *
 * @param  request  <code>ServletRequest</code>
 * @param  response  <code>ServletResponse</code>
 * @param  chain  <code>FilterChain</code>
 *
 * @throws  ServletException  if an error occurs
 * @throws  IOException  if an error occurs
 */// w ww  .  j  a v a  2 s.  c om
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    boolean success = false;
    String redirect = null;
    if (request instanceof HttpServletRequest) {
        final HttpSession session = ((HttpServletRequest) request).getSession(true);
        final Iterator<String> i = this.attributes.keySet().iterator();
        boolean loop = true;
        while (i.hasNext() && loop) {
            final String name = i.next();
            final Pattern pattern = this.attributes.get(name);
            final Object sessionAttr = session.getAttribute(name);
            if (sessionAttr != null) {
                final String value = String.valueOf(sessionAttr);
                if (pattern.matcher(value).matches()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(value + " matches " + pattern.pattern());
                    }
                    success = true;
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(value + " does not match " + pattern.pattern());
                    }
                    redirect = this.redirects.get(name);
                    success = false;
                    loop = false;
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No session attribute found for " + name);
                }
                if (this.requireAttribute) {
                    redirect = this.redirects.get(name);
                    success = false;
                    loop = false;
                } else {
                    success = true;
                }
            }
        }
    }

    if (!success) {
        if (redirect != null && !"".equals(redirect)) {
            final StringBuffer url = new StringBuffer(redirect);
            if (((HttpServletRequest) request).getRequestURI() != null) {
                url.append("?url=")
                        .append(URLEncoder.encode(((HttpServletRequest) request).getRequestURI(), "UTF-8"));
                if (((HttpServletRequest) request).getQueryString() != null) {
                    url.append(URLEncoder.encode("?", "UTF-8")).append(
                            URLEncoder.encode(((HttpServletRequest) request).getQueryString(), "UTF-8"));
                }
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Forwarding request to " + url.toString());
            }
            this.context.getRequestDispatcher(url.toString()).forward(request, response);
            return;
        } else {
            if (response instanceof HttpServletResponse) {
                ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN,
                        "Request blocked by filter, unable to perform redirect");
                return;
            } else {
                throw new ServletException("Request blocked by filter, unable to perform redirect");
            }
        }
    }
    chain.doFilter(request, response);
}

From source file:common.web.servlets.StaticFilesServlet.java

/** 
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request/*from   w  w  w. j a  va2 s .c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden");
}