Example usage for org.springframework.web.bind.support SessionStatus setComplete

List of usage examples for org.springframework.web.bind.support SessionStatus setComplete

Introduction

In this page you can find the example usage for org.springframework.web.bind.support SessionStatus setComplete.

Prototype

void setComplete();

Source Link

Document

Mark the current handler's session processing as complete, allowing for cleanup of session attributes.

Usage

From source file:org.nishkarma.petclinic.controller.PetController.java

@RequestMapping(value = "/{internationalPath:[a-zA-Z]{2,10}\\-[a-zA-Z]{2,10}}/owners/{ownerId}/pets/new", method = RequestMethod.POST)
public String processCreationForm(@ModelAttribute("pet") Pets pet, BindingResult result, SessionStatus status) {
    try {// w w w .j  ava  2s.co  m
        new PetValidator().validate(pet, result);
        BindingResultDebug.print(result);

        if (result.hasErrors()) {
            return "pets/createOrUpdatePetForm";
        }

        clinicService.savePet(pet);
        status.setComplete();
    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        throw new NishkarmaException(
                NishkarmaMessageSource.getMessage("exception_message", NishkarmaLocaleUtil.resolveLocale()));

    }

    return "redirect:/{internationalPath}/owners/{ownerId}";
}

From source file:org.nishkarma.petclinic.controller.PetController.java

@RequestMapping(value = "/{internationalPath:[a-zA-Z]{2,10}\\-[a-zA-Z]{2,10}}/owners/{ownerId}/pets/{petId}/edit", method = {
        RequestMethod.PUT, RequestMethod.POST })
public String processUpdateForm(@ModelAttribute("pet") Pets pet, BindingResult result, SessionStatus status) {
    try {/*from  ww w  .  ja  v  a 2 s.  co m*/
        // we're not using @Valid annotation here because it is easier to
        // define
        // such validation rule in Java
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "pets/createOrUpdatePetForm";
        }
        this.clinicService.savePet(pet);
        status.setComplete();

        return "redirect:/{internationalPath}/owners/{ownerId}";
    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        throw new NishkarmaException(
                NishkarmaMessageSource.getMessage("exception_message", NishkarmaLocaleUtil.resolveLocale()));

    }
}

From source file:org.nishkarma.petclinic.controller.VisitController.java

@RequestMapping(value = "/{internationalPath:[a-zA-Z]{2,10}\\-[a-zA-Z]{2,10}}/owners/{ownerId}/pets/{petId}/visits/new", method = RequestMethod.POST)
public String processNewVisitForm(@Valid @ModelAttribute("visit") Visits visit, BindingResult result,
        SessionStatus status) {
    try {/*from  w ww.  j ava  2 s  . co  m*/
        if (result.hasErrors()) {
            return "pets/createOrUpdateVisitForm";
        }
        this.clinicService.saveVisit(visit);
        status.setComplete();
    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
        throw new NishkarmaException(
                NishkarmaMessageSource.getMessage("exception_message", NishkarmaLocaleUtil.resolveLocale()));

    }
    return "redirect:/{internationalPath}/owners/{ownerId}";

}

From source file:org.springframework.samples.petclinic.web.OwnerController.java

@RequestMapping(value = "/owners/new", method = RequestMethod.POST)
public String processCreationForm(@Valid Owner owner, BindingResult result, SessionStatus status) {
    if (result.hasErrors()) {
        return "owners/createOrUpdateOwnerForm";
    } else {/*from  ww w .j  a  v a2s.  c o m*/
        this.clinicService.saveOwner(owner, owner.getId());
        status.setComplete();
        return "redirect:/owners/" + owner.getId();
    }
}

From source file:org.springframework.samples.petclinic.web.OwnerController.java

@RequestMapping(value = "/owners/{ownerId}/edit", method = RequestMethod.PUT)
public String processUpdateOwnerForm(@Valid Owner owner, BindingResult result, SessionStatus status) {
    if (result.hasErrors()) {
        return "owners/createOrUpdateOwnerForm";
    } else {//from  www.  jav  a 2  s.  co  m
        this.clinicService.saveOwner(owner, owner.getId());
        status.setComplete();
        return "redirect:/owners/{ownerId}";
    }
}

From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java

