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:net.triptech.metahive.web.DataSourceController.java

@RequestMapping(method = RequestMethod.PUT)
@PreAuthorize("hasAnyRole('ROLE_EDITOR','ROLE_ADMIN')")
public String update(@Valid DataSourceForm dataSourceForm, BindingResult bindingResult, Model uiModel,
        HttpServletRequest request) {//w  ww.j a va  2s .co m

    Person user = loadUser(request);

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

    Definition definition = Definition.findDefinition(dataSourceForm.getDefinition().getId());
    Organisation organisation = Organisation.findOrganisation(dataSourceForm.getOrganisation().getId());

    if (isInvalidOrganisation(organisation, user)) {
        FlashScope.appendMessage(getMessage("metahive_no_valid_organisation"), request);

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

    // Load the existing data source
    DataSource dataSource = DataSource.findDataSource(dataSourceForm.getId());

    if (dataSource == null) {
        // A valid data source was not found
        FlashScope.appendMessage(getMessage("metahive_object_not_found", DataSource.class), request);
        return "redirect:/definitions" + encodeUrlPathSegment(definition.getId().toString(), request);
    }

    if (bindingResult.hasErrors()) {
        uiModel.addAttribute("dataSource", dataSourceForm);

        FlashScope.appendMessage(getMessage("metahive_object_validation", DataSource.class), request);

        return "datasources/update";
    }

    dataSource = dataSourceForm.mergedDataSource(dataSource, user);

    uiModel.asMap().clear();

    dataSource.merge();

    Comment comment = dataSourceForm.newComment(CommentType.MODIFY, dataSource, user);
    comment.persist();

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

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

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

/**
 * Hanldes the processing for all of the artifact comment page targets.
 * /* w  w  w  .j a  v a 2s . c o m*/
 * @param model  the UI model for the current request
 * @param session  the HTTP session
 * @param redirectAttrs  request attributes that must be available in case of a page redirect
 * @param newSession  flag indicating that the user has requested to re-register in their session
 * @param commentForm  the form used to supply the field values for the submitted comment
 * @param pubType  the type of the publication to view (1.0/2.0)
 * @param isMembersOnlyPage  flag indicating whether the page being viewed is a members-only page
 * @param targetPage  the MVC name of the target page
 * @param submitCommentsUrl  the URL location of the comment submission page
 * @return String
 */
private String doCommentArtifactPage(Model model, HttpSession session, RedirectAttributes redirectAttrs,
        boolean newSession, ArtifactCommentForm commentForm, PublicationType pubType, boolean isMembersOnlyPage,
        String targetPage, String submitCommentsUrl) {
    boolean commentSuccess = false;
    try {
        if (newSession)
            session.removeAttribute("registrantId");
        Registrant registrant = getCurrentRegistrant(session);
        boolean processRegistrant = commentForm.isProcessForm() && (registrant == null);
        RegistrantForm registrantForm = commentForm.getRegistrantForm();

        registrantForm.setProcessForm(processRegistrant);
        handleRegistrantInfo(registrantForm, model, session);
        registrant = (Registrant) model.asMap().get("registrant");

        // If the registrant was created successfully, commit it and start a new
        // transaction for the comment
        if (processRegistrant && (registrant != null)) {
            DAOFactoryManager.getFactory().commitTransaction();
            DAOFactoryManager.getFactory().beginTransaction();
            registrant = getCurrentRegistrant(session);
        }

        if (commentForm.isProcessForm()) {
            commentSuccess = addArtifactComment(commentForm, registrant, model, session);
        }

        if (commentSuccess) {
            if (isMembersOnlyPage) {
                targetPage = "redirect:/specifications/members/CommentThankYou.html";
            } else {
                targetPage = "redirect:/specifications/CommentThankYou.html";
            }
            redirectAttrs.addAttribute("submitCommentsUrl", submitCommentsUrl);
            model.asMap().clear();

        } else {
            PublicationDAO pDao = DAOFactoryManager.getFactory().newPublicationDAO();
            Publication publication = pDao.getLatestPublication(pubType, getAllowedStates(isMembersOnlyPage));
            List<PublicationItem> publicationItems = new ArrayList<>();

            if (publication != null) {
                publicationItems.addAll(pDao.getPublicationItems(publication, PublicationItemType.ARTIFACT));
            }
            model.addAttribute("publication", publication);
            model.addAttribute("publicationItems", publicationItems);
            model.addAttribute("commentTypes", Arrays.asList(CommentType.values()));
            setupPublicationCheck(model, isMembersOnlyPage, pubType);
        }
        model.addAttribute("submitCommentsUrl", submitCommentsUrl);
        commentForm.setProcessForm(true);

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

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

/**
 * Hanldes the processing for all of the schema comment page targets.
 * /*  ww w  .j  a  v  a2 s.  c om*/
 * @param model  the UI model for the current request
 * @param session  the HTTP session
 * @param redirectAttrs  request attributes that must be available in case of a page redirect
 * @param newSession  flag indicating that the user has requested to re-register in their session
 * @param commentForm  the form used to supply the field values for the submitted comment
 * @param pubType  the type of the publication to view (1.0/2.0)
 * @param isMembersOnlyPage  flag indicating whether the page being viewed is a members-only page
 * @param targetPage  the MVC name of the target page
 * @param submitCommentsUrl  the URL location of the comment submission page
 * @return String
 */
private String doCommentSpecPage(Model model, HttpSession session, RedirectAttributes redirectAttrs,
        boolean newSession, SchemaCommentForm commentForm, PublicationType pubType, boolean isMembersOnlyPage,
        String targetPage, String submitCommentsUrl) {
    boolean commentSuccess = false;
    try {
        if (newSession)
            session.removeAttribute("registrantId");
        Registrant registrant = getCurrentRegistrant(session);
        boolean processRegistrant = commentForm.isProcessForm() && (registrant == null);
        RegistrantForm registrantForm = commentForm.getRegistrantForm();

        registrantForm.setProcessForm(processRegistrant);
        handleRegistrantInfo(registrantForm, model, session);
        registrant = (Registrant) model.asMap().get("registrant");

        // If the registrant was created successfully, commit it and start a new
        // transaction for the comment
        if (processRegistrant && (registrant != null)) {
            DAOFactoryManager.getFactory().commitTransaction();
            DAOFactoryManager.getFactory().beginTransaction();
            registrant = getCurrentRegistrant(session);
        }

        if (commentForm.isProcessForm()) {
            commentSuccess = addSchemaComment(commentForm, registrant, model, session);
        }

        if (commentSuccess) {
            if (isMembersOnlyPage) {
                targetPage = "redirect:/specifications/members/CommentThankYou.html";
            } else {
                targetPage = "redirect:/specifications/CommentThankYou.html";
            }
            redirectAttrs.addAttribute("submitCommentsUrl", submitCommentsUrl);
            model.asMap().clear();

        } else {
            PublicationDAO pDao = DAOFactoryManager.getFactory().newPublicationDAO();
            Publication publication = pDao.getLatestPublication(pubType, getAllowedStates(isMembersOnlyPage));
            List<PublicationItem> publicationItems = new ArrayList<>();

            if (publication != null) {
                publicationItems.addAll(pDao.getPublicationItems(publication, PublicationItemType.WSDL));
                publicationItems.addAll(pDao.getPublicationItems(publication, PublicationItemType.XML_SCHEMA));
                publicationItems.addAll(pDao.getPublicationItems(publication, PublicationItemType.JSON_SCHEMA));
            }

            model.addAttribute("publication", publication);
            model.addAttribute("publicationItems", publicationItems);
            model.addAttribute("commentTypes", Arrays.asList(CommentType.values()));
            setupPublicationCheck(model, isMembersOnlyPage, pubType);
        }
        model.addAttribute("submitCommentsUrl", submitCommentsUrl);
        commentForm.setProcessForm(true);

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

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

@RequestMapping({ "/cl/DownloadRegister.html", "/cl/DownloadRegister.htm" })
public String downloadCodeListRegisterPage(Model model, HttpSession session,
        @RequestParam(value = "releaseDate", required = true) String releaseDateStr,
        @RequestParam(value = "filename", required = true) String filename,
        @ModelAttribute("specificationForm") ViewSpecificationForm specificationForm) {
    String targetPage = "downloadCodeListRegister";
    try {//w  w  w  . j  av  a 2s.  com
        RegistrantForm registrantForm = specificationForm.getRegistrantForm();
        CodeListDAO cDao = DAOFactoryManager.getFactory().newCodeListDAO();
        try {
            CodeList codeList = cDao.getCodeList(CodeList.labelFormat.parse(releaseDateStr));

            handleRegistrantInfo(registrantForm, model, session);

            // If we processed the form successfully, clear our model so that its
            // attributes will not show up as URL parameters on redirect
            if (registrantForm.isProcessForm() && (model.asMap().get("registrant") != null)) {
                targetPage = "redirect:/content/specifications/downloads/cl/" + releaseDateStr + "/" + filename;
                model.asMap().clear();

            } else {
                model.addAttribute("codeList", codeList);
                model.addAttribute("releaseDate", releaseDateStr);
                model.addAttribute("filename", filename);
            }
            specificationForm.setProcessForm(true);

        } catch (ParseException e) {
            setErrorMessage("Invalid release date requested: \"" + releaseDateStr + "\"", model);
        }

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

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

@RequestMapping({ "/DownloadRegister.html", "/DownloadRegister.htm" })
public String downloadPublicationRegisterPage(Model model, HttpSession session,
        @RequestParam(value = "pubName", required = true) String pubName,
        @RequestParam(value = "pubType", required = true) String type,
        @RequestParam(value = "filename", required = true) String filename,
        @ModelAttribute("specificationForm") ViewSpecificationForm specificationForm) {
    String targetPage = "downloadRegister";
    try {/*from  w  w  w .  j a v  a2  s  . c om*/
        RegistrantForm registrantForm = specificationForm.getRegistrantForm();
        PublicationDAO pDao = DAOFactoryManager.getFactory().newPublicationDAO();
        PublicationType pubType = resolvePublicationType(type);
        Publication publication = pDao.getPublication(pubName, pubType);

        handleRegistrantInfo(registrantForm, model, session);

        // If we processed the form successfully, clear our model so that its
        // attributes will not show up as URL parameters on redirect
        if (registrantForm.isProcessForm() && (model.asMap().get("registrant") != null)) {
            targetPage = "redirect:/content/specifications/downloads/" + pubName + "/" + type + "/" + filename;
            model.asMap().clear();

        } else {
            model.addAttribute("publication", publication);
            model.addAttribute("pubName", pubName);
            model.addAttribute("pubType", pubType);
            model.addAttribute("filename", filename);
        }
        specificationForm.setProcessForm(true);

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

From source file:alfio.controller.api.ReservationApiController.java

@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/assign", method = RequestMethod.POST, headers = "X-Requested-With=XMLHttpRequest")
public Map<String, Object> assignTicketToPerson(@PathVariable("eventName") String eventName,
        @PathVariable("ticketIdentifier") String ticketIdentifier,
        @RequestParam(value = "single-ticket", required = false, defaultValue = "false") boolean singleTicket,
        UpdateTicketOwnerForm updateTicketOwner, BindingResult bindingResult, HttpServletRequest request,
        Model model, Authentication authentication) throws Exception {

    Optional<UserDetails> userDetails = Optional.ofNullable(authentication).map(Authentication::getPrincipal)
            .filter(UserDetails.class::isInstance).map(UserDetails.class::cast);

    Optional<Triple<ValidationResult, Event, Ticket>> assignmentResult = ticketHelper.assignTicket(eventName,
            ticketIdentifier, updateTicketOwner, Optional.of(bindingResult), request, t -> {
                Locale requestLocale = RequestContextUtils.getLocale(request);
                model.addAttribute("ticketFieldConfiguration",
                        ticketHelper.findTicketFieldConfigurationAndValue(t.getMiddle().getId(), t.getRight(),
                                requestLocale));
                model.addAttribute("value", t.getRight());
                model.addAttribute("validationResult", t.getLeft());
                model.addAttribute("countries", TicketHelper.getLocalizedCountries(requestLocale));
                model.addAttribute("event", t.getMiddle());
                model.addAttribute("useFirstAndLastName", t.getMiddle().mustUseFirstAndLastName());
                model.addAttribute("availableLanguages", i18nManager.getEventLanguages(eventName).stream()
                        .map(ContentLanguage.toLanguage(requestLocale)).collect(Collectors.toList()));
                String uuid = t.getRight().getUuid();
                model.addAttribute("urlSuffix", singleTicket ? "ticket/" + uuid + "/view" : uuid);
                model.addAttribute("elementNamePrefix", "");
            }, userDetails);//from w ww.  j a v  a2  s.co  m
    Map<String, Object> result = new HashMap<>();

    Optional<ValidationResult> validationResult = assignmentResult.map(Triple::getLeft);
    if (validationResult.isPresent() && validationResult.get().isSuccess()) {
        result.put("partial",
                templateManager.renderServletContextResource("/WEB-INF/templates/event/assign-ticket-result.ms",
                        model.asMap(), request, TemplateManager.TemplateOutput.HTML));
    }
    result.put("validationResult", validationResult.orElse(
            ValidationResult.failed(new ValidationResult.ErrorDescriptor("fullName", "error.fullname"))));
    return result;
}

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

@RequestMapping({ "/DoUpdateSpecification.html", "/DoUpdateSpecification.htm" })
public String doUpdateSpecificationPage(HttpSession session, Model model, RedirectAttributes redirectAttrs,
        @ModelAttribute("specificationForm") SpecificationForm specificationForm,
        @RequestParam(value = "archiveFile", required = false) MultipartFile archiveFile) {
    String targetPage = "updateSpecification";
    try {//from  www .  ja v a  2 s  .  c o m
        if (specificationForm.isProcessForm()) {
            PublicationDAO pDao = DAOFactoryManager.getFactory().newPublicationDAO();
            Publication publication = pDao.getPublication(specificationForm.getPublicationId());
            PublicationType publicationType = resolvePublicationType(specificationForm.getSpecType());
            PublicationState publicationState = (specificationForm.getPubState() == null) ? null
                    : PublicationState.valueOf(specificationForm.getPubState());

            publication.setName(StringUtils.trimString(specificationForm.getName()));
            publication.setType(publicationType);
            publication.setState(publicationState);

            try {
                ValidationResults vResults = ModelValidator.validate(publication);

                // Before we try to update the contents of the spefication, validate the
                // publication object to see if there are any errors.
                if (vResults.hasViolations()) {
                    throw new ValidationException(vResults);
                }

                if (!archiveFile.isEmpty()) {
                    pDao.updateSpecification(publication, archiveFile.getInputStream());
                }
                model.asMap().clear();
                redirectAttrs.addAttribute("publication", publication.getName());
                redirectAttrs.addAttribute("specType", publication.getType());
                targetPage = "redirect:/admin/ViewSpecification.html";

            } catch (ValidationException e) {
                addValidationErrors(e, model);

            } catch (Throwable t) {
                log.error("An error occurred while updating the spec: ", t);
                setErrorMessage(t.getMessage(), model);
            }
        }

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

From source file:alfio.controller.EventController.java

@RequestMapping(value = "/event/{eventName}/promoCode/{promoCode}", method = RequestMethod.POST)
@ResponseBody/*from   ww w  .  j a  v  a  2 s .  c  o  m*/
public ValidationResult savePromoCode(@PathVariable("eventName") String eventName,
        @PathVariable("promoCode") String promoCode, Model model, HttpServletRequest request) {

    SessionUtil.removeSpecialPriceData(request);

    Optional<Event> optional = eventRepository.findOptionalByShortName(eventName);
    if (!optional.isPresent()) {
        return ValidationResult.failed(new ValidationResult.ErrorDescriptor("event", ""));
    }
    Event event = optional.get();
    ZonedDateTime now = ZonedDateTime.now(event.getZoneId());
    Optional<String> maybeSpecialCode = Optional.ofNullable(StringUtils.trimToNull(promoCode));
    Optional<SpecialPrice> specialCode = maybeSpecialCode
            .flatMap((trimmedCode) -> specialPriceRepository.getByCode(trimmedCode));
    Optional<PromoCodeDiscount> promotionCodeDiscount = maybeSpecialCode
            .flatMap((trimmedCode) -> promoCodeRepository.findPromoCodeInEventOrOrganization(event.getId(),
                    trimmedCode));

    if (specialCode.isPresent()) {
        if (!optionally(() -> eventManager.getTicketCategoryById(specialCode.get().getTicketCategoryId(),
                event.getId())).isPresent()) {
            return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
        }

        if (specialCode.get().getStatus() != SpecialPrice.Status.FREE) {
            return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
        }

    } else if (promotionCodeDiscount.isPresent()
            && !promotionCodeDiscount.get().isCurrentlyValid(event.getZoneId(), now)) {
        return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
    } else if (!specialCode.isPresent() && !promotionCodeDiscount.isPresent()) {
        return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
    }

    if (maybeSpecialCode.isPresent() && !model.asMap().containsKey("hasErrors")) {
        if (specialCode.isPresent()) {
            SessionUtil.saveSpecialPriceCode(maybeSpecialCode.get(), request);
        } else if (promotionCodeDiscount.isPresent()) {
            SessionUtil.savePromotionCodeDiscount(maybeSpecialCode.get(), request);
        }
        return ValidationResult.success();
    }
    return ValidationResult.failed(new ValidationResult.ErrorDescriptor("promoCode", ""));
}

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

/**
 * Hanldes the processing for all of the view-specification page targets.
 * //from   w w w  .j av  a2 s .  c om
 * @param model  the UI model for the current request
 * @param session  the HTTP session
 * @param spec  indicates the name of the specification to view
 * @param newSession  flag indicating that the user has requested to re-register in their session
 * @param specificationForm  the form used to supply content when a new user registers
 * @param pubType  the type of the publication to view (1.0/2.0)
 * @param isMembersOnlyPage  flag indicating whether the page being viewed is a members-only page
 * @param targetPage  the MVC name of the target page
 * @param altPageLocation  the name of the alternate page location in case of registration or redirect
 * @return String
 */
private String doSpecificationPage(Model model, HttpSession session, String spec, boolean newSession,
        ViewSpecificationForm specificationForm, PublicationType pubType, boolean isMembersOnlyPage,
        String targetPage, String altPageLocation) {
    try {
        RegistrantForm registrantForm = specificationForm.getRegistrantForm();
        PublicationDAO pDao = DAOFactoryManager.getFactory().newPublicationDAO();
        Publication publication = null;

        if (spec != null) {
            publication = pDao.getPublication(spec, pubType);
        }
        if (publication == null) {
            publication = pDao.getLatestPublication(pubType, getAllowedStates(isMembersOnlyPage));
        }

        model.addAttribute("publication", publication);
        model.addAttribute("registrationPage", altPageLocation);
        model.addAttribute("releaseNotesUrl", isMembersOnlyPage ? "/specifications/members/ReleaseNotes.html"
                : "/specifications/ReleaseNotes.html");
        setupPublicationCheck(model, isMembersOnlyPage, pubType);

        if (newSession)
            session.removeAttribute("registrantId");
        handleRegistrantInfo(registrantForm, model, session);

        // If we processed the form successfully, clear our model so that its
        // attributes will not show up as URL parameters on redirect
        if (registrantForm.isProcessForm() && (model.asMap().get("registrant") != null)) {
            targetPage = "redirect:/specifications/" + altPageLocation;
            model.asMap().clear();
        }
        specificationForm.setProcessForm(true);

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

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

@RequestMapping({ "/CodeLists.html", "/CodeLists.htm" })
public String codeListPublicPage(Model model, HttpSession session,
        @RequestParam(value = "releaseDate", required = false) String releaseDateStr,
        @RequestParam(value = "newSession", required = false) boolean newSession,
        @ModelAttribute("specificationForm") ViewSpecificationForm specificationForm) {
    String targetPage = "codeListMain";

    try {// w w  w . j av a 2  s .  com
        RegistrantForm registrantForm = specificationForm.getRegistrantForm();
        CodeListDAO cDao = DAOFactoryManager.getFactory().newCodeListDAO();
        CodeList codeList = null;

        if ((releaseDateStr != null) && (releaseDateStr.trim().length() > 0)) {
            try {
                codeList = cDao.getCodeList(CodeList.labelFormat.parse(releaseDateStr.trim()));

            } catch (ParseException e) {
                setErrorMessage("Invalid release date requested: \"" + releaseDateStr + "\"", model);
            }
        }
        if (codeList == null) {
            codeList = cDao.getLatestCodeList();
        }

        model.addAttribute("codeList", codeList);
        model.addAttribute("registrationPage", "CodeLists.html");

        if (newSession)
            session.removeAttribute("registrantId");
        handleRegistrantInfo(registrantForm, model, session);

        // If we processed the form successfully, clear our model so that its
        // attributes will not show up as URL parameters on redirect
        if (registrantForm.isProcessForm() && (model.asMap().get("registrant") != null)) {
            targetPage = "redirect:/specifications/CodeLists.html";
            model.asMap().clear();
        }
        specificationForm.setProcessForm(true);

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