Example usage for org.springframework.validation BindingResult rejectValue

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

Introduction

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

Prototype

void rejectValue(@Nullable String field, String errorCode, @Nullable Object[] errorArgs,
        @Nullable String defaultMessage);

Source Link

Document

Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description.

Usage

From source file:alpha.portal.webapp.controller.CardFileUploadController.java

/**
 * handles the case, if the user clicks on one of the buttons.
 * //from w  w w  .  j  a  v a 2 s. c o  m
 * @param fileUpload
 *            the file upload
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @return success view
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final FileUpload fileUpload, final BindingResult errors,
        final HttpServletRequest request) throws IOException {

    final String caseId = request.getParameter("case");
    final String cardId = request.getParameter("card");
    final Locale locale = request.getLocale();

    this.setCancelView("redirect:/caseform?caseId=" + caseId + "&activeCardId=" + cardId);
    this.setSuccessView("redirect:/caseform?caseId=" + caseId + "&activeCardId=" + cardId);

    final AlphaCard card = this.alphaCardManager.get(new AlphaCardIdentifier(caseId, cardId));
    if (card == null) {
        this.saveError(request, this.getText("card.invalidId", locale));
        return this.getCancelView();
    }
    final Adornment contributor = card.getAlphaCardDescriptor()
            .getAdornment(AdornmentType.Contributor.getName());

    if ((contributor.getValue() == null) || contributor.getValue().isEmpty()) {

        this.saveError(request, this.getText("adornment.noAccess", locale));
        return this.getCancelView();

    } else {

        final Long contributorID = Long.parseLong(contributor.getValue());
        final User currentUser = this.getUserManager().getUserByUsername(request.getRemoteUser());

        if (contributorID != currentUser.getId()) {

            this.saveError(request, this.getText("adornment.noAccess", locale));
            return this.getCancelView();
        }
    }

    if (request.getParameter("cancel") != null)
        return this.getCancelView();

    if (this.validator != null) { // validator is null during testing
        fileUpload.setName("alphaCardPayloadFile");

        this.validator.validate(fileUpload, errors);

        if (errors.hasErrors())
            return "redirect:/cardfileupload?card=" + cardId + "&case=" + caseId;
    }

    // validate a file was entered
    if (fileUpload.getFile().length == 0) {
        final Object[] args = new Object[] { this.getText("uploadForm.file", request.getLocale()) };
        errors.rejectValue("file", "errors.required", args, "File");

        return "redirect:/cardfileupload?card=" + cardId + "&case=" + caseId;
    }

    final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    final MultipartFile file = multipartRequest.getFile("file");

    Payload payload = new Payload(file.getOriginalFilename(), file.getContentType());
    payload.setContent(file.getBytes());

    payload = this.payloadManager.saveNewPayload(payload, card);

    this.saveMessage(request, this.getText("card.payloadOK", locale));
    return this.getSuccessView();
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(User user, BindingResult errors, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null) {
        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            return getCancelView();
        } else {/*from   w ww  .  j ava 2s.c  o  m*/
            return getSuccessView();
        }
    }

    if (validator != null) { // validator is null during testing
        validator.validate(user, errors);

        if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
            return "userform";
        }
    }

    log.debug("entering 'onSubmit' method...");

    Locale locale = request.getLocale();

    if (request.getParameter("delete") != null) {
        getUserManager().removeUser(user.getId().toString());
        saveMessage(request, getText("user.deleted", user.getFullName(), locale));

        return getSuccessView();
    } else {

        // only attempt to change roles if user is admin for other users,
        // showForm() method will handle populating
        if (request.isUserInRole(Constants.ADMIN_ROLE) || request.isUserInRole(Constants.USER_ROLE)) {
            String[] userRoles = request.getParameterValues("userRoles");

            if (userRoles != null) {
                user.getRoles().clear();
                for (String roleName : userRoles) {
                    user.addRole(roleManager.getRole(roleName));
                }
            }
        }

        Integer originalVersion = user.getVersion();

        try {
            getUserManager().saveUser(user);
        } catch (AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
            log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (UserExistsException e) {
            errors.rejectValue("username", "errors.existing.user",
                    new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            // reset the version # to what was passed in
            user.setVersion(originalVersion);

            return "userform";
        }

        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            saveMessage(request, getText("user.saved", user.getFullName(), locale));

            // return to main Menu
            return getCancelView();
        } else {
            if (StringUtils.isBlank(request.getParameter("version"))) {
                saveMessage(request, getText("user.added", user.getFullName(), locale));

                // Send an account information e-mail
                message.setSubject(getText("signup.email.subject", locale));

                try {
                    sendUserMessage(user, getText("newuser.email.message", user.getFullName(), locale),
                            RequestUtil.getAppURL(request));
                } catch (MailException me) {
                    saveError(request, me.getCause().getLocalizedMessage());
                }

                return getSuccessView();
            } else {
                saveMessage(request, getText("user.updated.byAdmin", user.getFullName(), locale));
            }
        }
    }

    return "userform";
}

