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);

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:com.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java

/**
 * @author Amitpals This method combines the functionality of step2 and step3 of previous wizard for user creation
 *         which gets call from Finish Button of User Creation at step1
 * @param form/*www  . j  av a 2s  . c om*/
 * @param result
 * @param tenant
 * @param map which is to be filled by method. Contains all the UI accessible variables as an attribute
 * @param request
 * @return
 */
@RequestMapping(value = "/new/step1", method = RequestMethod.POST)
public String createUserStepTwo(@ModelAttribute("user") UserForm form, BindingResult result,
        @ModelAttribute("userTenant") com.citrix.cpbm.access.Tenant tenant, ModelMap map,
        HttpServletRequest request, HttpSession session) {
    logger.debug("### Entering user create : createUserStepTwo");
    boolean validationError = false;
    session.setAttribute("currentStep", "newUserCreationStep1");
    // This attribute decides(createnewuser.jsp) the stepNumber to be shown.
    // set it default to step1 in case of any error in form submission step one be shown
    UserStep1Validator validator = new UserStep1Validator();
    validator.validate(form, result);
    if (result.hasErrors()) {
        validationError = true;
    } else if (!isValidUserName(form.getUser().getUsername())) {
        // if the values entered are OK check lastly check username in DB
        result.rejectValue("user.username", "js.errors.register.user.usernameRemote");
        validationError = true;
    }

    if (validationError) {
        // Attributes to populate the drop downs
        map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
        map.addAttribute("defaultLocale", getDefaultLocale());
        return "users.new.step1";
    }

    String email = form.getUser().getEmail();
    map.addAttribute("userTenant", tenant);
    map.addAttribute("tenant", tenant);

    if (isEmailBlacklisted(email.toLowerCase())) {
        map.addAttribute("signuperror", "emaildomainblacklisted");
        if (isAdmin() && isSurrogatedTenant(getCurrentUser().getTenant(), tenant.getParam())) {
            setPage(map, Page.CRM_USER_ADD);
            map.addAttribute("showUserProfile", true);
        } else if (isAdmin() && !isSurrogatedTenant(getCurrentUser().getTenant(), tenant.getParam())) {
            setPage(map, Page.ADMIN_ALL_USERS);
            map.addAttribute("showUserProfile", true);
        } else {
            setPage(map, Page.USER_ADD);
        }
        // verify for max users. if not allowed then move to not authorize page
        if (!isAllowedToAddUser(tenant.getObject())) {
            String msg = messageSource.getMessage("max.users.reached.popup.message", null, null,
                    LocaleUtils.toLocale(config.getDefaultLocale()));
            throw new InvalidAjaxRequestException(msg);
        }
        map.addAttribute("displayChannel", false);
        map.addAttribute("channels", channelService.getChannels(null, null, null));
        map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
        map.addAttribute("defaultLocale", getDefaultLocale());
        return "users.new.step1";

    }
    String channelParam = form.getChannelParam();
    User currentUser = getCurrentUser();
    boolean isSystemRoot = currentUser.equals(userService.getSystemUser(Handle.ROOT));
    if (isSystemRoot && channelParam != null) {
        form.getUser().setSourceChannel(channelService.getChannel(channelParam)); // XXX Gaurav
    }
    if (isAdmin() && tenant.getParam().equals(getTenant().getParam())) {
        setPage(map, Page.ADMIN_ALL_USERS);
    } else if (tenant.getParam().equals(getTenant().getParam())) {
        setPage(map, Page.USER_ADD);
    } else {
        setPage(map, Page.CRM_USER_ADD);
        map.addAttribute("showUserProfile", true);
    }

    map.addAttribute("user", form);
    // step3 merged
    if (!request.getParameter("submitButtonEmail").equals("CustomeEmail")) {// finish button pressed
        // Check the flow once more
        logger.debug("### User creation : request Finish");
        com.citrix.cpbm.access.User user = form.getUser();
        user.setLocale(form.getUserLocale());
        if (form.getTimeZone() != null && form.getTimeZone() != "") {
            user.setTimeZone(form.getTimeZone());
        } else {
            user.setTimeZone(config.getValue(Names.com_citrix_cpbm_portal_settings_default_timezone));
        }
        user.getObject().setCreatedBy(getCurrentUser());
        if (form.getUserProfile() != null) {
            user.setProfile(profileService.getProfile(form.getUserProfile()));
        }
        userService.createUserInTenant(user, tenant, result);
        if (result.hasErrors()) {
            map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
            map.addAttribute("defaultLocale", getDefaultLocale());
            return "users.new.step1";
        }
        map.addAttribute("tenant", tenant);
        String message = "create.user";
        String messageArgs = user.getUsername() + "," + tenant.getName();
        eventService.createEvent(new Date(), tenant.getObject(), message, messageArgs, Source.PORTAL,
                Scope.ACCOUNT, Category.ACCOUNT, Severity.INFORMATION, true);
        session.setAttribute("currentStep", "newUserCreationStep3");// User successfully created show next step
        setNewUserPageCount(session, tenant.getObject());
        return "users.newuserregistration.finish";

    } else {
        setNewUserPageCount(session, tenant.getObject());
        Map<String, Object> model = new HashMap<String, Object>();
        String userLocale;
        model.put("user", form.getUser());
        model.put("custom", true);
        if (form.getUserLocale() == null) {
            userLocale = getDefaultLocale().toString();
        } else {
            userLocale = form.getUserLocale().toString();
        }
        String emailText = userService.getEmailTemplateAsStringByLocale(EmailTemplate.VERIFY_EMAIL, model,
                userLocale);
        map.addAttribute("emailText", emailText);
        logger.debug("### User creation : Customize Welcome EMail");
        session.setAttribute("currentStep", "newUserCreationStep2");// User successfully created show next step
        return "users.newuser.customemail";
    }
}

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

/**
 * @param form/* ww  w .jav  a2  s. c om*/
 * @param result
 * @param map
 * @param status
 * @return
 */
