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:info.magnolia.cms.filters.AggregatorFilter.java

@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    boolean success;
    try {/*w  ww . j a v  a  2 s  .com*/
        success = collect();
    } catch (AccessDeniedException e) {
        // don't throw further, simply return error and break filter chain
        log.debug(e.getMessage(), e);
        if (!response.isCommitted()) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
        // stop the chain
        return;
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    }

    if (!success) {
        log.debug("Resource not found, redirecting request for [{}] to 404 URI", request.getRequestURI());

        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            log.info("Unable to redirect to 404 page, response is already committed. URI was {}",
                    request.getRequestURI());
        }
        // stop the chain
        return;
    }
    chain.doFilter(request, response);
}

From source file:eu.trentorise.smartcampus.feedback.controller.FeedbackController.java

/**
 * Upload feedback data. Take as input {@link Feedback} instance as JSON String passed 
 * in 'body' param and the {@link MultipartFile} file param for the (optional) screenshot data.
 * @param request/*www.j av a  2  s. co m*/
 * @param response
 * @param body
 * @param file
 * @return
 */
@RequestMapping(value = "/feedback", method = RequestMethod.POST)
public @ResponseBody String feedback(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("body") String body, @RequestParam(required = false, value = "file") MultipartFile file) {
    User user = null;
    try {
        user = retrieveUser(request, response);
    } catch (AcServiceException e) {
        logger.error("Error reading the user: " + e.getMessage());
    }
    if (user == null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }

    try {
        Feedback feedback = mapper.readValue(body, Feedback.class);
        if (feedback == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return null;
        }
        feedback.setCreatorId("" + user.getId());
        feedback.setUser(feedback.getCreatorId());

        if (file != null) {
            String fileId = feedbackFileManager.storeFile(file.getBytes());
            feedback.setFileId(fileId);
        }
        feedback = feedbackManager.storeFeedback(feedback);
        return feedback.getId();
    } catch (Exception e) {
        logger.error("Error storing feedback: " + e.getMessage());
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
}

From source file:com.kesdip.license.web.servlet.UpdateServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//*from   ww  w  .j a  v  a  2s  .  c om*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    // make sure this is not a browser
    String userAgent = req.getHeader("user-agent");
    if (!userAgent.startsWith("Java")) {
        if (logger.isDebugEnabled()) {
            logger.debug("'" + userAgent + "' forbidden");
        }
        res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE);
        return;
    }
    // get the customer UUID
    String uuid = req.getRemoteUser();
    if (StringUtils.isEmpty(uuid)) {
        logger.debug("Empty customer uuid");
        res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE);
        return;
    }
    // if requesting site.xml or the root (Eclipse does both), check the DB
    String uri = req.getRequestURI();
    String servletPath = req.getServletPath();
    if (uri.endsWith(servletPath) || uri.endsWith(SITE_XML)) {
        if (!supportEnabled(uuid)) {
            logger.warn("Update denied for '" + uuid + "'");
            res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE);
            return;
        }
    }
    // if requesting site.xml, log the request
    if (uri.endsWith(SITE_XML)) {
        logUpdateRequest(uuid, req.getRemoteAddr(), userAgent);
    }
    // all OK, forward to the actual file
    String translatedUri = uri.substring(req.getContextPath().length()).replace(servletPath, actualUpdateRoot);
    if (logger.isTraceEnabled()) {
        logger.trace("Forwarding to '" + translatedUri + "'");
    }
    RequestDispatcher rd = servletContext.getRequestDispatcher(translatedUri);
    rd.forward(req, res);
}

From source file:org.basinmc.irc.bridge.github.TeamCityHandler.java

/**
 * {@inheritDoc}//ww  w . j a  v a 2 s  . c o  m
 */
@Override
public void handle(@Nonnull String target, @Nonnull Request baseRequest, @Nonnull HttpServletRequest request,
        @Nonnull HttpServletResponse response) throws IOException, ServletException {
    if (!target.startsWith("/build")) {
        return;
    }

    if (this.serverAddress != null && !this.serverAddress.isEmpty()
            && !this.serverAddress.equals(request.getRemoteAddr())) {
        logger.info("Access denied to build webhook from " + request.getRemoteAddr());

        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        baseRequest.setHandled(true);
        return;
    }

    JsonNode data;

    try (InputStream inputStream = request.getInputStream()) {
        data = reader.readTree(inputStream).get("build");
    }

    switch (target) {
    default:
        return;
    case "/build/started":
        this.bridge.sendMessage(String.format(MESSAGE_START, data.get("buildFullName").asText(),
                data.get("agentName").asText(), data.get("buildStatusUrl").asText()));
        break;
    case "/build/success":
        this.bridge.sendMessage(String.format(MESSAGE_SUCCESS, data.get("buildFullName").asText(),
                data.get("buildStatusUrl").asText()));
        break;
    case "/build/failure":
        this.bridge.sendMessage(String.format(MESSAGE_FAILURE, data.get("buildFullName").asText(),
                data.get("buildStatusUrl").asText()));
        break;
    }

    logger.info("Handled build webhook from " + request.getRemoteAddr());
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    baseRequest.setHandled(true);
}

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

/**
 * Shows a map of the location the header picture was taken at.
 *///from   w  ww.  ja  v  a2  s.co  m