From source file:alpha.portal.webapp.controller.UserFormController.java

/**
 * On submit./*w  ww.  j  a  v a 2 s .  c o m*/
 * 
 * @param user
 *            the user
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @param response
 *            the response
 * @param model
 *            the model
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final User user, final BindingResult errors, final HttpServletRequest request,
        final HttpServletResponse response, final Model model) throws Exception {
    if (request.getParameter("cancel") != null) {
        if (!StringUtils.equals(request.getParameter("from"), "list"))
            return this.getCancelView();
        else
            return this.getSuccessView();
    }

    if (this.validator != null) { // validator is null during testing
        this.validator.validate(user, errors);

        if (errors.hasErrors() && (request.getParameter("delete") == null)) {
            model.addAttribute("contributorRoles", this.contributorRoleManager.getAll());
            return "userform";
        }
    }

    this.log.debug("entering 'onSubmit' method...");

    final Locale locale = request.getLocale();

    if (request.getParameter("delete") != null) {
        this.getUserManager().removeUser(user.getId().toString());
        this.saveMessage(request, this.getText("user.deleted", user.getFullName(), locale));

        return this.getSuccessView();
    } else {

        // only attempt to change roles if user is admin for other users,
        // showForm() method will handle populating
        if (request.isUserInRole(Constants.ADMIN_ROLE)) {
            final String[] userRoles = request.getParameterValues("userRoles");

            if (userRoles != null) {
                user.getRoles().clear();
                for (final String roleName : userRoles) {
                    user.addRole(this.roleManager.getRole(roleName));
                }
            }
        }

        final Integer originalVersion = user.getVersion();

        try {
            this.getUserManager().saveUser(user);
        } catch (final AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor
            // userManagerSecurity
            this.log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (final UserExistsException e) {
            errors.rejectValue("username", "errors.existing.user",
                    new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            // reset the version # to what was passed in
            user.setVersion(originalVersion);

            model.addAttribute("contributorRoles", this.contributorRoleManager.getAll());
            return "userform";
        }

        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            this.saveMessage(request, this.getText("user.saved", user.getFullName(), locale));

            // return to main Menu
            return this.getCancelView();
        } else {
            if (StringUtils.isBlank(request.getParameter("version"))) {
                this.saveMessage(request, this.getText("user.added", user.getFullName(), locale));

                // Send an account information e-mail
                this.message.setSubject(this.getText("signup.email.subject", locale));

                try {
                    this.sendUserMessage(user,
                            this.getText("newuser.email.message", user.getFullName(), locale),
                            RequestUtil.getAppURL(request));
                } catch (final MailException me) {
                    this.saveError(request, me.getCause().getLocalizedMessage());
                }

                return this.getSuccessView();
            } else {
                this.saveMessage(request, this.getText("user.updated.byAdmin", user.getFullName(), locale));
            }
        }
    }

    return "redirect:/mainMenu";
}

From source file:org.n52.smartsensoreditor.controller.StartEditorControllerSML.java

/**
 * Starts editor with a service description
 *
 * @param pEditorBean//from   w w  w  . ja v a  2s. c  o  m
 * @param pResult
 * @return
 */
@RequestMapping(value = "/startServiceSOS", method = RequestMethod.POST)
public ModelAndView startServiceHandler(@ModelAttribute("startEditorBeanSML") StartEditorBeanSML pEditorBean,
        BindingResult pResult) {
    //Error handling
    ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceUrl", "errors.service.url.empty");
    ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceType", "errors.service.type.empty");

    if (pEditorBean.getServiceType().equalsIgnoreCase("ARCIMS")) {
        ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceName", "errors.service.name.empty");
    }

    if (pEditorBean.getServiceType().equalsIgnoreCase(SOS_SERVICE_TYPE)) {
        ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceTokenForSOS",
                "errors.service.tokenForSOS.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceProcedureIDForSOS",
                "errors.service.procedureIDForSOS.empty");
        ValidationUtils.rejectIfEmptyOrWhitespace(pResult, "serviceOperationForSOS",
                "errors.service.operationForSOS.empty");
    }

    if (pResult.hasErrors()) {
        LOG.debug("Form validation errors: " + pResult);
        // return form view
        return new ModelAndView(getFormView(), getModelMap());
    }
    //Set service URL
    String serviceUrl = pEditorBean.getServiceUrl();
    LOG.debug("ServiceUrl set to '" + serviceUrl + "'");
    //Create webservice
    if (pEditorBean.getServiceType().equalsIgnoreCase(SOS_SERVICE_TYPE)) {//serviceTypes are defined in codelist_enumeration.xml in identifier: CT_ServiceTypeExt.
        LOG.debug("Put SOS values into webserviceDescriptionDAO");
        StartEditorBeanSML editorBeanSML = (StartEditorBeanSML) pEditorBean;
        //Set procedureID
        String procId = editorBeanSML.getServiceProcedureIDForSOS();
        LOG.debug("Procedure ID set to '" + procId + "'");
        //Set token
        String token = editorBeanSML.getServiceTokenForSOS();
        LOG.debug("Token is set to '" + token + "'");

        //Set the token and the serviceUrl within the BackendBeanSml to insert them in the selectStates.jsp file.
        BackendBean backendBean = getBackendService().getBackend();
        if (backendBean instanceof BackendBeanSML) {
            BackendBeanSML backendBeanSML = ((BackendBeanSML) backendBean);
            backendBeanSML.setServiceURL(serviceUrl);
            LOG.debug("ServiceUrl is set in the BeackendBean '" + serviceUrl + "'");
            backendBeanSML.setServiceTokenSOS(token);
            LOG.debug("Token is set in the BackendBean '" + token + "'");
        }

        //For request
        Document catalogRequest = null;
        Document catalogResponse = null;
        Map parameterMap = new HashMap();
        parameterMap.put("procedureId", procId);

        SOSCatalogService sosService = getSOSCatalogServiceDAO();
        sosService.init(serviceUrl);
        sosService.addRequestHeader("Authorization", token);
        sosService.addRequestHeader("Content-Type", "application/soap+xml");

        //When a sensor should be edited
        if (editorBeanSML.getServiceOperationForSOS().equalsIgnoreCase(SOS_Operation_DESCRIBE)) {
            //Create Request and do transaction
            catalogRequest = getRequestFactory().createRequest("get", parameterMap);

            catalogResponse = sosService.transaction(catalogRequest);//does it really throw an exception??

            if (catalogResponse == null) {
                Map<String, Object> lModel = getModelMap();
                lModel.put("response", new TransactionResponseSOS());
                lModel.put("serverError", "errors.service.connect.request");
                lModel.put("sourcePage", "startService");
                return new ModelAndView(getFinishView(), lModel);
            }
            //For Transformation
            Document sensorML = DOMUtil.newDocument(true);
            Source source = new DOMSource(catalogResponse);
            Result result = new DOMResult(sensorML);

            String transformerFilePath = getTransformerFiles().get(SOS_SERVICE_TYPE.toLowerCase());
            getXsltTransformer().setRulesetSystemID(transformerFilePath);
            // transform
            getXsltTransformer().transform(source, result);
            getBackendService().initBackend(sensorML);

            getBackendService().setUpdate(true);
            return new ModelAndView(getSuccessView());

        }
        //When a sensor should be deleted
        if (editorBeanSML.getServiceOperationForSOS().equalsIgnoreCase(SOS_Operation_DELETE)) {
            catalogRequest = getRequestFactory().createRequest("delete", parameterMap);
            catalogResponse = sosService.transaction(catalogRequest);
            Map<String, Object> lModel = new HashMap<String, Object>();
            lModel.put("sourcePage", "startService");
            if (catalogResponse == null) {
                lModel.put("response", new TransactionResponseSOS());
                lModel.put("serverError", "errors.service.connect.request");
                return new ModelAndView(getFinishView(), lModel);
            }

            lModel.put("response", new TransactionResponseSOS(catalogResponse));
            return new ModelAndView(getFinishView(), lModel);
        }
    } else {
        WebServiceDescriptionDAO dao = getServiceFactory()
                .getDescriptionDAO(pEditorBean.getServiceType().toLowerCase());
        dao.setUrl(serviceUrl);
        LOG.trace("Current dao: " + dao);
        if (!"".equals(pEditorBean.getServiceName())) {
            dao.setServiceName(pEditorBean.getServiceName());
        }
        try {
            Document lDoc = dao.getDescription();
            if (LOG.isTraceEnabled()) {
                String docString = DOMUtil.convertToString(lDoc, true);
                LOG.trace("Retrieved document from DAO: " + docString);
            }
            if (lDoc != null) {
                getBackendService().setUpdate(true);

                getBackendService().initBackend(lDoc);
                return new ModelAndView(getSuccessView());
            }
        } catch (WebServiceDescriptionException e) {
            pResult.rejectValue("serviceUrl", "errors.service.connect", new Object[] { e.getMessage() },
                    "Capabilities error");
            return new ModelAndView(getFormView(), getModelMap());
        }

    }
    return new ModelAndView(getFormView());

}

