Example usage for java.sql Date after

List of usage examples for java.sql Date after

Introduction

In this page you can find the example usage for java.sql Date after.

Prototype

public boolean after(Date when) 

Source Link

Document

Tests if this date is after the specified date.

Usage

From source file:org.kuali.coeus.propdev.impl.core.LookupableDevelopmentProposalLookupableHelperServiceImpl.java

private boolean dateInRange(Date checkDate, Date lowerLimit, Date upperLimit) {
    if (checkDate == null) {
        return true;
    }//from w w  w .ja v  a  2s  .  c o  m
    if (lowerLimit != null && checkDate.before(lowerLimit)) {
        return false;
    }
    if (upperLimit != null && checkDate.after(upperLimit)) {
        return false;
    }
    return true;
}

From source file:org.kuali.kfs.coa.document.validation.impl.AccountGlobalRule.java

/**
 * This method checks to see if any expiration date field rules were violated Loops through each detail object and calls
 * {@link AccountGlobalRule#checkExpirationDate(MaintenanceDocument, AccountGlobalDetail)}
 *
 * @param maintenanceDocument//w ww . j a va2  s .  c  o m
 * @return false on rules violation
 */
protected boolean checkExpirationDate(MaintenanceDocument maintenanceDocument) {
    LOG.info("checkExpirationDate called");

    boolean success = true;
    Date newExpDate = newAccountGlobal.getAccountExpirationDate();

    // If creating a new account if acct_expiration_dt is set then
    // the acct_expiration_dt must be changed to a date that is today or later
    // unless the date was valid upon submission, this is an approval action
    // and the approver hasn't changed the value
    if (maintenanceDocument.isNew() && ObjectUtils.isNotNull(newExpDate)) {
        Date oldExpDate = null;

        if (maintenanceDocument.getDocumentHeader().getWorkflowDocument().isApprovalRequested()) {
            try {
                MaintenanceDocument oldMaintDoc = (MaintenanceDocument) SpringContext
                        .getBean(DocumentService.class)
                        .getByDocumentHeaderId(maintenanceDocument.getDocumentNumber());
                AccountGlobal oldAccountGlobal = (AccountGlobal) oldMaintDoc.getDocumentBusinessObject();
                if (ObjectUtils.isNotNull(oldAccountGlobal)) {
                    oldExpDate = oldAccountGlobal.getAccountExpirationDate();
                }
            } catch (WorkflowException ex) {
                LOG.warn("Error retrieving maintenance doc for doc #" + maintenanceDocument.getDocumentNumber()
                        + ". This shouldn't happen.", ex);
            }
        }

        if (ObjectUtils.isNull(oldExpDate) || !oldExpDate.equals(newExpDate)) {
            if (!newExpDate.after(today) && !newExpDate.equals(today)) {
                putFieldError("accountExpirationDate",
                        KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_TODAY_LATER);
                success &= false;
            }
        }
    }

    // a continuation account is required if the expiration date is completed.
    success &= checkContinuationAccount(maintenanceDocument, newExpDate);

    for (AccountGlobalDetail detail : newAccountGlobal.getAccountGlobalDetails()) {
        success &= checkExpirationDate(maintenanceDocument, detail);
    }
    return success;
}

From source file:org.kuali.kfs.coa.document.validation.impl.AccountGlobalRule.java

/**
 * This method checks to see if any expiration date field rules were violated in relation to the given detail record
 *
 * @param maintenanceDocument//from  w  w w  .  j av  a  2s  . c om
 * @param detail - the account detail we are investigating
 * @return false on rules violation
 */