@RequestMapping(value = { "/{userParam}/myprofile" }, method = RequestMethod.POST)
public String edit(@PathVariable String userParam, @Valid @ModelAttribute("user") UserForm form,
        BindingResult result, HttpServletRequest request, ModelMap map, SessionStatus status) {
    logger.debug("###Entering in edit(form,result,map,status) method @POST");
    com.citrix.cpbm.access.User user = form.getUser();

    MyProfileValidator validator = new MyProfileValidator();
    validator.validate(form, result);
    if (result.hasErrors()
            && !(result.getErrorCount() == 1 && result.getAllErrors().get(0).getCode().equals("Size")
                    && form.getUser().getUsername().equals("root"))) {
        displayErrors(result);
        // TODO to return the edit page with errors
        return "redirect:/portal/users/" + userParam + "/myprofile";
    }
    User logedInUser = this.getCurrentUser();
    if (isEmailBlacklisted(user.getEmail().toLowerCase())) {
        logger.info("Email Id : " + form.getUser().getEmail()
                + " rejected because it is not on the whitelist or part of the blacklist. Kindly contact support");
        result.rejectValue("user.email", "signup.emaildomain.blacklist.error");
        return edit(null, user.getObject().getUuid(), request, map);
    }
    if (form.getClearPassword() != null && !form.getClearPassword().isEmpty()) { // password reset
        if (form.getOldPassword() == null) {
            result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false,
                    new String[] { "errors.password.required" }, null, null));
        } else if (!user.getObject().authenticate(form.getOldPassword())) {
            result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false,
                    new String[] { "errors.password.invalid" }, null, null));
        } else {
            user.getObject().setClearPassword(form.getClearPassword());
        }
    }
    com.citrix.cpbm.access.User userClone = form.getUserClone();
    // TODO need to do Validation(Once fix this then remove @Ignore annotation against testUpdateUserFail from Test
    // Suit.
    form.setPhone(form.getPhone().replaceAll(PHONE_NUMBER_REGEX, "")); // removing all characters from phone number
    String oldPhone = userClone.getPhoneWithoutIsdCode() != null ? userClone.getPhoneWithoutIsdCode() : "";
    boolean phoneVerificationEnabled = false;
    if (!form.getPhone().equals(oldPhone.replaceAll(PHONE_NUMBER_REGEX, ""))
            || !form.getCountryCode().toString().equals(user.getCountryCode())) {

        if (connectorManagementService.getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION) != null
                && ((TelephoneVerificationService) connectorManagementService
                        .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).isEnabled()) {
            phoneVerificationEnabled = true;
        }

        if (phoneVerificationEnabled && !userService.hasAuthority(logedInUser, "ROLE_ACCOUNT_CRUD")) {
            String generatedPhoneVerificationPin = (String) request.getSession()
                    .getAttribute("phoneVerificationPin");
            String actualPhoneNumber = (String) request.getSession().getAttribute("phoneNumber");
            if (form.getUserEnteredPhoneVerificationPin() == null
                    || !form.getUserEnteredPhoneVerificationPin().equals(generatedPhoneVerificationPin)
                    || !areDigitsInPhoneNosEqual(form.getPhone(), actualPhoneNumber)) {
                map.addAttribute("userEditError", "phoneVerfication.error");
                result.rejectValue("phone", "phoneVerfication.error");
                parseResult(result, map);
                return edit(null, user.getObject().getUuid(), request, map);
            }
        }
    }
    String phoneNo = form.getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "")
            + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + form.getPhone().replaceAll(PHONE_NUMBER_REGEX, "");
    // Set the phone number
    if (!phoneVerificationEnabled && StringUtils.isEmpty(form.getPhone())) {
        user.setPhone(null);
    } else {
        user.setPhone(phoneNo);
    }

    if ((user.getObject().getTenant().getState() == State.ACTIVE
            || user.getObject().getTenant().getState() == State.LOCKED
            || user.getObject().getTenant().getState() == State.SUSPENDED)
            && !user.getEmail().equals(userClone.getEmail())) {
        userAlertPreferencesService.createUserAlertPreference(user.getObject(), user.getEmail(),
                AlertType.USER_EMAIL);
        // set email so that it wont be updated in users table and other places
        user.setEmail(userClone.getEmail());
        user.setEmailVerified(true);
    }
    userService.update(user, result);
    form.setUser(user);
    map.addAttribute("user", form);
    setPage(map, Page.USER_PERSONAL_PROFILE);
    status.setComplete();
    logger.debug("###Exiting edit(form,result,map,status) method @POST");
    map.clear();
    return "redirect:/portal/users/" + user.getObject().getParam() + "/myprofile";
}

From source file:alfio.controller.form.PaymentForm.java

