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:org.openmrs.module.appointmentscheduling.web.controller.AppointmentBlockFormController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(HttpServletRequest request, ModelMap model, AppointmentBlock appointmentBlock,
        BindingResult result, @RequestParam(value = "timeSlotLength", required = false) String timeSlotLength,
        @RequestParam(value = "emptyTypes", required = false) String emptyTypes,
        @RequestParam(value = "redirectedFrom", required = false) String redirectedFrom,
        @RequestParam(value = "action", required = false) String action) throws Exception {

    HttpSession httpSession = request.getSession();

    if (Context.isAuthenticated()) {
        if (emptyTypes.equals("yes")) {
            //need to nullify the appointment types.
            appointmentBlock.setTypes(null);
        }//from w  w w .  j ava2  s .co m
        AppointmentService appointmentService = Context.getService(AppointmentService.class);
        //if the user is voiding the selected appointment block
        if (action != null && action.equals("void")) {
            String voidReason = "Some Reason";//request.getParameter("voidReason");
            if (!(StringUtils.hasText(voidReason))) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "appointmentscheduling.AppointmentBlock.error.voidReasonEmpty");
                return null;
            }
            List<TimeSlot> currentTimeSlots = appointmentService
                    .getTimeSlotsInAppointmentBlock(appointmentBlock);
            List<Appointment> appointments = new ArrayList<Appointment>();
            for (TimeSlot timeSlot : currentTimeSlots) {
                List<Appointment> appointmentsInSlot = appointmentService.getAppointmentsInTimeSlot(timeSlot);
                for (Appointment appointment : appointmentsInSlot) {
                    appointments.add(appointment);
                }
            }
            //set appointments statuses from "Scheduled" to "Cancelled".
            for (Appointment appointment : appointments) {
                if (appointment.getStatus().toString()
                        .equalsIgnoreCase(AppointmentStatus.SCHEDULED.toString())) {
                    appointmentService.changeAppointmentStatus(appointment, AppointmentStatus.CANCELLED);
                }
            }
            //voiding appointment block
            appointmentService.voidAppointmentBlock(appointmentBlock, voidReason);
            //voiding time slots
            for (TimeSlot timeSlot : currentTimeSlots) {
                appointmentService.voidTimeSlot(timeSlot, voidReason);

            }
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "appointmentscheduling.AppointmentBlock.voidedSuccessfully");
        }
        //If the user is purging the AppointmentBlock
        else if (action != null && action.equals("purge")) {
            List<TimeSlot> currentTimeSlots = appointmentService
                    .getTimeSlotsInAppointmentBlock(appointmentBlock);
            //In case there are appointments within the appointment block we don't mind to purge it
            //purging the appointment block
            try {
                //purging the time slots
                for (TimeSlot timeSlot : currentTimeSlots) {
                    appointmentService.purgeTimeSlot(timeSlot);
                }
                appointmentService.purgeAppointmentBlock(appointmentBlock);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "appointmentscheduling.AppointmentBlock.purgedSuccessfully");
            } catch (DataIntegrityViolationException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
            }

        } else if (request.getParameter("save") != null) {
            new AppointmentBlockValidator().validate(appointmentBlock, result);
            if (result.hasErrors()) {
                return null;
            } else {
                //Error checking
                if (appointmentBlock.getStartDate().before(Calendar.getInstance().getTime())) {
                    result.rejectValue("startDate",
                            "appointmentscheduling.AppointmentBlock.error.dateCannotBeInThePast");
                    return null;
                }
                if (!appointmentBlock.getStartDate().before(appointmentBlock.getEndDate())) {
                    result.rejectValue("endDate",
                            "appointmentscheduling.AppointmentBlock.error.InvalidDateInterval");
                    return null;
                }
                if (timeSlotLength.isEmpty() || Integer.parseInt(timeSlotLength) <= 0) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "appointmentscheduling.AppointmentBlock.error.selectTimeSlot");
                    return null;
                }
                long appointmentBlocklengthInMinutes = (appointmentBlock.getEndDate().getTime()
                        - appointmentBlock.getStartDate().getTime()) / 60000;
                if (!timeSlotLength.isEmpty()
                        && (Integer.parseInt(timeSlotLength) > appointmentBlocklengthInMinutes)) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "appointmentscheduling.AppointmentBlock.error.maximalTimeSlot");
                    return null;
                }
                List<TimeSlot> currentTimeSlots = null;
                //if the appointment block is already created and now is being updated
                if (appointmentBlock.getCreator() != null) {
                    boolean canBeUpdated = true;
                    currentTimeSlots = appointmentService.getTimeSlotsInAppointmentBlock(appointmentBlock);
                    for (TimeSlot timeSlot : currentTimeSlots) {
                        if (appointmentService.getAppointmentsInTimeSlot(timeSlot).size() > 0) {
                            canBeUpdated = false;
                            break;
                        }
                    }
                    if (!canBeUpdated) {
                        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                                "appointmentscheduling.AppointmentBlock.error.appointmentsExist");
                        return null;
                    }
                }
                //Check if overlapping appointment blocks exist in the system(We will consider Time And Provider only)
                if (appointmentService.getOverlappingAppointmentBlocks(appointmentBlock).size() > 0) { //Overlapping exists
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "appointmentscheduling.AppointmentBlock.error.appointmentBlockOverlap");
                    return null;
                }
                //First we need to save the appointment block (before creating the time slot)
                appointmentService.saveAppointmentBlock(appointmentBlock);
                //Create the time slots.
                Integer slotLength = Integer.parseInt(timeSlotLength);
                int howManyTimeSlotsToCreate = (int) (appointmentBlocklengthInMinutes / slotLength);
                if (currentTimeSlots == null) {
                    currentTimeSlots = appointmentService.getTimeSlotsInAppointmentBlock(appointmentBlock);
                }
                if (currentTimeSlots.size() != howManyTimeSlotsToCreate) { //the time slot length changed therefore we need to update.
                    //First we will purge the current time slots.
                    for (TimeSlot timeSlot : currentTimeSlots) {
                        appointmentService.purgeTimeSlot(timeSlot);
                    }
                    //Then we will add the new time slots corresponding to the new time slot length 
                    Date startDate = appointmentBlock.getStartDate();
                    Date endDate = null;
                    Calendar cal;
                    //Create the time slots except the last one because it might be larger from the rest.
                    for (int i = 0; i < howManyTimeSlotsToCreate - 1; i++) {
                        cal = Context.getDateTimeFormat().getCalendar();
                        cal.setTime(startDate);
                        cal.add(Calendar.MINUTE, slotLength); // add slotLength minutes
                        endDate = cal.getTime();
                        TimeSlot timeSlot = new TimeSlot(appointmentBlock, startDate, endDate);
                        startDate = endDate;
                        appointmentService.saveTimeSlot(timeSlot);
                    }
                    //Create the last time slot that can be larger than the predefined time slot length.
                    TimeSlot timeSlot = new TimeSlot(appointmentBlock, startDate,
                            appointmentBlock.getEndDate());
                    appointmentService.saveTimeSlot(timeSlot);
                }
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "appointmentscheduling.AppointmentBlock.saved");
            }
        }

        // if the user is unvoiding the AppointmentBlock
        else if (request.getParameter("unvoid") != null) {
            appointmentService.unvoidAppointmentBlock(appointmentBlock);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "appointmentscheduling.AppointmentBlock.unvoidedSuccessfully");
        }

    }
    return "redirect:" + redirectedFrom;
}

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

