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:com.epam.training.storefront.controllers.pages.payment.PaymentDetailsPageController.java

private SopPaymentDetailsForm getSopPaymentDetailsForm(final Model model) {
    SopPaymentDetailsForm sopPaymentDetailsForm = new SopPaymentDetailsForm();
    if (model.containsAttribute("sopPaymentDetailsForm")) {
        sopPaymentDetailsForm = (SopPaymentDetailsForm) model.asMap().get("sopPaymentDetailsForm");
    }//from www  .ja va2 s .com

    return sopPaymentDetailsForm;
}

From source file:org.sloth.web.ajax.ObservationCreationBubbleController.java

/**
 * Handles the {@code POST}-request and registrates the {@code Observation}.
 *//* w  ww . j  a  v a 2s . c om*/
@RequestMapping(method = RequestMethod.POST)
public ModelAndView post(@RequestParam(LONGITUDE_PARAM) Double longitude,
        @RequestParam(LATITUDE_PARAM) Double latitude,
        @ModelAttribute(OBSERVATION_ATTRIBUTE) Observation observation, BindingResult result,
        SessionStatus status, HttpSession session, Model m) {
    if (isAuth(session)) {
        logger.info("Session is authed.");
        logger.info("Building Coordinate from given Lon: {} and Lat: {}.", longitude, latitude);
        observation.setCoordinate(new Coordinate(longitude, latitude));
        logger.info("Setting User {}.", getUser(session));
        observation.setUser(getUser(session));
        logger.info("Validating Observation {}", observation);
        observationValidator.validate(observation, result);
        if (result.hasErrors()) {
            logger.info("Found Errors.");
            logger.debug("{}", m.asMap().keySet());
            return new ModelAndView(FORM_VIEW, m.asMap());
        } else {
            try {
                logger.info("Trying to persist Observation {}", observation);
                observationService.registrate(observation);
                logger.info("Succesfully persisted Observation {}", observation);
                ModelAndView mav = new ModelAndView(SUCCESS_VIEW);
                mav.addObject(observation);
                return new ModelAndView(SUCCESS_VIEW, OBSERVATION_ATTRIBUTE, observation);
            } catch (Exception e) {
                logger.warn("Unexpected Exception.", e);
                return new ModelAndView(ERROR_VIEW);
            } finally {
                logger.info("Clearing session attributes");
                //status.setComplete();
            }
        }
    } else {
        logger.info("Session is not authed");
        return new ModelAndView(REJECT_VIEW);
    }
}

From source file:net.triptech.buildulator.web.UserController.java

@RequestMapping(method = RequestMethod.PUT)
public String update(@Valid Person person, BindingResult bindingResult, Model uiModel,
        HttpServletRequest request) {//  w w w .  j ava2 s.  c  o m

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

        FlashScope.appendMessage(getMessage("buildulator_object_validation", Person.class), request);

        return "user/update";
    }

    Person user = getUser(request);

    if (user != null
            && StringUtils.equalsIgnoreCase(user.getOpenIdIdentifier(), person.getOpenIdIdentifier())) {
        // Only save the change if the logged in user is the same

        // Set some defaults from the current user
        person.setUserStatus(user.getUserStatus());
        person.setUserRole(user.getUserRole());

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

        FlashScope.appendMessage(getMessage("buildulator_user_updated"), request);
    }

    return "redirect:/projects";
}

From source file:org.jasig.portlet.announcements.controller.AnnouncementsViewController.java

/**
 * Main method of this display controller. Calculates which topics should be shown to
 * this user and which announcements to show from those topics.
 * @param model/* w  w  w  .ja  v a  2s . c  o m*/
 * @param request
 * @param from
 * @return
 * @throws PortletException
 */
