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:mondrian.util.UtilCompatibleJdk15.java

/**
 * This generates a BigDecimal with a precision reflecting
 * the precision of the input double.//from ww w. ja  va2 s.  c  o  m
 *
 * @param d input double
 * @return BigDecimal
 */
public BigDecimal makeBigDecimalFromDouble(double d) {
    return new BigDecimal(d, MathContext.DECIMAL64);
}

From source file:mobi.nordpos.catalog.action.ProductCreateActionBean.java

public Resolution add() {
    Product product = getProduct();/*from w ww.  j  a  va  2  s  .c  o m*/
    product.setId(UUID.randomUUID().toString());
    try {
        productPersist.init(getDataBaseConnection());
        taxPersist.init(getDataBaseConnection());
        product.setTax(taxPersist.read(product.getTaxCategory().getId()));
        BigDecimal taxRate = product.getTax().getRate();

        if (getIsTaxInclude() && taxRate != BigDecimal.ZERO) {
            BigDecimal bdTaxRateMultiply = taxRate.add(BigDecimal.ONE);
            product.setPriceSell(product.getPriceSell().divide(bdTaxRateMultiply, MathContext.DECIMAL64));
        }

        getContext().getMessages().add(new SimpleMessage(getLocalizationKey("message.Product.added"),
                productPersist.add(product).getName(), product.getProductCategory().getName()));
    } catch (SQLException ex) {
        getContext().getValidationErrors().addGlobalError(new SimpleError(ex.getMessage()));
        return getContext().getSourcePageResolution();
    }
    return new ForwardResolution(CategoryProductListActionBean.class).addParameter("category.id",
            product.getProductCategory().getId());
}

From source file:com.aan.girsang.server.service.impl.TransaksiServiceImpl.java

@Transactional(isolation = Isolation.SERIALIZABLE)
@Override//from  ww w .  j a v  a 2s .  co m
public void simpan(Pembelian p) {
    Pembelian pembelian = pembelianDao.cariId(p.getNoRef());
    if (pembelian == null) {
        p.setNoRef(runningNumberTransaksiDao.ambilBerikutnyaDanSimpan(TransaksiRunningNumberEnum.PEMBELIAN));
        int i = 1;
        for (PembelianDetail detail : p.getPembelianDetails()) {
            detail.setId(p.getNoRef() + i++);
        }
    } else {
        int i = 1;
        for (PembelianDetail detail : p.getPembelianDetails()) {
            try {
                i++;
                if (detail.getId() == null) {
                    detail.setId(p.getNoRef() + i++);
                }
            } catch (Exception e) {
                i = i + 1;
                if (detail.getId() == null) {
                    detail.setId(p.getNoRef() + i++);
                }
            }
            if (detail.getId() == null) {
                detail.setId(p.getNoRef() + i++);
            }
        }
    }
    //update barang
    //<editor-fold defaultstate="collapsed" desc="Update Barang">
    for (PembelianDetail detail : p.getPembelianDetails()) {

        Barang b = barangDao.cariId(detail.getBarang().getPlu());
        if (detail.getUpdate() == true) {
            Double hargaBeli = Double.valueOf(TextComponentUtils
                    .getValueFromTextNumber(TextComponentUtils.formatNumber(detail.getHargaBarang())));
            Double isi = Double.valueOf(detail.getIsiPembelian());//harga beli di bagi isi
            Double hargaSatuan = hargaBeli / isi;
            BigDecimal hS = new BigDecimal(hargaSatuan, MathContext.DECIMAL64);
            b.setSatuanPembelian(detail.getSatuanPembelian());
            b.setHargaBeli(BigDecimal.valueOf(hargaSatuan));
            b.setIsiPembelian(detail.getIsiPembelian());

            //Simpan HPP Barang
            HPPBarang hPPBarang = new HPPBarang();
            hPPBarang.setIdHpp(runningNumberDao.ambilBerikutnyaDanSimpan(MasterRunningNumberEnum.HPP));
            hPPBarang.setTanggal(detail.getPembelian().getTanggal());
            hPPBarang.setBarang(b);
            hPPBarang.setHpp(detail.getHargaBarang());
            hPPBarang.setIsi(detail.getIsiPembelian());
            hPPBarang.setHppSatuan(BigDecimal.valueOf(hargaSatuan));

            barangDao.simpan(b);
            hPPDao.simpan(hPPBarang);
        }

    }
    //</editor-fold>
    pembelianDao.merge(p);
    simpanStokPembelian(p);
    simpanHutang();
}