protected boolean checkExpirationDate(MaintenanceDocument maintenanceDocument, AccountGlobalDetail detail) {
    boolean success = true;
    Date newExpDate = newAccountGlobal.getAccountExpirationDate();

    Date prevExpDate = null;

    // get previous expiration date for possible check later
    if (maintenanceDocument.getDocumentHeader().getWorkflowDocument().isApprovalRequested()) {
        try {
            MaintenanceDocument oldMaintDoc = (MaintenanceDocument) SpringContext.getBean(DocumentService.class)
                    .getByDocumentHeaderId(maintenanceDocument.getDocumentNumber());
            AccountGlobal oldAccountGlobal = (AccountGlobal) oldMaintDoc.getDocumentBusinessObject();
            if (ObjectUtils.isNotNull(oldAccountGlobal)) {
                prevExpDate = oldAccountGlobal.getAccountExpirationDate();
            }
        } catch (WorkflowException ex) {
            LOG.warn("Error retrieving maintenance doc for doc #" + maintenanceDocument.getDocumentNumber()
                    + ". This shouldn't happen.", ex);
        }
    }

    // load the object by keys
    Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class,
            detail.getPrimaryKeys());
    if (ObjectUtils.isNotNull(account)) {
        Date oldExpDate = account.getAccountExpirationDate();

        // When updating an account expiration date, the date must be today or later
        // (except for C&G accounts). Only run this test if this maint doc
        // is an edit doc
        if (isUpdatedExpirationDateInvalid(account, newAccountGlobal)) {
            // if the date was valid upon submission, and this is an approval,
            // we're not interested unless the approver changed the value
            if (ObjectUtils.isNull(prevExpDate) || !prevExpDate.equals(newExpDate)) {
                putFieldError("accountExpirationDate",
                        KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_TODAY_LATER);
                success &= false;
            }
        }

        // If creating a new account if acct_expiration_dt is set and the fund_group is not "CG" then
        // the acct_expiration_dt must be changed to a date that is today or later
        // unless the date was valid upon submission, this is an approval action
        // and the approver hasn't changed the value
        if (maintenanceDocument.isNew() && ObjectUtils.isNotNull(newExpDate)) {
            if (ObjectUtils.isNull(prevExpDate) || !prevExpDate.equals(newExpDate)) {
                if (ObjectUtils.isNotNull(newExpDate)
                        && ObjectUtils.isNull(newAccountGlobal.getSubFundGroup())) {
                    if (ObjectUtils.isNotNull(account.getSubFundGroup())) {
                        if (!account.isForContractsAndGrants()) {
                            if (!newExpDate.after(today) && !newExpDate.equals(today)) {
                                putGlobalError(KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_TODAY_LATER);
                                success &= false;
                            }
                        }
                    }
                }
            }
        }

        // acct_expiration_dt can not be before acct_effect_dt
        Date effectiveDate = account.getAccountEffectiveDate();
        if (ObjectUtils.isNotNull(effectiveDate) && ObjectUtils.isNotNull(newExpDate)) {
            if (newExpDate.before(effectiveDate)) {
                putGlobalError(
                        KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_CANNOT_BE_BEFORE_EFFECTIVE_DATE);
                success &= false;
            }
        }
    }

    return success;
}

From source file:org.kuali.kfs.coa.document.validation.impl.AccountGlobalRule.java

/**
 * This method checks to see if the updated expiration is not a valid one Only gets checked for specific {@link SubFundGroup}s
 *
 * @param oldAccount/*  w  w w  .  j a  v  a 2 s .c o m*/
 * @param newAccountGlobal
 * @return true if date has changed and is invalid
 */
protected boolean isUpdatedExpirationDateInvalid(Account oldAccount, AccountGlobal newAccountGlobal) {

    Date oldExpDate = oldAccount.getAccountExpirationDate();
    Date newExpDate = newAccountGlobal.getAccountExpirationDate();

    // When updating an account expiration date, the date must be today or later
    // (except for C&G accounts). Only run this test if this maint doc
    // is an edit doc
    boolean expDateHasChanged = false;

    // if the old version of the account had no expiration date, and the new
    // one has a date
    if (ObjectUtils.isNull(oldExpDate) && ObjectUtils.isNotNull(newExpDate)) {
        expDateHasChanged = true;
    }

    // if there was an old and a new expDate, but they're different
    else if (ObjectUtils.isNotNull(oldExpDate) && ObjectUtils.isNotNull(newExpDate)) {
        if (!oldExpDate.equals(newExpDate)) {
            expDateHasChanged = true;
        }
    }

    // if the expiration date hasnt changed, we're not interested
    if (!expDateHasChanged) {
        return false;
    }

    // if a subFundGroup isnt present, we cannot continue the testing
    SubFundGroup subFundGroup = newAccountGlobal.getSubFundGroup();
    if (ObjectUtils.isNull(subFundGroup)) {
        return false;
    }

    // get the fundGroup code
    String fundGroupCode = newAccountGlobal.getSubFundGroup().getFundGroupCode().trim();

    // if the account is part of the CG fund group, then this rule does not
    // apply, so we're done
    if (SpringContext.getBean(SubFundGroupService.class)
            .isForContractsAndGrants(newAccountGlobal.getSubFundGroup())) {
        return false;
    }

    // at this point, we know its not a CG fund group, so we must apply the rule

    // expirationDate must be today or later than today (cannot be before today)
    if (newExpDate.equals(today) || newExpDate.after(today)) {
        return false;
    } else {
        return true;
    }
}

From source file:org.kuali.kfs.coa.document.validation.impl.AccountRule.java

/**
 * This method checks to see if the account expiration date is today's date or earlier
 *
 * @param newAccount//  w  w  w  .  j  a  v a  2  s .c o  m
 * @return fails if the expiration date is null or after today's date
 */
protected boolean checkAccountExpirationDateValidTodayOrEarlier(Account newAccount) {

    // get today's date, with no time component
    Date todaysDate = new Date(getDateTimeService().getCurrentDate().getTime());
    todaysDate.setTime(DateUtils.truncate(todaysDate, Calendar.DAY_OF_MONTH).getTime());
    // TODO: convert this to using Wes' Kuali KfsDateUtils once we're using Date's instead of Timestamp

    // get the expiration date, if any
    Date expirationDate = newAccount.getAccountExpirationDate();
    if (ObjectUtils.isNull(expirationDate)) {
        putFieldError("accountExpirationDate",
                KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_CANNOT_BE_CLOSED_EXP_DATE_INVALID);
        return false;
    }

    // when closing an account, the account expiration date must be the current date or earlier
    expirationDate.setTime(DateUtils.truncate(expirationDate, Calendar.DAY_OF_MONTH).getTime());
    if (expirationDate.after(todaysDate)) {
        putFieldError("accountExpirationDate",
                KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_CANNOT_BE_CLOSED_EXP_DATE_INVALID);
        return false;
    }

    return true;
}

