Example usage for org.springframework.ui Model asMap

List of usage examples for org.springframework.ui Model asMap

Introduction

In this page you can find the example usage for org.springframework.ui Model asMap.

Prototype

Map<String, Object> asMap();

Source Link

Document

Return the current set of model attributes as a Map.

Usage

From source file:org.opentravel.pubs.controllers.AdminController.java

@RequestMapping({ "/DeleteCodeList.html", "/DeleteCodeList.htm" })
public String deleteCodeListPage(HttpSession session, Model model,
        @RequestParam(value = "confirmDelete", required = false) boolean confirmDelete,
        @RequestParam(value = "codeListId", required = false) Long codeListId) {
    String targetPage = "deleteCodeList";
    try {/*from   ww w.j a v  a  2  s  .  co  m*/
        CodeListDAO cDao = DAOFactoryManager.getFactory().newCodeListDAO();
        CodeList codeList = cDao.getCodeList(codeListId);

        if (confirmDelete) {
            cDao.deleteCodeList(codeList);
            targetPage = "redirect:/admin/index.html";
            model.asMap().clear();

        } else {
            model.addAttribute("codeList", codeList);
        }

    } catch (Throwable t) {
        log.error("Error during publication controller processing.", t);
        setErrorMessage(DEFAULT_ERROR_MESSAGE, model);
    }
    return applyCommonValues(model, targetPage);
}

From source file:org.duracloud.account.app.controller.AccountUsersController.java

@Transactional
@RequestMapping(value = USERS_EDIT_MAPPING, method = RequestMethod.POST)
public ModelAndView editUser(@PathVariable Long accountId, @PathVariable Long userId,
        @ModelAttribute(EDIT_ACCOUNT_USERS_FORM_KEY) AccountUserEditForm accountUserEditForm,
        BindingResult result, Model model, RedirectAttributes redirectAttributes) throws Exception {
    log.debug("editUser account {}", accountId);

    boolean hasErrors = result.hasErrors();
    if (!hasErrors) {
        Role role = Role.valueOf(accountUserEditForm.getRole());
        log.info("New role: {}", role);
        try {//from   www . ja  va  2 s. c o  m
            setUserRights(userService, accountId, userId, role);
            setSuccessFeedback("Successfully changed user role.", redirectAttributes);
        } catch (AccessDeniedException e) {
            result.addError(new ObjectError("role", "You are unauthorized to set the role for this user"));
            hasErrors = true;
        }
    }

    if (hasErrors) {
        addUserToModel(model);
        return new ModelAndView(ACCOUNT_USERS_VIEW_ID, model.asMap());
    }

    return createAccountRedirectModelAndView(accountId, ACCOUNT_USERS_PATH);
}

From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java

@RequestMapping(value = "/{id}/addMemberReviewFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'review')")
public String addMemberReviewFile(@PathVariable("id") Long id, @Valid MemberReviewFile memberReviewFile,
        BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        logger.warn(bindingResult.getAllErrors());
        return "redirect:/postecandidatures/" + id.toString();
    }/*w  w  w.  j a  v  a2  s . co  m*/
    uiModel.asMap().clear();

    // get PosteCandidature from id
    PosteCandidature postecandidature = PosteCandidature.findPosteCandidature(id);

    // upload file
    MultipartFile file = memberReviewFile.getFile();
    // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
    if (file != null) {
        String filename = file.getOriginalFilename();
        Long fileSize = file.getSize();

        boolean filenameAlreadyUsed = false;
        for (MemberReviewFile rFile : postecandidature.getMemberReviewFiles()) {
            if (rFile.getFilename().equals(filename)) {
                filenameAlreadyUsed = true;
                break;
            }
        }

        if (filenameAlreadyUsed) {
            uiModel.addAttribute("filename_already_used", filename);
            logger.info("addMemberReviewFile - upload restriction sur '" + filename
                    + "' un fichier de mme nom existe dj pour une candidature de "
                    + postecandidature.getCandidat().getEmailAddress());
        } else {

            if (fileSize != 0) {
                String contentType = file.getContentType();
                // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted
                contentType = contentType.replaceAll(":.*", "");

                InputStream inputStream = file.getInputStream();
                //byte[] bytes = IOUtils.toByteArray(inputStream);

                memberReviewFile.setFilename(filename);
                memberReviewFile.setFileSize(fileSize);
                memberReviewFile.setContentType(contentType);
                logger.info("Upload and set file in DB with filesize = " + fileSize);
                memberReviewFile.getBigFile().setBinaryFileStream(inputStream, fileSize);
                memberReviewFile.getBigFile().persist();

                Calendar cal = Calendar.getInstance();
                Date currentTime = cal.getTime();
                memberReviewFile.setSendTime(currentTime);

                User currentUser = getCurrentUser();
                memberReviewFile.setMember(currentUser);

                postecandidature.getMemberReviewFiles().add(memberReviewFile);

                //postecandidature.setModification(currentTime);

                postecandidature.persist();

                logService.logActionFile(LogService.UPLOAD_REVIEW_ACTION, postecandidature, memberReviewFile,
                        request, currentTime);
            }
        }
    } else {
        String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent);
    }

    return "redirect:/postecandidatures/" + id.toString();
}