From source file:com.inc.playground.playground.utils.NetworkUtilities.java

public static Double calculateDistance2(double originLon, double originLat, double distanceLon,
        double distanceLat) {
    final HttpResponse resp;

    BigDecimal originLon_tune_bg = new BigDecimal(originLon, MathContext.DECIMAL64);
    BigDecimal originLat_tune_bg = new BigDecimal(originLat, MathContext.DECIMAL64);
    BigDecimal distanceLon_tune_bg = new BigDecimal(distanceLon, MathContext.DECIMAL64);
    BigDecimal distanceLat_tune_bg = new BigDecimal(distanceLat, MathContext.DECIMAL64);

    String str_originLon_tune = (originLon_tune_bg + "").substring(0, 6);
    String str_originLat_tune = (originLat_tune_bg + "").substring(0, 6);
    String str_distanceLon_tune = (distanceLon_tune_bg + "").substring(0, 6);
    String str_distanceLat_tune = (distanceLat_tune_bg + "").substring(0, 6);

    /*/*from   w  w w  .  j a  v  a2 s . com*/
            String originLon_tune = String.format("%.3f", ( originLon));
            String originLat_tune =  String.format("%.3f", (originLat));
            String distanceLon_tune =String.format("%.3f", (distanceLon));
            String distanceLat_tune =String.format("%.3f", (distanceLat)) ;
    */

    String apiUrl = Constants.apiGetDistanceUrl.replace("X1", str_originLon_tune);
    apiUrl = apiUrl.replace("Y1", str_originLat_tune);
    apiUrl = apiUrl.replace("X2", str_distanceLon_tune);
    apiUrl = apiUrl.replace("Y2", str_distanceLat_tune);
    apiUrl = apiUrl.replace("APIKEY", Constants.apiKey);
    HttpGet http_client = new HttpGet(apiUrl);

    try {
        resp = getHttpClient().execute(http_client);
        String resopnseString = "";
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            InputStream istream = (resp.getEntity() != null) ? resp.getEntity().getContent() : null;
            if (istream != null) {
                BufferedReader ireader = new BufferedReader(new InputStreamReader(istream));
                String buf;
                while ((buf = ireader.readLine()) != null) {
                    resopnseString += buf;
                }
            }
        }
        if ((resopnseString != null) && (resopnseString.length() > 0)) {
            Log.v(TAG, "Successful authentication");
            Log.i(TAG, resopnseString);//resopnseString = "{"
            JSONObject convertedResponse = new JSONObject(resopnseString); //"{"
            Double distanceKm = new Double((convertedResponse.getJSONObject("rows").getJSONObject("elements")
                    .getJSONObject("distance").getInt("value")) / 1000);
            return distanceKm;

        } else {
            Log.e(TAG, "Error authenticating" + resp.getStatusLine());
            return null;
        }
    } catch (final IOException e) {
        Log.e(TAG, "IOException when getting authtoken", e);
        return null;
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return 2.0;
}

From source file:com.hotelbeds.hotelapimodel.auto.util.AssignUtils.java

public static BigDecimal safeBigDecimal(final String number, final int newScale) {
    BigDecimal result = null;//from ww w.ja v  a  2s.c om
    if (StringUtils.isNotEmpty(number)) {
        result = new BigDecimal(number, MathContext.DECIMAL64).setScale(newScale, BigDecimal.ROUND_HALF_EVEN);
    }
    return result;
}

