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:wad.controller.ReceiptController.java

@RequestMapping(method = RequestMethod.POST)
public String addReceipt(@RequestParam("file") MultipartFile file, @PathVariable Long expenseId,
        @ModelAttribute Receipt receipt, BindingResult bindingResult, @ModelAttribute Expense expense,
        SessionStatus status, RedirectAttributes redirectAttrs) throws IOException {

    if (expense == null || !expense.isEditableBy(userService.getCurrentUser())) {
        throw new ResourceNotFoundException();
    }/*from  w ww. ja  v a 2s.  com*/

    receipt.setName(file.getName());
    receipt.setMediaType(file.getContentType());
    receipt.setSize(file.getSize());
    receipt.setContent(file.getBytes());
    receipt.setSubmitted(new Date());
    receipt.setExpense(expense);

    receiptValidator.validate(receipt, bindingResult);

    if (bindingResult.hasErrors()) {
        redirectAttrs.addFlashAttribute("errors", bindingResult.getAllErrors());
        return "redirect:/expenses/" + expense.getId();
    }

    receiptRepository.save(receipt);

    status.setComplete();

    return "redirect:/expenses/" + expense.getId();
}

From source file:com.benfante.minimark.controllers.AssessmentFillingController.java

@RequestMapping
@Validation(view = FORM_VIEW)//from w w w  .ja  v a 2s.  co m
public String start(@ModelAttribute(ASSESSMENT_ATTR_NAME) AssessmentFilling assessmentFilling,
        BindingResult result, SessionStatus status, HttpServletRequest req, HttpSession session, Model model) {
    session.setAttribute(STUDENT_ID_ATTR_NAME, assessmentFilling.getIdentifier());
    AssessmentFilling prevFilling = assessmentFillingDao.findByAssessmentIdAndIdentifier(
            assessmentFilling.getAssessment().getId(), assessmentFilling.getIdentifier());
    if (prevFilling != null) { // this student already started this assessment
        model.addAttribute(ASSESSMENT_ATTR_NAME, prevFilling);
        FlashHelper.setRedirectError(req, "AssessmentAlreadyStarted");
        if (prevFilling.getSubmittedDate() != null) { // already submitted, return to the resul
            status.setComplete();
            logger.info(prevFilling.getLastName() + " " + prevFilling.getFirstName()
                    + " looked at the result of the assessment " + prevFilling.getId() + " (original:"
                    + prevFilling.getAssessment().getId() + ")");
            return "redirect:showResult.html?id=" + prevFilling.getId();
        } else { // return to the filling page
            logger.info(prevFilling.getLastName() + " " + prevFilling.getFirstName()
                    + " went again to fill the assessment " + prevFilling.getId() + " (original:"
                    + prevFilling.getAssessment().getId() + ")");
            return "redirect:fill.html";
        }
    } else {
        assessmentFilling.setLoggedIn(Boolean.TRUE);
        assessmentFilling.setStartDate(new Date());
        assessmentFillingDao.store(assessmentFilling);
        logger.info(assessmentFilling.getLastName() + " " + assessmentFilling.getFirstName()
                + " logged in assessment " + assessmentFilling.getId() + " (original:"
                + assessmentFilling.getAssessment().getId() + ")");
        return "redirect:fill.html";
    }
}

From source file:org.sloth.web.observation.EditObservationController.java

/**
 * Handles the {@code POST} request and saves the changes made.
 *//*from   ww  w. j a va  2s  .co m*/
@RequestMapping(method = POST)
public String processSubmit(@ModelAttribute Observation observation, BindingResult result, SessionStatus status,
        HttpSession session, HttpServletResponse response) throws IOException {
    if (isAdmin(session) || isOwnObservation(session, observation)) {
        this.observationValidator.validate(observation, result);
        if (result.hasErrors()) {
            return VIEW;
        } else {
            try {
                Observation oOrig = this.observationService.getObservation(observation.getId());
                mergeObservation(observation, oOrig);
                this.observationService.updateObservation(oOrig);
            } catch (Exception e) {
                logger.warn("Unexpected Exception", e);
                return internalErrorView(response);
            } finally {
                status.setComplete();
            }
            return "redirect:/o";
        }
    }
    return forbiddenView(response);
}

From source file:fi.koku.kks.controller.CreateCollectionController.java