From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java

@RequestMapping(value = "/{id}/addFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'manage')")
public String addFile(@PathVariable("id") Long id, @Valid PosteCandidatureFile posteCandidatureFile,
        BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        logger.warn(bindingResult.getAllErrors());
        return "redirect:/postecandidatures/" + id.toString();
    }//from  ww w.  j a v  a2 s .  co m
    uiModel.asMap().clear();

    // get PosteCandidature from id
    PosteCandidature posteCandidature = PosteCandidature.findPosteCandidature(id);

    // upload file
    MultipartFile file = posteCandidatureFile.getFile();

    // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
    if (file != null) {
        String filename = file.getOriginalFilename();

        boolean filenameAlreadyUsed = false;
        for (PosteCandidatureFile pcFile : posteCandidature.getCandidatureFiles()) {
            if (pcFile.getFilename().equals(filename)) {
                filenameAlreadyUsed = true;
                break;
            }
        }

        if (filenameAlreadyUsed) {
            uiModel.addAttribute("filename_already_used", filename);
            logger.warn("Upload Restriction sur '" + filename
                    + "' un fichier de mme nom existe dj pour une candidature de "
                    + posteCandidature.getCandidat().getEmailAddress());
        } else {

            Long fileSize = file.getSize();

            if (fileSize != 0) {
                String contentType = file.getContentType();
                // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted
                contentType = contentType.replaceAll(":.*", "");

                logger.info("Try to upload file '" + filename + "' with size=" + fileSize + " and contentType="
                        + contentType);

                Long maxFileMoSize = posteCandidatureFile.getFileType().getCandidatureFileMoSizeMax();
                Long maxFileSize = maxFileMoSize * 1024 * 1024;
                String mimeTypeRegexp = posteCandidatureFile.getFileType()
                        .getCandidatureContentTypeRestrictionRegexp();
                String filenameRegexp = posteCandidatureFile.getFileType()
                        .getCandidatureFilenameRestrictionRegexp();

                boolean sizeRestriction = maxFileSize > 0 && fileSize > maxFileSize;
                boolean contentTypeRestriction = !contentType.matches(mimeTypeRegexp);
                boolean filenameRestriction = !filename.matches(filenameRegexp);

                if (sizeRestriction || contentTypeRestriction || filenameRestriction) {
                    String restriction = sizeRestriction ? "SizeRestriction" : "";
                    restriction = contentTypeRestriction || filenameRestriction
                            ? restriction + "ContentTypeRestriction"
                            : restriction;
                    uiModel.addAttribute("upload_restricion_size_contentype", restriction);
                    logger.info("addFile - upload restriction sur " + filename + "' avec taille=" + fileSize
                            + " et contentType=" + contentType + " pour une candidature de "
                            + posteCandidature.getCandidat().getEmailAddress());
                } else {
                    InputStream inputStream = file.getInputStream();
                    //byte[] bytes = IOUtils.toByteArray(inputStream);

                    posteCandidatureFile.setFilename(filename);
                    posteCandidatureFile.setFileSize(fileSize);
                    posteCandidatureFile.setContentType(contentType);
                    logger.info("Upload and set file in DB with filesize = " + fileSize);
                    posteCandidatureFile.getBigFile().setBinaryFileStream(inputStream, fileSize);
                    posteCandidatureFile.getBigFile().persist();

                    Calendar cal = Calendar.getInstance();
                    Date currentTime = cal.getTime();
                    posteCandidatureFile.setSendTime(currentTime);

                    posteCandidature.getCandidatureFiles().add(posteCandidatureFile);

                    posteCandidature.setModification(currentTime);

                    posteCandidature.persist();

                    logService.logActionFile(LogService.UPLOAD_ACTION, posteCandidature, posteCandidatureFile,
                            request, currentTime);
                    returnReceiptService.logActionFile(LogService.UPLOAD_ACTION, posteCandidature,
                            posteCandidatureFile, request, currentTime);

                    pdfService.updateNbPages(posteCandidatureFile.getId());
                }
            }
        }
    } else {
        String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent);
    }

    return "redirect:/postecandidatures/" + id.toString();
}