From source file:org.kuali.kfs.coa.document.validation.impl.AccountRule.java

/**
 * This method checks to see if any expiration date field rules were violated
 *
 * @param maintenanceDocument//from   ww  w  . j av a2  s  .co  m
 * @return false on rules violation
 */
protected boolean checkExpirationDate(MaintenanceDocument maintenanceDocument) {

    LOG.info("checkExpirationDate called");

    boolean success = true;

    Date oldExpDate = oldAccount.getAccountExpirationDate();
    Date newExpDate = newAccount.getAccountExpirationDate();
    Date today = new Date(getDateTimeService().getCurrentTimestamp().getTime());
    today.setTime(DateUtils.truncate(today, Calendar.DAY_OF_MONTH).getTime()); // remove any time components

    // When updating an account expiration date, the date must be today or later
    // Only run this test if this maintenance doc
    // is an edit doc

    if (isUpdatedExpirationDateInvalid(maintenanceDocument)) {
        Account newAccount = (Account) maintenanceDocument.getNewMaintainableObject().getBusinessObject();
        if (newAccount.isClosed()) {
            /*If the Account is being closed and the date is before today's date, the EXP date can only be today*/
            putFieldError("accountExpirationDate",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_ACCT_CANNOT_BE_CLOSED_EXP_DATE_INVALID);
        } else {
            /*If the Account is not being closed and the date is before today's date, the EXP date can only be today or at a later date*/
            putFieldError("accountExpirationDate",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_TODAY_LATER);
        }
        success &= false;
    }

    // a continuation account is required if the expiration date is completed.
    if (ObjectUtils.isNotNull(newExpDate)) {
        if (StringUtils.isBlank(newAccount.getContinuationAccountNumber())) {
            putFieldError("continuationAccountNumber",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_CONTINUATION_ACCT_REQD_IF_EXP_DATE_COMPLETED);
        }
        if (StringUtils.isBlank(newAccount.getContinuationFinChrtOfAcctCd())) {
            putFieldError("continuationFinChrtOfAcctCd",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_CONTINUATION_FINCODE_REQD_IF_EXP_DATE_COMPLETED);
            success &= false;
        }
    }

    // If creating a new account if acct_expiration_dt is set then
    // the acct_expiration_dt must be changed to a date that is today or later
    if (maintenanceDocument.isNew() && ObjectUtils.isNotNull(newExpDate)) {
        Collection<String> fundGroups = SpringContext.getBean(ParameterService.class)
                .getParameterValuesAsString(Account.class,
                        KFSConstants.ChartApcParms.EXPIRATION_DATE_BACKDATING_FUND_GROUPS);
        if (fundGroups == null || ObjectUtils.isNull(newAccount.getSubFundGroup())
                || !fundGroups.contains(newAccount.getSubFundGroup().getFundGroupCode())) {
            if (!newExpDate.after(today) && !newExpDate.equals(today)) {
                putFieldError("accountExpirationDate",
                        KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_TODAY_LATER);
                success &= false;
            }
        }
    }

    // acct_expiration_dt can not be before acct_effect_dt
    Date effectiveDate = newAccount.getAccountEffectiveDate();
    if (ObjectUtils.isNotNull(effectiveDate) && ObjectUtils.isNotNull(newExpDate)) {
        if (newExpDate.before(effectiveDate)) {
            putFieldError("accountExpirationDate",
                    KFSKeyConstants.ERROR_DOCUMENT_ACCMAINT_EXP_DATE_CANNOT_BE_BEFORE_EFFECTIVE_DATE);
            success &= false;
        }
    }

    return success;
}

From source file:org.kuali.kfs.fp.document.DisbursementVoucherDocument.java

/**
 * Convenience method to set dv payee detail fields based on a given vendor.
 *
 * @param vendor//www.  j  a  v  a 2s  . co m
 */
