Example usage for org.springframework.validation BindingResult toString

List of usage examples for org.springframework.validation BindingResult toString

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:au.org.ala.biocache.web.OccurrenceController.java

/**
 * Occurrence search page uses SOLR JSON to display results
 *
 * Please NOTE that the q and fq provided to this URL should be obtained
 * from SearchResultDTO.urlParameters/* w w  w. j  a v a2  s  . c  o  m*/
 *
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/occurrences/download*", method = RequestMethod.GET)
public String occurrenceDownload(@Valid DownloadRequestParams requestParams, BindingResult result,
        @RequestParam(value = "ip", required = false) String ip,
        @RequestParam(value = "apiKey", required = false) String apiKey, Model model,
        HttpServletResponse response, HttpServletRequest request) throws Exception {
    //org.springframework.validation.BindException errors = new org.springframework.validation.BindException(requestParams,"requestParams");
    //validator.validate(requestParams, errors);
    //check to see if the DownloadRequestParams are valid
    if (result.hasErrors()) {
        logger.info("validation failed  " + result.getErrorCount() + " checks");
        logger.debug(result.toString());
        model.addAttribute("errorMessage", getValidationErrorMessage(result));
        //response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        return VALIDATION_ERROR;//result.toString();
    }

    ip = ip == null ? getIPAddress(request) : ip;//request.getRemoteAddr():ip;
    ServletOutputStream out = response.getOutputStream();
    //search params must have a query or formatted query for the downlaod to work
    if (requestParams.getQ().isEmpty() && requestParams.getFormattedQuery().isEmpty()) {
        return null;
    }
    if (apiKey != null) {
        return occurrenceSensitiveDownload(requestParams, apiKey, ip, false, response, request);
    }

    try {
        downloadService.writeQueryToStream(requestParams, response, ip, out, false, false);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:org.openmrs.module.personalhr.web.controller.PhrUserFormController.java

/**
 * @should work for an example/*from   w  w w.ja v a  2 s .  c om*/
 */
@RequestMapping(value = "/phr/user.form", method = RequestMethod.POST)
public String handleSubmission(final WebRequest request, final HttpSession httpSession, final ModelMap model,
        @RequestParam(required = false, value = "action") final String action,
        @RequestParam(required = false, value = "userFormPassword") String password,
        @RequestParam(required = false, value = "secretQuestion") final String secretQuestion,
        @RequestParam(required = false, value = "secretAnswer") final String secretAnswer,
        @RequestParam(required = false, value = "confirm") String confirm,
        @RequestParam(required = false, value = "forcePassword") final Boolean forcePassword,
        @RequestParam(required = false, value = "roleStrings") final String[] roles,
        @RequestParam(required = false, value = "createNewPerson") final String createNewPerson,
        @RequestParam(required = false, value = "sharingToken") String sharingToken,
        @ModelAttribute("user") final User user, final BindingResult errors) {

    if (sharingToken == null) {
        sharingToken = (String) model.get("sharingToken");
    }

    log.debug("Entering PhrUserFormController:handleSubmission..." + sharingToken);
    //add temporary privileges
    boolean isTemporary = false;
    boolean isAdministrator = false;
    if (!Context.isAuthenticated()) {
        Context.authenticate("temporary", "Temporary8");
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        Context.addProxyPrivilege("PHR Restricted Patient Access");
        isTemporary = true;
        log.debug("Added proxy privileges!");
    } else {
        if (PhrService.PhrBasicRole.PHR_ADMINISTRATOR.getValue()
                .equals(PersonalhrUtil.getService().getPhrRole(Context.getAuthenticatedUser()))) {
            isAdministrator = true;
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        }
    }

    try {
        final UserService us = Context.getUserService();
        final MessageSourceService mss = Context.getMessageSourceService();

        if (mss.getMessage("User.assumeIdentity").equals(action)) {
            Context.becomeUser(user.getSystemId());
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
            return "redirect:/phr/index.htm";

        } else if (mss.getMessage("User.delete").equals(action)) {
            try {
                Context.getUserService().purgeUser(user);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
                return "redirect:/phr/user.list";
            } catch (final Exception ex) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
                log.error("Failed to delete user", ex);
                return "redirect:/phr/user.form?userId=" + request.getParameter("userId");
            }

        } else if (mss.getMessage("User.retire").equals(action)) {
            final String retireReason = request.getParameter("retireReason");
            if (!(StringUtils.hasText(retireReason))) {
                errors.rejectValue("retireReason", "User.disableReason.empty");
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            } else {
                us.retireUser(user, retireReason);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
            }

        } else if (mss.getMessage("User.unRetire").equals(action)) {
            us.unretireUser(user);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
        } else {
            // check if username is already in the database
            if (us.hasDuplicateUsername(user)) {
                errors.rejectValue("username", "error.username.taken");
            }

            // check if password and password confirm are identical
            if ((password == null) || password.equals("XXXXXXXXXXXXXXX")) {
                password = "";
            }
            if ((confirm == null) || confirm.equals("XXXXXXXXXXXXXXX")) {
                confirm = "";
            }

            if (!password.equals(confirm)) {
                errors.reject("error.password.match");
            }

            if ((password.length() == 0) && isNewUser(user)) {
                errors.reject("error.password.weak");
            }

            //check password strength
            if (password.length() > 0) {
                try {
                    OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
                } catch (final PasswordException e) {
                    errors.reject(e.getMessage());
                }
            }

            final Set<Role> newRoles = new HashSet<Role>();
            if (roles != null) {
                for (final String r : roles) {
                    // Make sure that if we already have a detached instance of this role in the
                    // user's roles, that we don't fetch a second copy of that same role from
                    // the database, or else hibernate will throw a NonUniqueObjectException.
                    Role role = null;
                    if (user.getRoles() != null) {
                        for (final Role test : user.getRoles()) {
                            if (test.getRole().equals(r)) {
                                role = test;
                            }
                        }
                    }
                    if (role == null) {
                        role = us.getRole(r);
                        user.addRole(role);
                    }
                    newRoles.add(role);
                }
            } else {
                final Role role = us.getRole("PHR Restricted User");
                newRoles.add(role);
                user.addRole(role);
                log.debug("Added PHR Restricted User role only: " + role);
            }

            if (user.getRoles() == null) {
                newRoles.clear();
            } else {
                user.getRoles().retainAll(newRoles);
            }

            final String[] keys = request.getParameterValues("property");
            final String[] values = request.getParameterValues("value");

            if ((keys != null) && (values != null)) {
                for (int x = 0; x < keys.length; x++) {
                    final String key = keys[x];
                    final String val = values[x];
                    user.setUserProperty(key, val);
                }
            }

            new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);

            final UserValidator uv = new UserValidator();
            uv.validate(user, errors);

            if (errors.hasErrors()) {
                log.debug("errors validating user: " + errors.getErrorCount() + errors.toString());
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            }

            String emailEntered = request.getParameter("9");

            if (isNewUser(user) && !isAdministrator) {
                log.debug("Saving new user " + user.getUsername() + ", sharingToken=" + sharingToken);
                final PhrSharingToken token = Context.getService(PhrSharingTokenService.class)
                        .getSharingToken(sharingToken);

                //check token existence and name matching
                if (token == null || token.getExpireDate().before(new Date())) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register without a valid sharing token");
                    log.error("Failed to register without a valid sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register without a valid sharing token; user_name="
                                    + user.getName());

                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }
                    return "redirect:/phr/index.htm?noredirect=true";
                } else if ((token != null) && (token.getRelatedPerson() != null)) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register with a used sharing token");
                    log.error("Failed to register with a used sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register with a used sharing token; user_name=" + user.getName()
                                    + "; sharingToken=" + token);
                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }

                    return "redirect:/phr/index.htm?noredirect=true";
                } else if (emailEntered != null
                        && token.getRelatedPersonEmail().equalsIgnoreCase(emailEntered)) {
                    // look for person attributes (including email entered) in the request and save to user
                    for (final PersonAttributeType type : Context.getPersonService()
                            .getPersonAttributeTypes(PERSON_TYPE.PATIENT, ATTR_VIEW_TYPE.VIEWING)) {
                        final String paramName = type.getPersonAttributeTypeId().toString();
                        final String value = request.getParameter(paramName);

                        this.log.debug("paramName=" + paramName);

                        // if there is an error displaying the attribute, the value will be null
                        if (value != null) {
                            final PersonAttribute attribute = new PersonAttribute(type, value);
                            try {
                                final Object hydratedObject = attribute.getHydratedObject();
                                if ((hydratedObject == null) || "".equals(hydratedObject.toString())) {
                                    // if null is returned, the value should be blanked out
                                    attribute.setValue("");
                                } else if (hydratedObject instanceof Attributable) {
                                    attribute.setValue(((Attributable) hydratedObject).serialize());
                                } else if (!hydratedObject.getClass().getName().equals(type.getFormat())) {
                                    // if the classes doesn't match the format, the hydration failed somehow
                                    // TODO change the PersonAttribute.getHydratedObject() to not swallow all errors?
                                    throw new APIException();
                                }
                            } catch (final APIException e) {
                                errors.rejectValue("attributeMap[" + type.getName() + "]",
                                        "Invalid value for " + type.getName() + ": '" + value + "'");
                                this.log.warn("Got an invalid value: " + value
                                        + " while setting personAttributeType id #" + paramName, e);

                                // setting the value to empty so that the user can reset the value to something else
                                attribute.setValue("");

                            }
                            user.getPerson().addAttribute(attribute);
                        }
                    }

                    //create a new user by self registration
                    us.saveUser(user, password);

                    //update sharing token
                    token.setRelatedPerson(user.getPerson());
                    token.setChangedBy(user);
                    final Date date = new Date();
                    token.setDateChanged(date);
                    token.setActivateDate(date);
                    Context.getService(PhrSharingTokenService.class).savePhrSharingToken(token);
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalhr.user.signed.up");
                    log.debug("New self-registered user created: " + user.getUsername());
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), user,
                            httpSession.getId(), null, "info=New self-registered user created; user_name="
                                    + user.getName() + "; sharingToken=" + token);

                    //save email to messaging service
                    Integer addressId = saveEmail(user.getPerson(), emailEntered);

                    //set default messaging alert address
                    boolean shouldAlert = true;
                    PersonalhrUtil.setMessagingAlertSettings(user.getPerson(), shouldAlert, addressId);

                    //send email notification

                    // TODO get the deployUrl from the request object; also bad to inject /openmrs/ ...
                    final String deployUrl = Context.getRuntimeProperties().getProperty("deployment.url");//"https://65.111.248.164:8443/"; //"172.30.201.24";

                    final String url = deployUrl + "/openmrs/phr/index.htm";
                    final String passwordOption = Context.getAdministrationService()
                            .getGlobalProperty("personalhr.show.password");

                    String notification = NOTIFICATION_TEMPLATE;
                    notification = notification.replaceAll("OPENMRS_PHR_RELATED_PERSON",
                            user.getPerson().getGivenName());
                    notification = notification.replaceAll("OPENMRS_USERNAME", user.getUsername());
                    notification = notification.replaceAll("OPENMRS_PASSWORD",
                            showPassword(password, passwordOption));
                    notification = notification.replaceAll("OPENMRS_URL", url);

                    PersonalhrUtil.sendEmail(emailEntered, notification);
                } else {
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                            "Failed to create new user due to email mismatch: " + emailEntered);
                    log.debug("Failed to create new user due to email mismatch: "
                            + token.getRelatedPersonEmail() + " vs " + emailEntered);
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "info=Failed to create new user due to email mismatch: "
                                    + token.getRelatedPersonEmail() + "vs " + emailEntered + "; sharingToken="
                                    + token);
                }
            } else if (isNewUser(user) && isAdministrator) {
                //create a new user by PHR Administrator
                us.saveUser(user, password);
            } else {
                //modify an exiting user
                us.saveUser(user, null);

                if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
                    if (log.isDebugEnabled()) {
                        log.debug("calling changePassword for user " + user + " by user "
                                + Context.getAuthenticatedUser());
                    }
                    us.changePassword(user, password);
                }
                log.debug("Existing user " + user.getUsername() + " changed by user "
                        + Context.getAuthenticatedUser().getUsername());
                PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_UPDATE, new Date(),
                        Context.getAuthenticatedUser(), httpSession.getId(), null,
                        "info=Existing user updated; user_name=" + user.getName());
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }

            if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
                us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }
        }
    } finally {
        //remove temporary privileges
        if (isTemporary) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
            Context.removeProxyPrivilege("PHR Restricted Patient Access");
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            Context.logout();
            log.debug("Removed proxy privileges for self registration!");
        } else if (isAdministrator) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            log.debug("Removed proxy privileges for PHR Administrator!");
        }
    }
    return "redirect:/phr/index.htm?noredirect=true";
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractTenantController.java

