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:eu.trentorise.smartcampus.unidataservice.controller.rest.StudentInfoController.java

@RequestMapping(method = RequestMethod.GET, value = "/getstudentdata/{userId}")
public @ResponseBody StudentInfoData getStudentInfo(HttpServletRequest request, HttpServletResponse response,
        @PathVariable String userId) throws InvocationException {
    try {//from  w  w w . ja v  a  2  s. c  om
        User user = getUserObject(userId);
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        String token = getToken(request);
        String idAda = getIdAda(userId, token);
        StudentInfoData sd = getStudentInfo(idAda);
        if (sd != null) {
            return sd;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

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

From source file:com.sun.faban.harness.webclient.RunUploader.java

/**
 * Post method to upload the run.//w ww.  j ava  2 s  . com
 * @param request The servlet request
 * @param response The servlet response
 * @throws ServletException If the servlet fails
 * @throws IOException If there is an I/O error
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String host = null;
    String key = null;
    boolean origin = false; // Whether the upload is to the original
    // run requestor. If so, key is needed.

    DiskFileUpload fu = new DiskFileUpload();
    // No maximum size
    fu.setSizeMax(-1);
    // maximum size that will be stored in memory
    fu.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    fu.setRepositoryPath(Config.TMP_DIR);

    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }
    // assume we know there are two files. The first file is a small
    // text file, the second is unknown and is written to a file on
    // the server
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem item = (FileItem) i.next();
        String fieldName = item.getFieldName();
        if (item.isFormField()) {
            if ("host".equals(fieldName)) {
                host = item.getString();
            } else if ("key".equals(fieldName)) {
                key = item.getString();
            } else if ("origin".equals(fieldName)) {
                String value = item.getString();
                origin = Boolean.parseBoolean(value);
            }
            continue;
        }

        if (host == null) {
            logger.warning("Host not received on upload request!");
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            break;
        }

        // The host, origin, key info must be here before we receive
        // any file.
        if (origin) {
            if (Config.daemonMode != Config.DaemonModes.POLLEE) {
                logger.warning("Origin upload requested. Not pollee!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (key == null) {
                logger.warning("Origin upload requested. No key!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            if (!RunRetriever.authenticate(host, key)) {
                logger.warning("Origin upload requested. " + "Host/key mismatch: " + host + '/' + key + "!");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
        }

        if (!"jarfile".equals(fieldName)) // ignore
            continue;

        String fileName = item.getName();

        if (fileName == null) // We don't process files without names
            continue;

        // Now, this name may have a path attached, dependent on the
        // source browser. We need to cover all possible clients...
        char[] pathSeparators = { '/', '\\' };
        // Well, if there is another separator we did not account for,
        // just add it above.

        for (int j = 0; j < pathSeparators.length; j++) {
            int idx = fileName.lastIndexOf(pathSeparators[j]);
            if (idx != -1) {
                fileName = fileName.substring(idx + 1);
                break;
            }
        }

        // Ignore all non-jarfiles.
        if (!fileName.toLowerCase().endsWith(".jar"))
            continue;
        File uploadFile = new File(Config.TMP_DIR, host + '.' + fileName);
        try {
            item.write(uploadFile);
        } catch (Exception e) {
            throw new ServletException(e);
        }
        File runTmp = unjarTmp(uploadFile);

        String runId = null;

        if (origin) {
            // Change origin file to know where this run came from.
            File metaInf = new File(runTmp, "META-INF");
            File originFile = new File(metaInf, "origin");
            if (!originFile.exists()) {
                logger.warning("Origin upload requested. Origin file" + "does not exist!");
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Origin file does not exist!");
                break;
            }

            RunId origRun;
            try {
                origRun = new RunId(readStringFromFile(originFile).trim());
            } catch (IndexOutOfBoundsException e) {
                response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Origin file error. " + e.getMessage());
                break;
            }

            runId = origRun.getBenchName() + '.' + origRun.getRunSeq();
            String localHost = origRun.getHostName();
            if (!localHost.equals(Config.FABAN_HOST)) {
                logger.warning("Origin upload requested. Origin host " + localHost
                        + " does not match this host " + Config.FABAN_HOST + '!');
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                break;
            }
            writeStringToFile(runTmp.getName(), originFile);
        } else {
            runId = runTmp.getName();
        }

        if (recursiveCopy(runTmp, new File(Config.OUT_DIR, runId))) {
            uploadFile.delete();
            recursiveDelete(runTmp);
        } else {
            logger.warning("Origin upload requested. Copy error!");
            response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE);
            break;
        }

        response.setStatus(HttpServletResponse.SC_CREATED);
        break;
    }
}

From source file:com.skilrock.lms.web.loginMgmt.RolesInterceptor.java

/**
 * Handles a rejection by sending a 403 HTTP error
 * //from  w w w. j a va2s.c o m
 * @param invocation
 *            The invocation
 * @return The result code
 * @throws Exception
 */
protected String handleRejection(ActionInvocation invocation, HttpServletResponse response) throws Exception {
    // logger.debug("I am in Allowed roles444444444444444444444");
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
    return null;
}

From source file:com.logiclander.jaasmine.authentication.http.SimpleLogoutServlet.java

/**
 * Logs out the Subject associated with the user.
 *
 * After the logout is done, the request is dispatched to a Servlet or JSP
 * specified by the {@code postLogoutProcessorName} init-param.  If the
 * param was not specified, a {@code text/plain} message will be written
 * to the response./*from  w  w w  . ja v  a  2s .  c om*/
 *
 * This method is not idempotent.  If a request is made successfully once,
 * the user will be logged out.  Subsequent requests without a login will
 * cause an HTTP 403 - Forbidden to be returned.
 *
 * @param req the HttpServletRequest
 * @param resp the HttpServletResponse
 * @throws ServletException if a ServletException is thrown after the
 * request is dispatched to the post logout processor.
 * @throws IOException if an I/O error occurs.
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession sess = req.getSession();
    Subject subj = (Subject) sess.getAttribute(AuthenticationService.SUBJECT_KEY);

    if (subj == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Log out the Subject
    AuthenticationService as = new SimpleAuthenticationService(appName);
    as.logout(subj);

    // Invalidate the session
    sess.invalidate();

    resp.setStatus(HttpServletResponse.SC_OK);
    RequestDispatcher rd = getServletContext().getNamedDispatcher(postLogoutProcessorName);

    if (rd != null) {
        resp.setContentType("text/html");
        rd.include(req, resp);
    } else {
        sendPlainTextResponse(resp);
    }

}

From source file:com.betfair.tornjak.monitor.overlay.AuthUtilsTest.java

@Test
public void testNotAuthorised() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletContext context = mock(ServletContext.class);

    Principal p = mock(Principal.class);

    when(context.getAttribute("com.betfair.tornjak.monitor.overlay.RolePerms"))
            .thenReturn(new AuthBuilder().role("jmxadmin").allow(".*:.*:.*").getRolePerms());
    when(request.getUserPrincipal()).thenReturn(p);
    when(request.isUserInRole("jmxadmin")).thenReturn(false);

    Auth auth = AuthUtils.checkAuthorised(request, response, context);
    assertThat("User should not be authorised", auth, nullValue());

    verify(response, times(1)).sendError(HttpServletResponse.SC_FORBIDDEN);
    verifyNoMoreInteractions(response);// w ww.  j ava  2 s. c  om
}

From source file:de.thm.arsnova.controller.UserController.java

@RequestMapping(value = { "/{username}/resetpassword" }, method = RequestMethod.POST)
public void resetPassword(@PathVariable final String username, @RequestParam(required = false) final String key,
        @RequestParam(required = false) final String password, final HttpServletRequest request,
        final HttpServletResponse response) {
    DbUser dbUser = userService.getDbUser(username);
    if (null == dbUser) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);

        return;/*from  w ww  .j a  va2 s. co  m*/
    }

    if (null != key) {
        if (!userService.resetPassword(dbUser, key, password)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
    } else {
        userService.initiatePasswordReset(username);
    }
}

From source file:com.liusoft.dlog4j.action.ActionExtend.java

/**
 * Action???????? //  w w w.j  a  v a 2s  .c  o m
 * 1.??eventSubmit_XxxxdoXxxx
 * 2.?__method?do
 */
public final ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {
    ActionForward af = beforeExecute(mapping, form, req, res);
    if (af != null)
        return af;

    String param = null;
    String value = null;

    String __method = req.getParameter(METHOD_IDENT_PARAM);
    if (StringUtils.isNotBlank(__method)) {
        param = METHOD_PREFIX + __method;
    } else {
        for (Enumeration params = req.getParameterNames(); params.hasMoreElements();) {
            String t_param = (String) params.nextElement();
            if (t_param.startsWith(SUBMIT_BUTTON_PREFIX)) {
                value = req.getParameter(t_param);
                param = METHOD_PREFIX + t_param.substring(SUBMIT_BUTTON_PREFIX.length());
                break;
            }
        }
    }

    if (param == null)
        param = "doDefault";

    try {
        return callActionMethod(mapping, form, req, res, param, value);
    } catch (InvocationTargetException e) {
        Throwable t = e.getCause();
        if (t instanceof IllegalAccessException) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }
        log.error("Exception occur when calling " + param + " in action:" + getClass().getName(), t);
        if (t instanceof Exception)
            throw (Exception) t;
        else
            throw new Exception(t);
    } catch (NoSuchMethodException e) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return null;
    } finally {
        afterExecute(mapping, form, req, res);
    }
}