@RequestMapping(value = "/oauth/authorize")
public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
        SessionStatus sessionStatus, Principal principal) {

    logger.info("paramters:" + parameters.toString());
    logger.info("model:" + model.toString());
    // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
    // query off of the authorization request instead of referring back to the parameters map. The contents of the
    // parameters map will be stored without change in the AuthorizationRequest object once it is created.
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory()
            .createAuthorizationRequest(parameters);

    Set<String> responseTypes = authorizationRequest.getResponseTypes();

    if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
        throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
    }//  ww w  .j a v a 2s .  com

    if (authorizationRequest.getClientId() == null) {
        throw new InvalidClientException("A client id must be provided");
    }

    try {

        if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
            throw new InsufficientAuthenticationException(
                    "User must be authenticated with Spring Security before authorization can be completed.");
        }

        ClientDetails client = getClientDetailsService()
                .loadClientByClientId(authorizationRequest.getClientId());

        // The resolved redirect URI is either the redirect_uri from the parameters or the one from
        // clientDetails. Either way we need to store it on the AuthorizationRequest.
        String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
        String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
        if (!StringUtils.hasText(resolvedRedirect)) {
            throw new RedirectMismatchException(
                    "A redirectUri must be either supplied or preconfigured in the ClientDetails");
        }
        authorizationRequest.setRedirectUri(resolvedRedirect);

        // We intentionally only validate the parameters requested by the client (ignoring any data that may have
        // been added to the request by the manager).
        oauth2RequestValidator.validateScope(authorizationRequest, client);

        // Some systems may allow for approval decisions to be remembered or approved by default. Check for
        // such logic here, and set the approved flag on the authorization request accordingly.
        authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,
                (Authentication) principal);
        // TODO: is this call necessary?
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        // Validation is all done, so we can check for auto approval...
        if (authorizationRequest.isApproved()) {
            if (responseTypes.contains("token")) {
                return getImplicitGrantResponse(authorizationRequest);
            }
            if (responseTypes.contains("code")) {
                return new ModelAndView(
                        getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal));
            }
        }

        // Place auth request into the model so that it is stored in the session
        // for approveOrDeny to use. That way we make sure that auth request comes from the session,
        // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
        model.put("authorizationRequest", authorizationRequest);

        return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);

    } catch (RuntimeException e) {
        sessionStatus.setComplete();
        throw e;
    }

}

From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java

@RequestMapping(value = "/oauth/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model,
        SessionStatus sessionStatus, Principal principal) {
    logger.info("paramters2:" + approvalParameters.toString());
    logger.info("model:" + model.toString());
    logger.info("PID:" + approvalParameters.get("PID"));
    String PID = (String) approvalParameters.get("PID");
    httpSession.setAttribute("PID", PID);
    logger.info("session PID:" + httpSession.getAttribute("PID"));

    if (!(principal instanceof Authentication)) {
        sessionStatus.setComplete();
        throw new InsufficientAuthenticationException(
                "User must be authenticated with Spring Security before authorizing an access token.");
    }/* w  w  w. j av  a 2 s  . com*/

    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");

    if (authorizationRequest == null) {
        sessionStatus.setComplete();
        throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
    }

    try {
        Set<String> responseTypes = authorizationRequest.getResponseTypes();

        authorizationRequest.setApprovalParameters(approvalParameters);
        authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest,
                (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);

        if (authorizationRequest.getRedirectUri() == null) {
            sessionStatus.setComplete();
            throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
        }

        if (!authorizationRequest.isApproved()) {
            return new RedirectView(getUnsuccessfulRedirect(authorizationRequest,
                    new UserDeniedAuthorizationException("User denied access"),
                    responseTypes.contains("token")), false, true, false);
        }

        if (responseTypes.contains("token")) {
            return getImplicitGrantResponse(authorizationRequest).getView();
        }

        return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal);
    } finally {
        sessionStatus.setComplete();
    }

}

From source file:org.wise.portal.presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.java

/**
 * Maybe you want to be provided with the _page parameter (in order to map the same method for all), as you have in
 * AbstractWizardFormController.//  w  w  w. j  a  v a2  s  .  c o  m
 */
