Example usage for java.math MathContext DECIMAL64

List of usage examples for java.math MathContext DECIMAL64

Introduction

In this page you can find the example usage for java.math MathContext DECIMAL64.

Prototype

MathContext DECIMAL64

To view the source code for java.math MathContext DECIMAL64.

Click Source Link

Document

A MathContext object with a precision setting matching the IEEE 754R Decimal64 format, 16 digits, and a rounding mode of RoundingMode#HALF_EVEN HALF_EVEN , the IEEE 754R default.

Usage

From source file:org.apache.fineract.portfolio.savings.service.DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from   w  w w  .j  a  v a 2s  .c om*/
public CommandProcessingResult modifyRDApplication(final Long accountId, final JsonCommand command) {
    try {
        this.depositAccountDataValidator.validateRecurringDepositForUpdate(command.json());

        final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService
                .isSavingsInterestPostingAtCurrentPeriodEnd();
        final Integer financialYearBeginningMonth = this.configurationDomainService
                .retrieveFinancialYearBeginningMonth();

        final Map<String, Object> changes = new LinkedHashMap<>(20);

        final RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler
                .assembleFrom(accountId, DepositAccountType.RECURRING_DEPOSIT);
        checkClientOrGroupActive(account);
        account.modifyApplication(command, changes);
        account.validateNewApplicationState(DateUtils.getLocalDateOfTenant(),
                DepositAccountType.RECURRING_DEPOSIT.resourceName());

        if (!changes.isEmpty()) {
            updateFDAndRDCommonChanges(changes, command, account);
            final MathContext mc = MathContext.DECIMAL64;
            final CalendarInstance calendarInstance = this.calendarInstanceRepository
                    .findByEntityIdAndEntityTypeIdAndCalendarTypeId(accountId,
                            CalendarEntityType.SAVINGS.getValue(), CalendarType.COLLECTION.getValue());
            final Calendar calendar = calendarInstance.getCalendar();
            final PeriodFrequencyType frequencyType = CalendarFrequencyType
                    .from(CalendarUtils.getFrequency(calendar.getRecurrence()));
            Integer frequency = CalendarUtils.getInterval(calendar.getRecurrence());
            frequency = frequency == -1 ? 1 : frequency;
            account.generateSchedule(frequencyType, frequency, calendar);
            final boolean isPreMatureClosure = false;
            account.updateMaturityDateAndAmount(mc, isPreMatureClosure,
                    isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);
            account.validateApplicableInterestRate();
            this.savingAccountRepository.save(account);

        }

        // update calendar details
        if (!account.isCalendarInherited()) {
            final LocalDate calendarStartDate = account.depositStartDate();
            final Integer frequencyType = command
                    .integerValueSansLocaleOfParameterNamed(recurringFrequencyTypeParamName);
            final PeriodFrequencyType periodFrequencyType = PeriodFrequencyType.fromInt(frequencyType);
            final Integer frequency = command
                    .integerValueSansLocaleOfParameterNamed(recurringFrequencyParamName);
            final Integer repeatsOnDay = calendarStartDate.getDayOfWeek();

            CalendarInstance calendarInstance = this.calendarInstanceRepository
                    .findByEntityIdAndEntityTypeIdAndCalendarTypeId(accountId,
                            CalendarEntityType.SAVINGS.getValue(), CalendarType.COLLECTION.getValue());
            Calendar calendar = calendarInstance.getCalendar();
            calendar.updateRepeatingCalendar(calendarStartDate, CalendarFrequencyType.from(periodFrequencyType),
                    frequency, repeatsOnDay);
            this.calendarInstanceRepository.save(calendarInstance);
        }

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(accountId) //
                .withOfficeId(account.officeId()) //
                .withClientId(account.clientId()) //
                .withGroupId(account.groupId()) //
                .withSavingsId(accountId) //
                .with(changes) //
                .build();
    } catch (final DataAccessException dve) {
        handleDataIntegrityIssues(command, dve);
        return new CommandProcessingResult(Long.valueOf(-1));
    }
}

