Example usage for org.joda.time Days daysBetween

List of usage examples for org.joda.time Days daysBetween

Introduction

In this page you can find the example usage for org.joda.time Days daysBetween.

Prototype

public static Days daysBetween(ReadablePartial start, ReadablePartial end) 

Source Link

Document

Creates a Days representing the number of whole days between the two specified partial datetimes.

Usage

From source file:opticalworkshopmonitoringsystem.PolishingDivision.java

License:Open Source License

private void jTextField34FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField34FocusLost
    Date d1 = null;/*from  www  .  ja  v a  2s .  co  m*/
    Date d2 = null;
    sdate3 = jTextField6.getText() + "/" + jTextField31.getText() + "/" + jTextField33.getText();
    edate3 = jTextField30.getText() + "/" + jTextField32.getText() + "/" + jTextField34.getText();
    //d1=;
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    try {

        d1 = format.parse(sdate);
        d2 = format.parse(edate);

        DateTime dt1 = new DateTime(d1);
        DateTime dt2 = new DateTime(d2);
        jLabel23.setText(Days.daysBetween(dt1, dt2).getDays() + " days");
        t3 = Days.daysBetween(dt1, dt2).getDays();
        time3 = t3 + " days";

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Please enter a valid date");
    }
}

From source file:opticalworkshopmonitoringsystem.PolishingDivision.java

License:Open Source License

private void jTextField28FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField28FocusLost
    Date d1 = null;/*from w  ww. j a va2 s .  co m*/
    Date d2 = null;
    sdate = jTextField23.getText() + "/" + jTextField25.getText() + "/" + jTextField27.getText();
    edate = jTextField24.getText() + "/" + jTextField26.getText() + "/" + jTextField28.getText();
    //d1=;
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    try {

        d1 = format.parse(sdate);
        d2 = format.parse(edate);

        DateTime dt1 = new DateTime(d1);
        DateTime dt2 = new DateTime(d2);
        jLabel48.setText(Days.daysBetween(dt1, dt2).getDays() + " days");
        t = Days.daysBetween(dt1, dt2).getDays();
        time = t + " days";

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Please enter a valid date");
    }
}

From source file:opticalworkshopmonitoringsystem.PolishingUpdate.java

License:Open Source License

private void jTextField17FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField17FocusLost
    Date d1 = null;/*  www.jav a2  s .  c o  m*/
    Date d2 = null;
    sdate4 = jTextField16.getText();
    edate4 = jTextField17.getText();
    //d1=;
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    try {

        d1 = format.parse(sdate4);
        d2 = format.parse(edate4);

        DateTime dt1 = new DateTime(d1);
        DateTime dt2 = new DateTime(d2);
        jLabel25.setText(Days.daysBetween(dt1, dt2).getDays() + " days");
        t4 = Days.daysBetween(dt1, dt2).getDays();
        time4 = t4 + " days";

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Please enter a valid date");
    }
}

From source file:opticalworkshopmonitoringsystem.PolishingUpdate.java

License:Open Source License

private void jTextField6FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField6FocusLost
    Date d1 = null;/*  w w w .  j a  v a  2 s .co  m*/
    Date d2 = null;
    sdate1 = jTextField5.getText();
    edate1 = jTextField6.getText();
    //d1=;
    SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    try {

        d1 = format.parse(sdate1);
        d2 = format.parse(edate1);

        DateTime dt1 = new DateTime(d1);
        DateTime dt2 = new DateTime(d2);
        jLabel29.setText(Days.daysBetween(dt1, dt2).getDays() + " days");
        t1 = Days.daysBetween(dt1, dt2).getDays();
        time1 = t1 + " days";

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Please enter a valid date");
    }

}

From source file:org.apache.beam.sdk.io.clickhouse.ClickHouseWriter.java

License:Apache License