/**
 * This method used for Editing Tenant Logo
 * //w  w  w  .j  ava 2 s. co  m
 * @param tenantParam
 * @param tenantLogoForm
 * @param result
 * @param map
 * @return String (tenants.editcurrentlogo)
 */
@RequestMapping(value = "/{tenantParam}/editlogo", method = RequestMethod.POST)
public String editTenantLogo(@PathVariable String tenantParam,
        @ModelAttribute("tenantLogoForm") TenantLogoForm tenantLogoForm, BindingResult result, ModelMap map,
        HttpServletRequest httpServletRequest) {
    logger.debug("### edit logo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(httpServletRequest);
    if (fileSize != null) {
        result.reject("error.image.max.upload.size.exceeded", new Object[] { fileSize }, "");
        setPage(map, Page.HOME);
        return "tenants.editcurrentlogo";
    }

    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        Tenant tenant = tenantService.get(tenantParam);
        com.citrix.cpbm.access.Tenant proxyTenant = (com.citrix.cpbm.access.Tenant) CustomProxy
                .newInstance(tenant);
        String relativeImageDir = tenant.getParam();
        TenantLogoFormValidator validator = new TenantLogoFormValidator();
        validator.validate(tenantLogoForm, result);
        if (result.hasErrors()) {
            setPage(map, Page.HOME);
            return "tenants.editcurrentlogo";
        } else {
            MultipartFile logoFile = tenantLogoForm.getLogo();
            MultipartFile faviconFile = tenantLogoForm.getFavicon();
            try {
                if (StringUtils.isNotEmpty(logoFile.getOriginalFilename())) {
                    String logoFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir, relativeImageDir,
                            logoFile);
                    proxyTenant.getObject().setImagePath(logoFileRelativePath);
                }
                if (StringUtils.isNotEmpty(faviconFile.getOriginalFilename())) {
                    String faviconFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir,
                            relativeImageDir, faviconFile);
                    proxyTenant.getObject().setFaviconPath(faviconFileRelativePath);
                }
                tenantService.update(proxyTenant, result);
            } catch (IOException e) {
                logger.debug("###IO Exception in writing custom image file");
            }
        }
        return "redirect:/portal/home";
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        result.rejectValue("favicon", "error.custom.image.upload.dir");
        setPage(map, Page.HOME);
        return "tenants.editcurrentlogo";
    }
}

