Example usage for org.springframework.dao DataIntegrityViolationException getLocalizedMessage

List of usage examples for org.springframework.dao DataIntegrityViolationException getLocalizedMessage

Introduction

In this page you can find the example usage for org.springframework.dao DataIntegrityViolationException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.openmrs.web.controller.encounter.EncounterRoleFormController.java

private void purgeEncounterRole(HttpSession session, EncounterRole encounterRole, EncounterService service) {
    try {//from  w w  w  . ja  v a  2s . com
        service.purgeEncounterRole(encounterRole);
        session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "EncounterRole.purgedSuccessfully");
    } catch (DataIntegrityViolationException e) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
    } catch (APIException e) {
        session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.general: " + e.getLocalizedMessage());
    }
}

From source file:org.openmrs.web.controller.hl7.HL7SourceFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//ww w .j ava 2  s  .c  o  m
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (Context.isAuthenticated()) {
        HL7Source hl7Source = (HL7Source) obj;
        HL7Service hs = Context.getHL7Service();

        if (request.getParameter("save") != null) {
            hs.saveHL7Source(hl7Source);
            view = getSuccessView();
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "HL7Source.saved");
        }

        // if the user is retiring out the HL7Source
        //not implemented yet

        // if the user is purging the HL7Source
        else if (request.getParameter("purge") != null) {

            try {
                hs.purgeHL7Source(hl7Source);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "HL7Source.purgedSuccessfully");
                view = getSuccessView();
            } catch (DataIntegrityViolationException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
                view = "hl7Source.form?hl7SourceId=" + hl7Source.getHL7SourceId();
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
                view = "hl7Source.form?hl7SourceId=" + hl7Source.getHL7SourceId();
            }
        }

    }

    return new ModelAndView(new RedirectView(view));
}

From source file:org.openmrs.web.controller.person.RelationshipTypeFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db/*from  w  w  w.j av a2  s  . co m*/
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (Context.isAuthenticated()) {
        RelationshipType relationshipType = (RelationshipType) obj;
        PersonService ps = Context.getPersonService();

        //to save the relationship type
        if (request.getParameter("save") != null) {
            ps.saveRelationshipType(relationshipType);
            view = getSuccessView();
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "RelationshipType.saved");
        }

        // if the user is retiring out the relationshipType
        else if (request.getParameter("retire") != null) {
            String retireReason = request.getParameter("retireReason");
            if (relationshipType.getRelationshipTypeId() != null && !(StringUtils.hasText(retireReason))) {
                errors.reject("retireReason", "general.retiredReason.empty");
                return showForm(request, response, errors);
            }

            ps.retireRelationshipType(relationshipType, retireReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "RelationshipType.retiredSuccessfully");

            view = getSuccessView();
        }

        // if the user is purging the relationshipType
        else if (request.getParameter("purge") != null) {
            try {
                ps.purgeRelationshipType(relationshipType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "RelationshipType.purgedSuccessfully");
                view = getSuccessView();
            } catch (DataIntegrityViolationException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
                return showForm(request, response, errors);
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
                return showForm(request, response, errors);
            }
        }
        // if the user unretiring relationship type
        else if (request.getParameter("unretire") != null) {
            ps.unretireRelationshipType(relationshipType);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "RelationshipType.unretiredSuccessfully");
            view = getSuccessView();
        }

    }

    return new ModelAndView(new RedirectView(view));
}