@SuppressWarnings("unchecked")
static void writeValue(ClickHouseRowBinaryStream stream, ColumnType columnType, Object value)
        throws IOException {

    switch (columnType.typeName()) {
    case FIXEDSTRING:
        byte[] bytes;

        if (value instanceof String) {
            bytes = ((String) value).getBytes(Charsets.UTF_8);
        } else {//from w  w w.ja va  2 s  .co m
            bytes = ((byte[]) value);
        }

        stream.writeBytes(bytes);
        break;

    case FLOAT32:
        stream.writeFloat32((Float) value);
        break;

    case FLOAT64:
        stream.writeFloat64((Double) value);
        break;

    case INT8:
        stream.writeInt8((Byte) value);
        break;

    case INT16:
        stream.writeInt16((Short) value);
        break;

    case INT32:
        stream.writeInt32((Integer) value);
        break;

    case INT64:
        stream.writeInt64((Long) value);
        break;

    case STRING:
        stream.writeString((String) value);
        break;

    case UINT8:
        stream.writeUInt8((Short) value);
        break;

    case UINT16:
        stream.writeUInt16((Integer) value);
        break;

    case UINT32:
        stream.writeUInt32((Long) value);
        break;

    case UINT64:
        stream.writeUInt64((Long) value);
        break;

    case ENUM8:
        Integer enum8 = columnType.enumValues().get((String) value);
        Preconditions.checkNotNull(enum8,
                "unknown enum value '" + value + "', possible values: " + columnType.enumValues());
        stream.writeInt8(enum8);
        break;

    case ENUM16:
        Integer enum16 = columnType.enumValues().get((String) value);
        Preconditions.checkNotNull(enum16,
                "unknown enum value '" + value + "', possible values: " + columnType.enumValues());
        stream.writeInt16(enum16);
        break;

    case DATE:
        Days epochDays = Days.daysBetween(EPOCH_INSTANT, (ReadableInstant) value);
        stream.writeUInt16(epochDays.getDays());
        break;

    case DATETIME:
        long epochSeconds = ((ReadableInstant) value).getMillis() / 1000L;
        stream.writeUInt32(epochSeconds);
        break;

    case ARRAY:
        List<Object> values = (List<Object>) value;
        stream.writeUnsignedLeb128(values.size());
        for (Object arrayValue : values) {
            writeValue(stream, columnType.arrayElementType(), arrayValue);
        }
        break;
    }
}

From source file:org.apache.beam.sdk.io.gcp.spanner.MutationGroupEncoder.java

License:Apache License

private static int encodeDate(Date date) {

    MutableDateTime jodaDate = new MutableDateTime();
    jodaDate.setDate(date.getYear(), date.getMonth(), date.getDayOfMonth());

    return Days.daysBetween(MIN_DATE, jodaDate).getDays();
}

From source file:org.apache.beam.sdk.schemas.utils.AvroUtils.java

License:Apache License

@Nullable
private static Object genericFromBeamField(Schema.FieldType fieldType, org.apache.avro.Schema avroSchema,
        @Nullable Object value) {
    TypeWithNullability typeWithNullability = new TypeWithNullability(avroSchema);
    if (!fieldType.getNullable().equals(typeWithNullability.nullable)) {
        throw new IllegalArgumentException("FieldType " + fieldType + " and AVRO schema " + avroSchema
                + " don't have matching nullability");
    }/*from  w  w  w .  ja  v a2s .  co  m*/

    if (value == null) {
        return value;
    }

    switch (fieldType.getTypeName()) {
    case BYTE:
    case INT16:
    case INT32:
    case INT64:
    case FLOAT:
    case DOUBLE:
    case BOOLEAN:
        return value;

    case STRING:
        return new Utf8((String) value);

    case DECIMAL:
        BigDecimal decimal = (BigDecimal) value;
        LogicalType logicalType = typeWithNullability.type.getLogicalType();
        return new Conversions.DecimalConversion().toBytes(decimal, null, logicalType);

    case DATETIME:
        if (typeWithNullability.type.getType() == Type.INT) {
            ReadableInstant instant = (ReadableInstant) value;
            return (int) Days.daysBetween(Instant.EPOCH, instant).getDays();
        } else if (typeWithNullability.type.getType() == Type.LONG) {
            ReadableInstant instant = (ReadableInstant) value;
            return (long) instant.getMillis();
        } else {
            throw new IllegalArgumentException(
                    "Can't represent " + fieldType + " as " + typeWithNullability.type.getType());
        }

    case BYTES:
        return ByteBuffer.wrap((byte[]) value);

    case LOGICAL_TYPE:
        FixedBytesField fixedBytesField = FixedBytesField.fromBeamFieldType(fieldType);
        if (fixedBytesField != null) {
            byte[] byteArray = (byte[]) value;
            if (byteArray.length != fixedBytesField.getSize()) {
                throw new IllegalArgumentException("Incorrectly sized byte array.");
            }
            return GenericData.get().createFixed(null, (byte[]) value, typeWithNullability.type);
        }
        throw new RuntimeException("Unknown logical type " + fieldType.getLogicalType().getIdentifier());

    case ARRAY:
        List array = (List) value;
        List<Object> translatedArray = Lists.newArrayListWithExpectedSize(array.size());

        for (Object arrayElement : array) {
            translatedArray.add(genericFromBeamField(fieldType.getCollectionElementType(),
                    typeWithNullability.type.getElementType(), arrayElement));
        }
        return translatedArray;

    case MAP:
        Map map = Maps.newHashMap();
        Map<Object, Object> valueMap = (Map<Object, Object>) value;
        for (Map.Entry entry : valueMap.entrySet()) {
            Utf8 key = new Utf8((String) entry.getKey());
            map.put(key, genericFromBeamField(fieldType.getMapValueType(),
                    typeWithNullability.type.getValueType(), entry.getValue()));
        }
        return map;

    case ROW:
        return toGenericRecord((Row) value, typeWithNullability.type);

    default:
        throw new IllegalArgumentException("Unsupported type " + fieldType);
    }
}