From source file:org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Override
public SavingsAccountTransaction initiateSavingsTransfer(final Long accountId, final LocalDate transferDate) {

    AppUser user = getAppUserIfPresent();

    final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService
            .isSavingsInterestPostingAtCurrentPeriodEnd();
    final Integer financialYearBeginningMonth = this.configurationDomainService
            .retrieveFinancialYearBeginningMonth();

    final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(accountId);

    final Set<Long> existingTransactionIds = new HashSet<>();
    final Set<Long> existingReversedTransactionIds = new HashSet<>();
    updateExistingTransactionsDetails(savingsAccount, existingTransactionIds, existingReversedTransactionIds);

    final SavingsAccountTransaction newTransferTransaction = SavingsAccountTransaction
            .initiateTransfer(savingsAccount, savingsAccount.office(), transferDate, user);
    savingsAccount.getTransactions().add(newTransferTransaction);
    savingsAccount.setStatus(SavingsAccountStatusType.TRANSFER_IN_PROGRESS.getValue());
    final MathContext mc = MathContext.DECIMAL64;
    boolean isInterestTransfer = false;
    savingsAccount.calculateInterestUsing(mc, transferDate, isInterestTransfer,
            isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);

    this.savingsAccountTransactionRepository.save(newTransferTransaction);
    this.savingAccountRepository.save(savingsAccount);

    postJournalEntries(savingsAccount, existingTransactionIds, existingReversedTransactionIds);

    return newTransferTransaction;
}

From source file:org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Override
public SavingsAccountTransaction withdrawSavingsTransfer(final Long accountId, final LocalDate transferDate) {

    AppUser user = getAppUserIfPresent();

    final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService
            .isSavingsInterestPostingAtCurrentPeriodEnd();
    final Integer financialYearBeginningMonth = this.configurationDomainService
            .retrieveFinancialYearBeginningMonth();

    final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(accountId);

    final Set<Long> existingTransactionIds = new HashSet<>();
    final Set<Long> existingReversedTransactionIds = new HashSet<>();
    updateExistingTransactionsDetails(savingsAccount, existingTransactionIds, existingReversedTransactionIds);

    final SavingsAccountTransaction withdrawtransferTransaction = SavingsAccountTransaction
            .withdrawTransfer(savingsAccount, savingsAccount.office(), transferDate, user);
    savingsAccount.getTransactions().add(withdrawtransferTransaction);
    savingsAccount.setStatus(SavingsAccountStatusType.ACTIVE.getValue());
    final MathContext mc = MathContext.DECIMAL64;
    boolean isInterestTransfer = false;
    savingsAccount.calculateInterestUsing(mc, transferDate, isInterestTransfer,
            isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);

    this.savingsAccountTransactionRepository.save(withdrawtransferTransaction);
    this.savingAccountRepository.save(savingsAccount);

    postJournalEntries(savingsAccount, existingTransactionIds, existingReversedTransactionIds);

    return withdrawtransferTransaction;
}

From source file:org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Override
public SavingsAccountTransaction acceptSavingsTransfer(final Long accountId, final LocalDate transferDate,
        final Office acceptedInOffice, final Staff fieldOfficer) {

    AppUser user = getAppUserIfPresent();

    final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService
            .isSavingsInterestPostingAtCurrentPeriodEnd();
    final Integer financialYearBeginningMonth = this.configurationDomainService
            .retrieveFinancialYearBeginningMonth();

    final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(accountId);

    final Set<Long> existingTransactionIds = new HashSet<>();
    final Set<Long> existingReversedTransactionIds = new HashSet<>();
    updateExistingTransactionsDetails(savingsAccount, existingTransactionIds, existingReversedTransactionIds);

    final SavingsAccountTransaction acceptTransferTransaction = SavingsAccountTransaction
            .approveTransfer(savingsAccount, acceptedInOffice, transferDate, user);
    savingsAccount.getTransactions().add(acceptTransferTransaction);
    savingsAccount.setStatus(SavingsAccountStatusType.ACTIVE.getValue());
    if (fieldOfficer != null) {
        savingsAccount.reassignSavingsOfficer(fieldOfficer, transferDate);
    }/* www . j  a v  a 2  s.  c om*/
    boolean isInterestTransfer = false;
    final MathContext mc = MathContext.DECIMAL64;
    savingsAccount.calculateInterestUsing(mc, transferDate, isInterestTransfer,
            isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);

    this.savingsAccountTransactionRepository.save(acceptTransferTransaction);
    this.savingAccountRepository.save(savingsAccount);

    postJournalEntries(savingsAccount, existingTransactionIds, existingReversedTransactionIds);

    return acceptTransferTransaction;
}

