Example usage for java.util Date before

List of usage examples for java.util Date before

Introduction

In this page you can find the example usage for java.util Date before.

Prototype

public boolean before(Date when) 

Source Link

Document

Tests if this date is before the specified date.

Usage

From source file:org.openmrs.module.cohort.web.controller.EditCohortController.java

@RequestMapping(value = "/module/cohort/editCohort.form", method = RequestMethod.POST)
public void manageEditCohort1(ModelMap model, HttpSession httpSession, HttpServletRequest request,
        @RequestParam("cid") Integer id,
        @RequestParam(required = false, value = "voidReason") String voidReason,
        @ModelAttribute("cohortmodule") CohortM cohort) throws Exception {
    CohortService service1 = Context.getService(CohortService.class);
    List<String> cohorttype = new ArrayList<String>();
    LocationService service = Context.getLocationService();
    List<Location> formats = service.getAllLocations();
    model.addAttribute("locations", formats);
    List<CohortType> list1 = service1.getAllCohortTypes();
    for (int i = 0; i < list1.size(); i++) {
        CohortType c = list1.get(i);/*from w  w w .j  a  va 2s.c o m*/
        cohorttype.add(c.getName());
    }
    model.addAttribute("formats", cohorttype);
    List<String> cohortprg = new ArrayList<String>();
    List<CohortProgram> list2 = service1.findCohortProg();
    for (int j = 0; j < list2.size(); j++) {
        CohortProgram a = list2.get(j);
        cohortprg.add(a.getName());
    }
    model.addAttribute("formats1", cohortprg);
    List<CohortM> cohort1 = service1.findCohort(id);
    for (int j = 0; j < cohort1.size(); j++) {
        cohort = cohort1.get(j);
    }
    if ("Edit Cohort".equals(request.getParameter("Edit Cohort"))) {
        String givenName = request.getParameter("name");
        String givenDescription = request.getParameter("description");
        String givenStartDate = request.getParameter("startDate");
        String givenEndDate = request.getParameter("endDate");
        String givenLocation = request.getParameter("location");
        if (!givenName.equals("") && !givenDescription.equals("") && !givenStartDate.equals("")
                && !givenEndDate.equals("") && !givenLocation.equals("")) {
            java.util.Date parsedStartDate = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH)
                    .parse(givenStartDate);
            java.util.Date parsedEndDate = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH)
                    .parse(givenEndDate);
            if (parsedEndDate.before(parsedStartDate)) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "End date must be after Start date");
            } else {
                cohort.setName(givenName);
                cohort.setDescription(givenDescription);
                cohort.setStartDate(parsedStartDate);
                cohort.setEndDate(parsedEndDate);
                for (Location locations : service.getAllLocations()) {
                    if (locations.getName().equals(givenLocation)) {
                        cohort.setClocation(locations);
                        break;
                    }
                }
                service1.saveCohort(cohort);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Cohort Edit Success");
            }
        } else {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Fields cannot be empty");
        }

    }
    if ("void".equalsIgnoreCase(request.getParameter("void"))) {
        if (voidReason == "") {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "void Reason cannot be null");
        }
        cohort.setVoided(true);
        cohort.setVoidReason(voidReason);
        service1.saveCohort(cohort);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "cohort voided success");
    }
    if ("delete".equals(request.getParameter("delete"))) {
        service1.purgeCohort(cohort);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "delete success");
    }
}

From source file:gov.utah.dts.sdc.actions.ThirdPartyStudentAction.java