From source file:com.gst.portfolio.savings.service.DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from  w  w  w  .j  a va 2s  . c  o  m*/
public CommandProcessingResult submitFDApplication(final JsonCommand command) {
    try {
        this.depositAccountDataValidator.validateFixedDepositForSubmit(command.json());
        final AppUser submittedBy = this.context.authenticatedUser();

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

        final FixedDepositAccount account = (FixedDepositAccount) this.depositAccountAssembler
                .assembleFrom(command, submittedBy, DepositAccountType.FIXED_DEPOSIT);

        final MathContext mc = MathContext.DECIMAL64;
        final boolean isPreMatureClosure = false;

        account.updateMaturityDateAndAmountBeforeAccountActivation(mc, isPreMatureClosure,
                isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);
        this.fixedDepositAccountRepository.save(account);

        if (account.isAccountNumberRequiresAutoGeneration()) {
            AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository
                    .findByAccountType(EntityAccountType.CLIENT);
            account.updateAccountNo(this.accountNumberGenerator.generate(account, accountNumberFormat));

            this.savingAccountRepository.save(account);
        }

        // Save linked account information
        final Long savingsAccountId = command
                .longValueOfParameterNamed(DepositsApiConstants.linkedAccountParamName);
        if (savingsAccountId != null) {
            final SavingsAccount savingsAccount = this.depositAccountAssembler.assembleFrom(savingsAccountId,
                    DepositAccountType.SAVINGS_DEPOSIT);
            this.depositAccountDataValidator.validatelinkedSavingsAccount(savingsAccount, account);
            boolean isActive = true;
            final AccountAssociations accountAssociations = AccountAssociations.associateSavingsAccount(account,
                    savingsAccount, AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue(), isActive);
            this.accountAssociationsRepository.save(accountAssociations);
        }

        final Long savingsId = account.getId();

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(savingsId) //
                .withOfficeId(account.officeId()) //
                .withClientId(account.clientId()) //
                .withGroupId(account.groupId()) //
                .withSavingsId(savingsId) //
                .build();
    } catch (final DataAccessException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.gst.portfolio.savings.service.DepositAccountWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*from www.  jav a 2  s.c  o  m*/
public CommandProcessingResult activateFDAccount(final Long savingsId, final JsonCommand command) {

    final AppUser user = this.context.authenticatedUser();

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

    this.depositAccountTransactionDataValidator.validateActivation(command);
    final MathContext mc = MathContext.DECIMAL64;
    final FixedDepositAccount account = (FixedDepositAccount) this.depositAccountAssembler
            .assembleFrom(savingsId, DepositAccountType.FIXED_DEPOSIT);
    checkClientOrGroupActive(account);

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

    final Map<String, Object> changes = account.activate(user, command, DateUtils.getLocalDateOfTenant());

    if (!changes.isEmpty()) {
        final Locale locale = command.extractLocale();
        final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
        Money amountForDeposit = account.activateWithBalance();
        if (amountForDeposit.isGreaterThanZero()) {

            final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService
                    .retriveSavingsLinkedAssociation(savingsId);

            if (portfolioAccountData == null) {
                final PaymentDetail paymentDetail = null;
                this.depositAccountDomainService.handleFDDeposit(account, fmt, account.getActivationLocalDate(),
                        amountForDeposit.getAmount(), paymentDetail);
            } else {
                final SavingsAccount fromSavingsAccount = null;
                boolean isRegularTransaction = false;
                final boolean isExceptionForBalanceCheck = false;
                final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(
                        account.getActivationLocalDate(), amountForDeposit.getAmount(),
                        PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS,
                        portfolioAccountData.accountId(), account.getId(), "Account Transfer", locale, fmt,
                        null, null, null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null,
                        null, null, null, account, fromSavingsAccount, isRegularTransaction,
                        isExceptionForBalanceCheck);
                this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO);
            }
            final boolean isInterestTransfer = false;
            final LocalDate postInterestOnDate = null;
            if (account.isBeforeLastPostingPeriod(account.getActivationLocalDate())) {
                final LocalDate today = DateUtils.getLocalDateOfTenant();
                account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd,
                        financialYearBeginningMonth, postInterestOnDate);
            } else {
                final LocalDate today = DateUtils.getLocalDateOfTenant();
                account.calculateInterestUsing(mc, today, isInterestTransfer,
                        isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth,
                        postInterestOnDate);
            }

            updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);
        }

        final boolean isPreMatureClosure = false;
        account.updateMaturityDateAndAmount(mc, isPreMatureClosure, isSavingsInterestPostingAtCurrentPeriodEnd,
                financialYearBeginningMonth);
        List<DepositAccountOnHoldTransaction> depositAccountOnHoldTransactions = null;
        if (account.getOnHoldFunds().compareTo(BigDecimal.ZERO) == 1) {
            depositAccountOnHoldTransactions = this.depositAccountOnHoldTransactionRepository
                    .findBySavingsAccountAndReversedFalseOrderByCreatedDateAsc(account);
        }
        account.validateAccountBalanceDoesNotBecomeNegative(SavingsAccountTransactionType.PAY_CHARGE.name(),
                depositAccountOnHoldTransactions);
        this.savingAccountRepositoryWrapper.saveAndFlush(account);
    }

    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);

    return new CommandProcessingResultBuilder() //
            .withEntityId(savingsId) //
            .withOfficeId(account.officeId()) //
            .withClientId(account.clientId()) //
            .withGroupId(account.groupId()) //
            .withSavingsId(savingsId) //
            .with(changes) //
            .build();
}