From source file:com.virtusa.akura.common.controller.ManageSpecialEventsController.java

/**
 * Create or update SpecialEvent details.
 * /*  w  ww .  ja v  a2  s. c o  m*/
 * @param request - HttpServletRequest
 * @param model - ModelMap
 * @param specialEvents - SpecialEvents object
 * @param bindingResult - BindingResult
 * @return name of the view which is redirected to.
 * @throws AkuraAppException - if error occurs when save or update a FaithLifeRating instance.
 */
@RequestMapping(value = "/saveOrUpdateSpecialEvent.htm", method = RequestMethod.POST)
public String saveOrUpdateSpecialEvent(@ModelAttribute(MODEL_ATT_SPECIAL_EVENT) SpecialEvents specialEvents,
        BindingResult bindingResult, HttpServletRequest request, ModelMap model) throws AkuraAppException {

    String[] toList = null;

    if (request.getParameterValues(REQUEST_SELECTED_LIST) != null) {
        toList = request.getParameterValues(REQUEST_SELECTED_LIST);
    }

    // Trim the special event name
    specialEvents.setName(specialEvents.getName().trim());

    specialEventsValidator.validate(specialEvents, bindingResult);

    int intSpecialEventId = specialEvents.getSpecialEventsId();
    String strMessage = null;
    SpecialEvents spEvent;
    String finalToList = null;

    if (bindingResult.hasErrors()) {

        if (specialEvents.getSpecialEventsId() != 0) {
            spEvent = commonService.findSpecialEventsById(specialEvents.getSpecialEventsId());
            model.addAttribute(MODEL_ATT_SELECTED_OBJECT, spEvent);
        }

        errorMassage(model, specialEvents);

        if (request.getParameterValues(REQUEST_SELECTED_LIST) != null) {
            toList = request.getParameterValues(REQUEST_SELECTED_LIST);
            finalToList = this.toListToString(specialEvents, toList);

        }
        model.addAttribute(MODEL_ATT_OBJECT_PARTICIPANT, finalToList);
        model.addAttribute(MODEL_ATT_OBJECT_FORM, specialEvents);
        return VIEW_GET_CREATE_SPECIAL_EVENTS;
    } else {
        if (toList == null) {

            if (specialEvents.getSpecialEventsId() != 0) {
                spEvent = commonService.findSpecialEventsById(specialEvents.getSpecialEventsId());
                model.addAttribute(MODEL_ATT_SELECTED_OBJECT, spEvent);
            }

            errorMassage(model, specialEvents);
            if (request.getParameterValues(REQUEST_SELECTED_LIST) != null) {
                toList = request.getParameterValues(REQUEST_SELECTED_LIST);
                finalToList = this.toListToString(specialEvents, toList);

            }
            model.addAttribute(MODEL_ATT_OBJECT_PARTICIPANT, finalToList);
            strMessage = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.MANDATORY_FIELD_ERROR_CODE);
            model.addAttribute(MODEL_ATT_MESSAGE, strMessage);
            model.addAttribute(MODEL_ATT_OBJECT_FORM, specialEvents);
            return VIEW_GET_CREATE_SPECIAL_EVENTS;

        } else {
            try {

                if (commonService.isExistsSpecialEvents(specialEvents)) {

                    if (intSpecialEventId != 0) {
                        List<String> toListt = new ArrayList<String>();
                        spEvent = commonService.findSpecialEventsById(intSpecialEventId);

                        if (spEvent.getSpecialEventsId() == specialEvents.getSpecialEventsId()
                                && spEvent.getName().equalsIgnoreCase(specialEvents.getName())
                                && (spEvent.getDate().compareTo(specialEvents.getDate())) == 0
                                && spEvent.getParticipantCategory().getParticipantCategoryId() == specialEvents
                                        .getParticipantCategory().getParticipantCategoryId()
                                && spEvent.getDescription().equalsIgnoreCase(specialEvents.getDescription())) {
                            toList = request.getParameterValues(REQUEST_SELECTED_LIST);
                            List<String> toListtt = Arrays.asList(toList);
                            List<SpecialEventsParticipation> participants = commonService
                                    .getParticipantListBySpecialEvent(spEvent);

                            String participantId = null;
                            int partId = 0;
                            for (SpecialEventsParticipation participant : participants) {

                                if (spEvent.getParticipantCategory()
                                        .getParticipantCategoryId() == AkuraConstant.PARAM_INDEX_ONE) {
                                    partId = participant.getClassGrade().getClassGradeId();
                                } else if (spEvent.getParticipantCategory()
                                        .getParticipantCategoryId() == AkuraConstant.PARAM_INDEX_TWO) {
                                    partId = participant.getSportCategory().getSportCategoryId();
                                } else if (spEvent.getParticipantCategory()
                                        .getParticipantCategoryId() == AkuraConstant.PARAM_INDEX_THREE) {
                                    partId = participant.getClubSociety().getClubSocietyId();
                                }
                                participantId = String.valueOf(partId);
                                toListt.add(participantId);
                            }
                            if (toListt.equals(toListtt)) {
                                return VIEW_GET_CREATE_SPECIAL_EVENTS;
                            }
                        }
                        // editing selected object with detail or participation list
                        if (spEvent.getName().equalsIgnoreCase(specialEvents.getName())
                                && (spEvent.getDate().compareTo(specialEvents.getDate())) == 0) {

                            // deleting all specilEvents participation list related to given                             
                            List<SpecialEventsParticipation> participants = commonService
                                    .getParticipantListBySpecialEvent(spEvent);
                            commonService.deleteAllSpecialEventsParticipation(participants);
                            commonService.editSpecialEvents(specialEvents);
                            createSpecialEventsParticipant(toList, spEvent);
                            return VIEW_POST_CREAT_SPECIAL_EVENTS;

                        } else {

                            spEvent = commonService.findSpecialEventsById(specialEvents.getSpecialEventsId());
                            if (request.getParameterValues(REQUEST_SELECTED_LIST) != null) {
                                toList = request.getParameterValues(REQUEST_SELECTED_LIST);
                                finalToList = this.toListToString(specialEvents, toList);

                            }
                            model.addAttribute(MODEL_ATT_OBJECT_PARTICIPANT, finalToList);
                            model.addAttribute(MODEL_ATT_SELECTED_OBJECT, spEvent);
                            model.addAttribute(SHOW_EDIT_SECTION, SHOW_EDIT_SECTION);
                            model.addAttribute(MODEL_ATT_SELECTED_OBJECT_ID, intSpecialEventId);
                            bindingResult.rejectValue("specialEventsId",
                                    AkuraWebConstant.ALREADY_EXIST_ERROR_CODE);
                            return VIEW_GET_CREATE_SPECIAL_EVENTS;
                        }
                    } else {
                        model.addAttribute(MODEL_ATT_SELECTED_OBJECT_ID, intSpecialEventId);
                        errorMassage(model, specialEvents);
                        if (request.getParameterValues(REQUEST_SELECTED_LIST) != null) {
                            toList = request.getParameterValues(REQUEST_SELECTED_LIST);
                            finalToList = this.toListToString(specialEvents, toList);
                        }
                        model.addAttribute(MODEL_ATT_OBJECT_PARTICIPANT, finalToList);
                        model.addAttribute(SHOW_EDIT_SECTION, SHOW_EDIT_SECTION);
                        bindingResult.rejectValue("specialEventsId", AkuraWebConstant.ALREADY_EXIST_ERROR_CODE);
                        return VIEW_GET_CREATE_SPECIAL_EVENTS;
                    }
                } else {

                    if (intSpecialEventId == 0) {
                        spEvent = commonService.addSpecialEvents(specialEvents);
                        createSpecialEventsParticipant(toList, spEvent);

                    } else {
                        spEvent = commonService.findSpecialEventsById(intSpecialEventId);
                        SpecialEvents speEvent = commonService.findSpecialEventsById(intSpecialEventId);
                        // deleting all specilEvents participation list related to given specialEvent
                        List<SpecialEventsParticipation> participants = commonService
                                .getParticipantListBySpecialEvent(speEvent);
                        commonService.deleteAllSpecialEventsParticipation(participants);
                        commonService.editSpecialEvents(specialEvents);
                        createSpecialEventsParticipant(toList, speEvent);
                    }
                }
            } catch (AkuraAppException e) {
                if (e.getCause() instanceof DataIntegrityViolationException) {
                    strMessage = new ErrorMsgLoader().getErrorMessage(REF_UI_SPECIAL_EVENT_EDIT);
                    errorMassage(model, specialEvents);
                    // SpecialEvents newSpecialEvents = new SpecialEvents();
                    if (request.getParameterValues(REQUEST_SELECTED_LIST) != null) {
                        toList = request.getParameterValues(REQUEST_SELECTED_LIST);
                        finalToList = this.toListToString(specialEvents, toList);
                    }
                    model.addAttribute(MODEL_ATT_OBJECT_PARTICIPANT, finalToList);
                    model.addAttribute(MODEL_ATT_SELECTED_OBJECT_ID, intSpecialEventId);
                    model.addAttribute(SHOW_EDIT_SECTION, SHOW_EDIT_SECTION);
                    model.addAttribute(MODEL_ATT_MESSAGE, strMessage);
                    // model.addAttribute("specialEvents", newSpecialEvents);
                    return VIEW_GET_CREATE_SPECIAL_EVENTS;
                } else {
                    throw e;
                }
            }
        }
    }
    return VIEW_POST_CREAT_SPECIAL_EVENTS;
}

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