From source file:org.openmrs.web.controller.visit.VisitTypeFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//from w ww.j ava  2 s . co m
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (Context.isAuthenticated()) {
        VisitType visitType = (VisitType) obj;
        VisitService es = Context.getVisitService();

        if (request.getParameter("save") != null) {
            es.saveVisitType(visitType);
            view = getSuccessView();
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "VisitType.saved");
        }

        // if the user is retiring out the VisitType
        else if (request.getParameter("retire") != null) {
            String retireReason = request.getParameter("retireReason");
            if (visitType.getVisitTypeId() != null && !(StringUtils.hasText(retireReason))) {
                errors.reject("retireReason", "general.retiredReason.empty");
                return showForm(request, response, errors);
            }

            es.retireVisitType(visitType, retireReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "VisitType.retiredSuccessfully");

            view = getSuccessView();
        }

        // if the user is unretiring the VisitType
        else if (request.getParameter("unretire") != null) {
            es.unretireVisitType(visitType);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "VisitType.unretiredSuccessfully");
            view = getSuccessView();
        }

        // if the user is purging the visitType
        else if (request.getParameter("purge") != null) {

            try {
                es.purgeVisitType(visitType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "VisitType.purgedSuccessfully");
                view = getSuccessView();
            } catch (DataIntegrityViolationException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
                view = "visitType.form?visitTypeId=" + visitType.getVisitTypeId();
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
                view = "visitType.form?visitTypeId=" + visitType.getVisitTypeId();
            }
        }

    }

    return new ModelAndView(new RedirectView(view));
}

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

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(HttpServletRequest request, AppointmentType appointmentType, BindingResult result)
        throws Exception {

    HttpSession httpSession = request.getSession();

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

        if (request.getParameter("save") != null) {
            new AppointmentTypeValidator().validate(appointmentType, result);
            if (result.hasErrors()) {
                return null;
            } else {
                appointmentService.saveAppointmentType(appointmentType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "appointmentscheduling.AppointmentType.saved");
            }/*www.  j a  va  2 s .com*/
        }

        // if the user is retiring out the AppointmentType
        else if (request.getParameter("retire") != null) {
            String retireReason = request.getParameter("retireReason");
            if (appointmentType.getAppointmentTypeId() != null && !(StringUtils.hasText(retireReason))) {
                result.reject("retireReason", "general.retiredReason.empty");
                return null;
            }

            appointmentService.retireAppointmentType(appointmentType, retireReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "appointmentscheduling.AppointmentType.retiredSuccessfully");
        }

        // if the user is unretiring the AppointmentType
        else if (request.getParameter("unretire") != null) {
            appointmentService.unretireAppointmentType(appointmentType);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "appointmentscheduling.AppointmentType.unretiredSuccessfully");
        }

        // if the user is purging the appointmentType
        else if (request.getParameter("purge") != null) {

            try {
                appointmentService.purgeAppointmentType(appointmentType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "appointmentscheduling.AppointmentType.purgedSuccessfully");
            } catch (DataIntegrityViolationException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
                //view = "appointmentType.form?appointmentTypeId=" + appointmentType.getAppointmentTypeId();
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
                //view = "appointmentType.form?appointmentTypeId=" + appointmentType.getAppointmentTypeId();
            }
        }

    }

    return "redirect:appointmentTypeList.list";
}

From source file:org.openmrs.web.controller.visit.VisitAttributeTypeFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//from w  ww  .j a  v a  2 s .c  om
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (Context.isAuthenticated()) {
        VisitAttributeType visitAttributeType = (VisitAttributeType) obj;
        VisitService visitService = Context.getVisitService();

        if (request.getParameter("save") != null) {
            visitService.saveVisitAttributeType(visitAttributeType);
            view = getSuccessView();
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "VisitAttributeType.saved");
        }

        // if the user is retiring out the VisitAttributeType
        else if (request.getParameter("retire") != null) {
            String retireReason = request.getParameter("retireReason");
            if (visitAttributeType.getVisitAttributeTypeId() != null && !(StringUtils.hasText(retireReason))) {
                errors.reject("retireReason", "general.retiredReason.empty");
                return showForm(request, response, errors);
            }

            visitService.retireVisitAttributeType(visitAttributeType, retireReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "VisitAttributeType.retiredSuccessfully");

            view = getSuccessView();
        }

        // if the user is purging the visitAttributeType
        else if (request.getParameter("purge") != null) {

            try {
                visitService.purgeVisitAttributeType(visitAttributeType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "VisitAttributeType.purgedSuccessfully");
                view = getSuccessView();
            } catch (DataIntegrityViolationException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
                view = "visitAttributeType.form?visitAttributeTypeId="
                        + visitAttributeType.getVisitAttributeTypeId();
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
                view = "visitAttributeType.form?visitAttributeTypeId="
                        + visitAttributeType.getVisitAttributeTypeId();
            }
        } else if (request.getParameter("unretire") != null) {
            try {
                visitService.unretireVisitAttributeType(visitAttributeType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "VisitAttributeType.unretiredSuccessfully");
                view = getSuccessView();
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
                view = "visitAttributeType.form?visitAttributeTypeId="
                        + visitAttributeType.getVisitAttributeTypeId();
            }
        }
    }

    return new ModelAndView(new RedirectView(view));
}