@SuppressWarnings("unchecked")
@RenderMapping()
public String mainView(Model model, RenderRequest request,
        @RequestParam(value = "from", required = false) Integer from,
        @RequestParam(value = "to", required = false) Integer to) throws PortletException {

    if (from == null || to == null) {
        from = 0;
        to = (Integer) model.asMap().get("increment");
    }

    PortletPreferences prefs = request.getPreferences();

    List<Announcement> announcements;
    List<Announcement> emergencyAnnouncements;

    Element guestCacheElement = null;
    Element emergCacheElement = null;
    guestCacheElement = guestAnnouncementCache.get("guest");
    emergCacheElement = guestAnnouncementCache.get("emergency");

    final Boolean isGuest = (Boolean) model.asMap().get("isGuest");
    if (!isGuest || (guestCacheElement == null || emergCacheElement == null)) {

        // create a new announcement list
        announcements = new ArrayList<Announcement>();
        emergencyAnnouncements = new ArrayList<Announcement>();

        // fetch the user's topic subscription from the database
        List<TopicSubscription> myTopics = tss.getTopicSubscription(request);

        // add all the published announcements of each subscribed topic to the announcement list
        // to emergency announcements into their own list
        for (TopicSubscription ts : myTopics) {
            if (ts.getSubscribed() && ts.getTopic().getSubscriptionMethod() != Topic.EMERGENCY) {
                announcements.addAll(ts.getTopic().getPublishedAnnouncements());
            } else if (ts.getSubscribed() && ts.getTopic().getSubscriptionMethod() == Topic.EMERGENCY) {
                emergencyAnnouncements.addAll(ts.getTopic().getPublishedAnnouncements());
            }
        }

        // sort the list (since they are not sorted from the database)
        Comparator<Announcement> sortStrategy = AnnouncementSortStrategy
                .getStrategy(prefs.getValue(PREFERENCE_SORT_STRATEGY, DEFAULT_SORT_STRATEGY));
        Collections.sort(announcements, sortStrategy);
        Collections.sort(emergencyAnnouncements, sortStrategy);

        if (isGuest) {
            if (logger.isDebugEnabled())
                logger.debug("Guest cache expired. Regenerating guest cache.");

            guestAnnouncementCache.put(new Element("guest", announcements));
            guestAnnouncementCache.put(new Element("emergency", emergencyAnnouncements));
        }
    } else {
        // we're a guest and we're within the cache timeout period, so return the cached announcements
        if (logger.isDebugEnabled())
            logger.debug("Guest cache valid. Using guest cache.");
        announcements = (List<Announcement>) guestCacheElement.getObjectValue();
        emergencyAnnouncements = (List<Announcement>) emergCacheElement.getObjectValue();
    }

    // create a shortened list
    final Boolean useScrollingDisplay = (Boolean) model.asMap().get("useScrollingDisplay");
    final List<Announcement> announcementsShort = useScrollingDisplay ? announcements
            : paginateAnnouncements(announcements, from, to, model);

    // Disable the edit link where appropriate
    Boolean disableEdit = Boolean.valueOf(prefs.getValue(PREFERENCE_DISABLE_EDIT, "false"));
    model.addAttribute("disableEdit", disableEdit);

    model.addAttribute("from", new Integer(from));
    model.addAttribute("to", new Integer(to));
    model.addAttribute("hasMore", (!useScrollingDisplay && announcements.size() > to));
    model.addAttribute("announcements", announcementsShort);
    model.addAttribute("emergency", emergencyAnnouncements);
    model.addAttribute("hideAbstract", Boolean.valueOf(prefs.getValue(PREFERENCE_HIDE_ABSTRACT, "false")));
    return viewNameSelector.select(request, "displayAnnouncements");
}

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

@Transactional
@RequestMapping(value = { NEW_MAPPING }, method = RequestMethod.POST)
public ModelAndView add(@ModelAttribute(NEW_USER_FORM_KEY) @Valid NewUserForm newUserForm, BindingResult result,
        Model model, RedirectAttributes redirectAttributes) throws Exception {

    String name = null == newUserForm ? "null" : newUserForm.getUsername();
    log.debug("Add new user: {}", name);
    if (result.hasErrors()) {
        return new ModelAndView(NEW_USER_VIEW, model.asMap());
    }//  w ww .j  av  a 2 s. c om

    DuracloudUser user = this.userService.createNewUser(newUserForm.getUsername(), newUserForm.getPassword(),
            newUserForm.getFirstName(), newUserForm.getLastName(), newUserForm.getEmail(),
            newUserForm.getSecurityQuestion(), newUserForm.getSecurityAnswer());

    String redemptionCode = newUserForm.getRedemptionCode();
    Long accountId = -1L;
    if (!StringUtils.isEmpty(redemptionCode)) {
        try {
            accountId = this.userService.redeemAccountInvitation(user.getId(), redemptionCode);

        } catch (InvalidRedemptionCodeException ex) {
            addRedemptionFailedMessage();
        }
    }

    String userUrl = formatUserUrl(newUserForm.getUsername());

    if (accountId > -1) {
        userUrl += "?accountId=" + accountId;
    }

    ModelAndView mav = new ModelAndView("user-new-success");
    mav.addObject("userUrl", userUrl);
    return mav;
}

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

@Transactional
@RequestMapping(value = ACCOUNT_USERS_MAPPING + "/adduser", method = RequestMethod.POST)
public ModelAndView addUser(@PathVariable Long accountId,
        @ModelAttribute(USERNAME_FORM_KEY) @Valid UsernameForm usernameForm, BindingResult result, Model model,
        RedirectAttributes redirectAttributes) throws Exception {
    String username = usernameForm.getUsername();
    log.debug("entering addUser: adding {} to account {}", username, accountId);
    if (result.hasErrors()) {
        addUserToModel(model);//  w ww. j a  v a 2s. c om
        get(getAccountService(accountId), model);
        return new ModelAndView(ACCOUNT_USERS_VIEW_ID, model.asMap());
    }

    DuracloudUser user = userService.loadDuracloudUserByUsernameInternal(username);
    if (userService.addUserToAccount(accountId, user.getId())) {
        log.info("added user {} to account {}", new Object[] { username, accountId });

        String message = MessageFormat.format("Successfully added {0} to account.", username);
        setSuccessFeedback(message, redirectAttributes);

    }

    return createAccountRedirectModelAndView(accountId, ACCOUNT_USERS_PATH);
}