From source file:com.haulmont.cuba.web.controllers.LogDownloadController.java

protected UserSession getSession(String sessionId, HttpServletResponse response) throws IOException {
    UUID sessionUUID;//from  w  w w .j  a v  a  2 s  .c om
    try {
        sessionUUID = UUID.fromString(sessionId);
    } catch (Exception e) {
        log.error("Error parsing sessionId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
    AppContext.setSecurityContext(new SecurityContext(sessionUUID));
    try {
        UserSession session = userSessionService.getUserSession(sessionUUID);
        if (session == null)
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return session;
    } finally {
        AppContext.setSecurityContext(null);
    }
}

From source file:com.haulmont.cuba.portal.controllers.LogDownloadController.java

protected UserSession getSession(String sessionId, HttpServletResponse response) throws IOException {
    UUID sessionUUID;/*from  w  ww .  j  a v a  2s . c  om*/
    try {
        sessionUUID = UUID.fromString(sessionId);
    } catch (Exception e) {
        log.error("Error parsing sessionId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }

    AppContext.setSecurityContext(new SecurityContext(sessionUUID));
    try {
        UserSession session = userSessionService.getUserSession(sessionUUID);
        if (session == null)
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return session;
    } finally {
        AppContext.setSecurityContext(null);
    }
}

From source file:ejportal.webapp.action.UserAction.java

/**
 * Grab the user from the database based on the "id" passed in.
 * /* www . ja v  a2 s . c o  m*/
 * @return success if user found
 * @throws IOException
 *             can happen when sending a "forbidden" from
 *             response.sendError()
 */
public String edit() throws IOException {
    final HttpServletRequest request = this.getRequest();
    final boolean editProfile = (request.getRequestURI().indexOf("editProfile") > -1);

    // if URL is "editProfile" - make sure it's the current user
    if (editProfile && ((request.getParameter("id") != null) || (request.getParameter("from") != null))) {
        ServletActionContext.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
        this.log.warn("User '" + request.getRemoteUser() + "' is trying to edit user '"
                + request.getParameter("id") + "'");
        return null;
    }

    // if a user's id is passed in
    if (this.id != null) {
        // lookup the user using that id
        this.user = this.userManager.getUser(this.id);
    } else if (editProfile) {
        this.user = this.userManager.getUserByUsername(request.getRemoteUser());
    } else {
        this.user = new User();
        // TODO hier hart kondiert - evtl aendern
        this.user.addRole(new Role("ROLE_EXTERN"));
        // user.addRole(new Role(Constants.USER_ROLE));
    }

    if (this.user.getUsername() != null) {
        this.user.setConfirmPassword(this.user.getPassword());

        // if user logged in with remember me, display a warning that they
        // can't change passwords
        this.log.debug("checking for remember me login...");

        final AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
        final SecurityContext ctx = SecurityContextHolder.getContext();

        if (ctx != null) {
            final Authentication auth = ctx.getAuthentication();

            if (resolver.isRememberMe(auth)) {
                this.getSession().setAttribute("cookieLogin", "true");
                this.saveMessage(this.getText("userProfile.cookieLogin"));
            }
        }
    }

    return Action.SUCCESS;
}