From source file:com.razorfish.controllers.pages.ChinaAccountPageController.java

@RequestMapping(value = "/update-mobileNumber", method = RequestMethod.POST)
@RequireHardLogIn/*from  w  w  w.j  a  v a2  s  . com*/
public String updateMobileNumber(final UpdateMobileNumberForm updateMobileNumberForm,
        final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes)
        throws CMSItemNotFoundException {
    getMobileNumberValidator().validate(updateMobileNumberForm, bindingResult);

    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!bindingResult.hasErrors()
            && !updateMobileNumberForm.getMobileNumber().equals(updateMobileNumberForm.getChkMobileNumber())) {
        bindingResult.rejectValue("chkMobileNumber", "validation.checkMobileNumber.equals", new Object[] {},
                "validation.checkMobileNumber.equals");
    }
    if (bindingResult.hasErrors()) {
        returnAction = errorUpdatingMobileNumber(model);
    } else {
        try {
            final CustomerData currentCustomerData = customerFacade.getCurrentCustomer();
            final CustomerData customerData = new CustomerData();
            customerData.setMobileNumber(updateMobileNumberForm.getMobileNumber());
            customerData.setUid(currentCustomerData.getUid());
            customerData.setDisplayUid(currentCustomerData.getDisplayUid());

            customerFacade.updateMobileNumber(customerData, updateMobileNumberForm.getPassword());
            GlobalMessages.addFlashMessage(redirectAttributes, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "text.account.profile.confirmationUpdated", null);
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("password", "profile.currentPassword.invalid");
            returnAction = errorUpdatingMobileNumber(model);
        } catch (final DuplicateUidException e) {
            if (e.getCause().getCause() instanceof InterceptorException
                    && ((InterceptorException) e.getCause().getCause()).getInterceptor().getClass()
                            .equals(CustomerMobileNumberValidateInterceptor.class)) {
                bindingResult.rejectValue("mobileNumber", "registration.error.mobileNumber.exists.title");
                returnAction = errorUpdatingMobileNumber(model);
            }
        }
    }

    return returnAction;
}