public String update_change() throws Exception {
    log.debug("update_change");
    int dbCode = 0;
    int webCode = 0;

    int start = decodeTime(getRoadTestStartTime());
    Date startDate = new Date(getRoadTestCompletionDate().getTime() + start);
    log.debug("startDate " + startDate.toString());

    int end = decodeTime(getRoadTestEndTime());
    Date endDate = new Date(getRoadTestCompletionDate().getTime() + end);
    log.debug("endDate " + endDate.toString());

    if (endDate.before(startDate)) {
        addActionError("Start Time Must Be Before End Time");
        //set variables for jsp
        getCurrentStudent().setFileNumber(getFileNumber());
        getCurrentStudent().setFirstName(getFirstName());
        getCurrentStudent().setMiddleName(getMiddleName());
        getCurrentStudent().setLastName(getLastName());
        getCurrentStudent().setDob(getDob());
        getCurrentStudent().setStudentPk(getStudentPk());
        getCurrentStudent().setLicenseType(getLicenseType());
        return INPUT;
    }//from   w  w w . j a v  a2s . c  o  m

    if (getRoadTestScore().intValue() <= 20) {
        //add completion_data and send Completion update student record.
        webCode = webSend();
        if (webCode > 0) {
            //update Student
            Map<String, Object> hm = new HashMap<String, Object>();
            hm.put("studentPk", getStudentPk());
            hm.put("roadTestCompletionDate", getRoadTestCompletionDate());
            hm.put("roadTestScore", getRoadTestScore());
            hm.put("roadTestInstructorFk", getRoadInstructorPk());
            hm.put("roadTestCompletionSchoolNumber", getSchoolNumber(getSchoolFk()));
            hm.put("schoolFk", getSchoolFk());
            dbCode = getStudentService().update(hm);

            //update audit completion data
            updateRoadAuditDate(getRoadMap(startDate, endDate));
        }
        log.debug("Passed road test");
    } else {
        //just update completion data.
        log.debug("Failed road test inserting audit info only");
        updateRoadAuditDate(getRoadMap(startDate, endDate));
    }

    if (dbCode > 0) {
        addActionMessage("SDC saved student record.");
    }
    log.debug("update webResponse " + webCode + " dbResponse " + dbCode);

    return SUCCESS;
}

From source file:gov.utah.dts.sdc.actions.ThirdPartyStudentAction.java

public String update() throws Exception {
    log.debug("update");

    //getCurrentStudent().setSchoolFk(getSchoolFk());   // remedy ticket 360423

    int dbCode = 0;
    int webCode = 0;

    int start = decodeTime(getRoadTestStartTime());
    Date startDate = new Date(getRoadTestCompletionDate().getTime() + start);
    log.debug("startDate " + startDate.toString());

    int end = decodeTime(getRoadTestEndTime());
    Date endDate = new Date(getRoadTestCompletionDate().getTime() + end);
    log.debug("endDate " + endDate.toString());

    if (endDate.before(startDate)) {
        addActionError("Start Time Must Be Before End Time");
        //set variables for jsp
        getCurrentStudent().setFileNumber(getFileNumber());
        getCurrentStudent().setFirstName(getFirstName());
        getCurrentStudent().setMiddleName(getMiddleName());
        getCurrentStudent().setLastName(getLastName());
        getCurrentStudent().setDob(getDob());
        getCurrentStudent().setStudentPk(getStudentPk());
        getCurrentStudent().setLicenseType(getLicenseType());
        return INPUT;
    }//from   w  ww  .j a va 2  s  .com

    if (getRoadTestScore().intValue() <= 20) {
        //add completion_data and send Completion update student record.
        webCode = webSend();
        if (webCode > 0) {
            //update Student
            Map<String, Object> hm = new HashMap<String, Object>();
            hm.put("studentPk", getStudentPk());
            hm.put("roadTestCompletionDate", getRoadTestCompletionDate());
            hm.put("roadTestScore", getRoadTestScore());
            hm.put("roadTestInstructorFk", getRoadInstructorPk());
            hm.put("roadTestCompletionSchoolNumber", getSchoolNumber(getSchoolFk()));
            hm.put("schoolFk", getSchoolFk());
            dbCode = getStudentService().update(hm);
            //insert audit completion data
            insertRoadAuditDate(getRoadMap(startDate, endDate));
        }
        log.debug("Passed road test");
    } else {
        //just insert completion data.
        log.debug("Failed road test inserting audit info only");
        insertRoadAuditDate(getRoadMap(startDate, endDate));
    }

    if (dbCode > 0) {
        addActionMessage("SDC saved student record.");
    }
    log.debug("update webResponse " + webCode + " dbResponse " + dbCode);

    return SUCCESS;
}

From source file:br.com.hslife.orcamento.service.FaturaCartaoService.java