From source file:org.opentravel.pubs.controllers.AdminController.java

@RequestMapping({ "/DeleteSpecification.html", "/DeleteSpecification.htm" })
public String deleteSpecificationPage(HttpSession session, Model model,
        @RequestParam(value = "confirmDelete", required = false) boolean confirmDelete,
        @RequestParam(value = "publicationId", required = false) Long publicationId) {
    String targetPage = "deleteSpecification";
    try {/*from   w  ww .ja  v  a2  s  .co  m*/
        PublicationDAO pDao = DAOFactoryManager.getFactory().newPublicationDAO();
        Publication publication = pDao.getPublication(publicationId);

        if (confirmDelete) {
            pDao.deleteSpecification(publication);
            targetPage = "redirect:/admin/index.html";
            model.asMap().clear();

        } else {
            model.addAttribute("publication", publication);
        }

    } catch (Throwable t) {
        log.error("Error during publication controller processing.", t);
        setErrorMessage(DEFAULT_ERROR_MESSAGE, model);
    }
    return applyCommonValues(model, targetPage);
}

From source file:org.fenixedu.academic.thesis.ui.controller.ConfigurationController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView createConfiguration(@ModelAttribute ConfigurationBean configurationBean, Model model) {

    try {/*  ww w  .  j  a v a2s.c  om*/
        if (configurationBean.getExecutionDegree() == null) {
            model.addAttribute("unselectedExecutionDegreeException", true);
            return createConfigurationForm(model, configurationBean);
        }

        new ConfigurationBean.Builder(configurationBean).build();
    } catch (ConsistencyException exception) {
        model.addAttribute("createException", true);
        model.addAttribute("command", configurationBean);

        TreeSet<ExecutionYear> executionYearsList = new TreeSet<ExecutionYear>(
                ExecutionYear.REVERSE_COMPARATOR_BY_YEAR);
        executionYearsList.addAll(Bennu.getInstance().getExecutionYearsSet());
        model.addAttribute("executionYearsList", executionYearsList);

        return new ModelAndView("/configuration/create", model.asMap());
    } catch (IllegalArgumentException exception) {
        model.addAttribute("illegalArgumentException", true);
        model.addAttribute("command", configurationBean);

        TreeSet<ExecutionYear> executionYearsList = new TreeSet<ExecutionYear>(
                ExecutionYear.REVERSE_COMPARATOR_BY_YEAR);
        executionYearsList.addAll(Bennu.getInstance().getExecutionYearsSet());
        model.addAttribute("executionYearsList", executionYearsList);

        return new ModelAndView("/configuration/create", model.asMap());
    } catch (OverlappingIntervalsException e) {
        model.addAttribute("overlappingIntervalsException", true);
        model.addAttribute("command", configurationBean);

        TreeSet<ExecutionYear> executionYearsList = new TreeSet<ExecutionYear>(
                ExecutionYear.REVERSE_COMPARATOR_BY_YEAR);
        executionYearsList.addAll(Bennu.getInstance().getExecutionYearsSet());
        model.addAttribute("executionYearsList", executionYearsList);

        return new ModelAndView("/configuration/create", model.asMap());
    }

    return new ModelAndView("redirect:/configuration");
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.BusinessUnitManagementPageController.java

@RequestMapping(value = "/createuser", method = RequestMethod.GET)
@RequireHardLogIn//from  w  w  w  .  j  a va  2 s . c om
public String createCustomerOfUnit(@RequestParam("unit") final String unit,
        @RequestParam("role") final String role, final Model model, final HttpServletRequest request)
        throws CMSItemNotFoundException {
    final String url = createUser(model);
    final B2BCustomerForm b2bCustomerForm = (B2BCustomerForm) model.asMap().get("b2BCustomerForm");
    b2bCustomerForm.setParentB2BUnit(unit);
    b2bCustomerForm.setRoles(Collections.singleton(role));

    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageUnitsDetailsBreadcrumbs(unit);
    breadcrumbs.add(new Breadcrumb(
            String.format("/my-company/organization-management/manage-units/createuser/?unit=%s&role=%s",
                    urlEncode(unit), urlEncode(role)),
            getMessageSource().getMessage("text.company.organizationManagement", null,
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    model.addAttribute("action", "manage.units");
    model.addAttribute("saveUrl",
            String.format(
                    request.getContextPath()
                            + "/my-company/organization-management/manage-units/createuser?unit=%s&role=%s",
                    urlEncode(unit), urlEncode(role)));
    model.addAttribute("cancelUrl",
            String.format(
                    request.getContextPath()
                            + "/my-company/organization-management/manage-units/details?unit=%s",
                    urlEncode(unit)));
    return url;
}

From source file:de.hybris.platform.commerceorgaddon.controllers.pages.BusinessUnitManagementPageController.java

@RequestMapping(value = "/createuser", method = RequestMethod.GET)
@RequireHardLogIn/*from w w w . j a v  a  2  s.c o  m*/
public String createCustomerOfUnit(@RequestParam("unit") final String unit,
        @RequestParam("role") final String role, final Model model, final HttpServletRequest request)
        throws CMSItemNotFoundException {
    final String url = createUser(model);
    final B2BCustomerForm b2bCustomerForm = (B2BCustomerForm) model.asMap().get("b2BCustomerForm");
    b2bCustomerForm.setParentB2BUnit(unit);
    b2bCustomerForm.setRoles(Collections.singleton(role));

    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageUnitsDetailsBreadcrumbs(unit);
    breadcrumbs.add(new Breadcrumb(
            String.format("/my-company/organization-management/manage-units/createuser/?unit=%s&role=%s",
                    urlEncode(unit), urlEncode(role)),
            getMessageSource().getMessage("text.company.manage.units.createuser.breadcrumb", null,
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    model.addAttribute("action", "manage.units");
    model.addAttribute("saveUrl",
            String.format(
                    request.getContextPath()
                            + "/my-company/organization-management/manage-units/createuser?unit=%s&role=%s",
                    urlEncode(unit), urlEncode(role)));
    model.addAttribute("cancelUrl", getCancelUrl(MANAGE_UNIT_DETAILS_URL, request.getContextPath(), unit));
    return url;
}

From source file:net.triptech.metahive.web.DefinitionController.java

/**
 * Update the definition.//from w  ww. ja  v a  2 s.  com
 *
 * @param definition the definition
 * @param bindingResult the binding result
 * @param uiModel the ui model
 * @param request the http servlet request
 * @return the string
 */
@RequestMapping(method = RequestMethod.PUT)
@PreAuthorize("hasAnyRole('ROLE_EDITOR','ROLE_ADMIN')")
public String update(@Valid DefinitionForm definitionForm, BindingResult bindingResult, Model uiModel,
        HttpServletRequest request) {

    Person user = loadUser(request);

    if (user == null) {
        // A valid user is required
        FlashScope.appendMessage(getMessage("metahive_valid_user_required"), request);
        return "redirect:/definitions";
    }

    // Load the existing definition
    Definition definition = Definition.findDefinition(definitionForm.getId());

    if (definition == null) {
        // A valid definition was not found
        FlashScope.appendMessage(getMessage("metahive_object_not_found", Definition.class), request);
        return "redirect:/definitions";
    }

    if (bindingResult.hasErrors()) {
        uiModel.addAttribute("definition", definitionForm);
        FlashScope.appendMessage(getMessage("metahive_object_validation", Definition.class), request);
        return "definitions/update";
    }

    definition = definitionForm.mergedDefinition(definition, user);

    uiModel.asMap().clear();
    definition.merge();

    Comment comment = definitionForm.newComment(CommentType.MODIFY, definition, user);
    comment.persist();

    FlashScope.appendMessage(getMessage("metahive_edit_complete", Definition.class), request);

    return "redirect:/definitions/" + encodeUrlPathSegment(definition.getId().toString(), request);
}

From source file:net.triptech.metahive.web.RecordController.java

@RequestMapping(method = RequestMethod.POST)
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String create(@Valid RecordForm record, BindingResult bindingResult, Model uiModel,
        HttpServletRequest request) {//from w  w w . j a  va 2  s . c o  m

    Person user = loadUser(request);

    if (user == null) {
        // A valid user is required
        FlashScope.appendMessage(getMessage("metahive_valid_user_required"), request);
        return "redirect:/records";
    }

    if (StringUtils.isNotBlank(record.getRecordId())) {
        Record newRecord = record.newRecord(loadPreferences());
        newRecord.persist();
        newRecord.flush();
    }

    if (StringUtils.isNotBlank(record.getRecordIds())) {

        Collection<Record> records = record.parseRecords(loadPreferences());

        for (Record newRecord : records) {
            newRecord.persist();
            newRecord.flush();
        }
    }

    uiModel.asMap().clear();

    FlashScope.appendMessage(getMessage("metahive_create_complete", Record.class), request);

    return "redirect:/records";
}