@RequestMapping(method = RequestMethod.POST)
public String processPage(@RequestParam("_page") final int currentPage,
        final @ModelAttribute("passwordReminderParameters") PasswordReminderParameters passwordReminderParameters,
        BindingResult result, SessionStatus status, ModelMap modelMap, final HttpServletResponse response) {

    switch (currentPage) {
    case 1:
        // handle the submit username

        try {
            String username = passwordReminderParameters.getUsername();

            if (username == null) {
                result.rejectValue("username",
                        "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorNoUsername");
            } else {
                username = StringUtils.trimToNull(username);
                User user = userService.retrieveUserByUsername(username);

                /* check to see if user exists and ensure that user is a student */
                if (user == null || !(user.getUserDetails() instanceof StudentUserDetails)) {
                    result.rejectValue("username",
                            "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorUsernameNotFound");
                }
            }
        } catch (EmptyResultDataAccessException e) {
            result.rejectValue("username",
                    "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorUsernameNotFound");
        }
        if (result.hasErrors()) {
            return "forgotaccount/student/passwordreminder";
        }

        // passed validation, put username and account question into page
        String username = passwordReminderParameters.getUsername();

        username = StringUtils.trimToNull(username);
        User user = userService.retrieveUserByUsername(username);

        StudentUserDetails userDetails = (StudentUserDetails) user.getUserDetails();

        modelMap.put(USERNAME, userDetails.getUsername());
        modelMap.put(ACCOUNT_QUESTION, userDetails.getAccountQuestion());

        passwordReminderParameters.setAccountQuestion(userDetails.getAccountQuestion());
        passwordReminderParameters.setAccountAnswer(userDetails.getAccountAnswer());

        return "forgotaccount/student/passwordreminder2";
    case 2:
        // handle the submit with account answer

        ValidationUtils.rejectIfEmptyOrWhitespace(result, "submittedAccountAnswer",
                "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorSubmittedAccountQuestion");

        String submittedAccountAnswer = passwordReminderParameters.getSubmittedAccountAnswer();

        String accountAnswer = passwordReminderParameters.getAccountAnswer();

        accountAnswer = StringUtils.lowerCase(accountAnswer);

        submittedAccountAnswer = StringUtils.lowerCase(submittedAccountAnswer);

        if (accountAnswer == null) {
            /*
             * the account answer is null perhaps because the session has
             * timed out so we will redirect them back to the first
             * password reminder page where they enter their user name
             */
            return "forgotaccount/student/passwordreminder";
        } else if (!accountAnswer.equals(submittedAccountAnswer)) {
            //they have provided an incorrect account answer
            result.reject(
                    "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorSubmittedAccountQuestion");
        }

        if (result.hasErrors()) {
            modelMap.put(USERNAME, passwordReminderParameters.getUsername());
            modelMap.put(ACCOUNT_QUESTION, passwordReminderParameters.getAccountQuestion());

            return "forgotaccount/student/passwordreminder2";
        }

        // passed validation, go to next page
        return "forgotaccount/student/passwordreminder3";
    case 3:
        // handle the submit with new passwords

        ValidationUtils.rejectIfEmptyOrWhitespace(result, "verifyPassword",
                "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorVerifyNewPassword");

        ValidationUtils.rejectIfEmptyOrWhitespace(result, "newPassword",
                "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorVerifyNewPassword");

        if (result.hasErrors()) {
            return "forgotaccount/student/passwordreminder3";
        }

        String newPassword = passwordReminderParameters.getNewPassword();

        String verifyPassword = passwordReminderParameters.getVerifyPassword();

        if (!verifyPassword.equals(newPassword)) {
            result.reject(
                    "presentation.web.controllers.forgotaccount.student.PasswordReminderWizardController.errorVerifyNewPassword");
        }
        if (result.hasErrors()) {
            return "forgotaccount/student/passwordreminder3";
        }

        // passed validation, save new password
        String usernameSubmitted = passwordReminderParameters.getUsername();

        usernameSubmitted = StringUtils.trimToNull(usernameSubmitted);
        User userSubmitted = userService.retrieveUserByUsername(usernameSubmitted);

        if (newPassword != null) {
            userService.updateUserPassword(userSubmitted, newPassword);
        }

        //clear the command object from the session
        status.setComplete();

        modelMap.put("username", passwordReminderParameters.get(PasswordReminderParameters.USERNAME));
        return "forgotaccount/student/passwordreminder4";
    }

    return null;
}

From source file:org.wise.portal.presentation.web.controllers.teacher.run.CreateRunController.java

@RequestMapping(params = "_cancel")
public String processCancel(final HttpServletRequest request, final HttpServletResponse response,
        final SessionStatus status) {
    status.setComplete();
    return "redirect:/teacher/index.html";
}

From source file:org.wise.portal.presentation.web.controllers.teacher.run.CreateRunController.java

/**
 * Creates a run./*from  ww  w.  ja  v a 2  s .c  om*/
 * 
 * This method is called if there is a submit that validates and contains the "_finish"
 * request parameter.
 */