@Override
public void quitarFaturaDebitoConta(FaturaCartao faturaCartao, Conta contaCorrente, double valorAQuitar,
        Date dataPagamento) {
    if (Math.abs(Util.arredondar(valorAQuitar)) < Math.abs(Util.arredondar(faturaCartao.getValorMinimo()))) {
        throw new BusinessException("Valor de pagamento no pode ser menor que o valor mnimo da fatura!");
    }//  w  ww .ja  v a2 s. co  m

    if (Math.abs(Util.arredondar(valorAQuitar)) > Math
            .abs(Util.arredondar(faturaCartao.getValorFatura() + faturaCartao.getSaldoDevedor()))) {
        throw new BusinessException("No  possvel quitar um valor maior que o valor total da fatura!");
    }

    if (dataPagamento.before(contaCorrente.getDataAbertura())) {
        throw new BusinessException(
                "Data de pagamento deve ser posterior a data de abertura da conta selecionada!");
    }

    // Traz a fatura e seta seus atributos
    FaturaCartao fatura = getRepository().findById(faturaCartao.getId());
    fatura.setStatusFaturaCartao(StatusFaturaCartao.QUITADA);
    fatura.setDataPagamento(dataPagamento);
    fatura.setValorPago(valorAQuitar);
    fatura.setValorMinimo(faturaCartao.getValorMinimo());

    // Cria o lanamento que ir quitar a fatura
    LancamentoConta lancamentoPagamento = new LancamentoConta();
    lancamentoPagamento.setConta(contaCorrente);
    lancamentoPagamento.setMoeda(contaCorrente.getMoeda());
    lancamentoPagamento.setDataPagamento(dataPagamento);
    lancamentoPagamento.setDescricao("Pagamento Fatura " + fatura.getLabel() + ", "
            + faturaCartao.getConta().getCartaoCredito().getDescricao());
    lancamentoPagamento.setStatusLancamentoConta(StatusLancamentoConta.QUITADO);
    lancamentoPagamento.setValorPago(valorAQuitar);
    lancamentoPagamento.setTipoLancamento(TipoLancamento.DESPESA);
    lancamentoPagamento.setCategoria(faturaCartao.getCategoriaSelecionada());
    lancamentoPagamento.setFavorecido(faturaCartao.getFavorecidoSelecionado());
    lancamentoPagamento.setMeioPagamento(faturaCartao.getMeioPagamentoSelecionado());

    // Determina o valor do saldo devedor
    double saldoDevedor = (faturaCartao.getValorFatura() + faturaCartao.getSaldoDevedor()) - valorAQuitar;

    // Salva o lanamento
    getLancamentoContaRepository().save(lancamentoPagamento);

    // Atribui o lanamento  fatura
    fatura.setLancamentoPagamento(lancamentoPagamento);

    // Salva a fatura paga
    getRepository().update(fatura);

    // Busca a fatura aberta e atribui o saldo devedor a ela. Depois salva
    FaturaCartao faturaAtual = getRepository().findFaturaCartaoAberta(faturaCartao.getConta());
    faturaAtual.setSaldoDevedor(saldoDevedor);
    getRepository().update(faturaAtual);
}

From source file:com.iorga.webappwatcher.analyzer.model.session.DurationPerPrincipalStats.java