From source file:com.gst.portfolio.savings.service.DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*w w w .  j a va  2s  .co m*/
public CommandProcessingResult submitRDApplication(final JsonCommand command) {
    try {
        this.depositAccountDataValidator.validateRecurringDepositForSubmit(command.json());
        final AppUser submittedBy = this.context.authenticatedUser();

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

        final RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler
                .assembleFrom(command, submittedBy, DepositAccountType.RECURRING_DEPOSIT);

        this.recurringDepositAccountRepository.save(account);

        if (account.isAccountNumberRequiresAutoGeneration()) {
            final AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository
                    .findByAccountType(EntityAccountType.SAVINGS);
            account.updateAccountNo(this.accountNumberGenerator.generate(account, accountNumberFormat));
        }

        final Long savingsId = account.getId();
        final CalendarInstance calendarInstance = getCalendarInstance(command, account);
        this.calendarInstanceRepository.save(calendarInstance);

        // FIXME: Avoid save separately (Calendar instance requires account
        // details)
        final MathContext mc = MathContext.DECIMAL64;
        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);

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(savingsId) //
                .withOfficeId(account.officeId()) //
                .withClientId(account.clientId()) //
                .withGroupId(account.groupId()) //
                .withSavingsId(savingsId) //
                .build();
    } catch (final DataAccessException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.gst.portfolio.savings.service.DepositAccountWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*  w  ww  .ja  v a2  s .co m*/
public CommandProcessingResult activateRDAccount(final Long savingsId, final JsonCommand command) {
    boolean isRegularTransaction = false;

    final AppUser user = this.context.authenticatedUser();

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

    this.depositAccountTransactionDataValidator.validateActivation(command);

    final RecurringDepositAccount account = (RecurringDepositAccount) this.depositAccountAssembler
            .assembleFrom(savingsId, DepositAccountType.RECURRING_DEPOSIT);
    checkClientOrGroupActive(account);

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

    final Map<String, Object> changes = account.activate(user, command, DateUtils.getLocalDateOfTenant());

    if (!changes.isEmpty()) {
        final Locale locale = command.extractLocale();
        final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
        Money amountForDeposit = account.activateWithBalance();
        if (amountForDeposit.isGreaterThanZero()) {
            final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService
                    .retriveSavingsLinkedAssociation(savingsId);
            if (portfolioAccountData == null) {
                this.depositAccountDomainService.handleRDDeposit(account, fmt, account.getActivationLocalDate(),
                        amountForDeposit.getAmount(), null, isRegularTransaction);
            } else {
                final boolean isExceptionForBalanceCheck = false;
                final SavingsAccount fromSavingsAccount = null;
                final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(
                        account.getActivationLocalDate(), amountForDeposit.getAmount(),
                        PortfolioAccountType.SAVINGS, PortfolioAccountType.SAVINGS,
                        portfolioAccountData.accountId(), account.getId(), "Account Transfer", locale, fmt,
                        null, null, null, null, null, AccountTransferType.ACCOUNT_TRANSFER.getValue(), null,
                        null, null, null, account, fromSavingsAccount, isRegularTransaction,
                        isExceptionForBalanceCheck);
                this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO);
            }
            updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);
        }

        final MathContext mc = MathContext.DECIMAL64;

        // submitted and activation date are different then recalculate
        // maturity date and schedule
        if (!account.accountSubmittedAndActivationOnSameDate()) {
            final boolean isPreMatureClosure = false;
            final CalendarInstance calendarInstance = this.calendarInstanceRepository
                    .findByEntityIdAndEntityTypeIdAndCalendarTypeId(savingsId,
                            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);
            account.updateMaturityDateAndAmount(mc, isPreMatureClosure,
                    isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);
        }

        final LocalDate overdueUptoDate = DateUtils.getLocalDateOfTenant();
        account.updateOverduePayments(overdueUptoDate);
        final boolean isInterestTransfer = false;
        final LocalDate postInterestOnDate = null;
        if (account.isBeforeLastPostingPeriod(account.getActivationLocalDate())) {
            final LocalDate today = DateUtils.getLocalDateOfTenant();
            account.postInterest(mc, today, isInterestTransfer, isSavingsInterestPostingAtCurrentPeriodEnd,
                    financialYearBeginningMonth, postInterestOnDate);
        } else {
            final LocalDate today = DateUtils.getLocalDateOfTenant();
            account.calculateInterestUsing(mc, today, isInterestTransfer,
                    isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth,
                    postInterestOnDate);
        }
        List<DepositAccountOnHoldTransaction> depositAccountOnHoldTransactions = null;
        if (account.getOnHoldFunds().compareTo(BigDecimal.ZERO) == 1) {
            depositAccountOnHoldTransactions = this.depositAccountOnHoldTransactionRepository
                    .findBySavingsAccountAndReversedFalseOrderByCreatedDateAsc(account);
        }

        account.validateAccountBalanceDoesNotBecomeNegative(SavingsAccountTransactionType.PAY_CHARGE.name(),
                depositAccountOnHoldTransactions);

        this.savingAccountRepositoryWrapper.saveAndFlush(account);
    }

    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);

    return new CommandProcessingResultBuilder() //
            .withEntityId(savingsId) //
            .withOfficeId(account.officeId()) //
            .withClientId(account.clientId()) //
            .withGroupId(account.groupId()) //
            .withSavingsId(savingsId) //
            .with(changes) //
            .build();
}