From source file:org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*  www.  j a v a  2s  . c  o  m*/
public CommandProcessingResult waiveCharge(final Long savingsAccountId, final Long savingsAccountChargeId) {

    AppUser user = getAppUserIfPresent();

    final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService
            .isSavingsInterestPostingAtCurrentPeriodEnd();
    final Integer financialYearBeginningMonth = this.configurationDomainService
            .retrieveFinancialYearBeginningMonth();

    final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository
            .findOneWithNotFoundDetection(savingsAccountChargeId, savingsAccountId);

    // Get Savings account from savings charge
    final SavingsAccount account = savingsAccountCharge.savingsAccount();
    this.savingAccountAssembler.assignSavingAccountHelpers(account);

    final Set<Long> existingTransactionIds = new HashSet<>();
    final Set<Long> existingReversedTransactionIds = new HashSet<>();
    updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);

    account.waiveCharge(savingsAccountChargeId, user);
    boolean isInterestTransfer = false;
    final MathContext mc = MathContext.DECIMAL64;
    if (account.isBeforeLastPostingPeriod(savingsAccountCharge.getDueLocalDate())) {
        final LocalDate today = DateUtils.getLocalDateOfTenant();
        account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd,
                financialYearBeginningMonth);
    } else {
        final LocalDate today = DateUtils.getLocalDateOfTenant();
        account.calculateInterestUsing(mc, today, isInterestTransfer,
                isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);
    }
    List<DepositAccountOnHoldTransaction> depositAccountOnHoldTransactions = null;
    if (account.getOnHoldFunds().compareTo(BigDecimal.ZERO) == 1) {
        depositAccountOnHoldTransactions = this.depositAccountOnHoldTransactionRepository
                .findBySavingsAccountAndReversedFalseOrderByCreatedDateAsc(account);
    }

    account.validateAccountBalanceDoesNotBecomeNegative(SavingsApiConstants.waiveChargeTransactionAction,
            depositAccountOnHoldTransactions);

    this.savingAccountRepository.saveAndFlush(account);

    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);

    return new CommandProcessingResultBuilder() //
            .withEntityId(savingsAccountChargeId) //
            .withOfficeId(account.officeId()) //
            .withClientId(account.clientId()) //
            .withGroupId(account.groupId()) //
            .withSavingsId(savingsAccountId) //
            .build();
}

From source file:org.apache.fineract.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Transactional
private void payCharge(final SavingsAccountCharge savingsAccountCharge, final LocalDate transactionDate,
        final BigDecimal amountPaid, final DateTimeFormatter formatter, final AppUser user) {

    final boolean isSavingsInterestPostingAtCurrentPeriodEnd = this.configurationDomainService
            .isSavingsInterestPostingAtCurrentPeriodEnd();
    final Integer financialYearBeginningMonth = this.configurationDomainService
            .retrieveFinancialYearBeginningMonth();

    // Get Savings account from savings charge
    final SavingsAccount account = savingsAccountCharge.savingsAccount();
    this.savingAccountAssembler.assignSavingAccountHelpers(account);
    final Set<Long> existingTransactionIds = new HashSet<>();
    final Set<Long> existingReversedTransactionIds = new HashSet<>();
    updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);
    account.payCharge(savingsAccountCharge, amountPaid, transactionDate, formatter, user);
    boolean isInterestTransfer = false;
    final MathContext mc = MathContext.DECIMAL64;
    if (account.isBeforeLastPostingPeriod(transactionDate)) {
        final LocalDate today = DateUtils.getLocalDateOfTenant();
        account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd,
                financialYearBeginningMonth);
    } else {//from  ww  w .j  a va 2 s  .  c om
        final LocalDate today = DateUtils.getLocalDateOfTenant();
        account.calculateInterestUsing(mc, today, isInterestTransfer,
                isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);
    }
    List<DepositAccountOnHoldTransaction> depositAccountOnHoldTransactions = null;
    if (account.getOnHoldFunds().compareTo(BigDecimal.ZERO) == 1) {
        depositAccountOnHoldTransactions = this.depositAccountOnHoldTransactionRepository
                .findBySavingsAccountAndReversedFalseOrderByCreatedDateAsc(account);
    }

    account.validateAccountBalanceDoesNotBecomeNegative(
            "." + SavingsAccountTransactionType.PAY_CHARGE.getCode(), depositAccountOnHoldTransactions);

    this.savingAccountRepository.save(account);

    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);
}

From source file:org.apache.hive.storage.jdbc.spitter.DecimalIntervalSplitter.java

@Override
public List<MutablePair<String, String>> getIntervals(String lowerBound, String upperBound, int numPartitions,
        TypeInfo typeInfo) {//from  w w w.j  ava2s. c o  m
    List<MutablePair<String, String>> intervals = new ArrayList<>();
    DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) typeInfo;
    int scale = decimalTypeInfo.getScale();
    BigDecimal decimalLower = new BigDecimal(lowerBound);
    BigDecimal decimalUpper = new BigDecimal(upperBound);
    BigDecimal decimalInterval = (decimalUpper.subtract(decimalLower)).divide(new BigDecimal(numPartitions),
            MathContext.DECIMAL64);
    BigDecimal splitDecimalLower, splitDecimalUpper;
    for (int i = 0; i < numPartitions; i++) {
        splitDecimalLower = decimalLower.add(decimalInterval.multiply(new BigDecimal(i))).setScale(scale,
                RoundingMode.HALF_EVEN);
        splitDecimalUpper = decimalLower.add(decimalInterval.multiply(new BigDecimal(i + 1))).setScale(scale,
                RoundingMode.HALF_EVEN);
        if (splitDecimalLower.compareTo(splitDecimalUpper) < 0) {
            intervals.add(new MutablePair<String, String>(splitDecimalLower.toPlainString(),
                    splitDecimalUpper.toPlainString()));
        }
    }
    return intervals;
}