/**
 * Post method for creating Tenant./*from w w w . jav a 2s .  c  o  m*/
 * 
 * @param form the Tenant form. {@link TenantForm}
 * @param result {@link BindingResult}
 * @param map {@link ModelMap}
 * @param sessionStatus
 * @param request the {@link HttpServletRequest}
 * @return View.
 * @throws Exception
 */
@RequestMapping(value = { "", "/" }, method = RequestMethod.POST)
public String create(@ModelAttribute("account") final TenantForm form, BindingResult result, ModelMap map,
        SessionStatus sessionStatus, HttpServletRequest request) throws Exception {
    logger.debug("###Entering in create(form,map,status) method @POST");
    String promocode = form.getTrialCode();
    if (promocode != null) {
        CampaignPromotion campaignPromotion = promotionService.locatePromotionByToken(promocode);
        if (campaignPromotion == null) {
            logger.debug("Campaign is not valid");
            result.reject("trialCode", messageSource.getMessage("errors.registration.invalid_trial_code", null,
                    getSessionLocale(request)));
            return "tenants.new";
        }
    }
    String email = form.getUser().getEmail();
    if (isEmailBlacklisted(email.toLowerCase())) {
        map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
        map.addAttribute("defaultLocale", getDefaultLocale());
        map.addAttribute("ipToCountryCode", form.getUser().getAddress().getCountry());
        form.setAccountTypes(tenantService.getManualRegistrationAccountTypes());
        map.addAttribute("tenant", CustomProxy.newInstance(getCurrentUser().getTenant()));
        map.addAttribute("account", form);
        map.addAttribute("channels", channelService.getChannels(null, null, null));
        List<Country> filteredCountryList = getFilteredCountryList(form.getCountryList());
        map.addAttribute("filteredCountryList", filteredCountryList);
        map.addAttribute("signuperror", "emaildomainblacklisted");
        return "tenants.new";
    }
    if (result.hasErrors()) {
        displayErrors(result);
        parseResult(result, map);
        return "tenants.new";
    }
    // set currency
    for (CurrencyValue cv : form.getCurrencyValueList()) {
        if (cv.getCurrencyCode().equals(form.getCurrency())) {
            form.getTenant().setCurrency(cv);
            break;
        }
    }
    form.getTenant().setAddress(form.getUser().getAddress());

    if (form.isAllowSecondary()) {
        form.getTenant().setSecondaryAddress(form.getSecondaryAddress());
    }
    AccountType at = tenantService.getAccountTypeById(form.getAccountTypeId());
    List<PaymentMode> paymentModes = at.getSupportedPaymentModes();
    if (paymentModes != null && paymentModes.size() > 0) {
        form.getTenant().getObject().getTenantExtraInformation().setPaymentMode(paymentModes.get(0));
    }
    List<String> errorMsgList = new ArrayList<String>();
    try {
        final com.citrix.cpbm.access.User owner = form.getUser();

        String phoneNo = owner.getObject().getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "")
                + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + owner.getPhone().replaceAll(PHONE_NUMBER_REGEX, "");
        owner.setPhone(phoneNo);
        owner.setLocale(form.getUser().getLocale());
        form.getTenant().setRemoteAddress(getRemoteUserIp(request));
        String channelParam = form.getChannelParam();
        if (at.equals(tenantService.getTrialAccountType())) {
            com.citrix.cpbm.access.Tenant trialTenant = form.getTenant();
            trialTenant.setAccountType(at);
            registrationService.registerTrialAccount(form.getTrialCode(), trialTenant, owner, channelParam);
        } else {
            tenantService.createAccount(form.getTenant(), owner, channelParam, form.getAccountTypeId(), result);
            com.citrix.cpbm.access.Tenant tenant = form.getTenant();
            if (promocode != null && !promocode.isEmpty()) {
                promotionService.createTenantPromotion(promocode, tenant.getObject());
            }
        }
        map.addAttribute("tenant", form.getTenant());
        String homeUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_home_url);
        String cloudmktgUrl = config.getValue(Names.com_citrix_cpbm_portal_marketing_marketing_url);
        if (homeUrl != null) {
            map.addAttribute("homeUrl", homeUrl);
        }
        if (cloudmktgUrl != null) {
            map.addAttribute("cloudmktgUrl", cloudmktgUrl);
        }
        sessionStatus.setComplete(); // clean up parameters in session.
    } catch (DataAccessException ex) {
        logger.error(ex);
        result.reject("errors.registration", new Object[] { ex.getMessage() }, null);
        errorMsgList.add("You must accept the terms and conditions to use this service");
    } catch (LDAPException le) {
        logger.error(le);
        result.reject("errors.registration", new Object[] { le.getMessage() }, null);
    } catch (Exception ex) {
        logger.error("###handleTenantCreationError:" + ex.getMessage());
        throw ex;
    }
    if (result.hasErrors()) {
        displayErrors(result);
        form.reset();
        if (errorMsgList.size() > 0) {
            map.addAttribute("errorMsgList", errorMsgList);
            map.addAttribute("errormsg", true);
        }
        logger.debug("###Exiting register(registration,result,captchaChallenge,captchaResponse,"
                + "map,sessionStatus,request) method @POST");
        throw new AjaxFormValidationException(result);
        // return "tenants.new";
    } else {
        String tenantParam = form.getTenant().getUuid();
        map.clear();
        map.addAttribute("tenantParam", tenantParam);
        map.addAttribute("tenantName", form.getTenant().getName());
        map.addAttribute("tenantAccountTypeName", form.getTenant().getAccountType().getName());
        map.addAttribute("tenantAccountId", form.getTenant().getObject().getAccountId());
        map.addAttribute("tenantOwnerUserName", form.getTenant().getOwner().getUsername());
        map.addAttribute("tenantId", form.getTenant().getObject().getId());
        logger.debug("###Exiting create(registration,result,map,sessionStatus,request) method @POST");
        return result.toString();
    }
}