@RequestMapping(params = "_finish")
protected ModelAndView processFinish(final @ModelAttribute("runParameters") RunParameters runParameters,
        final BindingResult result, final HttpServletRequest request, final HttpServletResponse response,
        final SessionStatus status) throws Exception {

    Project project = runParameters.getProject();
    Project newProject; // copied project that will be used for new run.
    Integer projectWiseVersion = project.getWiseVersion();
    if (projectWiseVersion != null && projectWiseVersion == 5) {
        User user = ControllerUtil.getSignedInUser();
        CredentialManager.setRequestCredentials(request, user);
        String pathAllowedToAccess = CredentialManager.getAllowedPathAccess(request);

        /*
         * get the project folder path
         * e.g.
         * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum/667
         */
        String projectFolderPath = FileManager.getProjectFolderPath(project);

        /*
         * get the curriculum base
         * e.g.
         * /Users/geoffreykwan/dev/apache-tomcat-5.5.27/webapps/curriculum
         */
        String curriculumBaseDir = wiseProperties.getProperty("curriculum_base_dir");

        if (SecurityUtils.isAllowedAccess(pathAllowedToAccess, projectFolderPath)) {
            String newProjectDirname = FileManager.copyProject(curriculumBaseDir, projectFolderPath);
            String newProjectPath = "/" + newProjectDirname + "/project.json";
            String newProjectName = project.getName();
            Long parentProjectId = (Long) project.getId();
            ModuleParameters mParams = new ModuleParameters();
            mParams.setUrl(newProjectPath);
            Curnit curnit = curnitService.createCurnit(mParams);
            ProjectParameters pParams = new ProjectParameters();
            pParams.setCurnitId(curnit.getId());
            pParams.setOwner(user);
            pParams.setProjectname(newProjectName);
            pParams.setProjectType(ProjectType.LD);
            pParams.setWiseVersion(5);
            pParams.setParentProjectId(parentProjectId);
            // get the project's metadata from the parent
            ProjectMetadata parentProjectMetadata = project.getMetadata();
            if (parentProjectMetadata != null) {
                // copy into new metadata object
                ProjectMetadata newProjectMetadata = new ProjectMetadataImpl(
                        parentProjectMetadata.toJSONString());
                pParams.setMetadata(newProjectMetadata);
            }
            newProject = projectService.createProject(pParams);

        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return new ModelAndView("errors/accessdenied");
        }
    } else {
        // this will be a new run using a WISE4 project. The new project has already been created.
        // get newProjectId from request and use that to set up the run
        String newProjectId = request.getParameter("newProjectId");
        newProject = projectService.getById(new Long(newProjectId));
    }

    Run run;
    try {
        runParameters.setProject(newProject);
        Locale userLocale = request.getLocale();
        runParameters.setLocale(userLocale);
        runParameters.setPostLevel(5); // always use the highest post-level (starting WISE5)
        run = this.runService.createRun(runParameters);

        User owner = runParameters.getOwner();
        HashSet<User> members = new HashSet<>();
        members.add(owner);

        // create a workgroup for the owners of the run (teacher)
        workgroupService.createWISEWorkgroup("teacher", members, run, null);

    } catch (ObjectNotFoundException e) {
        result.rejectValue("curnitId", "error.curnit-not_found", new Object[] { runParameters.getCurnitId() },
                "Project Not Found.");
        return null;
    }
    ModelAndView modelAndView = new ModelAndView(COMPLETE_VIEW_NAME);
    modelAndView.addObject(RUN_KEY, run);
    Set<String> runIdsToArchive = runParameters.getRunIdsToArchive();
    if (runIdsToArchive != null) {
        for (String runIdStr : runIdsToArchive) {
            Long runId = Long.valueOf(runIdStr);
            Run runToArchive = runService.retrieveById(runId);
            runService.endRun(runToArchive);
        }
    }

    // send email to the recipients in new thread
    //tries to retrieve the user from the session
    User user = ControllerUtil.getSignedInUser();
    Locale locale = request.getLocale();
    String fullWiseContextPath = ControllerUtil.getPortalUrlString(request); // e.g. http://localhost:8080/wise

    CreateRunEmailService emailService = new CreateRunEmailService(runParameters, run, user, locale,
            fullWiseContextPath);
    Thread thread = new Thread(emailService);
    thread.start();

    status.setComplete();
    return modelAndView;
}