From source file:org.kew.rmf.matchconf.web.CustomWireController.java

@RequestMapping(value = "/{configType}_configs/{configName}/wires", method = RequestMethod.POST, produces = "text/html")
public String create(@PathVariable("configType") String configType,
        @PathVariable("configName") String configName, @Valid Wire wire, BindingResult bindingResult,
        Model uiModel, HttpServletRequest httpServletRequest) {
    // assert unique_together:config&name
    if (Configuration.findConfigurationsByNameEquals(configName).getSingleResult()
            .getWireForName(wire.getName()) != null) {
        bindingResult.addError(new ObjectError("wire.name",
                "There is already a Wire set up for this configuration with this name."));
    }/*from  www  . ja  v a  2s.co  m*/
    this.customValidation(configName, wire, bindingResult);
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, configName, wire);
        return String.format("%s_config_wires/create", configType);
    }
    uiModel.asMap().clear();
    Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult();
    wire.setConfiguration(config);
    wire.persist();
    config.getWiring().add(wire);
    config.merge();
    return String.format("redirect:/%s_configs/", configType)
            + encodeUrlPathSegment(configName, httpServletRequest) + "/wires/"
            + encodeUrlPathSegment(wire.getName(), httpServletRequest);
}

From source file:org.kew.rmf.matchconf.web.CustomReporterController.java

@RequestMapping(value = "/{configType}_configs/{configName}/reporters", method = RequestMethod.POST, produces = "text/html")
public String create(@PathVariable("configType") String configType,
        @PathVariable("configName") String configName, @Valid Reporter reporter, BindingResult bindingResult,
        Model uiModel, HttpServletRequest httpServletRequest) {
    // assert unique_together:config&name
    if (Configuration.findConfigurationsByNameEquals(configName).getSingleResult()
            .getReporterForName(reporter.getName()) != null) {
        bindingResult.addError(new ObjectError("reporter.name",
                "There is already a LuceneReporter set up for this configuration with this name."));
    }// w  w  w .j a v  a  2 s.  c o  m
    this.customValidation(configName, reporter, bindingResult);
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, configType, configName, reporter);
        return "config_reporters/create";
    }
    uiModel.asMap().clear();
    Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult();
    reporter.setConfig(config);
    reporter.persist();
    config.getReporters().add(reporter);
    config.merge();
    return String.format("redirect:/%s_configs/", configType)
            + encodeUrlPathSegment(configName, httpServletRequest) + "/reporters/"
            + encodeUrlPathSegment(reporter.getName(), httpServletRequest);
}

From source file:org.kew.rmf.matchconf.web.CustomMatcherController.java

@RequestMapping(value = "/{configType}_configs/{configName}/matchers", method = RequestMethod.POST, produces = "text/html")
public String create(@PathVariable("configType") String configType,
        @PathVariable("configName") String configName, @Valid Matcher matcher, BindingResult bindingResult,
        Model uiModel, HttpServletRequest httpServletRequest) {
    Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult();
    // assert unique_together:config&name
    if (config.getMatcherForName(matcher.getName()) != null) {
        bindingResult.addError(new ObjectError("matcher.name",
                "There is already a Matcher set up for this configuration with this name."));
    }//w  w  w .j a  v a2 s .  c  om
    this.customValidation(configName, matcher, bindingResult);
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, configType, configName, matcher);
        return "config_matchers/create";
    }
    uiModel.asMap().clear();
    matcher.setConfiguration(config);
    matcher.persist();
    config.getMatchers().add(matcher);
    config.merge();
    return "redirect:/{configType}_configs/" + encodeUrlPathSegment(configName, httpServletRequest)
            + "/matchers/" + encodeUrlPathSegment(matcher.getName(), httpServletRequest);
}

From source file:org.kew.rmf.matchconf.web.CustomTransformerController.java

@RequestMapping(value = "/{configType}_configs/{configName}/transformers", method = RequestMethod.POST, produces = "text/html")
public String create(@PathVariable("configType") String configType,
        @PathVariable("configName") String configName, @Valid Transformer transformer,
        BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
    // assert unique_together:config&name
    if (Configuration.findConfigurationsByNameEquals(configName).getSingleResult()
            .getTransformerForName(transformer.getName()) != null) {
        bindingResult.addError(new ObjectError("transformer.name",
                "There is already a Transformer set up for this configuration with this name."));
    }/*from  w w  w  .  ja  v a 2  s  . c  o m*/
    this.customValidation(configName, transformer, bindingResult);
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, configType, configName, transformer);
        return "config_transformers/create";
    }
    uiModel.asMap().clear();
    Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult();
    transformer.setConfiguration(config);
    transformer.persist();
    config.getTransformers().add(transformer);
    config.merge();
    return "redirect:/{configType}_configs/" + encodeUrlPathSegment(configName, httpServletRequest)
            + "/transformers/" + encodeUrlPathSegment(transformer.getName(), httpServletRequest);
}