public void validate(BindingResult bindingResult, TotalPrice reservationCost, Event event,
        List<TicketFieldConfiguration> fieldConf) {

    List<PaymentProxy> allowedPaymentMethods = event.getAllowedPaymentProxies();

    Optional<PaymentProxy> paymentProxyOptional = Optional.ofNullable(paymentMethod);
    PaymentProxy paymentProxy = paymentProxyOptional.filter(allowedPaymentMethods::contains)
            .orElse(PaymentProxy.STRIPE);
    boolean priceGreaterThanZero = reservationCost.getPriceWithVAT() > 0;
    boolean multiplePaymentMethods = allowedPaymentMethods.size() > 1;
    if (multiplePaymentMethods && priceGreaterThanZero && !paymentProxyOptional.isPresent()) {
        bindingResult.reject(ErrorsCode.STEP_2_MISSING_PAYMENT_METHOD);
    } else if (priceGreaterThanZero
            && (paymentProxy == PaymentProxy.STRIPE && StringUtils.isBlank(stripeToken))) {
        bindingResult.reject(ErrorsCode.STEP_2_MISSING_STRIPE_TOKEN);
    }/*ww  w  .j a  v  a 2s . c o m*/

    if (Objects.isNull(termAndConditionsAccepted) || !termAndConditionsAccepted) {
        bindingResult.reject(ErrorsCode.STEP_2_TERMS_NOT_ACCEPTED);
    }

    email = StringUtils.trim(email);

    fullName = StringUtils.trim(fullName);
    firstName = StringUtils.trim(firstName);
    lastName = StringUtils.trim(lastName);

    billingAddress = StringUtils.trim(billingAddress);

    ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "email", ErrorsCode.STEP_2_EMPTY_EMAIL);
    rejectIfOverLength(bindingResult, "email", ErrorsCode.STEP_2_MAX_LENGTH_EMAIL, email, 255);

    if (event.mustUseFirstAndLastName()) {
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "firstName",
                ErrorsCode.STEP_2_EMPTY_FIRSTNAME);
        rejectIfOverLength(bindingResult, "firstName", ErrorsCode.STEP_2_MAX_LENGTH_FIRSTNAME, fullName, 255);
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "lastName", ErrorsCode.STEP_2_EMPTY_LASTNAME);
        rejectIfOverLength(bindingResult, "lastName", ErrorsCode.STEP_2_MAX_LENGTH_LASTNAME, fullName, 255);
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "fullName", ErrorsCode.STEP_2_EMPTY_FULLNAME);
        rejectIfOverLength(bindingResult, "fullName", ErrorsCode.STEP_2_MAX_LENGTH_FULLNAME, fullName, 255);
    }

    rejectIfOverLength(bindingResult, "billingAddress", ErrorsCode.STEP_2_MAX_LENGTH_BILLING_ADDRESS,
            billingAddress, 450);

    if (email != null && !email.contains("@") && !bindingResult.hasFieldErrors("email")) {
        bindingResult.rejectValue("email", ErrorsCode.STEP_2_INVALID_EMAIL);
    }

    if (hasPaypalTokens() && !PaypalManager.isValidHMAC(new CustomerName(fullName, firstName, lastName, event),
            email, billingAddress, hmac, event)) {
        bindingResult.reject(ErrorsCode.STEP_2_INVALID_HMAC);
    }

    if (!postponeAssignment) {
        boolean success = Optional.ofNullable(tickets).filter(m -> !m.isEmpty()).map(m -> m.entrySet().stream()
                .map(e -> Validator.validateTicketAssignment(e.getValue(), fieldConf, Optional.empty(), event)))
                .filter(s -> s.allMatch(ValidationResult::isSuccess)).isPresent();
        if (!success) {
            bindingResult.reject(ErrorsCode.STEP_2_MISSING_ATTENDEE_DATA);
        }
    }
}

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

/**
 * deletes subscription//  w w w.j av  a2  s . c o  m
 * 
 * @param subscriptionId
 * @param map which is to be filled by method. Contains all the UI accessible variables as an attribute
 * @param form
 * @param result
 * @return
 */
@ResponseBody
@RequestMapping(value = "/alerts/edit", method = RequestMethod.POST)
public SpendAlertSubscription editSpendAlertSubscription(
        @RequestParam(value = "Id", required = true) String subscriptionId,
        @RequestParam(value = "newValue", required = true) String newVal,
        @ModelAttribute("subscriptionForm") CustomAlertForm form, BindingResult result, ModelMap map,
        HttpServletRequest request) {
    logger.debug("###Entering editSubscription method @POST");
    SpendAlertSubscription subscription = notificationService
            .getSpendAlertSubscription(new Long(subscriptionId));
    if (newVal == null) {
        result.rejectValue("tenantPercentage", "js.errors.tenantPercentage.required");
        throw new AjaxFormValidationException(result);
    }
    BigDecimal percentage = new BigDecimal(newVal);
    if ((percentage.intValue() < 0) || (percentage.intValue() > 100)) {
        result.rejectValue("tenantPercentage", "js.errors.tenantPercentage.percentage");
        throw new AjaxFormValidationException(result);
    }
    Tenant effectiveTenant = (Tenant) request.getAttribute(UserContextInterceptor.EFFECTIVE_TENANT_KEY);
    form.setTenantPercentage(new BigDecimal(newVal));
    if (effectiveTenant != null) {
        List<SpendAlertSubscription> spendAlertSubscription = notificationService
                .getAllSubscriptions(effectiveTenant);
        if (CollectionUtils.isNotEmpty(spendAlertSubscription)) {
            for (SpendAlertSubscription spendAlertSubscription2 : spendAlertSubscription) {
                if (spendAlertSubscription2.getPercentage().doubleValue() == form.getTenantPercentage()
                        .doubleValue()) {
                    result.rejectValue("tenantPercentage", "js.errors.tenantPercentage.validatePercentage");
                    throw new AjaxFormValidationException(result);
                }
            }
        }
    }
    subscription.setPercentage(percentage);
    subscription = notificationService.saveSubscription(subscription);
    logger.debug("###Leaving editSubscription method @POST");

    return subscription;
}

From source file:com.virtusa.akura.student.controller.StudentParentController.java

/**
 * Save or update the Donation object in Admin parent view.
 * /*from ww w.j  a va  2s .c  om*/
 * @param parentWrapper - WrapperParent object.
 * @param model - a HashMap that contains information of the parent
 * @param request - an object of HttpServletRequest.
 * @param result - containing list of errors and wrapperParent instance to which data was bound
 * @param session - an object of HttpSession to hold the studentid.
 * @throws AkuraAppException - The exception details that occurred when submitting donation details.
 * @return name of the view which is redirected to.
 */
@RequestMapping(value = REQ_MAP_VALUE_SAVE_UPDATE_DONATION, method = RequestMethod.POST)
public String saveDonation(@ModelAttribute(PARENT_WRAPPER) ParentWrapper parentWrapper, BindingResult result,
        ModelMap model, final HttpServletRequest request, HttpSession session) throws AkuraAppException {

    // The variable used to return the appropriate page.
    String returnPage = REDIRECT_ADMIN_PARENT;
    Integer studentId = (Integer) session.getAttribute(STUDENT_ID);

    donationValidator.validate(parentWrapper, result);
    if (result.hasErrors()) {
        model.addAttribute(DISPLAY_PANEL, Boolean.TRUE);
        returnPage = VIEW_PARENT; // "Admin/Parent_details";
    } else {
        // ParentDonation parentDonation = new ParentDonation();
        Donation donation = parentWrapper.getDonation();
        int donationTypeId = parentWrapper.getDonation().getDonationType().getDonationTypeId();
        DonationType donationType = commonService.findDonationType(donationTypeId);
        if (donationType != null) {
            donation.setDonationType(donationType);
        }
        if (session.getAttribute(STUDENT_ID) != null) {

            List<StudentParent> studentParentList = parentService.getStudentParentListByStudentId(studentId);
            if (studentParentList.isEmpty()) {
                result.rejectValue(DONATION_DONATION_ID, DONATION_DESCRIPTION_ERROR_MSG);
                returnPage = VIEW_PARENT;//
            } else {
                Parent studentParent = studentParentList.get(0).getParent();

                // check donation information is exists
                boolean isExistisDonation = parentService.isExistsDonation(donation);

                // save donation.
                if (!isExistisDonation && (studentParent != null) && (donation.getDonationId() == 0)) {
                    ParentDonation parentDonation = new ParentDonation();
                    Donation saveDonation = parentService.addDonation(donation);
                    parentDonation.setDonation(saveDonation);
                    parentDonation.setParent(studentParent);
                    parentService.addParentDonation(parentDonation);

                } else if (!isExistisDonation && donation != null && donation.getDonationId() != 0) {
                    parentService.modifyDonation(donation);
                } else if (isExistisDonation) {
                    message = new ErrorMsgLoader().getErrorMessage(DONATION_EXISTS_ERROR_MSG);
                    model.addAttribute(MESSAGE, message);
                    model.addAttribute(DISPLAY_PANEL, true);
                    returnPage = VIEW_PARENT;//
                } else {
                    message = new ErrorMsgLoader().getErrorMessage(DONATION_DESCRIPTION_ERROR_MSG);
                    model.addAttribute(MESSAGE, message);
                    model.addAttribute(DISPLAY_PANEL, true);
                    returnPage = VIEW_PARENT;//
                }
            }
        }
    }

    setDonationListToModel(studentId, model);
    setupStudentRatingDetails(model, session);
    return returnPage;
}