/**
 * Perform the logic of the controller to Generate Exam Results Report.
 * /* w w w  .j a va2 s. c  o m*/
 * @param response of type HttpServletResponse
 * @param staffProfileReportTemplate - model object
 * @param errors - BindingResult
 * @param request - HttpServletRequest
 * @return modelAndView
 * @param modelMap of type modelMap.
 * @throws AkuraAppException AkuraAppException
 * @throws ParseException ParseException
 */

@RequestMapping(value = STAFF_PROFILE_REPORT_HTM)
public ModelAndView onSubmit(HttpServletResponse response,
        @ModelAttribute(STAFF_PROFILE_REPORT_TEMPLATE) StaffProfileReportTemplate staffProfileReportTemplate,
        BindingResult errors, HttpServletRequest request, ModelMap modelMap)
        throws AkuraAppException, ParseException {

    String redirectURL = STAFF_PROFILE_REPORT_URL;
    Map<String, Object> map = new HashMap<String, Object>();
    String[] toListStr1 = new String[] { "2", String.valueOf(INDEX_THREE), String.valueOf(INDEX_FOUR),
            String.valueOf(INDEX_FIVE), String.valueOf(INDEX_SIX), String.valueOf(INDEX_SEVEN),
            String.valueOf(INDEX_EIGHT), String.valueOf(INDEX_NINE), String.valueOf(INDEX_TEN),
            String.valueOf(INDEX_ELEVEN), String.valueOf(INDEX_TWELVE), String.valueOf(INDEX_THIRTEEN),
            String.valueOf(INDEX_FOURTEEN), String.valueOf(INDEX_FIFTEEN), String.valueOf(INDEX_SIXTEEN),
            String.valueOf(INDEX_SEVENTEEN), String.valueOf(INDEX_EIGHTEEN), String.valueOf(INDEX_NINETEEN),
            String.valueOf(INDEX_TWENTY), String.valueOf(INDEX_TWENTYONE), String.valueOf(INDEX_TWENTYTWO),
            String.valueOf(INDEX_TWENTYTHREE), String.valueOf(INDEX_TWENTYFOUR),
            String.valueOf(INDEX_TWENTYFIVE) };

    String selectedAddmission = request.getParameter(SELECTED_ADDMISSION);
    String selectedStatus = request.getParameter(SELECTED_STATUS);
    String selectedCategory = request.getParameter(SELECTED_CATEGORY);
    String selectedList = null;
    String fromList = null;
    StaffCategory staffCategory = staffCommonService.getStaffCategory(Integer.parseInt(selectedCategory));

    String flag = request.getParameter(REQ_FLAG);
    boolean booleanFlag = Boolean.parseBoolean(flag);
    if (!booleanFlag) {
        toListStr1 = request.getParameterValues(REQUEST_TO_LIST);
        selectedList = (String) request.getParameter(SELECTED_ARRAY);
        fromList = (String) request.getParameter(REMOVED_FROM_ARRAY);
    }
    map.put(DEPARTURE_DATE_KEY, AkuraWebConstant.EMPTY_STRING);
    if (selectedCategory != null) {
        if (selectedCategory.equals(AkuraConstant.STRING_ZERO)) {
            String message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_MANDATORY_FIELD_REQUIRED);
            modelMap.addAttribute(MESSAGE, message);
            modelMap.addAttribute(MODEL_ATT_SELECTED_STATUS, selectedStatus);
            redirectURL = REPORTING_STAFF_PROFILE_REPORT_VIEW;
            return new ModelAndView(redirectURL, map);
        }
    }
    if (selectedStatus != null) {
        if (selectedStatus.equals(AkuraConstant.STRING_ZERO)) {

            String message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_MANDATORY_FIELD_REQUIRED);
            modelMap.addAttribute(MESSAGE, message);
            if (staffCategory != null) {
                modelMap.addAttribute(MODEL_ATT_SELECTED_STAFF_CATEGORY_ID, staffCategory.getCatogaryID());
            } else {
                modelMap.addAttribute(MODEL_ATT_SELECTED_STAFF_CATEGORY_ID, 0);
            }
            modelMap.addAttribute(MODEL_ATT_SELECTED_ADDMISSION_NO, selectedAddmission);
            modelMap.addAttribute(MODEL_ATT_SELECTED_STATUS, selectedStatus);
            modelMap.addAttribute(SELECTED_TO_LIST, selectedList);
            modelMap.addAttribute(REMOVED_FROM_ARRAY, fromList);
            if (toListStr1 == null) {
                redirectURL = showReportForm(modelMap, staffCategory);
            } else {
                redirectURL = REPORTING_STAFF_PROFILE_REPORT_VIEW;
            }
            return new ModelAndView(redirectURL, map);
        }
    }
    if (selectedAddmission != null) {
        staffProfileReportTemplate.setStaffRegNo(selectedAddmission);
    } else {
        if (staffCategory != null) {
            modelMap.addAttribute(MODEL_ATT_SELECTED_STAFF_CATEGORY_ID, staffCategory.getCatogaryID());
        }
        modelMap.addAttribute(MODEL_ATT_SELECTED_STATUS, selectedStatus);
        modelMap.addAttribute(SELECTED_TO_LIST, selectedList);
        modelMap.addAttribute(REMOVED_FROM_ARRAY, fromList);
        if (toListStr1 == null) {
            redirectURL = showReportForm(modelMap, staffCategory);
        } else {
            redirectURL = REPORTING_STAFF_PROFILE_REPORT_VIEW;
        }
        return new ModelAndView(redirectURL, map);
    }
    staffProfileReportValidator.validate(staffProfileReportTemplate, errors);
    if (errors.hasErrors()) {
        if (staffCategory != null) {
            modelMap.addAttribute(MODEL_ATT_SELECTED_STAFF_CATEGORY_ID, staffCategory.getCatogaryID());
        }
        modelMap.addAttribute(MODEL_ATT_SELECTED_ADDMISSION_NO, selectedAddmission);
        modelMap.addAttribute(MODEL_ATT_SELECTED_STATUS, selectedStatus);
        modelMap.addAttribute(SELECTED_TO_LIST, selectedList);
        modelMap.addAttribute(REMOVED_FROM_ARRAY, fromList);
        if (toListStr1 == null) {
            redirectURL = showReportForm(modelMap, staffCategory);
        } else {
            redirectURL = REPORTING_STAFF_PROFILE_REPORT_VIEW;
        }

        return new ModelAndView(redirectURL, map);

    } else {
        String staffRegNo = staffProfileReportTemplate.getStaffRegNo().trim();
        if (selectedAddmission.equals(AkuraConstant.STRING_ZERO)) {
            String message = new ErrorMsgLoader().getErrorMessage(ERROR_MSG_MANDATORY_FIELD_REQUIRED);
            modelMap.addAttribute(MESSAGE, message);

            if (staffCategory != null) {
                modelMap.addAttribute(MODEL_ATT_SELECTED_STAFF_CATEGORY_ID, staffCategory.getCatogaryID());
            } else {
                modelMap.addAttribute(MODEL_ATT_SELECTED_STAFF_CATEGORY_ID, 0);
            }

            modelMap.addAttribute(MODEL_ATT_SELECTED_STATUS, selectedStatus);
            modelMap.addAttribute(SELECTED_TO_LIST, selectedList);
            modelMap.addAttribute(REMOVED_FROM_ARRAY, fromList);
            if (toListStr1 == null) {
                redirectURL = showReportForm(modelMap, staffCategory);
            } else {
                redirectURL = REPORTING_STAFF_PROFILE_REPORT_VIEW;
            }
            return new ModelAndView(redirectURL, map);
        }
        if (staffService.isValidRegistrationNo(staffRegNo)) {

            int staffId = staffService.findStaffIdForRegistrationNo(staffRegNo);

            Staff staff = staffService.findStaff(staffId);

            String year = AkuraWebConstant.EMPTY_STRING;
            if (staff != null && staff.getDateOfDeparture() != null) {
                year = DateUtil.getStringYear(staff.getDateOfDeparture());
            }

            if (year != AkuraWebConstant.EMPTY_STRING) {
                Date departureDateObj = staff.getDateOfDeparture();
                map.put(DEPARTURE_DATE_KEY,
                        PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, DATE_DEPARTURE_FIELD_KEY));
                map.put(DEPARTURE_DATE_VALUE, DateUtil.getFormatDate(departureDateObj));

            } else {
                map.put(DEPARTURE_DATE_VALUE, AkuraWebConstant.SPACE);
            }

            List<StaffProfileReportTemplate> staffProfileList = staffService
                    .getStaffProfileTemplateByStaffId(staffId);

            if (staffProfileList != null && !staffProfileList.isEmpty()) {
                generateReport(map, staff, staffProfileList, toListStr1);
            }
        } else {
            errors.rejectValue(STAFF_REG_NO, STAFF_REGISTRATON_NOT_EXISTS_MSG);
            redirectURL = REPORTING_STAFF_PROFILE_REPORT_VIEW;
        }
    }
    return new ModelAndView(redirectURL, map);
}