From source file:de.appsolve.padelcampus.admin.controller.general.AdminGeneralModulesController.java

private void checkTitleRequirements(Module module, BindingResult result) {
    switch (module.getModuleType()) {
    case Blog://from  ww  w .j  a v  a2  s. co m
    case Page:
    case Events:

        //make sure title does not conflict with existing request mappings
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMapping.getHandlerMethods()
                .entrySet()) {
            RequestMappingInfo requestMappingInfo = entry.getKey();
            List<String> matchingPatterns = requestMappingInfo.getPatternsCondition()
                    .getMatchingPatterns("/" + module.getUrlTitle());
            for (String pattern : matchingPatterns) {
                if (!pattern.equals("/{moduleId}")) {
                    result.rejectValue("title", "ModuleWithUrlTitleAlreadyExists",
                            new Object[] { module.getUrlTitle() }, "ModuleWithUrlTitleAlreadyExists");
                    return;
                }
            }
        }

        Module existingModule = moduleDAO.findByUrlTitle(module.getUrlTitle());
        if (existingModule != null && !existingModule.equals(module)) {
            result.rejectValue("title", "ModuleWithUrlTitleAlreadyExists",
                    new Object[] { module.getUrlTitle() }, "ModuleWithUrlTitleAlreadyExists");
        }
        break;
    }
}