@Framed
@View(pattern = "/header/${header.id}/map/${#simplify(header.name)}.html", name = "header.map")
public String headerMapView(@PathPart("header.id") Header header, HttpServletRequest req) throws ViewException {
    if (!headerService.isVisible(header)) {
        throw new ErrorResponseException(HttpServletResponse.SC_FORBIDDEN);
    }

    req.setAttribute("headerImage", header);

    return "view/headerMap.jsp";
}

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

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

    if (log.isDebugEnabled()) {
        log.debug("entering 'onSubmit' method...");
    }
    Locale locale = request.getLocale();

    user.setEnabled(true);

    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));

    try {
        this.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());
        return "signup";
    }

    saveMessage(request, getText("user.registered", user.getUsername(), locale));
    request.getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);

    // log user in automatically
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(),
            user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);

    // Send user an e-mail
    if (log.isDebugEnabled()) {
        log.debug("Sending user '" + user.getUsername() + "' an account information e-mail");
    }

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

    try {
        sendUserMessage(user, getText("signup.email.message", locale), RequestUtil.getAppURL(request));
    } catch (MailException me) {
        saveError(request, me.getMostSpecificCause().getMessage());
    }

    return getSuccessView();
}

From source file:org.apache.hadoop.security.AuthenticationWithProxyUserFilter.java

/**
 * This method provide the ability to do pre/post tasks
 * in filter chain. Override this method to authorize
 * proxy user between AuthenticationFilter and next filter.
 * @param filterChain the filter chain object.
 * @param request the request object./*from www  . j a v a 2  s.  co  m*/
 * @param response the response object.
 *
 * @throws IOException
 * @throws ServletException
 */
@Override
protected void doFilter(FilterChain filterChain, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // authorize proxy user before calling next filter.
    String proxyUser = getDoAs(request);
    if (proxyUser != null) {
        UserGroupInformation realUser = UserGroupInformation.createRemoteUser(request.getRemoteUser());
        UserGroupInformation proxyUserInfo = UserGroupInformation.createProxyUser(proxyUser, realUser);

        try {
            ProxyUsers.authorize(proxyUserInfo, request.getRemoteAddr());
        } catch (AuthorizationException ex) {
            HttpExceptionUtils.createServletExceptionResponse(response, HttpServletResponse.SC_FORBIDDEN, ex);
            // stop filter chain if there is an Authorization Exception.
            return;
        }

        final UserGroupInformation finalProxyUser = proxyUserInfo;
        // Change the remote user after proxy user is authorized.
        request = new HttpServletRequestWrapper(request) {
            @Override
            public String getRemoteUser() {
                return finalProxyUser.getUserName();
            }
        };

    }
    filterChain.doFilter(request, response);
}

From source file:com.flexive.war.filter.BackendAuthorizationFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    // get URI without application context path
    final UserTicket ticket = FxContext.getUserTicket();
    if (ticket.isGuest() && servletRequest instanceof FxRequest) {
        final FxRequest request = (FxRequest) servletRequest;
        if (request.isDynamicContent()) {
            // not logged in at all - forward to login page
            FilterUtils.sendRedirect(servletRequest, servletResponse, "/pub/login.jsf"
                    // guess whether we got a session timeout (from within the backend) or a new request
                    + (StringUtils.indexOf(((HttpServletRequest) servletRequest).getHeader("Referer"),
                            "/adm/") != -1 ? "?sessionExpired=true" : ""));
        } else {//from   w ww .  ja va2s  .c om
            // static content (e.g. images), forbid access
            ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } else if (!ticket.isInRole(Role.BackendAccess)) {
        // logged in, but lacks role for backend access - show error page
        servletRequest.getRequestDispatcher("/pub/backendRestricted.jsf").forward(servletRequest,
                servletResponse);
    } else {
        // proceed
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:io.wcm.caconfig.editor.impl.ConfigNamesServlet.java

@Override
protected void doGet(@NotNull SlingHttpServletRequest request, @NotNull SlingHttpServletResponse response)
        throws ServletException, IOException {
    if (!editorConfig.isEnabled()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*w ww  .j  av  a  2s  . co  m*/
    }

    Resource contextResource = request.getResource();
    try {
        JSONObject result = new JSONObject();
        result.putOpt("contextPath", getContextPath(contextResource));
        result.put("configNames", getConfigNames(contextResource));

        response.setContentType("application/json;charset=" + CharEncoding.UTF_8);
        response.getWriter().write(result.toString());
    } catch (JSONException ex) {
        throw new ServletException("Unable to generate JSON.", ex);
    }
}

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

/**
 * {@inheritDoc}//  w  w  w . j a va 2  s .c o  m
 * @see org.springframework.security.ui.AccessDeniedHandler#handle(
 *    javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 *    org.springframework.security.AccessDeniedException)
 */
public void handle(final ServletRequest req, final ServletResponse res, final AccessDeniedException e)
        throws IOException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (errorPage != null || (ajaxErrorPage != null && request.getHeader(ajaxHeader) != null)) {
        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 commonRedirectUrl = scheme + "://" + serverName + ((includePort) ? (":" + serverPort) : "")
                + contextPath;
        String redirectUrl = commonRedirectUrl;
        if (ajaxErrorPage != null && request.getHeader(ajaxHeader) != null) {
            redirectUrl += ajaxErrorPage;
        } else if (errorPage != null) {
            redirectUrl += errorPage;
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
        }

        response.sendRedirect(response.encodeRedirectURL(redirectUrl));
    }

    if (!response.isCommitted()) {
        // Send 403 (we do this after response has been written)
        response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
    }
}