From source file:org.openmrs.web.controller.provider.ProviderAttributeTypeFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//from w w  w.j  a  va  2  s.  c  om
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (Context.isAuthenticated()) {
        ProviderAttributeType providerAttributeType = (ProviderAttributeType) obj;
        ProviderService providerService = Context.getProviderService();

        if (request.getParameter("save") != null) {
            providerService.saveProviderAttributeType(providerAttributeType);
            view = getSuccessView();
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "ProviderAttributeType.saved");
        }

        // if the user is retiring out the ProviderAttributeType
        else if (request.getParameter("retire") != null) {
            String retireReason = request.getParameter("retireReason");
            if (providerAttributeType.getProviderAttributeTypeId() != null
                    && !(StringUtils.hasText(retireReason))) {
                errors.reject("retireReason", "general.retiredReason.empty");
                return showForm(request, response, errors);
            }

            providerService.retireProviderAttributeType(providerAttributeType, retireReason);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "ProviderAttributeType.retiredSuccessfully");

            view = getSuccessView();
        }

        // if the user is purging the providerAttributeType
        else if (request.getParameter("purge") != null) {

            try {
                providerService.purgeProviderAttributeType(providerAttributeType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "ProviderAttributeType.purgedSuccessfully");
                view = getSuccessView();
            } catch (DataIntegrityViolationException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "error.object.inuse.cannot.purge");
                view = "providerAttributeType.form?providerAttributeTypeId="
                        + providerAttributeType.getProviderAttributeTypeId();
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
                view = "providerAttributeType.form?providerAttributeTypeId="
                        + providerAttributeType.getProviderAttributeTypeId();
            }
        } else if (request.getParameter("unretire") != null) {
            try {
                providerService.unretireProviderAttributeType(providerAttributeType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "ProviderAttributeType.unretiredSuccessfully");
                view = getSuccessView();
            } catch (APIException e) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                        "error.general: " + e.getLocalizedMessage());
                view = "providerAttributeType.form?providerAttributeTypeId="
                        + providerAttributeType.getProviderAttributeTypeId();
            }
        }
    }

    return new ModelAndView(new RedirectView(view));
}