@ActionMapping(params = "action=createCollection")
public void create(PortletSession session, @ModelAttribute(value = "child") Person child, Creation creation,
        BindingResult bindingResult, ActionResponse response, SessionStatus sessionStatus) {

    LOG.debug("create collection");

    creation.validate(creation, bindingResult);
    if (!bindingResult.hasErrors()) {

        Creatable a = Creatable.create(creation.getField());
        String name = "".equals(creation.getName()) ? a.getName() : creation.getName();
        String id = kksService.createKksCollection(name, a.getId(), child.getPic(),
                Utils.getPicFromSession(session));

        if (id == null) {
            bindingResult.reject("collection.create.failed");
        }//from   w  ww  .  ja v a  2s. co  m

        creation.setField("");
        creation.setName("");
        response.setRenderParameter("action", "showChild");
        response.setRenderParameter("pic", child.getPic());

        if (id != null) {
            sessionStatus.setComplete();
        }
    } else {
        response.setRenderParameter("action", "showChild");
        response.setRenderParameter("pic", child.getPic());
    }
}

From source file:org.openmrs.module.patientflags.web.FindFlaggedPatientsController.java

@RequestMapping(method = RequestMethod.GET, params = "tags")
public ModelAndView processSubmit(@ModelAttribute("filter") Filter filter, BindingResult result,
        SessionStatus status) {

    if (result.hasErrors()) {
        return new ModelAndView("/module/patientflags/findFlaggedPatients");
    }/*from ww  w  .j a va2  s.com*/

    FlagService flagService = Context.getService(FlagService.class);

    // get the flags to test on
    List<Flag> flags = flagService.getFlagsByFilter(filter);

    // returns a map of flagged Patients and the respective flags
    Cohort flaggedPatients = flagService.getFlaggedPatients(flags);
    Cohort allPatients = Context.getPatientSetService().getAllPatients();

    // create the model map
    ModelMap model = new ModelMap();
    model.addAttribute("flaggedPatients", flaggedPatients.getMemberIds());
    model.addAttribute("allPatients", allPatients);

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

    // displays the query results
    return new ModelAndView("/module/patientflags/findFlaggedPatientsResults", model);
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.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) {

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

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

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

    // Check to ensure the Authorization Request was not modified during the user approval step
    @SuppressWarnings("unchecked")
    Map<String, Object> originalAuthorizationRequest = (Map<String, Object>) model
            .get(ORIGINAL_AUTHORIZATION_REQUEST);
    if (isAuthorizationRequestModified(authorizationRequest, originalAuthorizationRequest)) {
        logger.warn("The requested scopes are invalid");
        throw new InvalidRequestException("Changes were detected from the original authorization request.");
    }

    for (String approvalParameter : approvalParameters.keySet()) {
        if (approvalParameter.startsWith(SCOPE_PREFIX)) {
            String scope = approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length());
            Set<String> originalScopes = (Set<String>) originalAuthorizationRequest.get("scope");
            if (!originalScopes.contains(scope)) {
                sessionStatus.setComplete();

                logger.warn("The requested scopes are invalid");
                return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new InvalidScopeException(
                        "The requested scopes are invalid. Please use valid scope names in the request."),
                        false), false, true, false);
            }
        }
    }

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

        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") || responseTypes.contains("id_token")) {
            return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal, grantType)
                    .getView();
        }

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

}

From source file:nl.surfnet.coin.teams.control.DetailTeamController.java

@RequestMapping(value = "/dodeleteteam.shtml", method = RequestMethod.POST)
public RedirectView deleteTeam(ModelMap modelMap, HttpServletRequest request,
        @ModelAttribute(TokenUtil.TOKENCHECK) String sessionToken, @RequestParam() String token,
        @RequestParam("team") String teamId, SessionStatus status) throws UnsupportedEncodingException {
    TokenUtil.checkTokens(sessionToken, token, status);

    Person person = (Person) request.getSession().getAttribute(LoginInterceptor.PERSON_SESSION_KEY);
    String personId = person.getId();

    if (!StringUtils.hasText(teamId)) {
        status.setComplete();
        modelMap.clear();//  ww  w  .  j  av  a  2  s  .co  m
        throw new RuntimeException("Parameter error.");
    }

    Member member = grouperTeamService.findMember(teamId, personId);
    if (member.getRoles().contains(Role.Admin)) {
        // Delete the team
        Team team = grouperTeamService.findTeamById(teamId);
        final List<Invitation> invitationsForTeam = teamInviteService.findAllInvitationsForTeam(team);
        for (Invitation invitation : invitationsForTeam) {
            teamInviteService.delete(invitation);
        }
        final List<TeamExternalGroup> teamExternalGroups = teamExternalGroupDao.getByTeamIdentifier(teamId);
        for (TeamExternalGroup teamExternalGroup : teamExternalGroups) {
            teamExternalGroupDao.delete(teamExternalGroup);
        }
        grouperTeamService.deleteTeam(teamId);
        AuditLog.log("User {} deleted team {}", personId, teamId);

        status.setComplete();
        return new RedirectView("home.shtml?teams=my&view=" + ViewUtil.getView(request), false, true, false);
    }

    status.setComplete();
    modelMap.clear();
    return new RedirectView(
            "detailteam.shtml?team=" + URLEncoder.encode(teamId, UTF_8) + "&view=" + ViewUtil.getView(request));
}