From source file:com.gst.portfolio.savings.service.DepositApplicationProcessWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override// ww  w  .ja  va2  s.c o  m
public CommandProcessingResult modifyFDApplication(final Long accountId, final JsonCommand command) {
    try {
        this.depositAccountDataValidator.validateFixedDepositForUpdate(command.json());

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

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

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

        if (!changes.isEmpty()) {
            updateFDAndRDCommonChanges(changes, command, account);
            final MathContext mc = MathContext.DECIMAL64;
            final boolean isPreMatureClosure = false;
            account.updateMaturityDateAndAmountBeforeAccountActivation(mc, isPreMatureClosure,
                    isSavingsInterestPostingAtCurrentPeriodEnd, financialYearBeginningMonth);
            this.savingAccountRepository.save(account);
        }

        boolean isLinkedAccRequired = command
                .booleanPrimitiveValueOfParameterNamed(transferInterestToSavingsParamName);

        // Save linked account information
        final Long savingsAccountId = command
                .longValueOfParameterNamed(DepositsApiConstants.linkedAccountParamName);
        AccountAssociations accountAssociations = this.accountAssociationsRepository.findBySavingsIdAndType(
                accountId, AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue());
        if (savingsAccountId == null) {
            if (accountAssociations != null) {
                if (this.fromJsonHelper.parameterExists(DepositsApiConstants.linkedAccountParamName,
                        command.parsedJson())) {
                    this.accountAssociationsRepository.delete(accountAssociations);
                    changes.put(DepositsApiConstants.linkedAccountParamName, null);
                    if (isLinkedAccRequired) {
                        this.depositAccountDataValidator.throwLinkedAccountRequiredError();
                    }
                }
            } else if (isLinkedAccRequired) {
                this.depositAccountDataValidator.throwLinkedAccountRequiredError();
            }
        } else {
            boolean isModified = false;
            if (accountAssociations == null) {
                isModified = true;
            } else {
                final SavingsAccount savingsAccount = accountAssociations.linkedSavingsAccount();
                if (savingsAccount == null || savingsAccount.getId() != savingsAccountId) {
                    isModified = true;
                }
            }
            if (isModified) {
                final SavingsAccount savingsAccount = this.depositAccountAssembler
                        .assembleFrom(savingsAccountId, DepositAccountType.SAVINGS_DEPOSIT);
                this.depositAccountDataValidator.validatelinkedSavingsAccount(savingsAccount, account);
                if (accountAssociations == null) {
                    boolean isActive = true;
                    accountAssociations = AccountAssociations.associateSavingsAccount(account, savingsAccount,
                            AccountAssociationType.LINKED_ACCOUNT_ASSOCIATION.getValue(), isActive);
                } else {
                    accountAssociations.updateLinkedSavingsAccount(savingsAccount);
                }
                changes.put(DepositsApiConstants.linkedAccountParamName, savingsAccountId);
                this.accountAssociationsRepository.save(accountAssociations);
            }
        }

        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.getMostSpecificCause(), dve);
        return new CommandProcessingResult(Long.valueOf(-1));
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return new CommandProcessingResult(Long.valueOf(-1));
    }
}