From source file:org.jasig.portlet.announcements.mvc.portlet.admin.AdminTopicController.java

/**
 * Saves the Topic that was submitted/*from w w w.j a  va  2 s.  c om*/
 *
 * @param topic
 * @param result
 * @param status
 * @param request
 * @param response
 * @throws PortletException
 */
@RequestMapping(params = "action=addTopic")
public void actionAddTopicForm(@ModelAttribute("topic") Topic topic, BindingResult result, SessionStatus status,
        ActionRequest request, ActionResponse response) throws PortletException {

    if (!UserPermissionChecker.isPortalAdmin(request)) {
        throw new UnauthorizedException("You do not have access to create a topic");
    }

    new TopicValidator().validate(topic, result);
    if (result.hasErrors()) {
        if (log.isDebugEnabled())
            log.debug("Error in form: " + result.toString());
        response.setRenderParameter("action", "addTopic");
        return;
    }

    if (!result.hasErrors() && topic != null) {
        if (log.isDebugEnabled())
            log.debug("No errors in form");

        // no id has been assigned by hibernate, so this must be a new topic
        if (!topic.hasId()) {
            topic.setCreator(request.getRemoteUser());
            announcementService.addOrSaveTopic(topic);
        } else {
            Long id = topic.getId();
            Topic oldTopic = announcementService.getTopic(id);

            oldTopic.setTitle(topic.getTitle());
            oldTopic.setDescription(topic.getDescription());
            oldTopic.setAllowRss(topic.isAllowRss());
            oldTopic.setSubscriptionMethod(topic.getSubscriptionMethod());
            announcementService.addOrSaveTopic(oldTopic);
        }
        status.setComplete();

        response.setRenderParameter("action", "baseAdmin");
    }
}