From source file:csns.web.controller.SiteBlockControllerS.java

@RequestMapping(value = "/site/{qtr}/{cc}-{sn}/block/addItem", method = RequestMethod.POST)
public String addItem(@PathVariable String qtr, @PathVariable String cc, @PathVariable int sn,
        @ModelAttribute Item item, @RequestParam Long blockId,
        @RequestParam(value = "uploadedFile", required = false) MultipartFile uploadedFile,
        BindingResult bindingResult, SessionStatus sessionStatus) {
    itemValidator.validate(item, uploadedFile, bindingResult);
    if (bindingResult.hasErrors())
        return "site/block/addItem";

    User user = SecurityUtils.getUser();
    Block block = blockDao.getBlock(blockId);
    Resource resource = item.getResource();
    if (resource.getType() != ResourceType.NONE) {
        if (resource.getType() == ResourceType.FILE && uploadedFile != null && !uploadedFile.isEmpty())
            resource.setFile(fileIO.save(uploadedFile, user, true));
        block.getItems().add(item);/*from   ww  w  . ja  v a 2  s  . c o m*/
        block = blockDao.saveBlock(block);
        sessionStatus.setComplete();

        logger.info(user.getUsername() + " added an item to block " + block.getId());
    }
    return "redirect:list";
}

From source file:it.jugpadova.controllers.JuggerEditController.java

@RequestMapping(method = RequestMethod.POST)
@Validation(view = FORM_VIEW, continueOnErrors = true)
protected ModelAndView save(HttpServletRequest req, @ModelAttribute(JUGGER_ATTRIBUTE) EditJugger ej,
        BindingResult result, SessionStatus status) throws IOException {
    final Jugger jugger = ej.getJugger();
    validateJugger(jugger, result);//from  ww w.  j a v a 2  s  . com
    if (result.hasErrors()) {
        return new ModelAndView(FORM_VIEW);
    }
    if (StringUtils.isNotBlank(ej.getPassword())) {
        jugger.getUser().setPassword(
                SecurityUtilities.encodePassword(ej.getPassword(), jugger.getUser().getUsername()));
    }
    juggerBo.update(jugger, ej.getRequireReliability().isRequireReliability(),
            ej.getRequireReliability().getComment(), Utilities.getBaseUrl(req));
    ModelAndView mv = new ModelAndView("redirect:/jugger/edit.form");
    mv.addObject("jugger.user.username", jugger.getUser().getUsername());
    Utilities.addMessageCode(mv, "juggerUpdateSuccessful");
    status.setComplete();
    return mv;
}

From source file:org.openmrs.module.sdmxhddataexport.web.controller.report.ReportDataElementController.java

@RequestMapping(value = "/module/sdmxhddataexport/reportDataElement.form", method = RequestMethod.POST)
public String post(@ModelAttribute("reportDataElement") ReportDataElement reportDataElement,
        BindingResult bindingResult, SessionStatus status, Model model) {
    new ReportDataElementValidator().validate(reportDataElement, bindingResult);
    if (bindingResult.hasErrors()) {
        System.out.println("binding errors");
        return "/module/sdmxhddataexport/report/reportDataElement";
    } else {//from  w ww  .  jav  a  2  s. c  om
        System.out.println("Supposedly No errors");
        SDMXHDDataExportService sDMXHDDataExportService = Context.getService(SDMXHDDataExportService.class);
        reportDataElement.setCreatedOn(new java.util.Date());
        sDMXHDDataExportService.saveReportDataElement(reportDataElement);
        status.setComplete();
        return "redirect:/module/sdmxhddataexport/reportDataElement.form?reportId="
                + reportDataElement.getReport().getId();
    }

}