public void templateVendor(VendorDetail vendor, VendorAddress vendorAddress) {
    if (vendor == null) {
        return;
    }

    this.getDvPayeeDetail().setDisbursementVoucherPayeeTypeCode(KFSConstants.PaymentPayeeTypes.VENDOR);
    this.getDvPayeeDetail().setDisbVchrPayeeIdNumber(vendor.getVendorNumber());
    this.getDvPayeeDetail().setDisbVchrPayeePersonName(vendor.getVendorName());

    this.getDvPayeeDetail().setDisbVchrAlienPaymentCode(vendor.getVendorHeader().getVendorForeignIndicator());

    if (ObjectUtils.isNotNull(vendorAddress)
            && ObjectUtils.isNotNull(vendorAddress.getVendorAddressGeneratedIdentifier())) {
        this.getDvPayeeDetail().setDisbVchrVendorAddressIdNumber(
                vendorAddress.getVendorAddressGeneratedIdentifier().toString());
        this.getDvPayeeDetail().setDisbVchrPayeeLine1Addr(vendorAddress.getVendorLine1Address());
        this.getDvPayeeDetail().setDisbVchrPayeeLine2Addr(vendorAddress.getVendorLine2Address());
        this.getDvPayeeDetail().setDisbVchrPayeeCityName(vendorAddress.getVendorCityName());
        this.getDvPayeeDetail().setDisbVchrPayeeStateCode(vendorAddress.getVendorStateCode());
        this.getDvPayeeDetail().setDisbVchrPayeeZipCode(vendorAddress.getVendorZipCode());
        this.getDvPayeeDetail().setDisbVchrPayeeCountryCode(vendorAddress.getVendorCountryCode());
    } else {
        this.getDvPayeeDetail().setDisbVchrVendorAddressIdNumber(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeLine1Addr(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeLine2Addr(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeCityName(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeStateCode(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeZipCode(StringUtils.EMPTY);
        this.getDvPayeeDetail().setDisbVchrPayeeCountryCode(StringUtils.EMPTY);
    }

    this.getDvPayeeDetail().setDisbVchrAlienPaymentCode(vendor.getVendorHeader().getVendorForeignIndicator());
    this.getDvPayeeDetail().setDvPayeeSubjectPaymentCode(
            VendorConstants.VendorTypes.SUBJECT_PAYMENT.equals(vendor.getVendorHeader().getVendorTypeCode()));
    this.getDvPayeeDetail().setDisbVchrEmployeePaidOutsidePayrollCode(
            getVendorService().isVendorInstitutionEmployee(vendor.getVendorHeaderGeneratedIdentifier()));

    this.getDvPayeeDetail().setHasMultipleVendorAddresses(1 < vendor.getVendorAddresses().size());

    boolean w9AndW8Checked = false;
    if ((ObjectUtils.isNotNull(vendor.getVendorHeader().getVendorW9ReceivedIndicator())
            && vendor.getVendorHeader().getVendorW9ReceivedIndicator() == true)
            || (ObjectUtils.isNotNull(vendor.getVendorHeader().getVendorW8BenReceivedIndicator())
                    && vendor.getVendorHeader().getVendorW8BenReceivedIndicator() == true)) {

        w9AndW8Checked = true;
    }

    //    this.disbVchrPayeeW9CompleteCode = vendor.getVendorHeader().getVendorW8BenReceivedIndicator()  == null ? false : vendor.getVendorHeader().getVendorW8BenReceivedIndicator();
    this.disbVchrPayeeW9CompleteCode = w9AndW8Checked;

    Date vendorFederalWithholdingTaxBeginDate = vendor.getVendorHeader()
            .getVendorFederalWithholdingTaxBeginningDate();
    Date vendorFederalWithholdingTaxEndDate = vendor.getVendorHeader().getVendorFederalWithholdingTaxEndDate();
    java.util.Date today = getDateTimeService().getCurrentDate();
    if ((vendorFederalWithholdingTaxBeginDate != null && vendorFederalWithholdingTaxBeginDate.before(today))
            && (vendorFederalWithholdingTaxEndDate == null
                    || vendorFederalWithholdingTaxEndDate.after(today))) {
        this.disbVchrPayeeTaxControlCode = DisbursementVoucherConstants.TAX_CONTROL_CODE_BEGIN_WITHHOLDING;
    }

    // if vendor is foreign, default alien payment code to true
    if (getVendorService().isVendorForeign(vendor.getVendorHeaderGeneratedIdentifier())) {
        getDvPayeeDetail().setDisbVchrAlienPaymentCode(true);
    }
}

From source file:org.kuali.kfs.module.ar.batch.service.impl.VerifyBillingFrequencyServiceImpl.java

protected boolean validateBillingFrequency(ContractsAndGrantsBillingAward award, Date lastBilledDate) {
    final Date today = getDateTimeService().getCurrentSqlDate();
    AccountingPeriod currPeriod = accountingPeriodService.getByDate(today);

    Date[] pair = getStartDateAndEndDateOfPreviousBillingPeriod(award, currPeriod);
    Date previousAccountingPeriodStartDate = pair[0];
    Date previousAccountingPeriodEndDate = pair[1];
    if (previousAccountingPeriodStartDate.after(previousAccountingPeriodEndDate)) {
        return false;
    }//from w  ww . java2 s.  com
    return calculateIfWithinGracePeriod(today, previousAccountingPeriodEndDate,
            previousAccountingPeriodStartDate, lastBilledDate,
            award.getBillingFrequency().getGracePeriodDays());
}

From source file:org.kuali.kfs.module.ar.batch.service.impl.VerifyBillingFrequencyServiceImpl.java

@Override
public Date[] getStartDateAndEndDateOfPreviousBillingPeriod(ContractsAndGrantsBillingAward award,
        AccountingPeriod currPeriod) {/* w w w.jav a  2  s  .  com*/
    Date[] startDt_EndDt = new Date[2];
    Date previousAccountingPeriodEndDay = null;
    Date previousAccountingPeriodStartDay = null;
    Date tmpEndDate;
    Date lastBilledDate = award.getLastBilledDate();
    String billingFrequency = award.getBillingFrequencyCode();
    ArrayList<Date> periodEndDateListOfCurrFiscalYear = getSortedListOfPeriodEndDatesOfCurrentFiscalYear(
            currPeriod);

    // this is used later on when obtaining the last date of the previous fiscal year as the previousAccountPeriodEndDay
    // it subtracts one from the fiscal year for the currPeriod passed in rather than assuming we want the
    // previous fiscal year to the current active fiscal year, just in case a past period is sent in as currPeriod
    // this is mostly just to facilitate unit tests but does make the code more robust (theoretically at least)
    int previousYear = currPeriod.getUniversityFiscalYear() - 1;

    int periodEndDateListOfCurrFiscalYearSize = 0;
    if (periodEndDateListOfCurrFiscalYear != null) {
        periodEndDateListOfCurrFiscalYearSize = periodEndDateListOfCurrFiscalYear.size();
    }

    // 2.billed monthly. ( Milestone and Predetermined Scheduled billing frequencies will also be invoiced as monthly.)
    if (billingFrequency.equalsIgnoreCase(ArConstants.MONTHLY_BILLING_SCHEDULE_CODE)
            || billingFrequency.equalsIgnoreCase(ArConstants.MILESTONE_BILLING_SCHEDULE_CODE)
            || billingFrequency.equalsIgnoreCase(ArConstants.PREDETERMINED_BILLING_SCHEDULE_CODE)) {
        // 2.1 find end date
        if (lastBilledDate != null) {
            if (periodEndDateListOfCurrFiscalYearSize > 0 && currPeriod.getUniversityFiscalPeriodEndDate()
                    .equals(periodEndDateListOfCurrFiscalYear.get(0))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime()); // assume the calendar date, discussion
            } else {
                int i = -1;
                for (i = 0; i < periodEndDateListOfCurrFiscalYear.size(); i++) {
                    if (currPeriod.getUniversityFiscalPeriodEndDate()
                            .equals(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }

                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i - 1);
            }
        } else {
            if (periodEndDateListOfCurrFiscalYearSize > 0 && currPeriod.getUniversityFiscalPeriodEndDate()
                    .equals(periodEndDateListOfCurrFiscalYear.get(0))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                // get end date by award's beginning date
                // if the lastBilledDate = null, means the the award is billed from its start date till the previous period end
                // date, so the calculation would be:
                int i = -1;
                for (i = 0; i < periodEndDateListOfCurrFiscalYear.size(); i++) {
                    if (currPeriod.getUniversityFiscalPeriodEndDate()
                            .equals(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }

                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i - 1);
            }
        }

        // 2.2 find start date
        // PreviousAccountingPeriodStartDate = previous accounting period endDate of previous accounting period + 1 day
        // for example current date is 2012.8.16, then PreviousAccountingPeriodStartDate = 2012.6.30 + 1day, which is 2012.7.1

        AccountingPeriod period = accountingPeriodService.getByDate(previousAccountingPeriodEndDay);
        if (period.getUniversityFiscalYear().intValue() < currPeriod.getUniversityFiscalYear().intValue()) {

            if (lastBilledDate == null) {
                previousAccountingPeriodStartDay = award.getAwardBeginningDate();
            } else {
                ArrayList<Date> acctPeriodEndDateListOfPreviousFiscalYear = getSortedListOfPeriodEndDatesOfCurrentFiscalYear(
                        period);

                int i = -1;
                for (i = acctPeriodEndDateListOfPreviousFiscalYear.size() - 1; i >= 0; i -= 1) {
                    tmpEndDate = acctPeriodEndDateListOfPreviousFiscalYear.get(i);

                    if (tmpEndDate.before(previousAccountingPeriodEndDay)) {
                        previousAccountingPeriodStartDay = calculateNextDay(tmpEndDate);
                        break;
                    }
                }

            }
        } else if (period.getUniversityFiscalYear().intValue() == currPeriod.getUniversityFiscalYear()
                .intValue()) {
            if (lastBilledDate == null) {
                previousAccountingPeriodStartDay = award.getAwardBeginningDate();
            } else {
                if (periodEndDateListOfCurrFiscalYearSize > 0
                        && previousAccountingPeriodEndDay.equals(periodEndDateListOfCurrFiscalYear.get(0))) {
                    final Date firstDayOfCurrentFiscalYear = new Date(universityDateService
                            .getFirstDateOfFiscalYear(currPeriod.getUniversityFiscalYear()).getTime());
                    previousAccountingPeriodStartDay = firstDayOfCurrentFiscalYear;
                } else {
                    int i = -1;
                    for (i = 0; i < periodEndDateListOfCurrFiscalYear.size(); i++) {
                        tmpEndDate = periodEndDateListOfCurrFiscalYear.get(i);

                        if (!tmpEndDate.before(previousAccountingPeriodEndDay)) {
                            break;
                        }
                    }
                    previousAccountingPeriodStartDay = calculateNextDay(
                            periodEndDateListOfCurrFiscalYear.get(i - 1));
                }
            }
        }
    }

    // 3.billed quarterly
    if (billingFrequency.equalsIgnoreCase(ArConstants.QUATERLY_BILLING_SCHEDULE_CODE)) {
        // 3.1 find end date
        if (lastBilledDate != null) {
            if (periodEndDateListOfCurrFiscalYearSize > 2 && !currPeriod.getUniversityFiscalPeriodEndDate()
                    .after(periodEndDateListOfCurrFiscalYear.get(2))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                int i = 0;
                for (i = 2; i < periodEndDateListOfCurrFiscalYear.size(); i += 3) {
                    // find the PreviousAccountingPeriodEndDate by current fiscal period end date and last billed date.
                    // for exmple, if current date is 2011.10.8, then the code will get out from for loop when looping to i =5
                    // (2011.12.31), so previous end date is 2011.9.30(i=5-3=2)
                    if (!currPeriod.getUniversityFiscalPeriodEndDate()
                            .after(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }
                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i - 3);
            }

        } else {

            if (periodEndDateListOfCurrFiscalYearSize > 0 && currPeriod.getUniversityFiscalPeriodEndDate()
                    .equals(periodEndDateListOfCurrFiscalYear.get(0))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                Date dt = accountingPeriodService.getByDate(award.getAwardBeginningDate())
                        .getUniversityFiscalPeriodEndDate();

                int i = -1;
                for (i = 2; i < periodEndDateListOfCurrFiscalYear.size(); i += 3) {
                    // find the closest period end date by the award beginning date,
                    // for exmple award is created on 7/15/2012 and billed quarterly, then the next billing date for this award is
                    // 9/30/2012
                    if (!dt.after(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }
                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i);

            }
        }
        // 3.2 find start date
        // PreviousAccountingPeriodStartDate falls into previous fiscal year
        AccountingPeriod period = accountingPeriodService.getByDate(previousAccountingPeriodEndDay);
        if (lastBilledDate == null) {
            previousAccountingPeriodStartDay = award.getAwardBeginningDate();
        } else {
            if (period.getUniversityFiscalYear().intValue() < currPeriod.getUniversityFiscalYear().intValue()) {

                ArrayList<Date> acctPeriodEndDateListOfPreviousFiscalYear = getSortedListOfPeriodEndDatesOfCurrentFiscalYear(
                        period);

                int j = -1;
                for (j = acctPeriodEndDateListOfPreviousFiscalYear.size() - 1; j >= 0; j -= 3) {
                    tmpEndDate = acctPeriodEndDateListOfPreviousFiscalYear.get(j);

                    if (tmpEndDate.before(previousAccountingPeriodEndDay)) {
                        previousAccountingPeriodStartDay = calculateNextDay(tmpEndDate);
                        break;
                    }
                }

            } else if (period.getUniversityFiscalYear().intValue() == currPeriod.getUniversityFiscalYear()
                    .intValue()) {

                if (periodEndDateListOfCurrFiscalYearSize > 2
                        && !previousAccountingPeriodEndDay.after(periodEndDateListOfCurrFiscalYear.get(2))) {
                    final Date firstDayOfCurrentFiscalYear = new Date(universityDateService
                            .getFirstDateOfFiscalYear(currPeriod.getUniversityFiscalYear()).getTime());
                    previousAccountingPeriodStartDay = firstDayOfCurrentFiscalYear;
                } else {
                    int i = -1;
                    for (i = 2; i < periodEndDateListOfCurrFiscalYear.size(); i += 3) {
                        tmpEndDate = periodEndDateListOfCurrFiscalYear.get(i);

                        if (!tmpEndDate.before(previousAccountingPeriodEndDay)) {
                            break;
                        }
                    }
                    previousAccountingPeriodStartDay = calculateNextDay(
                            periodEndDateListOfCurrFiscalYear.get(i - 3));
                }
            }
        }
    }

    // 4.billed semi-annually
    if (billingFrequency.equalsIgnoreCase(ArConstants.SEMI_ANNUALLY_BILLING_SCHEDULE_CODE)) {
        // 4.1 find end date
        if (lastBilledDate != null) {
            // if the current month is in the first fiscal semi-year of the current year,
            // then get the last day of the previous fiscal year as PreviousAccountingPeriodEndDate
            if (!currPeriod.getUniversityFiscalPeriodEndDate()
                    .after(periodEndDateListOfCurrFiscalYear.get(5))) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                int i = -1;
                for (i = 5; i < periodEndDateListOfCurrFiscalYear.size(); i += 6) {
                    if (!currPeriod.getUniversityFiscalPeriodEndDate()
                            .after(periodEndDateListOfCurrFiscalYear.get(i))) {
                        break;
                    }
                }
                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i - 6);
            }
        } else {
            Date dt = accountingPeriodService.getByDate(award.getAwardBeginningDate())
                    .getUniversityFiscalPeriodEndDate();

            if (accountingPeriodService.getByDate(award.getAwardBeginningDate()).getUniversityFiscalYear()
                    .compareTo(currPeriod.getUniversityFiscalYear()) < 0) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                for (int i = 5; i < periodEndDateListOfCurrFiscalYear.size(); i += 6) {
                    // find the closest period end date by the award beginning date,
                    // for exmple award is created on 7/15/2012 and billed annually, then the next billing date for this award
                    // is 12/31/2012
                    if (dt.before(periodEndDateListOfCurrFiscalYear.get(i))
                            || dt.equals(periodEndDateListOfCurrFiscalYear.get(i))) {
                        previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(i);
                        break;
                    }
                }
            }
        }

        // 4.2 find start date
        // PreviousAccountingPeriodStartDate falls into previous fiscal year
        AccountingPeriod period = accountingPeriodService.getByDate(previousAccountingPeriodEndDay);
        if (lastBilledDate == null) {
            previousAccountingPeriodStartDay = award.getAwardBeginningDate();
        } else {
            if (period.getUniversityFiscalYear() < currPeriod.getUniversityFiscalYear()) {
                ArrayList<Date> periodEndDateListOfPreviousFiscalYear = getSortedListOfPeriodEndDatesOfCurrentFiscalYear(
                        period);

                int i = -1;
                for (i = periodEndDateListOfPreviousFiscalYear.size() - 1; i >= 0; i -= 6) {
                    tmpEndDate = periodEndDateListOfPreviousFiscalYear.get(i);

                    if (tmpEndDate.before(previousAccountingPeriodEndDay)) {
                        previousAccountingPeriodStartDay = calculateNextDay(tmpEndDate);
                        break;
                    }
                }

            }
            // PreviousAccountingPeriodStartDate falls into current fiscal year
            else if (period.getUniversityFiscalYear().intValue() == currPeriod.getUniversityFiscalYear()
                    .intValue()) {

                // previousAccoutingPeriodEndDay falls in the first fiscal period
                if (!previousAccountingPeriodEndDay.after(periodEndDateListOfCurrFiscalYear.get(5))) {
                    final Date firstDayOfCurrentFiscalYear = new Date(universityDateService
                            .getFirstDateOfFiscalYear(currPeriod.getUniversityFiscalYear()).getTime());
                    previousAccountingPeriodStartDay = firstDayOfCurrentFiscalYear;
                }
                // previousAccoutingPeriodEndDay does not falls in the first fiscal period
                else {
                    int i = -1;
                    for (i = 5; i < periodEndDateListOfCurrFiscalYear.size(); i += 6) {
                        tmpEndDate = periodEndDateListOfCurrFiscalYear.get(i);

                        if (!tmpEndDate.before(previousAccountingPeriodEndDay)) {
                            break;
                        }
                    }
                    previousAccountingPeriodStartDay = calculateNextDay(
                            periodEndDateListOfCurrFiscalYear.get(i - 6));

                }
            }
        }
    }

    // 5.billed annually
    if (billingFrequency.equalsIgnoreCase(ArConstants.ANNUALLY_BILLING_SCHEDULE_CODE)) {
        // 5.1 find end date
        if (lastBilledDate != null) {
            previousAccountingPeriodEndDay = new Date(
                    universityDateService.getLastDateOfFiscalYear(previousYear).getTime()); // assume the calendar date, discussion needed
        } else {
            if (accountingPeriodService.getByDate(award.getAwardBeginningDate()).getUniversityFiscalYear()
                    .compareTo(currPeriod.getUniversityFiscalYear()) < 0) {
                previousAccountingPeriodEndDay = new Date(
                        universityDateService.getLastDateOfFiscalYear(previousYear).getTime());
            } else {
                previousAccountingPeriodEndDay = periodEndDateListOfCurrFiscalYear.get(11);
            }
        }

        // 5.2 find start date
        if (lastBilledDate == null) {
            previousAccountingPeriodStartDay = award.getAwardBeginningDate();
        } else {
            previousAccountingPeriodStartDay = new Date(
                    universityDateService.getFirstDateOfFiscalYear(previousYear).getTime());
        }
    }

    // 6.billed for LOC Review - A Random billing period
    if (billingFrequency.equalsIgnoreCase(ArConstants.LOC_BILLING_SCHEDULE_CODE)) {

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        previousAccountingPeriodEndDay = new Date(cal.getTime().getTime());

        // 5.2 find start date
        if (lastBilledDate == null) {
            previousAccountingPeriodStartDay = award.getAwardBeginningDate();
        } else {
            previousAccountingPeriodStartDay = calculateNextDay(lastBilledDate);
        }
    }

    startDt_EndDt[0] = previousAccountingPeriodStartDay;
    startDt_EndDt[1] = previousAccountingPeriodEndDay;
    return startDt_EndDt;
}

From source file:org.kuali.kfs.module.ar.document.CustomerInvoiceDocument.java

/**
 * If this invoice is a reversal, set the open indicator to false
 *
 * @see org.kuali.kfs.sys.document.FinancialSystemTransactionalDocumentBase#prepareForSave()
 *///  ww w  . j a va  2  s .c o  m
@Override
public void prepareForSave() {
    if (this.isInvoiceReversal()) {
        setOpenInvoiceIndicator(false);
    }

    //  make sure the docHeader gets its doc total right.  This is here because there's an ordering
    // bug in the struts classes for invoice that is preventing this from being set right.  There is
    // probably a better way to fix this that can be pursued later.
    getFinancialSystemDocumentHeader().setFinancialDocumentTotalAmount(getTotalDollarAmount());

    captureWorkflowHeaderInformation();

    //  invoice recurrence stuff, if there is a recurrence object
    if (ObjectUtils.isNotNull(this.getCustomerInvoiceRecurrenceDetails()) && getProcessRecurrenceFlag()) {

        //  wire up the recurrence customer number if one exists
        if (ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getCustomerNumber())) {
            this.getCustomerInvoiceRecurrenceDetails()
                    .setCustomerNumber(this.getAccountsReceivableDocumentHeader().getCustomerNumber());
        }

        customerInvoiceRecurrenceDetails.setInvoiceNumber(getDocumentNumber());

        // calc recurrence number if only end-date specified
        if (ObjectUtils.isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentTotalRecurrenceNumber())
                && ObjectUtils
                        .isNotNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate())) {

            Calendar beginCalendar = Calendar.getInstance();
            beginCalendar.setTime(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate());
            Date beginDate = this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate();
            Calendar endCalendar = Calendar.getInstance();

            endCalendar.setTime(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate());
            Date endDate = this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate();
            Calendar nextCalendar = Calendar.getInstance();
            Date nextDate = beginDate;

            int totalRecurrences = 0;
            int addCounter = 0;
            String intervalCode = this.getCustomerInvoiceRecurrenceDetails()
                    .getDocumentRecurrenceIntervalCode();
            if (intervalCode.equals("M")) {
                addCounter = 1;
            }
            if (intervalCode.equals("Q")) {
                addCounter = 3;
            }
            /* perform this loop while begin_date is less than or equal to end_date */
            while (!(beginDate.after(endDate))) {
                beginCalendar.setTime(beginDate);
                beginCalendar.add(Calendar.MONTH, addCounter);
                beginDate = KfsDateUtils.convertToSqlDate(beginCalendar.getTime());
                totalRecurrences++;

                nextDate = beginDate;
                nextCalendar.setTime(nextDate);
                nextCalendar.add(Calendar.MONTH, addCounter);
                nextDate = KfsDateUtils.convertToSqlDate(nextCalendar.getTime());
                if (endDate.after(beginDate) && endDate.before(nextDate)) {
                    totalRecurrences++;
                    break;
                }
            }
            if (totalRecurrences > 0) {
                this.getCustomerInvoiceRecurrenceDetails().setDocumentTotalRecurrenceNumber(totalRecurrences);
            }
        }

        //  calc end-date if only recurrence-number is specified
        if (ObjectUtils.isNotNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentTotalRecurrenceNumber())
                && ObjectUtils
                        .isNull(this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceEndDate())) {

            Calendar beginCalendar = Calendar.getInstance();
            beginCalendar.setTime(new Timestamp(
                    this.getCustomerInvoiceRecurrenceDetails().getDocumentRecurrenceBeginDate().getTime()));
            Calendar endCalendar = Calendar.getInstance();
            endCalendar = beginCalendar;

            int addCounter = 0;
            Integer documentTotalRecurrenceNumber = this.getCustomerInvoiceRecurrenceDetails()
                    .getDocumentTotalRecurrenceNumber();
            String intervalCode = this.getCustomerInvoiceRecurrenceDetails()
                    .getDocumentRecurrenceIntervalCode();
            if (intervalCode.equals("M")) {
                addCounter = -1;
                addCounter += documentTotalRecurrenceNumber * 1;
            }
            if (intervalCode.equals("Q")) {
                addCounter = -3;
                addCounter += documentTotalRecurrenceNumber * 3;
            }
            endCalendar.add(Calendar.MONTH, addCounter);
            this.getCustomerInvoiceRecurrenceDetails()
                    .setDocumentRecurrenceEndDate(KfsDateUtils.convertToSqlDate(endCalendar.getTime()));
        }
    }

    // Force upper case
    //TODO Force to upper case here since DD forceUpperCase doesn't work. Revert this temp fix after Rice fix.
    setBilledByOrganizationCode(StringUtils.upperCase(billedByOrganizationCode));
    accountsReceivableDocumentHeader.setProcessingOrganizationCode(
            StringUtils.upperCase(accountsReceivableDocumentHeader.getProcessingOrganizationCode()));
    accountsReceivableDocumentHeader
            .setCustomerNumber(StringUtils.upperCase(accountsReceivableDocumentHeader.getCustomerNumber()));

    if (ObjectUtils.isNull(getCustomerShipToAddressIdentifier())) {
        setCustomerShipToAddress(null);
        setCustomerShipToAddressOnInvoice(null);
    }

}