From source file:com.jd.survey.web.security.AccountController.java

/**
 * Updates logged in user information/*from   w  ww .  j  a va2s  . com*/
 * @param proceed
 * @param user
 * @param bindingResult
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_SURVEY_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed, @Valid User user,
        BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");
    try {
        User loggedInUser = userService.user_findByLogin(principal.getName());
        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                uiModel.addAttribute("user", user);
                return "account/update";
            }
            if (userService.user_findByLogin(user.getLogin()) != null
                    && userService.user_ValidateLoginIsUnique(user) == true) {
                bindingResult.rejectValue("login", "field_unique");
                uiModel.addAttribute("user", user);
                return "account/update";
            }
            if (userService.user_findByEmail(user.getEmail()) != null
                    && userService.user_ValidateEmailIsUnique(user) == true) {
                bindingResult.rejectValue("email", "field_unique");
                uiModel.addAttribute("user", user);
                return "account/update";
            }
            uiModel.asMap().clear();
            user = userService.user_updateInformation(user);
            return "redirect:/account/show";

        } else {
            return "redirect:/account/show";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.security.AuthorityController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(@Valid Authority authority, BindingResult bindingResult, Principal principal,
        Model uiModel, HttpServletRequest httpServletRequest) {
    log.info("create(): handles " + RequestMethod.POST.toString());
    try {/*  w  ww . j a va2 s  .  c o  m*/
        User user = userService.user_findByLogin(principal.getName());
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, authority, user);
            return "security/authorities/create";
        }
        if (!userService.authority_ValidateNameIsUnique(authority)) {
            bindingResult.rejectValue("name", "field_unique");
            populateEditForm(uiModel, authority, user);
            return "security/authorities/create";
        }

        uiModel.asMap().clear();
        authority = userService.authority_merge(authority);
        return "redirect:/security/authorities/"
                + encodeUrlPathSegment(authority.getId().toString(), httpServletRequest);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}