From source file:org.openmrs.module.appointmentscheduling.web.controller.AppointmentFormController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(HttpServletRequest request, Appointment appointment, BindingResult result,
        @RequestParam(value = "fromDate", required = false) Date fromDate,
        @RequestParam(value = "toDate", required = false) Date toDate,
        @RequestParam(value = "flow", required = false) String flow,
        @RequestParam(value = "origin", required = false) String origin) throws Exception {
    HttpSession httpSession = request.getSession();

    if (Context.isAuthenticated()) {
        AppointmentService appointmentService = Context.getService(AppointmentService.class);

        if (request.getParameter("save") != null) {
            new AppointmentValidator().validate(appointment, result);

            if (result.hasErrors())
                return null;
            else {
                appointment.setDateCreated(new Date());
                if (flow != null) {
                    appointment.setStatus(AppointmentStatus.WALKIN);
                    //Start a new visit
                    String visitTypeIdString = Context.getAdministrationService()
                            .getGlobalProperty(AppointmentUtils.GP_DEFAULT_VISIT_TYPE);
                    Integer visitTypeId = Integer.parseInt(visitTypeIdString);
                    VisitType defaultVisitType = Context.getVisitService().getVisitType(visitTypeId);

                    Visit visit = new Visit(appointment.getPatient(), defaultVisitType, new Date());
                    visit.setLocation(appointment.getTimeSlot().getAppointmentBlock().getLocation());
                    visit = Context.getVisitService().saveVisit(visit);
                    appointment.setVisit(visit);
                } else
                    appointment.setStatus(AppointmentStatus.SCHEDULED);
                appointmentService.saveAppointment(appointment);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "appointmentscheduling.Appointment.saved");
                //Check whether to redirect to appointments manage form (origin=null) or to patientDashboard (origin=dashboard)
                if (origin == null)
                    return "redirect:appointmentList.list";
                else if (origin.equals("dashboard"))
                    return "redirect:/patientDashboard.form?patientId="
                            + appointment.getPatient().getId().toString();
            }/*from w w  w. j  a  v a 2s  .c  o  m*/
        }
        if (request.getParameter("findAvailableTime") != null) {
            if (fromDate != null && toDate != null && !fromDate.before(toDate))
                result.rejectValue("timeSlot", "appointmentscheduling.Appointment.error.InvalidDateInterval");
        }
    }
    return null;
}

From source file:com.virtusa.akura.reporting.controller.GenarateExamResultsReportController.java

/**
 * Perform the logic of the controller to Generate Exam Results Report.
 *
 * @param response of type HttpServletResponse
 * @param exam - model object//w  w w  .j a  v a  2s  . c  om
 * @param errors - BindingResult
 * @return modelAndView
 * @throws AkuraAppException AkuraAppException
 */
@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(HttpServletResponse response, @ModelAttribute(EXAM_RESULTS_MODEL) ExamResults exam,
        BindingResult errors) throws AkuraAppException {

    String redirectURL = EXAM_REULTS_REPORT;
    Map<String, Object> map = new HashMap<String, Object>();
    examResultsReportValidator.validate(exam, errors);

    if (errors.hasErrors()) {
        redirectURL = REPORTING_EXAM_RESULTS_VIEW;
    } else {
        String examAdmissionNo = exam.getExamAdmissionNo();
        int examId = exam.getExamId();

        List<ExamResults> examResultsList = studentService.findExamResultsByExamAdmissionNo(examAdmissionNo,
                examId);

        if (!examResultsList.isEmpty()) {
            ExamResults tempExamResult = examResultsList.get(0);

            JRBeanCollectionDataSource jrBeanDataSource = new JRBeanCollectionDataSource(examResultsList);

            map.put(TITLE,
                    PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_EXAM_RESULTS_TITLE));
            map.put(LOGO_PATH, ReportUtil.getReportLogo());
            map.put(STYLE_TEMPLATE, PropertyReader.getPropertyValue(SYSTEM_CONFIG, APPSERVER_HOME)
                    + PropertyReader.getPropertyValue(SYSTEM_CONFIG, STYLE_PATH));
            map.put(FULL_NAME, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, FULL_NAME_TEXT));
            map.put(INDEX_NO, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, EXAM_INDEX_NO_TEXT));
            map.put(SUBJECTS, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, SUBJECTS_TEXT));
            map.put(MARKS_GRADE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, MARKS_GRADE_TEXT));
            if (!tempExamResult.isMarkType()) {
                map.put(DESCRIPTION,
                        PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, DESCRIPTION_TEXT));
            }
            map.put(DATE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, DATE_TEXT));
            map.put(PRINCIPLE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, PRINCIPLE_TEXT));
            map.put(REPORT_GENERATED_ON,
                    PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_GENERATED_ON_TEXT));
            map.put(GENERATED_DATE, DateUtil.getReportGeneratedDate(
                    PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_GENERATED_DATE_LOCALE)));
            map.put(PAGE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, REPORT_PAGE));
            map.put(GPL, AkuraWebConstant.REPORT_GPL);
            map.put(DATASOURCE, jrBeanDataSource);

        } else {
            errors.rejectValue(EXAM_ADMISSION_NO, NO_RESULTS_ERROR_MSG);
            redirectURL = REPORTING_EXAM_RESULTS_VIEW;
        }
    }

    return new ModelAndView(redirectURL, map);
}

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