private TimeSlice getTimeSlice(final Date date, final long timeSliceDurationMillis) {
    final int index = lastAccessedTimeSliceIndex;
    if (index == -1) {
        // no last accessed time slice, we must found the slice by dichotomy
        return findOrCreateTimeSlice(date, timeSliceDurationMillis);
    } else {//from w w  w.j av a2  s  . c  o  m
        // let's see if the date fits in current time slice
        final TimeSlice currentTimeSlice = timeSlices.get(index);
        if (isDateInTimeSlice(date, currentTimeSlice)) {
            return returnTimeSlice(currentTimeSlice, index);
        } else if (date.before(currentTimeSlice.startDate)) {
            // the date is before, let's check the previous index
            assert index > 0; // should never append because the time slice should already have been created
            final int previousIndex = index - 1;
            final TimeSlice previousTimeSlice = timeSlices.get(previousIndex);
            if (isDateInTimeSlice(date, previousTimeSlice)) {
                return returnTimeSlice(previousTimeSlice, previousIndex);
            } else {
                // does not fit in the previous time slice, must find it or create it by dichotomy
                return findOrCreateTimeSlice(date, timeSliceDurationMillis);
            }
        } else {
            // we are after, let's check if the next slice exists and create it other wise
            final int nextIndex = index + 1;
            if (timeSlices.size() <= nextIndex) {
                // let's create the new time slice
                final TimeSlice timeSlice = createNewTimeSlice(date, timeSliceDurationMillis);
                return returnTimeSlice(timeSlice, nextIndex);
            } else {
                final TimeSlice nextTimeSlice = timeSlices.get(nextIndex);
                if (isDateInTimeSlice(date, nextTimeSlice)) {
                    return returnTimeSlice(nextTimeSlice, nextIndex);
                } else {
                    // does not fit in the next time slice, must find it or create it by dichotomy
                    return findOrCreateTimeSlice(date, timeSliceDurationMillis);
                }
            }
        }
    }
}

From source file:fr.paris.lutece.plugins.crm.web.demand.DemandTypeJspBean.java

/**
 * Get the data of the demand type//from   w w  w .ja  v  a 2s  .co m
 * @param request {@link HttpServletRequest}
 * @param demandType the {@link DemandType}
 * @return an empty string if there are no errors, messages otherwise
 */