From source file:org.apache.beam.sdk.schemas.utils.AvroUtils.java

License:Apache License

/**
 * Strict conversion from AVRO to Beam, strict because it doesn't do widening or narrowing during
 * conversion./*from  w  ww. ja v  a 2 s .  c  o  m*/
 *
 * @param value {@link GenericRecord} or any nested value
 * @param avroSchema schema for value
 * @param fieldType target beam field type
 * @return value converted for {@link Row}
 */
@SuppressWarnings("unchecked")
@Nullable
public static Object convertAvroFieldStrict(@Nullable Object value, @Nonnull org.apache.avro.Schema avroSchema,
        @Nonnull Schema.FieldType fieldType) {
    if (value == null) {
        return null;
    }

    TypeWithNullability type = new TypeWithNullability(avroSchema);
    LogicalType logicalType = LogicalTypes.fromSchema(type.type);
    if (logicalType != null) {
        if (logicalType instanceof LogicalTypes.Decimal) {
            ByteBuffer byteBuffer = (ByteBuffer) value;
            BigDecimal bigDecimal = new Conversions.DecimalConversion().fromBytes(byteBuffer.duplicate(),
                    type.type, logicalType);
            return convertDecimal(bigDecimal, fieldType);
        } else if (logicalType instanceof LogicalTypes.TimestampMillis) {
            if (value instanceof ReadableInstant) {
                return convertDateTimeStrict(((ReadableInstant) value).getMillis(), fieldType);
            } else {
                return convertDateTimeStrict((Long) value, fieldType);
            }
        } else if (logicalType instanceof LogicalTypes.Date) {
            if (value instanceof ReadableInstant) {
                int epochDays = Days.daysBetween(Instant.EPOCH, (ReadableInstant) value).getDays();
                return convertDateStrict(epochDays, fieldType);
            } else {
                return convertDateStrict((Integer) value, fieldType);
            }
        }
    }

    switch (type.type.getType()) {
    case FIXED:
        return convertFixedStrict((GenericFixed) value, fieldType);

    case BYTES:
        return convertBytesStrict((ByteBuffer) value, fieldType);

    case STRING:
        return convertStringStrict((CharSequence) value, fieldType);

    case INT:
        return convertIntStrict((Integer) value, fieldType);

    case LONG:
        return convertLongStrict((Long) value, fieldType);

    case FLOAT:
        return convertFloatStrict((Float) value, fieldType);

    case DOUBLE:
        return convertDoubleStrict((Double) value, fieldType);

    case BOOLEAN:
        return convertBooleanStrict((Boolean) value, fieldType);

    case RECORD:
        return convertRecordStrict((GenericRecord) value, fieldType);

    case ENUM:
        // enums are either Java enums, or GenericEnumSymbol,
        // they don't share common interface, but override toString()
        return convertEnumStrict(value, fieldType);

    case ARRAY:
        return convertArrayStrict((List<Object>) value, type.type.getElementType(), fieldType);

    case MAP:
        return convertMapStrict((Map<CharSequence, Object>) value, type.type.getValueType(), fieldType);

    case UNION:
        throw new IllegalArgumentException("Can't convert 'union', only nullable fields are supported");

    case NULL:
        throw new IllegalArgumentException("Can't convert 'null' to non-nullable field");

    default:
        throw new AssertionError("Unexpected AVRO Schema.Type: " + type.type.getType());
    }
}