From source file:org.estatio.dom.lease.invoicing.InvoiceCalculationService.java

/**
 * Calculates a term with a given invoicing frequency
 *///  ww w.j  av a 2 s  .  co m
@Programmatic
public List<CalculationResult> calculateDueDateRange(final LeaseTerm leaseTerm,
        final InvoiceCalculationParameters parameters) {
    final List<CalculationResult> results = Lists.newArrayList();
    final LocalDateInterval termInterval = leaseTerm.getEffectiveInterval();
    final LocalDateInterval rangeInterval = parameters.invoiceRunType().equals(InvoiceRunType.RETRO_RUN)
            && leaseTerm.getLeaseItem().getLease().getStartDate()
                    .compareTo(parameters.dueDateRange().startDate()) < 0
                            ? new LocalDateInterval(leaseTerm.getLeaseItem().getLease().getStartDate(),
                                    parameters.dueDateRange().endDateExcluding(),
                                    IntervalEnding.EXCLUDING_END_DATE)
                            : parameters.dueDateRange();
    final InvoicingFrequency invoicingFrequency = leaseTerm.getLeaseItem().getInvoicingFrequency();
    // TODO: As a result of EST-413 the check for 'termInterval != null &&
    // termInterval.isValid()' is removed because this is blocking the
    // calculation of periods outside the interval of the leases. As a
    // result the invoice calculation will be more eager so improving
    // performance, EST-315, should get some attention.
    if (rangeInterval.isValid()) {
        final List<InvoicingInterval> intervals = invoicingFrequency.intervalsInDueDateRange(rangeInterval,
                termInterval);
        for (final InvoicingInterval invoicingInterval : intervals) {
            final LocalDateInterval effectiveInterval = invoicingInterval.asLocalDateInterval()
                    .overlap(termInterval);
            if (effectiveInterval == null) {
                results.add(new CalculationResult(invoicingInterval));
            } else {
                final BigDecimal overlapDays = new BigDecimal(effectiveInterval.days());
                final BigDecimal frequencyDays = new BigDecimal(invoicingInterval.days());
                final BigDecimal rangeFactor = leaseTerm.valueType().equals(LeaseTermValueType.FIXED)
                        ? BigDecimal.ONE
                        : overlapDays.divide(frequencyDays, MathContext.DECIMAL64);
                final BigDecimal annualFactor = invoicingFrequency.annualMultiplier();
                final LocalDate epochDate = ObjectUtils.firstNonNull(leaseTerm.getLeaseItem().getEpochDate(),
                        systemEpochDate());
                BigDecimal mockValue = BigDecimal.ZERO;
                if (epochDate != null && invoicingInterval.dueDate().isBefore(epochDate)) {
                    mockValue = leaseTerm.valueForDate(epochDate);
                }
                results.add(new CalculationResult(invoicingInterval, effectiveInterval,
                        calculateValue(rangeFactor, annualFactor,
                                leaseTerm.valueForDate(
                                        parameters.dueDateRange().endDateExcluding().minusDays(1))),
                        calculateValue(rangeFactor, annualFactor,
                                leaseTerm.valueForDate(invoicingInterval.dueDate())),
                        calculateValue(rangeFactor, annualFactor, mockValue)));
            }
        }
    }
    return results;
}

From source file:org.goko.core.common.measure.quantity.AbstractQuantity.java

/** (inheritDoc)
 * @see org.goko.core.common.measure.quantity.Quantity#divide(java.lang.Number)
 *///from  ww w .  ja  va  2s . c o  m
@Override
public Q divide(BigDecimal n) {
    return createQuantity(value.divide(n, MathContext.DECIMAL64), unit);
}

From source file:org.goko.core.common.measure.quantity.AbstractQuantity.java

/** (inheritDoc)
 * @see org.goko.core.common.measure.quantity.Quantity#divide(int)
 */// ww  w. j  a  va 2 s.co m
@Override
public Q divide(int n) {
    return createQuantity(value.divide(new BigDecimal(n), MathContext.DECIMAL64), unit);
}