private String getDemandTypeData(HttpServletRequest request, DemandType demandType) {
    String strUrl = StringUtils.EMPTY;
    String strLabel = request.getParameter(CRMConstants.PARAMETER_DEMAND_TYPE_LABEL);
    String strUrlResource = request.getParameter(CRMConstants.PARAMETER_URL_RESOURCE);

    if (StringUtils.isNotBlank(strLabel) && StringUtils.isNotBlank(strUrlResource)) {
        String strUrlInfo = request.getParameter(CRMConstants.PARAMETER_URL_INFO);
        String strUrlContact = request.getParameter(CRMConstants.PARAMETER_URL_CONTACT);
        String strDateBegin = request.getParameter(CRMConstants.PARAMETER_DATE_BEGIN);
        String strDateEnd = request.getParameter(CRMConstants.PARAMETER_DATE_END);
        String strOrder = request.getParameter(CRMConstants.PARAMETER_ORDER);
        String strIdCategory = request.getParameter(CRMConstants.PARAMETER_CATEGORY_ID_CATEGORY);
        String strWorkgroupKey = request.getParameter(CRMConstants.PARAMETER_WORKGROUP_KEY);
        String strRoleKey = request.getParameter(CRMConstants.PARAMETER_ROLE_KEY);
        String strTarget = request.getParameter(CRMConstants.PARAMETER_TARGET);
        String strUrlDelete = request.getParameter(CRMConstants.PARAMETER_URL_DELETE);
        String strIncludeIdCrmUser = request.getParameter(CRMConstants.PARAMETER_INCLUDE_ID_CRM_USER);
        String strNeedAuthentication = request.getParameter(CRMConstants.PARAMETER_NEED_AUTHENTICATION);
        String strNeedValidation = request.getParameter(CRMConstants.PARAMETER_NEED_VALIDATION);

        int nOrder = 0;

        if (StringUtils.isNotBlank(strOrder) && StringUtils.isNumeric(strOrder)) {
            nOrder = Integer.parseInt(strOrder);
        }

        int nIdCategory = -1;

        if (StringUtils.isNotBlank(strIdCategory) && StringUtils.isNumeric(strIdCategory)) {
            nIdCategory = Integer.parseInt(strIdCategory);
        }

        int nTarget = 0;

        if (StringUtils.isNotBlank(strTarget) && StringUtils.isNumeric(strTarget)) {
            nTarget = Integer.parseInt(strTarget);
        }

        Date dateBegin = null;
        Date dateEnd = null;

        if (StringUtils.isNotBlank(strDateBegin)) {
            dateBegin = DateUtil.formatDateLongYear(strDateBegin, getLocale());

            if (dateBegin != null) {
                if (dateBegin.before(new Date(0))) {
                    strUrl = AdminMessageService.getMessageUrl(request,
                            CRMConstants.MESSAGE_INVALID_DATE_BEFORE_70, AdminMessage.TYPE_STOP);
                }
            } else {
                strUrl = AdminMessageService.getMessageUrl(request, CRMConstants.MESSAGE_INVALID_DATEBEGIN,
                        AdminMessage.TYPE_STOP);
            }
        }

        if (StringUtils.isBlank(strUrl) && StringUtils.isNotBlank(strDateEnd)) {
            dateEnd = DateUtil.formatDateLongYear(strDateEnd, getLocale());

            if (dateEnd != null) {
                if (dateEnd.before(new Date(0))) {
                    strUrl = AdminMessageService.getMessageUrl(request,
                            CRMConstants.MESSAGE_INVALID_DATE_BEFORE_70, AdminMessage.TYPE_STOP);
                }
            } else {
                strUrl = AdminMessageService.getMessageUrl(request, CRMConstants.MESSAGE_INVALID_DATEEND,
                        AdminMessage.TYPE_STOP);
            }
        }

        // validate period (dateEnd > dateBegin )
        if (StringUtils.isBlank(strUrl) && (dateBegin != null) && (dateEnd != null)) {
            if (dateEnd.before(dateBegin)) {
                strUrl = AdminMessageService.getMessageUrl(request,
                        CRMConstants.MESSAGE_ERROR_DATEEND_BEFORE_DATEBEGIN, AdminMessage.TYPE_STOP);
            }
        }

        if (StringUtils.isBlank(strUrl)) {
            demandType.setLabel(strLabel);
            demandType.setUrlResource(
                    StringUtils.isNotBlank(strUrlResource) ? strUrlResource : StringUtils.EMPTY);
            demandType.setUrlInfo(StringUtils.isNotBlank(strUrlInfo) ? strUrlInfo : StringUtils.EMPTY);
            demandType.setUrlContact(StringUtils.isNotBlank(strUrlContact) ? strUrlContact : StringUtils.EMPTY);
            demandType.setOrder(nOrder);
            demandType.setIdCategory(nIdCategory);
            demandType.setDateBegin(dateBegin);
            demandType.setDateEnd(dateEnd);
            demandType.setWorkgroup(
                    StringUtils.isNotBlank(strWorkgroupKey) ? strWorkgroupKey : StringUtils.EMPTY);
            demandType.setRole(StringUtils.isNotBlank(strRoleKey) ? strRoleKey : StringUtils.EMPTY);
            demandType.setTarget(TargetEnum.getTarget(nTarget));
            demandType.setUrlDelete(StringUtils.isNotBlank(strUrlDelete) ? strUrlDelete : StringUtils.EMPTY);
            demandType.setIncludeIdCrmUser(strIncludeIdCrmUser != null);
            demandType.setNeedAuthentication(strNeedAuthentication != null);
            demandType.setNeedValidation(strNeedValidation != null);
        }
    } else {
        strUrl = AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP);
    }

    return strUrl;
}

From source file:eionet.web.action.VocabularyConceptActionBean.java

/**
 * Validates save concept.//from   w  ww  .  ja va 2 s  .  c om
 *
 * @throws ServiceException
 */