From source file:org.openmrs.web.controller.encounter.EncounterTypeFormController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db/*ww  w . j a  v a  2 s.  com*/
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (Context.isAuthenticated()) {
        EncounterType encounterType = (EncounterType) obj;
        EncounterService es = Context.getEncounterService();

        try {
            if (request.getParameter("save") != null) {
                es.saveEncounterType(encounterType);
                view = getSuccessView();
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "EncounterType.saved");
            }

            // if the user is retiring out the EncounterType
            else if (request.getParameter("retire") != null) {
                String retireReason = request.getParameter("retireReason");
                if (encounterType.getEncounterTypeId() != null && !(StringUtils.hasText(retireReason))) {
                    errors.reject("retireReason", "general.retiredReason.empty");
                    return showForm(request, response, errors);
                }
                es.retireEncounterType(encounterType, retireReason);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "EncounterType.retiredSuccessfully");

                view = getSuccessView();
            }

            // if the user is unretiring the EncounterType
            else if (request.getParameter("unretire") != null) {
                es.unretireEncounterType(encounterType);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "EncounterType.unretiredSuccessfully");

                view = getSuccessView();
            }

            // if the user is purging the encounterType
            else if (request.getParameter("purge") != null) {

                try {
                    es.purgeEncounterType(encounterType);
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "EncounterType.purgedSuccessfully");
                    view = getSuccessView();
                } catch (DataIntegrityViolationException e) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "error.object.inuse.cannot.purge");
                    view = "encounterType.form?encounterTypeId=" + encounterType.getEncounterTypeId();
                } catch (APIException e) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "error.general: " + e.getLocalizedMessage());
                    view = "encounterType.form?encounterTypeId=" + encounterType.getEncounterTypeId();
                }
            }
        } catch (EncounterTypeLockedException e) {
            log.error(
                    "tried to save, retire, unretire or delete encounter type while encounter types were locked",
                    e);
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "EncounterType.encounterTypes.locked");
            if (encounterType.getEncounterTypeId() != null) {
                view = "encounterType.form?encounterTypeId=" + encounterType.getEncounterTypeId();
            }
        }
    }

    return new ModelAndView(new RedirectView(view));
}

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

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(HttpServletRequest request, ModelMap model,
        @RequestParam(value = "fromDate", required = false) Date fromDate,
        @RequestParam(value = "toDate", required = false) Date toDate,
        @RequestParam(value = "locationId", required = false) Location location,
        @RequestParam(value = "chosenType", required = false) Integer appointmentTypeId,
        @RequestParam(value = "chosenProvider", required = false) Integer providerId,
        @RequestParam(value = "appointmentBlockId", required = false) Integer appointmentBlockId,
        @RequestParam(value = "action", required = false) String action) throws Exception {
    AppointmentBlock appointmentBlock = null;
    if (Context.isAuthenticated()) {
        HttpSession httpSession = request.getSession();
        if (!fromDate.before(toDate)) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    "appointmentscheduling.AppointmentBlock.error.InvalidDateInterval");
        }//from  w  w  w . ja  v  a2s  . co  m
        // save details from the appointment block list page using http session
        httpSession.setAttribute("chosenLocation", location);
        httpSession.setAttribute("fromDate", Context.getDateTimeFormat().format(fromDate).toString());
        httpSession.setAttribute("toDate", Context.getDateTimeFormat().format(toDate).toString());
        httpSession.setAttribute("lastLocale", Context.getLocale());
        httpSession.setAttribute("chosenProvider", providerId);
        httpSession.setAttribute("chosenType", appointmentTypeId);
        AppointmentService appointmentService = Context.getService(AppointmentService.class);
        //if the user is adding a new AppointmentBlock
        if (request.getParameter("add") != null) {
            return "redirect:appointmentBlockForm.form" + "?redirectedFrom=appointmentBlockList.list";
        }
        //if the user is editing an existing AppointmentBlock
        else if (request.getParameter("edit") != null) {
            if (appointmentBlockId != null) {
                return "redirect:appointmentBlockForm.form?appointmentBlockId=" + appointmentBlockId
                        + "&redirectedFrom=appointmentBlockList.list";
            } else {
                //In case appointment block was not selected
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                        "appointmentscheduling.AppointmentBlock.error.selectAppointmentBlock");
                return null;
            }
        }
        //if the user is changing to calendar view
        else if (action != null && action.equals("changeToCalendarView")) {
            return "redirect:appointmentBlockCalendar.list";
        }
        //in case appointment block was not selected
        else if (appointmentBlockId == null) {
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "appointmentscheduling.AppointmentBlock.error.selectAppointmentBlock");
            return null;
        } else { //retrieve the selected appointment block from the data base
            appointmentBlock = appointmentService.getAppointmentBlock(appointmentBlockId);

        }
        //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");

            return "redirect:appointmentBlockList.list";
        }
        //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());
            }
            return "redirect:appointmentBlockList.list";

        }

        // if the user is unvoiding the AppointmentBlock
        else if (request.getParameter("unvoid") != null) {
            List<TimeSlot> currentTimeSlots = appointmentService
                    .getTimeSlotsInAppointmentBlock(appointmentBlock);
            List<Appointment> appointmentsThatShouldBeUnvoided = new ArrayList<Appointment>();
            for (TimeSlot timeSlot : currentTimeSlots) {
                List<Appointment> currentAppointments = appointmentService.getAppointmentsInTimeSlot(timeSlot);
                for (Appointment appointment : currentAppointments) {
                    if (!appointmentsThatShouldBeUnvoided.contains(appointment))
                        appointmentsThatShouldBeUnvoided.add(appointment);
                }
            }
            //unvoiding the appointment block
            appointmentService.unvoidAppointmentBlock(appointmentBlock);
            //unvoiding the appointments
            for (Appointment appointment : appointmentsThatShouldBeUnvoided) {
                appointmentService.unvoidAppointment(appointment);
            }
            //unvoiding the time slots
            for (TimeSlot timeSlot : currentTimeSlots) {
                appointmentService.unvoidTimeSlot(timeSlot);
            }

            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                    "appointmentscheduling.AppointmentBlock.unvoidedSuccessfully");

            return "redirect:appointmentBlockList.list";
        }
    } // Context authentication.
    return null;
}

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   ww  w . j a v  a  2s  . c om*/
        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;
}