protected String createUser(final B2BCustomerForm b2BCustomerForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectModel) throws CMSItemNotFoundException {

    if (bindingResult.hasErrors()) {
        GlobalMessages.addErrorMessage(model, "form.global.error");
        model.addAttribute(b2BCustomerForm);
        return editUser(b2BCustomerForm.getUid(), model);
    }/*from www  . j  av  a2s  .  c o m*/

    final CustomerData b2bCustomerData = new CustomerData();
    b2bCustomerData.setTitleCode(b2BCustomerForm.getTitleCode());
    b2bCustomerData.setFirstName(b2BCustomerForm.getFirstName());
    b2bCustomerData.setLastName(b2BCustomerForm.getLastName());
    b2bCustomerData.setEmail(b2BCustomerForm.getEmail());
    b2bCustomerData.setDisplayUid(b2BCustomerForm.getEmail());
    b2bCustomerData.setUnit(companyB2BCommerceFacade.getUnitForUid(b2BCustomerForm.getParentB2BUnit()));
    b2bCustomerData.setRoles(b2BCustomerForm.getRoles());
    model.addAttribute(b2BCustomerForm);
    model.addAttribute("titleData", getUserFacade().getTitles());
    model.addAttribute("roles", populateRolesCheckBoxes(companyB2BCommerceFacade.getUserGroups()));

    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.getBreadcrumbs(null);
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/", getMessageSource().getMessage(
            "text.company.organizationManagement", null, getI18nService().getCurrentLocale()), null));
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-user", getMessageSource()
            .getMessage("text.company.manageUsers", null, getI18nService().getCurrentLocale()), null));
    model.addAttribute("breadcrumbs", breadcrumbs);

    try {
        b2bCommerceUserFacade.updateCustomer(b2bCustomerData);
        b2bCustomerData.setUid(b2BCustomerForm.getEmail().toLowerCase());
        GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
                "text.confirmation.user.added");
    } catch (final DuplicateUidException e) {
        bindingResult.rejectValue("email", "text.manageuser.error.email.exists.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        model.addAttribute("b2BCustomerForm", b2BCustomerForm);
        return editUser(b2BCustomerForm.getUid(), model);

    }
    return String.format(REDIRECT_TO_USER_DETAILS, urlEncode(b2bCustomerData.getUid()));
}

From source file:com.virtusa.akura.reporting.controller.GenarateTeacherWisePresentAndAbsentDaysReportController.java

/**
 * Perform the logic of the controller to generate Teacher Wise Attendance Report .
 *
 * @param teacherWisePresentAbsentTemplate of type TeacherWisePresentAbsentTemplate
 * @param request of type HttpServletRequest
 * @param response of type HttpServletResponse
 * @param errors of type BindingResult/*from   w  w  w  .jav a2s  .co  m*/
 * @return java.lang.String
 * @param map of type ModelMap
 * @throws AkuraAppException AkuraAppException
 * @throws ParseException ParseException
 */