@ValidationMethod(on = { "saveConcept" })
public void validateSaveConcept() throws ServiceException {
    if (!isUpdateRight()) {
        addGlobalValidationError("No permission to modify vocabulary");
    }

    if (StringUtils.isEmpty(getConceptIdentifier())) {
        addGlobalValidationError("Vocabulary concept identifier is missing");
    } else {
        if (vocabularyFolder.isNumericConceptIdentifiers()) {
            if (!Util.isNumericID(getConceptIdentifier())) {
                addGlobalValidationError("Vocabulary concept identifier must be numeric value");
            }
        } else {
            if (!Util.isValidIdentifier(getConceptIdentifier())) {
                addGlobalValidationError("Vocabulary concept identifier contains illegal characters (/%?#:\\)");
            }
            if (VocabularyFolderActionBean.RESERVED_VOCABULARY_EVENTS.contains(getConceptIdentifier())) {
                addGlobalValidationError(
                        "This vocabulary concept identifier is reserved value and cannot be used");
            }
        }
    }
    if (StringUtils.isEmpty(vocabularyConcept.getLabel())) {
        addGlobalValidationError("Vocabulary concept label is missing");
    }

    //check for dates, they cannot be set to future
    Date today = new Date(System.currentTimeMillis());

    if (vocabularyConcept.getStatusModified() != null && today.before(vocabularyConcept.getStatusModified())) {
        addGlobalValidationError("Status modified date cannot be set to future");
    }

    if (vocabularyConcept.getAcceptedDate() != null && today.before(vocabularyConcept.getAcceptedDate())) {
        addGlobalValidationError("Accepted date cannot be set to future");
    }

    if (vocabularyConcept.getNotAcceptedDate() != null
            && today.before(vocabularyConcept.getNotAcceptedDate())) {
        addGlobalValidationError("Not accepted date cannot be set to future");
    }

    // Validate unique identifier
    if (!vocabularyService.isUniqueConceptIdentifier(getConceptIdentifier(), vocabularyFolder.getId(),
            vocabularyConcept.getId())) {
        addGlobalValidationError("Vocabulary concept identifier is not unique");
    }

    List<String> uniqueValues = new ArrayList<String>();

    if (vocabularyConcept.getElementAttributes() != null) {
        for (List<DataElement> elems : vocabularyConcept.getElementAttributes()) {
            uniqueValues.clear();
            if (elems != null) {
                DataElement metaInfo = elems.get(0);
                for (DataElement elem : elems) {
                    if (elem != null) {
                        if (vocabularyService.isReferenceElement(elem.getId())
                                && elem.getRelatedConceptId() == null) {
                            if (elem.getAttributeValue() != null
                                    && !Util.isValidUri(elem.getAttributeValue())) {
                                addGlobalValidationError("Related match to an external vocabulary \""
                                        + metaInfo.getName() + "\" value \"" + elem.getAttributeValue()
                                        + "\" is not a valid URI. \n The allowed schemes are: "
                                        + "http, https, ftp, mailto, tel and urn");
                            }
                        }

                        if (uniqueValues.contains(elem.getUniqueValueHash())) {
                            addGlobalValidationError("'" + metaInfo.getName() + "'"
                                    + " has the same value more than once: " + elem.getValueText());
                        }
                        uniqueValues.add(elem.getUniqueValueHash());
                    }
                }
            }
        }
    }

    if (isValidationErrors()) {
        initBeans();
        addElementMetadata();
        initElemVocabularyNames();
        editDivId = null;
        Resolution resolution = new ForwardResolution(EDIT_VOCABULARY_CONCEPT_JSP);
        getContext().setSourcePageResolution(resolution);
    }
}

From source file:com.lottery.gui.MainLotteryForm.java