From source file:com.jd.survey.web.security.AuthorityController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid Authority authority, BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");
    try {//  w  ww .j  a va  2 s.c  o m
        User user = userService.user_findByLogin(principal.getName());
        if (proceed != null) {
            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, authority, user);
                return "authorities/update";
            }
            if (!userService.authority_ValidateNameIsUnique(authority)) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, authority, user);
                return "security/authorities/create";
            }
            uiModel.asMap().clear();
            authority = userService.authority_merge(authority);
            log.info("redirecting to: " + "redirect:/security/authorities/"
                    + encodeUrlPathSegment(authority.getId().toString(), httpServletRequest));
            return "redirect:/security/authorities/"
                    + encodeUrlPathSegment(authority.getId().toString(), httpServletRequest);

        } else {
            return "redirect:/security/authorities";
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.security.DepartmentController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String createPost(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid Department department, BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {/* w  w w . j av a2s.  com*/
        User user = userService.user_findByLogin(principal.getName());

        if (proceed != null) {

            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, department, user);
                return "security/departments/create";
            }
            if (surveySettingsService.department_findByName(department.getName()) != null) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, department, user);
                return "security/departments/create";
            }
            uiModel.asMap().clear();
            department = surveySettingsService.department_merge(department);
            return "redirect:/security/departments/"
                    + encodeUrlPathSegment(department.getId().toString(), httpServletRequest);
        } else {

            return "redirect:/security/departments?page=1&size=10";

        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}

From source file:com.jd.survey.web.security.DepartmentController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(method = RequestMethod.PUT, produces = "text/html")
public String update(@RequestParam(value = "_proceed", required = false) String proceed,
        @Valid Department department, BindingResult bindingResult, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("update(): handles PUT");
    try {/*from   w ww  .j  a  va  2  s  .co  m*/
        User user = userService.user_findByLogin(principal.getName());
        if (proceed != null) {

            if (bindingResult.hasErrors()) {
                populateEditForm(uiModel, department, user);
                return "security/departments/update";
            }
            if (surveySettingsService.department_findByName(department.getName()) != null
                    && !surveySettingsService.department_findByName(department.getName()).getId()
                            .equals(department.getId())) {
                bindingResult.rejectValue("name", "field_unique");
                populateEditForm(uiModel, department, user);
                return "security/departments/update";
            }
            uiModel.asMap().clear();
            department = surveySettingsService.department_merge(department);
            return "redirect:/security/departments/"
                    + encodeUrlPathSegment(department.getId().toString(), httpServletRequest);

        } else {

            return "redirect:/security/departments?page=1&size=10";

        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}