@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute(TEMPLATENAME) TeacherWisePresentAbsentTemplate teacherWisePresentAbsentTemplate,
        BindingResult errors, ModelMap map) throws AkuraAppException, ParseException {

    String selectedClass = request.getParameter(SELECTED_CLASS);
    String selectedAddmissionWithName = request.getParameter(SELECTED_ADDMISSION);
    ModelAndView modelAndView = new ModelAndView();

    Map<String, Object> params = new HashMap<String, Object>();
    params.put(DATE_DEPARTURE_FIELD, AkuraWebConstant.EMPTY_STRING);
    params.put(DATE_TO_FIELD, teacherWisePresentAbsentTemplate.getDateTo());
    String selectedAddmission = null;
    if (selectedAddmissionWithName != null) {
        String[] selectedAdmissionArray = selectedAddmissionWithName.split("-");
        selectedAddmission = selectedAdmissionArray[0].trim();
    }
    if (selectedAddmission != null) {
        teacherWisePresentAbsentTemplate.setTeacherRegNo(selectedAddmission);
    }
    if (selectedAddmission == null) {
        String message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_MANDATORY_FIELD_REQUIRED);
        map.addAttribute(MESSAGE, message);

        StaffCategory staffCategory = staffCommonService.getStaffCategory(Integer.parseInt(selectedClass));

        if (staffCategory != null) {
            map.addAttribute(MODEL_ATT_SELECTED_CLASS_GRADE_ID, staffCategory.getCatogaryID());
        }

        modelAndView.setViewName(MODELANDVIEW);
        return modelAndView;
    }

    presentAndAbsentDaysValidator.validate(teacherWisePresentAbsentTemplate, errors);
    if (errors.hasErrors()) {

        return setPreviousDataWhileError(map, selectedClass, selectedAddmission, modelAndView);
    }

    if (selectedClass.equals(AkuraWebConstant.STRING_ZERO)) {

        String message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_MANDATORY_FIELD_REQUIRED);
        map.addAttribute(MESSAGE, message);
        return setPreviousDataWhileError(map, selectedClass, selectedAddmission, modelAndView);
    }

    String teacherRegNo = teacherWisePresentAbsentTemplate.getTeacherRegNo();
    int staffId = staffService.findStaffIdForRegistrationNo(teacherRegNo);

    if (staffId == 0) {

        errors.rejectValue(FIELD_NAME, STAFFID_ERROR_MSG);
        modelAndView.setViewName(MODELANDVIEW);
        return modelAndView;
    }

    Staff staff = staffService.findStaff(staffId);

    String year = AkuraWebConstant.EMPTY_STRING;
    if (staff.getDateOfDeparture() != null) {
        year = DateUtil.getStringYear(staff.getDateOfDeparture());
    }
    TeacherAttendance tempTAa = new TeacherAttendance();
    List<TeacherAttendance> absentList = new ArrayList<TeacherAttendance>();
    if (year != AkuraWebConstant.EMPTY_STRING) {
        Date departureDateObj = staff.getDateOfDeparture();
        tempTAa.setDateOfDeparture(DateUtil.getFormatDate(departureDateObj));
        teacherWisePresentAbsentTemplate.setDateTo(DateUtil.getFormatDate(departureDateObj));

        params.put(DATE_DEPARTURE_FIELD,
                PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, DATE_DEPARTURE_FIELD_KEY));
        params.put(DEPARTURE_DATE_VALUE, DateUtil.getFormatDate(departureDateObj));
    } else {
        params.put(DEPARTURE_DATE_VALUE, AkuraWebConstant.EMPTY_STRING);
    }

    absentList.add(tempTAa);

    String startDate = teacherWisePresentAbsentTemplate.getDateFrom();

    SimpleDateFormat sdf = new SimpleDateFormat(YEAR_MONTH_DAY);
    Date dateFrom = sdf.parse(teacherWisePresentAbsentTemplate.getDateFrom());

    if (staff.getDateOfHire() != null) {

        setHireDate(teacherWisePresentAbsentTemplate, params, staff, dateFrom);
    }

    String endDate = teacherWisePresentAbsentTemplate.getDateTo();
    Date startDateObj = DateUtil.getParseDate(teacherWisePresentAbsentTemplate.getDateFrom());
    Date endDateObj = DateUtil.getParseDate(endDate);

    List<TeacherAttendance> attendanceList = attendanceReportingService
            .teacherWisePresentAndAbsentDays(teacherWisePresentAbsentTemplate);
    List<StaffLeave> staffLeaveList = staffService.getStaffLeaveListByDatePeriodAndStaffId(startDateObj,
            endDateObj, staffId);

    Calendar start = Calendar.getInstance();
    start.setTime(startDateObj);
    Calendar end = Calendar.getInstance();
    end.setTime(endDateObj);
    List<String> presentList = new ArrayList<String>();
    List<Holiday> holidayList = getHolidayList(startDateObj, endDateObj);

    boolean flag = false;
    boolean isHoliday = false;
    boolean isReason = false;
    String temp = null;
    int count = 0;

    while (!start.after(end)) {

        for (TeacherAttendance ta : attendanceList) {
            if (DateUtil.getFormatDate(start.getTime()).equals(ta.getDate())) {
                temp = ta.getDate();
                flag = true;
                break;
            }
        }
        isReason = false;
        isHoliday = isHoliday(holidayList, start.getTime(), start);

        if (flag) {
            presentList.add(temp);
            flag = false;
            temp = null;
            count++;
        } else {
            if (!isHoliday) {
                TeacherAttendance tempTA = new TeacherAttendance();
                tempTA.setDate(DateUtil.getFormatDate(start.getTime()).toString());

                for (StaffLeave staffLeave : staffLeaveList) {
                    if (DateUtil.isDateBetween(staffLeave.getFromDate(), staffLeave.getToDate(),
                            start.getTime())) {
                        isReason = setReasonAndApprovalBy(tempTA, staffLeave);

                        break;
                    }
                }
                if (!isReason) {
                    setReportParametersWhenNotReason(tempTA);
                }
                absentList.add(tempTA);
                count++;
            }
        }
        start.add(Calendar.DATE, 1);
    }
    JRBeanCollectionDataSource jrBeanDataSource = new JRBeanCollectionDataSource(absentList);
    setReportParameters(params, teacherRegNo, staff, absentList, startDate, presentList, count);

    ReportUtil.displayReportInPdfForm(response, jrBeanDataSource, params, JRXML_NAME);
    return null;
}

From source file:com.virtusa.akura.student.controller.StudentDetailController.java

/**
 * @param student - Student obj./*  ww w.j a  v  a2s .c  o m*/
 * @param result - BindingResult.
 * @param session - HttpSession
 * @param model - a hashMap that contains student's data
 * @param request - represents an instance of HttpServletRequest
 * @throws AkuraAppException - AkuraAppException.
 * @return name of the view which is redirected to.
 */