From source file:de.hybris.platform.ytelcoacceleratorstorefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-email", method = RequestMethod.POST)
public String updateEmail(@Valid final UpdateEmailForm updateEmailForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectAttributes) throws CMSItemNotFoundException {
    String returnAction = REDIRECT_TO_PROFILE_PAGE;

    if (!updateEmailForm.getEmail().equals(updateEmailForm.getChkEmail())) {
        bindingResult.rejectValue("chkEmail", "validation.checkEmail.equals", new Object[] {},
                "validation.checkEmail.equals");
    }/* www .ja v a  2s .  co m*/

    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
        setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
        model.addAttribute("breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
        returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage;
    } else {
        try {
            customerFacade.changeUid(updateEmailForm.getEmail().toLowerCase(), updateEmailForm.getPassword());

            //temporary solution to set oryginal UID - with new version of commerceservices it will not be necessary
            final CustomerData customerData = customerFacade.getCurrentCustomer();
            customerData.setDisplayUid(updateEmailForm.getEmail());
            customerFacade.updateProfile(customerData);
            //end of temporary solution

            redirectAttributes.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER,
                    Collections.singletonList("text.account.profile.confirmationUpdated"));

            // Replace the spring security authentication with the new UID
            final String newUid = customerFacade.getCurrentCustomer().getUid().toLowerCase();
            final Authentication oldAuthentication = SecurityContextHolder.getContext().getAuthentication();
            final UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
                    newUid, null, oldAuthentication.getAuthorities());
            newAuthentication.setDetails(oldAuthentication.getDetails());
            SecurityContextHolder.getContext().setAuthentication(newAuthentication);
        } catch (final DuplicateUidException e) {
            redirectAttributes.addFlashAttribute(GlobalMessages.INFO_MESSAGES_HOLDER,
                    Collections.singletonList("text.account.profile.emailNotChanged"));
        } catch (final PasswordMismatchException passwordMismatchException) {
            bindingResult.rejectValue("email", "profile.currentPassword.invalid");
            GlobalMessages.addErrorMessage(model, "form.global.error");
            storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
            setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
            model.addAttribute("breadcrumbs", accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile"));
            returnAction = ControllerConstants.Views.Pages.Account.AccountProfileEmailEditPage;
        }
    }

    return returnAction;
}

From source file:de.hybris.telcotrail.storefront.controllers.pages.AccountPageController.java

