List of usage examples for java.util Date before
public boolean before(Date when)
From source file:com.manydesigns.portofino.pageactions.crud.CrudAction4ItsProject.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public void processExpired(Object row) { Map rowMap = (HashMap) row; Date t_time = (Date) rowMap.get("c_warranty_end"); if (null != t_time) { rowMap.put("c_is_expired", t_time.before(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH))); }/* w w w.jav a2 s.c o m*/ }
From source file:com.sun.identity.security.cert.AMCRLStore.java
private boolean needCRLUpdate(X509CRL crl) { Date nextCRLUpdate = null; if (crl == null) { return true; }//from ww w. j a v a 2s . c o m // Check CRLNextUpdate in CRL nextCRLUpdate = crl.getNextUpdate(); if (debug.messageEnabled()) { debug.message("AMCRLStore.needCRLUpdate: nextCrlUpdate = " + nextCRLUpdate); } return ((nextCRLUpdate != null) && nextCRLUpdate.before(new Date())); }
From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.checkout.SingleStepCheckoutController.java
/** * Util method to copy values from place order form to TriggerData for replenishment * /*from w ww . ja v a2 s. com*/ * @param placeOrderForm * @param triggerData * @throws ParseException */ protected void populateTriggerDataFromPlaceOrderForm(final PlaceOrderForm placeOrderForm, final TriggerData triggerData) throws ParseException { final Date replenishmentStartDate = placeOrderForm.getReplenishmentStartDate(); final Calendar calendar = Calendar.getInstance(getI18nService().getCurrentTimeZone(), getI18nService().getCurrentLocale()); triggerData.setActivationTime( (replenishmentStartDate.before(calendar.getTime()) ? calendar.getTime() : replenishmentStartDate)); final B2BReplenishmentRecurrenceEnum recurrenceValue = placeOrderForm.getReplenishmentRecurrence(); if (B2BReplenishmentRecurrenceEnum.DAILY.equals(recurrenceValue)) { triggerData.setDay(Integer.valueOf(placeOrderForm.getnDays())); triggerData.setRelative(Boolean.TRUE); } else if (B2BReplenishmentRecurrenceEnum.WEEKLY.equals(recurrenceValue)) { triggerData.setDaysOfWeek(placeOrderForm.getnDaysOfWeek()); triggerData.setWeekInterval(Integer.valueOf(placeOrderForm.getnWeeks())); triggerData.setHour(Integer.valueOf(0)); triggerData.setMinute(Integer.valueOf(0)); } else if (B2BReplenishmentRecurrenceEnum.MONTHLY.equals(recurrenceValue)) { triggerData.setDay(Integer.valueOf(placeOrderForm.getNthDayOfMonth())); triggerData.setRelative(Boolean.FALSE); } }
From source file:Controller.UserController.java
@RequestMapping(value = "/Book") public String book(HttpServletRequest request) { boolean errorFlag = false; boolean loginFlag = false; if (request.getAttribute("message") != null) { errorFlag = true;// www . j a v a2 s . c o m } if (request.getAttribute("login") != null) { loginFlag = true; } HttpSession session = request.getSession(); String url = "redirect:/Common"; if (request.getParameter("language") != null) { url = "redirect:/Common" + "?language=" + request.getParameter("language"); } String selectedDate = ""; SimpleDateFormat fortmatMMddyyyy = new SimpleDateFormat("MM/dd/yyyy"); try { if (errorFlag || loginFlag) { selectedDate = (request.getAttribute("selectedDate").toString()); } else { selectedDate = request.getParameter("selectedDate"); } Date chosenDate = fortmatMMddyyyy.parse(selectedDate); Date toDay = new Date(); if (chosenDate.before(toDay)) { selectedDate = fortmatMMddyyyy.format(toDay); } int numberOfAdults, numberOfChilds, packageID; try { if (errorFlag || loginFlag) { numberOfAdults = Integer.parseInt(request.getAttribute("numberOfAdults").toString()); } else { numberOfAdults = Integer.parseInt(request.getParameter("numberOfAdults")); } } catch (NumberFormatException e) { numberOfAdults = 1; } try { if (errorFlag || loginFlag) { numberOfChilds = Integer.parseInt(request.getAttribute("numberOfChilds").toString()); } else { numberOfChilds = Integer.parseInt(request.getParameter("numberOfChilds")); } } catch (NumberFormatException e) { numberOfChilds = 1; } try { if (errorFlag || loginFlag) { packageID = Integer.parseInt(request.getAttribute("packageID").toString()); } else { packageID = Integer.parseInt(request.getParameter("packageID")); } } catch (NumberFormatException e) { packageID = 0; } if (packageID > 0 && numberOfAdults > 0) { PackageDTO packgeDTO = tripperService.getPackageForPayment(packageID); List<Double> prices = tripperService.getPriceOfSelectedDate(selectedDate, packgeDTO); if (prices.get(0) > 0) { if (prices.get(1) <= 0 || (prices.get(1) > 0 && numberOfChilds > 0)) { request.setAttribute("selectedDate", selectedDate); request.setAttribute("numberOfAdults", numberOfAdults); request.setAttribute("numberOfChilds", numberOfChilds); request.setAttribute("priceForAdult", prices.get(0)); request.setAttribute("priceForChild", prices.get(1)); request.setAttribute("packageDTO", packgeDTO); if (request.getAttribute("message") != null) { request.setAttribute("message", request.getAttribute("message")); } url = "/tripper/payment"; } } } return url; } catch (Exception e) { String content = "Function: UserController - book\n" + "***Input***\n" + "message: " + request.getParameter("message") + " || " + request.getAttribute("message") + "\n" + "selectedDate: " + request.getParameter("selectedDate") + " || " + request.getAttribute("selectedDate") + "\n" + "numberOfAdults: " + request.getParameter("numberOfAdults") + " || " + request.getAttribute("numberOfAdults") + "\n" + "numberOfChilds: " + request.getParameter("numberOfChilds") + " || " + request.getAttribute("numberOfChilds") + "\n" + "packageID: " + request.getParameter("packageID") + " || " + request.getAttribute("packageID") + "\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********"; request.setAttribute("errorID", session.getId()); request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e)); return "forward:/Common/Error"; } }
From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.AccountPageController.java
@RequestMapping(value = "/quote/quoteOrderDecision") @RequireHardLogIn/* ww w . j av a2 s .c o m*/ public String quoteOrderDecision(@ModelAttribute("quoteOrderDecisionForm") final QuoteOrderForm quoteOrderForm, final Model model, final RedirectAttributes redirectModel) throws CMSItemNotFoundException { storeCmsPageInModel(model, getContentPageForLabelOrId(MY_QUOTES_CMS_PAGE)); setUpMetaDataForContentPage(model, getContentPageForLabelOrId(MY_QUOTES_CMS_PAGE)); String orderCode = null; try { orderCode = quoteOrderForm.getOrderCode(); final String comment = XSSFilterUtil.filter(quoteOrderForm.getComments()); if ("NEGOTIATEQUOTE".equals(quoteOrderForm.getSelectedQuoteDecision())) { if (StringUtils.isBlank(comment)) { setUpCommentIsEmptyError(quoteOrderForm, model); return quotesDetails(orderCode, model); } orderFacade.createAndSetNewOrderFromNegotiateQuote(orderCode, comment); } if ("ACCEPTQUOTE".equals(quoteOrderForm.getSelectedQuoteDecision())) { final OrderData orderDetails = orderFacade.getOrderDetailsForCode(orderCode); final Date quoteExpirationDate = orderDetails.getQuoteExpirationDate(); if (quoteExpirationDate != null && quoteExpirationDate.before(new Date())) { GlobalMessages.addErrorMessage(model, "text.quote.expired"); return quotesDetails(orderCode, model); } orderFacade.createAndSetNewOrderFromApprovedQuote(orderCode, comment); return REDIRECT_PREFIX + "/checkout/orderConfirmation/" + orderCode; } if ("CANCELQUOTE".equals(quoteOrderForm.getSelectedQuoteDecision())) { orderFacade.cancelOrder(orderCode, comment); } if ("ADDADDITIONALCOMMENT".equals(quoteOrderForm.getSelectedQuoteDecision())) { if (StringUtils.isBlank(comment)) { setUpCommentIsEmptyError(quoteOrderForm, model); return quotesDetails(orderCode, model); } orderFacade.addAdditionalComment(orderCode, comment); GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER, "text.confirmation.quote.comment.added"); return String.format(REDIRECT_TO_QUOTES_DETAILS, orderCode); } } catch (final UnknownIdentifierException e) { LOG.warn("Attempted to load a order that does not exist or is not visible", e); return REDIRECT_MY_ACCOUNT; } return REDIRECT_PREFIX + "/checkout/quoteOrderConfirmation/" + orderCode; }
From source file:org.starfishrespect.myconsumption.server.business.sensors.flukso.FluksoRetriever.java
/** * Tries to retrieve data available for the sensor in a given interval * * @param startTime Start of the interval * @param endTime End of the interval. Must be higher of equal than startTime, and lower than actual time * @return the retrieved data/* w w w. j av a2 s. c o m*/ * @throws RetrieveException if any error occurs */ @Override public SensorData getData(Date startTime, Date endTime) throws RetrieveException { if (startTime.after(endTime)) { throw new RequestException(0, "Start Time must be lower than end time"); } // cut data in day interval and retrieve with minute precision SensorData data = new SensorData(); long now = Calendar.getInstance().getTimeInMillis(); // last day Date currentComparisonDate = new Date(now - 86400000L); if (endTime.after(currentComparisonDate)) { if (startTime.after(currentComparisonDate)) { data.append(retrieve(startTime, endTime, maximumResolution(endTime))); } else { data.append(retrieve(currentComparisonDate, endTime, maximumResolution(endTime))); } endTime = currentComparisonDate; } if (endTime.before(startTime)) { return data; } // last week currentComparisonDate = new Date(now - 604800000L); if (endTime.after(currentComparisonDate)) { if (startTime.after(currentComparisonDate)) { data.append(retrieve(startTime, endTime, maximumResolution(endTime))); } else { data.append(retrieve(currentComparisonDate, endTime, maximumResolution(endTime))); } endTime = currentComparisonDate; } if (endTime.before(startTime)) { return data; } // last year currentComparisonDate = new Date(now - 31536000000L); if (endTime.after(currentComparisonDate)) { if (startTime.after(currentComparisonDate)) { data.append(retrieve(startTime, endTime, maximumResolution(endTime))); } else { data.append(retrieve(currentComparisonDate, endTime, maximumResolution(endTime))); } endTime = currentComparisonDate; } if (endTime.before(startTime)) { return data; } // retrieve annual values while (startTime.before(endTime)) { currentComparisonDate = new Date(endTime.getTime() - 31536000000L); if (startTime.after(currentComparisonDate)) { data.append(retrieve(startTime, endTime, maximumResolution(endTime))); } else { data.append(retrieve(currentComparisonDate, endTime, maximumResolution(endTime))); } endTime = currentComparisonDate; if (!data.mayHaveMoreData()) { break; } } return data; }
From source file:com.ibm.xsp.webdav.resource.DAVResourceDominoAttachments.java
private void fetchChildrenForNotesDocument() { LOGGER.debug("Fetching children for " + this.getName()); Document curDoc = null;// w ww . j a v a 2 s . com String docID = null; Vector<IDAVResource> resMembers = new Vector<IDAVResource>(); String notesURL = this.getInternalAddress(); curDoc = DominoProxy.getDocument(notesURL); if (curDoc == null) { LOGGER.error("Could not retrieve the document"); return; } // Read the repository list to get the view try { docID = curDoc.getUniversalID(); LOGGER.debug("Openend document " + docID); // No children if there are no attachments if (!curDoc.hasEmbedded()) { // E.C. It is a directory, so fetch the children documents as // resources LOGGER.error("Current doc with unid=" + curDoc.getUniversalID() + " has no embedded files. Try to find children"); DocumentCollection responses = curDoc.getResponses(); int numOfResponses = responses.getCount(); if (numOfResponses > 0) { LOGGER.error("Current doc has " + numOfResponses + " responses"); Document docResp = responses.getFirstDocument(); while (docResp != null) { LOGGER.error("Doc response has unid=" + docResp.getUniversalID()); @SuppressWarnings("rawtypes") Vector allEmbedded = DominoProxy.evaluate("@AttachmentNames", docResp); int numOfAttchments = allEmbedded.size(); if (numOfAttchments == 0) { // No attachments in here! LOGGER.error("Doc response has no attachment; is a directory"); LOGGER.debug(docID + " has no attachments (@AttachmentNames)"); // embed // as // doc DAVResourceDominoAttachments resAtt = getDocumentResource(docResp); if (resAtt != null) { LOGGER.error("Created DavResourceDomino Attachments from getDocumentResource-OK"); resMembers.add(resAtt); LOGGER.error("Resource successfull added"); } else { LOGGER.error( "Problem, DavResourceDomino Attachments from getDocumentResource- FAILED"); } } else { LOGGER.error("Doc response has attachments;"); String curAttName = allEmbedded.get(0).toString(); DAVResourceDominoAttachments curAttachment = getAttachmentResource(this.isReadOnly(), docResp, curAttName); if (curAttachment != null) { // Now add it to the Vector LOGGER.error("Created DavResourceDominoAttachments with getAttachmentResource-OK"); resMembers.add(curAttachment); LOGGER.error("Resource successfull added"); Date viewDate = this.getLastModified(); Date docDate = curAttachment.getLastModified(); if (viewDate == null || (docDate != null && viewDate.before(docDate))) { this.setLastModified(docDate); } LOGGER.error("Resource successfull updated last modified"); LOGGER.debug("Processing complete attachment " + curAttName); } else { LOGGER.error("Could not load attachment " + curAttName); } } Document docTmp = docResp; docResp = responses.getNextDocument(docResp); docTmp.recycle(); } // end while } // end if numresp>0 try { if (curDoc != null) { curDoc.recycle(); } } catch (Exception e) { LOGGER.error(e); } // Now save back the members to the main object this.setMembers(resMembers); return; } // Get all attachments @SuppressWarnings("rawtypes") Vector allEmbedded = DominoProxy.evaluate("@AttachmentNames", curDoc); int numOfAttchments = allEmbedded.size(); if (numOfAttchments == 0) { // No attachments in here! LOGGER.debug(docID + " has no attachments (@AttachmentNames)"); return; } LOGGER.debug(docID + " has " + new Integer(numOfAttchments).toString() + " attachment(s)"); // Initialize an empty vector at the right size // We might need to enlarge it if we have more attachments resMembers = new Vector<IDAVResource>(numOfAttchments); for (int i = 0; i < numOfAttchments; i++) { String curAttName = allEmbedded.get(i).toString(); DAVResourceDominoAttachments curAttachment = getAttachmentResource(this.isReadOnly(), curDoc, curAttName); if (curAttachment != null) { // Now add it to the Vector resMembers.add(curAttachment); LOGGER.debug("Processing complete attachment " + curAttName); } else { LOGGER.error("Could not load attachment " + curAttName); } } } catch (NotesException ne) { LOGGER.error(ne); } catch (Exception e) { LOGGER.error(e); } finally { try { if (curDoc != null) { curDoc.recycle(); } } catch (Exception e) { LOGGER.error(e); } // Now save back the members to the main object this.setMembers(resMembers); LOGGER.debug("Completed reading attachments resources from Notes document"); } }
From source file:eu.europa.esig.dss.validation.process.AdESTValidation.java
/** * Check of: best-signature-time against the signing certificate issuance date. * * c) If step 2 returned INDETERMINATE/CRYPTO_CONSTRAINTS_FAILURE_NO_POE and the material concerned by this * failure is the signature value or a signed attribute, check, if the algorithm(s) concerned were still * considered reliable at best-signature-time, continue with step d. Otherwise, terminate with * INDETERMINATE/CRYPTO_CONSTRAINTS_FAILURE_NO_POE. * * @param conclusion the conclusion to use to add the result of the check. * @return false if the check failed and the process should stop, true otherwise. *///from www .ja va2 s . c o m private boolean checkAlgorithmReliableAtBestSignatureTimeConstraint(final Conclusion conclusion) { final Constraint constraint = constraintData.getAlgorithmReliableAtBestSignatureTimeConstraint(); if (constraint == null) { return true; } constraint.create(signatureXmlNode, MessageTag.TSV_WACRABST); constraint.setIndications(Indication.INDETERMINATE, SubIndication.CRYPTO_CONSTRAINTS_FAILURE_NO_POE, MessageTag.TSV_WACRABST_ANS); boolean ok = false; final XmlDom error = bvpConclusion.getElement("./Error"); if (error != null) { final String algorithmExpirationDateString = error.getAttribute("AlgorithmExpirationDate"); if (StringUtils.isNotBlank(algorithmExpirationDateString)) { final Date algorithmExpirationDate = DSSUtils.parseDate(DSSUtils.DEFAULT_DATE_FORMAT, algorithmExpirationDateString); if (!algorithmExpirationDate.before(bestSignatureTime)) { ok = true; } } } constraint.setValue(ok); final String formatedBestSignatureTime = DSSUtils.formatDate(bestSignatureTime); constraint.setAttribute(AttributeValue.BEST_SIGNATURE_TIME, formatedBestSignatureTime); // TODO: (Bob: 2014 Mar 16) // final XmlDom errorXmlDom = bvpConclusion.getElement("./Error"); // conclusionNode.addChild(errorXmlDom); constraint.setConclusionReceiver(conclusion); return constraint.check(); }
From source file:com.mobileman.projecth.web.controller.patient.MedikamenteController.java
@Transactional @RequestMapping(method = RequestMethod.POST, value = "/patient/medikamente_eingeben") public String medicamentePost(HttpServletRequest request, HttpServletResponse response, Model model) throws UnsupportedEncodingException { KeepScroll.save(request, model);/* ww w.ja va 2 s . c om*/ // save request parameters into map request.setCharacterEncoding("UTF-8"); ViewState.copyViewState(request, model); String diseaseCode = request.getParameter("selectdisease"); model.addAttribute("selected_disease_code", diseaseCode); String selectunits = request.getParameter("selectunits"); model.addAttribute("selectedUnits", selectunits); String takingFrequnecyStr = request.getParameter("select_taking_frequency"); model.addAttribute("select_taking_frequency", takingFrequnecyStr); MedicationFrequency medicationFrequency = (takingFrequnecyStr == null || takingFrequnecyStr.equals("0")) ? null : MedicationFrequency.valueOf(takingFrequnecyStr); String selectedHistoryMedication = request.getParameter("selecthistory"); model.addAttribute("selected_history_medication", selectedHistoryMedication); Long patientMedicationId = NumUtils.convert2long(request.getParameter("patientMedicationId")); if (patientMedicationId != null) { return medicamenteEditPost(request, response, model, patientMedicationId); } boolean error = false; if (StringUtils.isNotBlank(request.getParameter("search.x"))) { model.addAttribute("wasSearch", true); // search // String filter = request.getParameter("filter"); List<Medication> medications = null; try { if (StringUtils.isNotBlank(filter)) { medications = medicationService.findAllByNameOrPzn(filter, Locale.GERMANY); } else { // error model.addAttribute("errorsearchnodata", true); } } catch (Exception ex) { ex.printStackTrace(); model.addAttribute("errorsearch", true); } // clear fields setupFields(model, null, null, null); if (medications != null) { // store result // if zero clear text boxes // if only one save into text boxes // if more fill list if (medications.size() == 0) { model.addAttribute("infosearchnotfound", true); } else if (medications.size() == 1) { Medication tmp = medications.get(0); setupFields(model, tmp.getName(), tmp.getPzn(), tmp.getStandardUnitSize()); // setup fields } else if (medications.size() > 1) { // fill combo model.addAttribute("searchresult", medications); } } } else { model.addAttribute("wasEnter", true); Long medid = null; // find for mednumer String pzn = request.getParameter("pzn"); try { Medication med = medicationService.findByPzn(pzn, Locale.GERMANY); if (med != null) { medid = med.getId(); } } catch (Exception e) { } if (medid == null) { // insert new medicine String name = request.getParameter("name"); String units = request.getParameter("unitssize"); if (StringUtils.isBlank(name)) { error = true; model.addAttribute("errorname", true); } if (StringUtils.isBlank(units)) { error = true; model.addAttribute("errorunits", true); } if (!error) { try { Medication med = new Medication(); med.setLocale(Locale.GERMANY); med.setName(name); if (pzn != null && pzn.trim().length() > 0) { med.setPzn(new PznBarcode()); med.getPzn().setNumber(pzn); } med.setCreatedatetime(new Date()); med.setStandardUnitSize(units); medid = medicationService.save(med); } catch (Exception e) { // show error model.addAttribute("erroraddmed", true); } } } Double units = NumUtils.convert2double(selectunits); if (units == null) { model.addAttribute("errorselectunits", true); error = true; } if (StringUtils.isBlank(diseaseCode) || "0".equals(diseaseCode)) { model.addAttribute("errordisease", true); error = true; } if (medicationFrequency == null) { model.addAttribute("error_taking_frequency", true); error = true; } String startDateStr = request.getParameter("consum_start_date"); String endDateStr = request.getParameter("consum_end_date"); Date dateStart = DateUtils.normalStr2date(startDateStr); Date endDate = DateUtils.normalStr2date(endDateStr); if (dateStart == null) { model.addAttribute("error_consum_start_date", true); error = true; } if (endDate == null) { model.addAttribute("error_consum_end_date", true); error = true; } if (dateStart != null && endDate != null) { if (endDate.before(dateStart)) { model.addAttribute("error_consum_end_date", true); error = true; } } String comment = request.getParameter("comment"); if (!error && medid != null) { Disease disease = diseasService.findByCode(diseaseCode); Patient patient = new DataHolder(request).getPatient(); try { patientMedicationService.addConsumedMedication(patient.getId(), disease.getId(), medid, units, medicationFrequency, dateStart, endDate, comment); model.addAttribute("infoconsume", true); } catch (Exception ex) { model.addAttribute("errorconsume", true); } } } String result = medicamenteEingebenGet(request, response, model); if (!error) { setupFields(model, null, null, null); } return result; }
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 ww w. j av a2s . com*/ // 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; }