From source file:org.apache.druid.sql.calcite.planner.Calcites.java

License:Apache License

/**
 * Calcite expects "DATE" types to be number of days from the epoch to the UTC date matching the local time fields.
 *
 * @param dateTime joda timestamp/*from w w  w.j av  a 2s  .co  m*/
 * @param timeZone session time zone
 *
 * @return Calcite style date
 */
public static int jodaToCalciteDate(final DateTime dateTime, final DateTimeZone timeZone) {
    final DateTime date = dateTime.withZone(timeZone).dayOfMonth().roundFloorCopy();
    return Days.daysBetween(DateTimes.EPOCH, date.withZoneRetainFields(DateTimeZone.UTC)).getDays();
}

From source file:org.apache.fineract.portfolio.loanaccount.loanschedule.domain.AbstractLoanScheduleGenerator.java

License:Apache License

private LoanScheduleModel generate(final MathContext mc, final LoanApplicationTerms loanApplicationTerms,
        final Set<LoanCharge> loanCharges, final HolidayDetailDTO holidayDetailDTO,
        final LoanScheduleParams loanScheduleParams) {

    final ApplicationCurrency applicationCurrency = loanApplicationTerms.getApplicationCurrency();
    // generate list of proposed schedule due dates
    LocalDate loanEndDate = this.scheduledDateGenerator.getLastRepaymentDate(loanApplicationTerms,
            holidayDetailDTO);/*w ww  .j a v a  2s  . co m*/
    LoanTermVariationsData lastDueDateVariation = loanApplicationTerms.getLoanTermVariations()
            .fetchLoanTermDueDateVariationsData(loanEndDate);
    if (lastDueDateVariation != null) {
        loanEndDate = lastDueDateVariation.getDateValue();
    }
    loanApplicationTerms.updateLoanEndDate(loanEndDate);

    // determine the total charges due at time of disbursement
    final BigDecimal chargesDueAtTimeOfDisbursement = deriveTotalChargesDueAtTimeOfDisbursement(loanCharges);

    // setup variables for tracking important facts required for loan
    // schedule generation.

    final MonetaryCurrency currency = loanApplicationTerms.getCurrency();
    final int numberOfRepayments = loanApplicationTerms.fetchNumberOfRepaymentsAfterExceptions();

    LoanScheduleParams scheduleParams = null;
    if (loanScheduleParams == null) {
        scheduleParams = LoanScheduleParams.createLoanScheduleParams(currency,
                Money.of(currency, chargesDueAtTimeOfDisbursement),
                loanApplicationTerms.getExpectedDisbursementDate(),
                getPrincipalToBeScheduled(loanApplicationTerms));
    } else if (!loanScheduleParams.isPartialUpdate()) {
        scheduleParams = LoanScheduleParams.createLoanScheduleParams(currency,
                Money.of(currency, chargesDueAtTimeOfDisbursement),
                loanApplicationTerms.getExpectedDisbursementDate(),
                getPrincipalToBeScheduled(loanApplicationTerms), loanScheduleParams);
    } else {
        scheduleParams = loanScheduleParams;
    }

    final Collection<RecalculationDetail> transactions = scheduleParams.getRecalculationDetails();
    final LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor = scheduleParams
            .getLoanRepaymentScheduleTransactionProcessor();

    final Collection<LoanScheduleModelPeriod> periods = createNewLoanScheduleListWithDisbursementDetails(
            numberOfRepayments, loanApplicationTerms, chargesDueAtTimeOfDisbursement);

    // Determine the total interest owed over the full loan for FLAT
    // interest method .
    final Money totalInterestChargedForFullLoanTerm = loanApplicationTerms
            .calculateTotalInterestCharged(this.paymentPeriodsInOneYearCalculator, mc);

    boolean isFirstRepayment = true;
    LocalDate firstRepaymentdate = this.scheduledDateGenerator.generateNextRepaymentDate(
            loanApplicationTerms.getExpectedDisbursementDate(), loanApplicationTerms, isFirstRepayment,
            holidayDetailDTO);
    final LocalDate idealDisbursementDate = this.scheduledDateGenerator
            .idealDisbursementDateBasedOnFirstRepaymentDate(
                    loanApplicationTerms.getLoanTermPeriodFrequencyType(),
                    loanApplicationTerms.getRepaymentEvery(), firstRepaymentdate);

    if (!scheduleParams.isPartialUpdate()) {
        // Set Fixed Principal Amount
        updateAmortization(mc, loanApplicationTerms, scheduleParams.getPeriodNumber(),
                scheduleParams.getOutstandingBalance());

        if (loanApplicationTerms.isMultiDisburseLoan()) {
            // fetches the first tranche amount and also updates other
            // tranche
            // details to map
            BigDecimal disburseAmt = getDisbursementAmount(loanApplicationTerms,
                    scheduleParams.getPeriodStartDate(), periods, chargesDueAtTimeOfDisbursement,
                    scheduleParams.getDisburseDetailMap(), scheduleParams.applyInterestRecalculation());
            scheduleParams.setPrincipalToBeScheduled(Money.of(currency, disburseAmt));
            loanApplicationTerms.setPrincipal(loanApplicationTerms.getPrincipal().zero().plus(disburseAmt));
            scheduleParams.setOutstandingBalance(Money.of(currency, disburseAmt));
            scheduleParams.setOutstandingBalanceAsPerRest(Money.of(currency, disburseAmt));
        }
    }

    // charges which depends on total loan interest will be added to this
    // set and handled separately after all installments generated
    final Set<LoanCharge> nonCompoundingCharges = seperateTotalCompoundingPercentageCharges(loanCharges);

    LocalDate currentDate = DateUtils.getLocalDateOfTenant();
    LocalDate lastRestDate = currentDate;
    if (loanApplicationTerms.getRestCalendarInstance() != null) {
        lastRestDate = getNextRestScheduleDate(currentDate.minusDays(1), loanApplicationTerms,
                holidayDetailDTO);
    }

    boolean isNextRepaymentAvailable = true;
    Boolean extendTermForDailyRepayments = false;

    if (holidayDetailDTO.getWorkingDays().getExtendTermForDailyRepayments() == true
            && loanApplicationTerms.getRepaymentPeriodFrequencyType() == PeriodFrequencyType.DAYS
            && loanApplicationTerms.getRepaymentEvery() == 1) {
        holidayDetailDTO.getWorkingDays()
                .setRepaymentReschedulingType(RepaymentRescheduleType.MOVE_TO_NEXT_WORKING_DAY.getValue());
        extendTermForDailyRepayments = true;
    }

    final Collection<LoanTermVariationsData> interestRates = loanApplicationTerms.getLoanTermVariations()
            .getInterestRateChanges();

    // this block is to start the schedule generation from specified date
    if (scheduleParams.isPartialUpdate()) {
        if (loanApplicationTerms.isMultiDisburseLoan()) {
            loanApplicationTerms.setPrincipal(scheduleParams.getPrincipalToBeScheduled());
        }

        applyLoanVariationsForPartialScheduleGenerate(loanApplicationTerms, scheduleParams, interestRates);

        isFirstRepayment = false;
    }
    while (!scheduleParams.getOutstandingBalance().isZero()
            || !scheduleParams.getDisburseDetailMap().isEmpty()) {
        LocalDate previousRepaymentDate = scheduleParams.getActualRepaymentDate();
        scheduleParams.setActualRepaymentDate(
                this.scheduledDateGenerator.generateNextRepaymentDate(scheduleParams.getActualRepaymentDate(),
                        loanApplicationTerms, isFirstRepayment, holidayDetailDTO));
        isFirstRepayment = false;
        LocalDate scheduledDueDate = this.scheduledDateGenerator.adjustRepaymentDate(
                scheduleParams.getActualRepaymentDate(), loanApplicationTerms, holidayDetailDTO);

        // calculated interest start date for the period
        LocalDate periodStartDateApplicableForInterest = calculateInterestStartDateForPeriod(
                loanApplicationTerms, scheduleParams.getPeriodStartDate(), idealDisbursementDate,
                firstRepaymentdate);

        // Loan Schedule Exceptions that need to be applied for Loan Account
        LoanTermVariationParams termVariationParams = applyLoanTermVariations(loanApplicationTerms,
                scheduleParams, previousRepaymentDate, scheduledDueDate);

        scheduledDueDate = termVariationParams.getScheduledDueDate();
        // Updates total days in term
        scheduleParams.addLoanTermInDays(
                Days.daysBetween(scheduleParams.getPeriodStartDate(), scheduledDueDate).getDays());
        if (termVariationParams.isSkipPeriod()) {
            continue;
        }

        if (scheduleParams.getPeriodStartDate().isAfter(scheduledDueDate)) {
            throw new ScheduleDateException("Due date can't be before period start date", scheduledDueDate);
        }

        if (!scheduleParams.getLatePaymentMap().isEmpty()) {
            populateCompoundingDatesInPeriod(scheduleParams.getPeriodStartDate(), scheduledDueDate, currentDate,
                    loanApplicationTerms, holidayDetailDTO, scheduleParams.getCompoundingMap(), loanCharges,
                    currency);
            scheduleParams.getCompoundingDateVariations().put(scheduleParams.getPeriodStartDate(),
                    new TreeMap<>(scheduleParams.getCompoundingMap()));
        }

        if (extendTermForDailyRepayments) {
            scheduleParams.setActualRepaymentDate(scheduledDueDate);
        }

        // this block is to generate the schedule till the specified
        // date(used for calculating preclosure)
        if (scheduleParams.getScheduleTillDate() != null
                && !scheduledDueDate.isBefore(scheduleParams.getScheduleTillDate())) {
            scheduledDueDate = scheduleParams.getScheduleTillDate();
            isNextRepaymentAvailable = false;
        }

        // populates the collection with transactions till the due date of
        // the period for interest recalculation enabled loans
        Collection<RecalculationDetail> applicableTransactions = getApplicableTransactionsForPeriod(
                scheduleParams.applyInterestRecalculation(), scheduledDueDate, transactions);

        final double interestCalculationGraceOnRepaymentPeriodFraction = this.paymentPeriodsInOneYearCalculator
                .calculatePortionOfRepaymentPeriodInterestChargingGrace(periodStartDateApplicableForInterest,
                        scheduledDueDate, loanApplicationTerms.getInterestChargedFromLocalDate(),
                        loanApplicationTerms.getLoanTermPeriodFrequencyType(),
                        loanApplicationTerms.getRepaymentEvery());
        ScheduleCurrentPeriodParams currentPeriodParams = new ScheduleCurrentPeriodParams(currency,
                interestCalculationGraceOnRepaymentPeriodFraction);

        if (loanApplicationTerms.isMultiDisburseLoan()) {
            updateBalanceBasedOnDisbursement(loanApplicationTerms, chargesDueAtTimeOfDisbursement,
                    scheduleParams, periods, scheduledDueDate);
        }

        // process repayments to the schedule as per the repayment
        // transaction processor configuration
        // will add a new schedule with interest till the transaction date
        // for a loan repayment which falls between the
        // two periods for interest first repayment strategies
        handleRecalculationForNonDueDateTransactions(mc, loanApplicationTerms, loanCharges, holidayDetailDTO,
                scheduleParams, periods, totalInterestChargedForFullLoanTerm, idealDisbursementDate,
                firstRepaymentdate, lastRestDate, scheduledDueDate, periodStartDateApplicableForInterest,
                applicableTransactions, currentPeriodParams);

        if (currentPeriodParams.isSkipCurrentLoop()) {
            continue;
        }
        periodStartDateApplicableForInterest = calculateInterestStartDateForPeriod(loanApplicationTerms,
                scheduleParams.getPeriodStartDate(), idealDisbursementDate, firstRepaymentdate);

        // backup for pre-close transaction
        updateCompoundingDetails(scheduleParams, periodStartDateApplicableForInterest);

        // 5 determine principal,interest of repayment period
        PrincipalInterest principalInterestForThisPeriod = calculatePrincipalInterestComponentsForPeriod(
                this.paymentPeriodsInOneYearCalculator,
                currentPeriodParams.getInterestCalculationGraceOnRepaymentPeriodFraction(),
                scheduleParams.getTotalCumulativePrincipal().minus(scheduleParams.getReducePrincipal()),
                scheduleParams.getTotalCumulativeInterest(), totalInterestChargedForFullLoanTerm,
                scheduleParams.getTotalOutstandingInterestPaymentDueToGrace(),
                scheduleParams.getOutstandingBalanceAsPerRest(), loanApplicationTerms,
                scheduleParams.getPeriodNumber(), mc, mergeVariationsToMap(scheduleParams),
                scheduleParams.getCompoundingMap(), periodStartDateApplicableForInterest, scheduledDueDate,
                interestRates);

        // will check for EMI amount greater than interest calculated
        if (loanApplicationTerms.getFixedEmiAmount() != null && loanApplicationTerms.getFixedEmiAmount()
                .compareTo(principalInterestForThisPeriod.interest().getAmount()) == -1) {
            String errorMsg = "EMI amount must be greater than : "
                    + principalInterestForThisPeriod.interest().getAmount();
            throw new MultiDisbursementEmiAmountException(errorMsg,
                    principalInterestForThisPeriod.interest().getAmount(),
                    loanApplicationTerms.getFixedEmiAmount());
        }

        // update cumulative fields for principal & interest
        currentPeriodParams.setInterestForThisPeriod(principalInterestForThisPeriod.interest());
        Money lastTotalOutstandingInterestPaymentDueToGrace = scheduleParams
                .getTotalOutstandingInterestPaymentDueToGrace();
        scheduleParams.setTotalOutstandingInterestPaymentDueToGrace(
                principalInterestForThisPeriod.interestPaymentDueToGrace());
        currentPeriodParams.setPrincipalForThisPeriod(principalInterestForThisPeriod.principal());

        // applies early payments on principal portion
        updatePrincipalPortionBasedOnPreviousEarlyPayments(currency, scheduleParams, currentPeriodParams);

        // updates amounts with current earlyPaidAmount
        updateAmountsBasedOnCurrentEarlyPayments(mc, loanApplicationTerms, scheduleParams, currentPeriodParams);

        if (scheduleParams.getOutstandingBalance().isLessThanZero() || !isNextRepaymentAvailable) {
            currentPeriodParams.plusPrincipalForThisPeriod(scheduleParams.getOutstandingBalance());
            scheduleParams.setOutstandingBalance(Money.zero(currency));
        }

        if (!isNextRepaymentAvailable) {
            scheduleParams.getDisburseDetailMap().clear();
        }

        // applies charges for the period
        applyChargesForCurrentPeriod(loanCharges, currency, scheduleParams, scheduledDueDate,
                currentPeriodParams);

        // sum up real totalInstallmentDue from components
        final Money totalInstallmentDue = currentPeriodParams.fetchTotalAmountForPeriod();

        // if previous installment is last then add interest to same
        // installment
        if (currentPeriodParams.getLastInstallment() != null
                && currentPeriodParams.getPrincipalForThisPeriod().isZero()) {
            currentPeriodParams.getLastInstallment()
                    .addInterestAmount(currentPeriodParams.getInterestForThisPeriod());
            continue;
        }

        // create repayment period from parts
        LoanScheduleModelPeriod installment = LoanScheduleModelRepaymentPeriod.repayment(
                scheduleParams.getInstalmentNumber(), scheduleParams.getPeriodStartDate(), scheduledDueDate,
                currentPeriodParams.getPrincipalForThisPeriod(), scheduleParams.getOutstandingBalance(),
                currentPeriodParams.getInterestForThisPeriod(),
                currentPeriodParams.getFeeChargesForInstallment(),
                currentPeriodParams.getPenaltyChargesForInstallment(), totalInstallmentDue, false);

        // apply loan transactions on installments to identify early/late
        // payments for interest recalculation
        installment = handleRecalculationForTransactions(mc, loanApplicationTerms, holidayDetailDTO, currency,
                scheduleParams, loanRepaymentScheduleTransactionProcessor, totalInterestChargedForFullLoanTerm,
                lastRestDate, scheduledDueDate, periodStartDateApplicableForInterest, applicableTransactions,
                currentPeriodParams, lastTotalOutstandingInterestPaymentDueToGrace, installment, loanCharges);
        periods.add(installment);

        // Updates principal paid map with efective date for reducing
        // the amount from outstanding balance(interest calculation)
        updateAmountsWithEffectiveDate(loanApplicationTerms, holidayDetailDTO, scheduleParams, scheduledDueDate,
                currentPeriodParams, installment);

        // handle cumulative fields

        scheduleParams.addTotalCumulativePrincipal(currentPeriodParams.getPrincipalForThisPeriod());
        scheduleParams.addTotalRepaymentExpected(totalInstallmentDue);
        scheduleParams.addTotalCumulativeInterest(currentPeriodParams.getInterestForThisPeriod());
        scheduleParams.setPeriodStartDate(scheduledDueDate);
        scheduleParams.incrementInstalmentNumber();
        scheduleParams.incrementPeriodNumber();
        scheduleParams.getCompoundingDateVariations().clear();
        if (termVariationParams.isRecalculateAmounts()) {
            loanApplicationTerms.setCurrentPeriodFixedEmiAmount(null);
            loanApplicationTerms.setCurrentPeriodFixedPrincipalAmount(null);
            adjustInstallmentOrPrincipalAmount(loanApplicationTerms,
                    scheduleParams.getTotalCumulativePrincipal(), scheduleParams.getPeriodNumber(), mc);
        }
    }

    // this condition is to add the interest from grace period if not
    // already applied.
    if (scheduleParams.getTotalOutstandingInterestPaymentDueToGrace().isGreaterThanZero()) {
        LoanScheduleModelPeriod installment = ((List<LoanScheduleModelPeriod>) periods).get(periods.size() - 1);
        installment.addInterestAmount(scheduleParams.getTotalOutstandingInterestPaymentDueToGrace());
        scheduleParams.addTotalRepaymentExpected(scheduleParams.getTotalOutstandingInterestPaymentDueToGrace());
        scheduleParams
                .addTotalCumulativeInterest(scheduleParams.getTotalOutstandingInterestPaymentDueToGrace());
        scheduleParams.setTotalOutstandingInterestPaymentDueToGrace(Money.zero(currency));
    }

    // determine fees and penalties for charges which depends on total
    // loan interest
    updatePeriodsWithCharges(currency, scheduleParams, periods, nonCompoundingCharges);

    // this block is to add extra re-payment schedules with interest portion
    // if the loan not paid with in loan term

    if (scheduleParams.getScheduleTillDate() != null) {
        currentDate = scheduleParams.getScheduleTillDate();
    }
    if (scheduleParams.applyInterestRecalculation() && scheduleParams.getLatePaymentMap().size() > 0
            && currentDate.isAfter(scheduleParams.getPeriodStartDate())) {
        Money totalInterest = addInterestOnlyRepaymentScheduleForCurrentdate(mc, loanApplicationTerms,
                holidayDetailDTO, currency, periods, currentDate, loanRepaymentScheduleTransactionProcessor,
                transactions, loanCharges, scheduleParams);
        scheduleParams.addTotalCumulativeInterest(totalInterest);
    }

    loanApplicationTerms.resetFixedEmiAmount();
    final BigDecimal totalPrincipalPaid = BigDecimal.ZERO;
    final BigDecimal totalOutstanding = BigDecimal.ZERO;

    return LoanScheduleModel.from(periods, applicationCurrency, scheduleParams.getLoanTermInDays(),
            scheduleParams.getPrincipalToBeScheduled(),
            scheduleParams.getTotalCumulativePrincipal().getAmount(), totalPrincipalPaid,
            scheduleParams.getTotalCumulativeInterest().getAmount(),
            scheduleParams.getTotalFeeChargesCharged().getAmount(),
            scheduleParams.getTotalPenaltyChargesCharged().getAmount(),
            scheduleParams.getTotalRepaymentExpected().getAmount(), totalOutstanding);
}