@RequestMapping(value = "/update-password", method = RequestMethod.POST)
public String updatePassword(@Valid final UpdatePasswordForm updatePasswordForm,
        final BindingResult bindingResult, final Model model, final RedirectAttributes redirectAttributes)
        throws CMSItemNotFoundException {
    if (!bindingResult.hasErrors()) {
        if (updatePasswordForm.getNewPassword().equals(updatePasswordForm.getCheckNewPassword())) {
            try {
                customerFacade.changePassword(updatePasswordForm.getCurrentPassword(),
                        updatePasswordForm.getNewPassword());
            } catch (final PasswordMismatchException localException) {
                bindingResult.rejectValue("currentPassword", "profile.currentPassword.invalid", new Object[] {},
                        "profile.currentPassword.invalid");
            }/*ww  w. j a va  2 s . c o m*/
        } else {
            bindingResult.rejectValue("checkNewPassword", "validation.checkPwd.equals", new Object[] {},
                    "validation.checkPwd.equals");
        }
    }

    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        storeCmsPageInModel(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));
        setUpMetaDataForContentPage(model, getContentPageForLabelOrId(PROFILE_CMS_PAGE));

        model.addAttribute("breadcrumbs",
                accountBreadcrumbBuilder.getBreadcrumbs("text.account.profile.updatePasswordForm"));
        return ControllerConstants.Views.Pages.Account.AccountChangePasswordPage;
    } else {
        redirectAttributes.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER,
                Collections.singletonList("text.account.confirmation.password.updated"));
        return REDIRECT_TO_PROFILE_PAGE;
    }
}

From source file:fr.hoteia.qalingo.web.mvc.controller.user.UserController.java

@RequestMapping(value = BoUrls.USER_EDIT_URL, method = RequestMethod.POST)
public ModelAndView submitUserEdit(final HttpServletRequest request, final Model model,
        @Valid UserForm userForm, BindingResult result, ModelMap modelMap) throws Exception {

    final String userId = userForm.getId();
    User user = userService.getUserById(userId);
    if (result.hasErrors()) {
        return userEdit(request, model);
    }/*from w  w  w. j  a  v a2s.c  o  m*/

    // SANITY CHECK
    if (BooleanUtils.negate(userForm.getLogin().equalsIgnoreCase(user.getLogin()))) {
        User userCheck = userService.getUserByLoginOrEmail(userForm.getLogin());
        if (userCheck != null) {
            result.rejectValue("login", "error.form.user.update.login.already.exist", null,
                    "This email customer account already exist!.");
            return userEdit(request, model);
        }
    }
    if (BooleanUtils.negate(userForm.getEmail().equalsIgnoreCase(user.getEmail()))) {
        User userCheck = userService.getUserByLoginOrEmail(userForm.getEmail());
        if (userCheck != null) {
            result.rejectValue("email", "error.form.user.update.email.already.exist", null,
                    "This email customer account already exist!.");
            return userEdit(request, model);
        }
    }

    // UPDATE USER
    webBackofficeService.updateUser(user, userForm);

    Map<String, String> urlParams = new HashMap<String, String>();
    urlParams.put(RequestConstants.REQUEST_PARAMETER_USER_ID, userId);
    return new ModelAndView(new RedirectView(backofficeUrlService.generateUrl(BoUrls.USER_DETAILS,
            requestUtil.getRequestData(request), urlParams)));
}

From source file:org.anyframe.iam.admin.securedresources.web.AnnotationResourcesController.java

/**
 * add Resource data/* w  w  w  .  ja v  a2s .  com*/
 * @param sr SecuredResources domain object
 * @param bindingResult an object to check input data with validation rules
 * @param status SessionStatus object to block double submit
 * @return move to "resources/list.do"
 * @throws Exception fail to add resource
 */
@RequestMapping("/resources/add.do")
public String add(@RequestParam(value = "skipvalidation", required = false) String skipValidation,
        @ModelAttribute("resources") SecuredResources sr, BindingResult bindingResult, HttpSession session,
        SessionStatus status) throws Exception {

    if (!("Y").equals(skipValidation)) {
        beanValidator.validate(sr, bindingResult);
        boolean isMatched = candidateSecuredResourcesService.checkMatched(sr.getResourcePattern(),
                sr.getResourceType());
        if (!isMatched) {
            bindingResult.rejectValue("resourcePattern", "errors.resourcepattern",
                    new Object[] { sr.getResourcePattern() }, "check resource pattern.");
        }
        if (bindingResult.hasErrors()) {
            return "/resources/resourcedetail";
        }
    }
    String[] systemName = new String[1];
    systemName[0] = (String) session.getAttribute("systemName");
    sr.setSystemName(systemName[0]);

    String currentTime = DateUtil.getCurrentTime("yyyyMMdd");

    sr.setCreateDate(currentTime);
    securedResourcesService.save(sr);
    status.setComplete();

    return "forward:/resources/list.do";
}