@RequestMapping(REQ_MAP_SAVE_STUDENT_DETAIL)
public String onSubmit(@ModelAttribute(MODEL_ATT_STUDENT) Student student, BindingResult result,
        HttpSession session, HttpServletRequest request, ModelMap model) throws AkuraAppException {

    String returnResult = VIEW_GET_STUDENT_DETAIL_PAGE;
    studentDetailValidator.validate(student, result);
    String selectedCountryCodeRes = request.getParameter(SELECTED_COUNTRYCODE_RES);
    String selectedCountryCodeMob = request.getParameter(SELECTED_COUNTRYCODE_MOB);
    String selectedCountryCodeEmgRes = request.getParameter(SELECTED_COUNTRYCODE_EMG_RES);
    String selectedCountryCodeEmgMob = request.getParameter(SELECTED_COUNTRYCODE_EMG_MOB);
    String selectedCountryCodeEmgOff = request.getParameter(SELECTED_COUNTRYCODE_EMG_OFFICE);
    try {
        if (result.hasErrors()) {
            handleValidationError(student, model);
            resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff, model);
            return VIEW_GET_STUDENT_DETAIL_PAGE;
        }

        trimProperties(student);
        UserInfo userInfo = (UserInfo) session.getAttribute(USER);

        if (userInfo instanceof StudentDetails
                && !userInfo.getUserLevelIdentifier().equals(student.getAdmissionNo())) {
            handleValidationError(student, model);
            result.rejectValue(STUDENT_ID, ERR_TUDENT_ADMISSIONNO_VIOLATE);
            resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff, model);
            return VIEW_GET_STUDENT_DETAIL_PAGE;
        }

        // if check for initial save
        if (student != null && student.getStudentId() != 0) {

            Student stuObDB = studentService.findStudent(student.getStudentId());
            if (stuObDB == null) {
                student.setStudentId(0);
            } else {
                String admissionNoDB = stuObDB.getAdmissionNo();

                if (!admissionNoDB.equals(student.getAdmissionNo())) {
                    if (studentService.isAdmissionNoExist(student.getAdmissionNo())) {
                        handleValidationError(student, model);
                        result.rejectValue(STUDENT_ID, ERR_STUDENT_ADMISSIONNO_DUPLCATE);
                        resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob,
                                selectedCountryCodeEmgRes, selectedCountryCodeEmgMob, selectedCountryCodeEmgOff,
                                model);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    } else {

                        if (!student.getSiblingAdmitionNo().trim().isEmpty()) {
                            if (!studentService.isAdmissionNoExist(student.getSiblingAdmitionNo())
                                    || student.getAdmissionNo().equals(student.getSiblingAdmitionNo())) {
                                result.rejectValue(SIBLING_ADMISSIONNO, ERR_SIBLING_ADMISSIONNO_VIOLATE);
                                resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob,
                                        selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                        selectedCountryCodeEmgOff, model);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }
                        if (!student.getResidenceNo().isEmpty() && !selectedCountryCodeRes.isEmpty()) {
                            if (student.getResidenceNo() != null
                                    && !selectedCountryCodeRes.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(student.getResidenceNo(),
                                            selectedCountryCodeRes)) {
                                displayResidencePhoneNumberDetails(student, selectedCountryCodeRes);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }

                        if (!student.getMobileNo().isEmpty() && !selectedCountryCodeMob.isEmpty()) {
                            if (student.getMobileNo() != null
                                    && !selectedCountryCodeMob.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(student.getMobileNo(),
                                            selectedCountryCodeMob)) {
                                displayMobilePhoneNumberDetails(student, selectedCountryCodeMob);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }

                        if (!student.getEmergencyContactResidenceNo().isEmpty()
                                && !selectedCountryCodeEmgRes.isEmpty()) {
                            if (student.getEmergencyContactResidenceNo() != null
                                    && !selectedCountryCodeEmgRes.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(
                                            student.getEmergencyContactResidenceNo(),
                                            selectedCountryCodeEmgRes)) {
                                displayEmgResidencePhoneNumberDetails(student, selectedCountryCodeEmgRes);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }

                        if (!student.getEmergencyContactMobileNo().isEmpty()
                                && !selectedCountryCodeEmgMob.isEmpty()) {
                            if (student.getEmergencyContactMobileNo() != null
                                    && !selectedCountryCodeEmgMob.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(
                                            student.getEmergencyContactMobileNo(), selectedCountryCodeEmgMob)) {
                                displayEmgMobilePhoneNumberDetails(student, selectedCountryCodeEmgMob);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }

                        if (!student.getEmergencyContactOfficeNo().isEmpty()
                                && !selectedCountryCodeEmgOff.isEmpty()) {
                            if (student.getEmergencyContactOfficeNo() != null
                                    && !selectedCountryCodeEmgOff.equals(AkuraConstant.STRING_ZERO)
                                    && PhoneNumberValidateUtil.isValidPhoneNumber(
                                            student.getEmergencyContactOfficeNo(), selectedCountryCodeEmgOff)) {
                                displayEmgOfficePhoneNumberDetails(student, selectedCountryCodeEmgOff);
                            } else {
                                displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                        selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                                return VIEW_GET_STUDENT_DETAIL_PAGE;
                            }
                        }
                        updateStudent(student);

                        // Update if user login exist for this student
                        UserLogin userLogin = userService
                                .getUserLoginByIdentificationNo(stuObDB.getAdmissionNo());
                        if (userLogin != null) {
                            userLogin.setUserIdentificationNo(student.getAdmissionNo());
                            userService.updateUser(userLogin);
                        }

                        // updated message pass through query string
                        String successUpdate = new ErrorMsgLoader()
                                .getErrorMessage(COMMON_MESSAGE_SUCCESSFULLY_UPDATED);
                        return VIEW_STUDENT_DETAIL + QUERY_STRING_UPDATE + successUpdate;
                    }
                } else {
                    try {
                        if (student.getMPhoto() != null) {
                            MultipartFile multipartFile = student.getMPhoto();
                            if (multipartFile.getSize() > 0) {
                                student.setPhoto(multipartFile.getBytes());
                            }
                        }
                    } catch (IOException e) {

                        LOG.error(ERROR_WHILE_RETRIEVING_FILE + e.toString());
                        throw new AkuraAppException(AkuraConstant.FILE_NOT_FOUND, e);
                    }
                    if (!student.getSiblingAdmitionNo().trim().isEmpty()) {
                        if (!studentService.isAdmissionNoExist(student.getSiblingAdmitionNo())
                                || student.getAdmissionNo().equals(student.getSiblingAdmitionNo())) {
                            result.rejectValue(SIBLING_ADMISSIONNO, ERR_SIBLING_ADMISSIONNO_VIOLATE);
                            returnResult = VIEW_GET_STUDENT_DETAIL_PAGE;
                            resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob,
                                    selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                    selectedCountryCodeEmgOff, model);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getResidenceNo().isEmpty() && !selectedCountryCodeRes.isEmpty()) {
                        if (student.getResidenceNo() != null
                                && !selectedCountryCodeRes.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(student.getResidenceNo(),
                                        selectedCountryCodeRes)) {
                            displayResidencePhoneNumberDetails(student, selectedCountryCodeRes);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getMobileNo().isEmpty() && !selectedCountryCodeMob.isEmpty()) {
                        if (student.getMobileNo() != null
                                && !selectedCountryCodeMob.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(student.getMobileNo(),
                                        selectedCountryCodeMob)) {
                            displayMobilePhoneNumberDetails(student, selectedCountryCodeMob);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getEmergencyContactResidenceNo().isEmpty()
                            && !selectedCountryCodeEmgRes.isEmpty()) {
                        if (student.getEmergencyContactResidenceNo() != null
                                && !selectedCountryCodeEmgRes.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(
                                        student.getEmergencyContactResidenceNo(), selectedCountryCodeEmgRes)) {
                            displayEmgResidencePhoneNumberDetails(student, selectedCountryCodeEmgRes);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getEmergencyContactMobileNo().isEmpty()
                            && !selectedCountryCodeEmgMob.isEmpty()) {
                        if (student.getEmergencyContactMobileNo() != null
                                && !selectedCountryCodeEmgMob.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(
                                        student.getEmergencyContactMobileNo(), selectedCountryCodeEmgMob)) {
                            displayEmgMobilePhoneNumberDetails(student, selectedCountryCodeEmgMob);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }

                    if (!student.getEmergencyContactOfficeNo().isEmpty()
                            && !selectedCountryCodeEmgOff.isEmpty()) {
                        if (student.getEmergencyContactOfficeNo() != null
                                && !selectedCountryCodeEmgOff.equals(AkuraConstant.STRING_ZERO)
                                && PhoneNumberValidateUtil.isValidPhoneNumber(
                                        student.getEmergencyContactOfficeNo(), selectedCountryCodeEmgOff)) {
                            displayEmgOfficePhoneNumberDetails(student, selectedCountryCodeEmgOff);
                        } else {
                            displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                    selectedCountryCodeMob, selectedCountryCodeEmgRes,
                                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff);
                            return VIEW_GET_STUDENT_DETAIL_PAGE;
                        }
                    }
                    updateStudent(student);

                    // updated message pass through query string
                    String successUpdate = new ErrorMsgLoader()
                            .getErrorMessage(COMMON_MESSAGE_SUCCESSFULLY_UPDATED);
                    return VIEW_STUDENT_DETAIL + QUERY_STRING_UPDATE + successUpdate;
                }
            }
        }

        if (student != null && student.getStudentId() == 0) {
            if (studentService.isAdmissionNoExist(student.getAdmissionNo())) {

                model.addAttribute(MODEL_ATT_IMAGE_PATH, RESOURCES_NO_PROFILE_IMAGE);
                result.rejectValue(STUDENT_ID, ERR_STUDENT_ADMISSIONNO_DUPLCATE);
                returnResult = VIEW_GET_STUDENT_DETAIL_PAGE;
                resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                        selectedCountryCodeEmgMob, selectedCountryCodeEmgOff, model);
                return VIEW_GET_STUDENT_DETAIL_PAGE;
            } else {
                if (student.getMPhoto() != null) {
                    try {
                        MultipartFile multipartFile = student.getMPhoto();
                        if (multipartFile.getSize() > 0) {
                            student.setPhoto(multipartFile.getBytes());
                        }
                    } catch (IOException e) {
                        LOG.error(ERROR_WHILE_RETRIEVING_FILE + e.toString());
                        throw new AkuraAppException(AkuraConstant.FILE_NOT_FOUND, e);
                    }
                }
                if (!student.getSiblingAdmitionNo().trim().isEmpty()) {
                    if (!studentService.isAdmissionNoExist(student.getSiblingAdmitionNo())
                            || student.getAdmissionNo().equals(student.getSiblingAdmitionNo())) {
                        result.rejectValue(SIBLING_ADMISSIONNO, ERR_SIBLING_ADMISSIONNO_VIOLATE);
                        returnResult = VIEW_GET_STUDENT_DETAIL_PAGE;
                        resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob,
                                selectedCountryCodeEmgRes, selectedCountryCodeEmgMob, selectedCountryCodeEmgOff,
                                model);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                student.setStatusId(1);

                if (!student.getResidenceNo().isEmpty() && !selectedCountryCodeRes.isEmpty()) {
                    if (student.getResidenceNo() != null
                            && !selectedCountryCodeRes.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(student.getResidenceNo(),
                                    selectedCountryCodeRes)) {
                        displayResidencePhoneNumberDetails(student, selectedCountryCodeRes);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                if (!student.getMobileNo().isEmpty() && !selectedCountryCodeMob.isEmpty()) {
                    if (student.getMobileNo() != null
                            && !selectedCountryCodeMob.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(student.getMobileNo(),
                                    selectedCountryCodeMob)) {
                        displayMobilePhoneNumberDetails(student, selectedCountryCodeMob);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                if (!student.getEmergencyContactResidenceNo().isEmpty()
                        && !selectedCountryCodeEmgRes.isEmpty()) {
                    if (student.getEmergencyContactResidenceNo() != null
                            && !selectedCountryCodeEmgRes.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(
                                    student.getEmergencyContactResidenceNo(), selectedCountryCodeEmgRes)) {
                        displayEmgResidencePhoneNumberDetails(student, selectedCountryCodeEmgRes);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                if (!student.getEmergencyContactMobileNo().isEmpty() && !selectedCountryCodeEmgMob.isEmpty()) {
                    if (student.getEmergencyContactMobileNo() != null
                            && !selectedCountryCodeEmgMob.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(student.getEmergencyContactMobileNo(),
                                    selectedCountryCodeEmgMob)) {
                        displayEmgMobilePhoneNumberDetails(student, selectedCountryCodeEmgMob);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                if (!student.getEmergencyContactOfficeNo().isEmpty() && !selectedCountryCodeEmgOff.isEmpty()) {
                    if (student.getEmergencyContactOfficeNo() != null
                            && !selectedCountryCodeEmgOff.equals(AkuraConstant.STRING_ZERO)
                            && PhoneNumberValidateUtil.isValidPhoneNumber(student.getEmergencyContactOfficeNo(),
                                    selectedCountryCodeEmgOff)) {
                        displayEmgOfficePhoneNumberDetails(student, selectedCountryCodeEmgOff);
                    } else {
                        displayCountryFlagsWhenError(student, model, selectedCountryCodeRes,
                                selectedCountryCodeMob, selectedCountryCodeEmgRes, selectedCountryCodeEmgMob,
                                selectedCountryCodeEmgOff);
                        return VIEW_GET_STUDENT_DETAIL_PAGE;
                    }
                }

                studentService.saveStudent(student);
                if (checkStudentDisabilityFilled(student.getStudentDisability())) {
                    student.getStudentDisability().setStudentId(student.getStudentId());
                    trimStudentDisabilityObj(student.getStudentDisability());
                    studentService.saveStudentDisability(student.getStudentDisability());
                }
                returnResult = VIEW_NEW_STUDENT_DETAIL;
            }
        }
    } catch (AkuraAppException e) {
        if (e.getCause() instanceof TransientDataAccessResourceException) {
            String message = new ErrorMsgLoader().getErrorMessage(IMAGE_DATABASE_SIZE);
            model.addAttribute(ERROR_MESSAGE, message);
            resetCountryFlags(selectedCountryCodeRes, selectedCountryCodeMob, selectedCountryCodeEmgRes,
                    selectedCountryCodeEmgMob, selectedCountryCodeEmgOff, model);
            return returnResult;
        }
    }

    return VIEW_NEW_STUDENT_DETAIL;
}