private void btnBuyTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuyTicketActionPerformed
    if (StringUtils.isBlank(tfBuyerName.getText().trim())) {
        JOptionPane.showMessageDialog(this, "Buyer name is blank!");
        tfBuyerName.requestFocusInWindow();
        return;//from w  ww  .jav  a 2s.  c om
    }

    if (StringUtils.isBlank(ftfBuyStartDate.getText().trim())) {
        JOptionPane.showMessageDialog(this, "Start date is invalid (dd/MM/yyyy)!");
        ftfBuyStartDate.requestFocusInWindow();
        return;
    }

    Date startDate = null;

    try {
        startDate = LotteryUtils.getDate(ftfBuyStartDate.getText().trim());
    } catch (ParseException ex) {
        JOptionPane.showMessageDialog(this, "Start date is invalid (dd/MM/yyyy)!");
        ftfBuyStartDate.requestFocusInWindow();
        LOGGER.error(ex);
        return;
    }

    Date targetDate = LotteryUtils.getTargetDate(startDate);

    Date today = new Date();
    if (today.after(startDate)) {
        JOptionPane.showMessageDialog(this, "Start date must be greater than today!");
        tfBuyerName.requestFocusInWindow();
        return;
    }

    int dialogResult = JOptionPane.showConfirmDialog(this,
            "Would You Like to generate ticket for: " + tfBuyerName.getText() + "?", "Warning",
            JOptionPane.YES_OPTION);
    if (dialogResult == JOptionPane.NO_OPTION) {
        return;
    }

    //        Date today = new Date();
    //        Date startDate = LotteryUtils.getNextDate(today);

    //        int startDay = LotteryUtils.getDayOfMonth(startDate);
    //        int maxDayOfMonth = LotteryUtils.getLastDayOfMonth(startDate);
    //
    //        buyerService.getAll();

    Buyer buyer = new Buyer();
    buyer.setName(tfBuyerName.getText().trim());
    buyer.setIc(tfBuyerIc.getText().trim());

    List<String> linesBallsDb = new ArrayList<>();
    List<Ticket> newTickets = new ArrayList<>();
    Date queryDate = startDate;

    int count = 0;
    try {
        //            for (int dayOfMonth = startDay; dayOfMonth <= maxDayOfMonth; dayOfMonth++) {
        for (; queryDate.before(targetDate);) {

            List<TicketTable> ticketTables = ticketTableService.getByDate(queryDate);
            linesBallsDb = LotteryUtils.getAllLinesBalls(ticketTables);
            Ticket newTicket = LotteryUtils.generateTicket(linesBallsDb, queryDate, count++);
            newTicket.setBuyer(buyer);
            newTickets.add(newTicket);
            queryDate = LotteryUtils.getNextDate(queryDate);

        }

        buyer.setTickets(newTickets);

        LotteryUtils.generatePhysicalTicket(buyer, System.currentTimeMillis() + "_" + buyer.getName() + ".xls");

        buyerService.saveOrUpdate(buyer);
        JOptionPane.showMessageDialog(this, "Generate ticket successfully for " + tfBuyerName.getText() + "!");

        btnResetActionPerformed(null);
    } catch (LotteryException ex) {
        LOGGER.error("Generate ticket exception: ", ex);
        JOptionPane.showMessageDialog(this, "Please help to try again!");
    } catch (Exception ex2) {
        LOGGER.error("Generate ticket exception: ", ex2);
        JOptionPane.showMessageDialog(this,
                "Something goes wrong! Please try again or report to administrator!");
    }

}

From source file:com.joinsystem.goku.common.utils.DateUtil.java

/**
 * ?//from   w w w  .  j av  a 2  s. co  m
 * @param  start1
 * @param  end1
 * @param  start2
 * @param  end2
 * @return boolean true false
 */
public boolean hasCommon(Date start1, Date end1, Date start2, Date end2) {
    if (end1.before(start2) || end2.before(start1))
        return false;
    else
        return true;
}

From source file:com.salesmanager.core.util.ProductUtil.java

public static BigDecimal determinePrice(ProductPrice productPrice) {
    Date dt = new Date();
    BigDecimal price = productPrice.getProductPriceAmount();
    ProductPriceSpecial ppspecial = productPrice.getSpecial();
    if (ppspecial != null) {
        // this type of discount supercedes
        if (ppspecial.getProductPriceSpecialStartDate() != null
                && ppspecial.getProductPriceSpecialEndDate() != null) {
            if (ppspecial.getProductPriceSpecialStartDate().before(new Date(dt.getTime()))
                    && ppspecial.getProductPriceSpecialEndDate().after(new Date(dt.getTime()))) {

                price = ppspecial.getProductPriceSpecialAmount();

            } else if (ppspecial.getProductPriceSpecialDurationDays() > -1) {

                Date startDate = ppspecial.getProductPriceSpecialStartDate();

                int numDays = ppspecial.getProductPriceSpecialDurationDays();
                Date purchased = new Date();
                Calendar c = Calendar.getInstance();
                c.setTime(dt);//w w  w  .  j  av  a 2  s.  com
                c.add(Calendar.DATE, numDays);
                // if(dt.before(c.getTime())) {

                if (dt.before(c.getTime()) && ppspecial.getProductPriceSpecialAmount()
                        .floatValue() < productPrice.getProductPriceAmount().floatValue()) {
                    price = ppspecial.getProductPriceSpecialAmount();
                } else {
                    price = productPrice.getProductPriceAmount();
                }

            }

        }
    }

    return price;
}