Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

In this page you can find the example usage for java.math BigDecimal compareTo.

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:ejb.session.loan.LoanPaymentSessionBean.java

@Override
public String loanRepaymentFromAccount(String loanAccountNumber, String depositAccountNumber,
        BigDecimal amount) {

    try {/* www  . j  ava  2s.c  o m*/
        DepositAccount fromAccount = depositBean.getAccountFromId(depositAccountNumber);
        LoanAccount loanAccount = loanAccountBean.getLoanAccountByAccountNumber(loanAccountNumber);
        if (fromAccount.getBalance().compareTo(amount) < 0) {
            // not enough money
            return "FAIL";
        } else {
            depositBean.transferFromAccount(fromAccount, amount);
            BigDecimal outPrin = new BigDecimal(loanAccount.getOutstandingPrincipal());
            if (amount.compareTo(outPrin) > 0) {
                return "FAIL2";
            }
            if (amount.compareTo(new BigDecimal(10000)) >= 0) {
                return "FAIL3";
            }
            loanAccountRepayment(loanAccountNumber, amount.doubleValue());
            return "SUCCESS";
        }

    } catch (DepositAccountNotFoundException e) {
        System.out
                .println("DepositAccountNotFoundException LoanRepaymentSessionBean loanRepaymentFromAccount()");
        return "FAIL0";
    }

}

From source file:com.streamsets.pipeline.stage.origin.salesforce.ForceSource.java

private String fixOffset(String offsetColumn, String offset) {
    com.sforce.soap.partner.Field sfdcField = ((SobjectRecordCreator) recordCreator)
            .getFieldMetadata(sobjectType, offsetColumn);
    if (SobjectRecordCreator.DECIMAL_TYPES.contains(sfdcField.getType().toString()) && offset.contains("E")) {
        BigDecimal val = new BigDecimal(offset);
        offset = val.toPlainString();
        if (val.compareTo(MAX_OFFSET_INT) > 0 && !offset.contains(".")) {
            // We need the ".0" suffix since Salesforce doesn't like integer
            // bigger than 2147483647
            offset += ".0";
        }/*from w  w  w  .  ja  v  a  2 s  .c o  m*/
    }
    return offset;
}

From source file:nl.strohalm.cyclos.services.transactions.InvoiceServiceImpl.java

private Validator getValidator(final Invoice invoice) {
    final Validator validator = new Validator("invoice");
    validator.property("from").required();
    validator.property("to").add(new PropertyValidation() {
        private static final long serialVersionUID = -5222363482447066104L;

        @Override/*from  www.  j  a  va 2  s. com*/
        public ValidationError validate(final Object object, final Object name, final Object value) {
            final Invoice invoice = (Invoice) object;
            // Can't be the same from / to
            if (invoice.getFrom() != null && invoice.getTo() != null
                    && invoice.getFrom().equals(invoice.getTo())) {
                return new InvalidError();
            }
            return null;
        }
    });
    validator.property("description").required().maxLength(1000);
    validator.property("amount").required().positiveNonZero();

    if (LoggedUser.hasUser()) {
        final boolean asMember = !LoggedUser.accountOwner().equals(invoice.getFrom());
        if (asMember || LoggedUser.isMember() || LoggedUser.isOperator()) {
            validator.property("destinationAccountType").required();
        } else {
            validator.property("transferType").required();
        }
    }
    validator.general(new GeneralValidation() {
        private static final long serialVersionUID = 4085922259108191939L;

        @Override
        public ValidationError validate(final Object object) {
            // Validate the scheduled payments
            final Invoice invoice = (Invoice) object;
            final List<InvoicePayment> payments = invoice.getPayments();
            if (CollectionUtils.isEmpty(payments)) {
                return null;
            }

            // Validate the from member
            Member fromMember = invoice.getFromMember();
            if (fromMember == null && LoggedUser.isMember()) {
                fromMember = LoggedUser.element();
            }
            Calendar maxPaymentDate = null;
            if (fromMember != null) {
                fromMember = fetchService.fetch(fromMember,
                        RelationshipHelper.nested(Element.Relationships.GROUP));
                final MemberGroup group = fromMember.getMemberGroup();

                // Validate the max payments
                final int maxSchedulingPayments = group.getMemberSettings().getMaxSchedulingPayments();
                if (payments.size() > maxSchedulingPayments) {
                    return new ValidationError("errors.greaterEquals",
                            messageResolver.message("transfer.paymentCount"), maxSchedulingPayments);
                }

                // Get the maximum payment date
                final TimePeriod maxSchedulingPeriod = group.getMemberSettings().getMaxSchedulingPeriod();
                if (maxSchedulingPeriod != null) {
                    maxPaymentDate = maxSchedulingPeriod.add(DateHelper.truncate(Calendar.getInstance()));
                }
            }

            final BigDecimal invoiceAmount = invoice.getAmount();
            final BigDecimal minimumPayment = paymentService.getMinimumPayment();
            BigDecimal totalAmount = BigDecimal.ZERO;
            Calendar lastDate = DateHelper.truncate(Calendar.getInstance());
            for (final InvoicePayment payment : payments) {
                final Calendar date = payment.getDate();

                // Validate the max payment date
                if (maxPaymentDate != null && date.after(maxPaymentDate)) {
                    final LocalSettings localSettings = settingsService.getLocalSettings();
                    final CalendarConverter dateConverter = localSettings.getRawDateConverter();
                    return new ValidationError("payment.invalid.schedulingDate",
                            dateConverter.toString(maxPaymentDate));
                }

                final BigDecimal amount = payment.getAmount();

                if (amount == null || amount.compareTo(minimumPayment) < 0) {
                    return new RequiredError(messageResolver.message("transfer.amount"));
                }
                if (date == null) {
                    return new RequiredError(messageResolver.message("transfer.date"));
                } else if (date.before(lastDate)) {
                    return new ValidationError("invoice.invalid.paymentDates");
                }
                totalAmount = totalAmount.add(amount);
                lastDate = date;
            }
            if (invoiceAmount != null && totalAmount.compareTo(invoiceAmount) != 0) {
                return new ValidationError("invoice.invalid.paymentAmount");
            }
            return null;
        }

    });

    // Custom fields
    final List<TransferType> possibleTransferTypes = getPossibleTransferTypes(invoice);
    if (possibleTransferTypes.size() == 1) {
        validator.chained(new DelegatingValidator(new DelegatingValidator.DelegateSource() {
            @Override
            public Validator getValidator() {
                final TransferType transferType = possibleTransferTypes.iterator().next();
                return paymentCustomFieldService.getValueValidator(transferType);
            }
        }));
    }

    return validator;
}

From source file:nl.strohalm.cyclos.services.accountfees.AccountFeeServiceImpl.java

@Override
public BigDecimal calculateAmount(final AccountFeeLog feeLog, final Member member) {
    AccountFee fee = feeLog.getAccountFee();

    if (!fee.getGroups().contains(member.getGroup())) {
        // The member is not affected by this fee log
        return null;
    }//from  ww  w .jav  a  2s.c om

    final Period period = feeLog.getPeriod();
    final MemberAccountType accountType = fee.getAccountType();
    final ChargeMode chargeMode = fee.getChargeMode();
    final BigDecimal freeBase = fee.getFreeBase();

    // Calculate the charge amount
    BigDecimal chargedAmount = BigDecimal.ZERO;
    BigDecimal amount = BigDecimal.ZERO;
    Calendar endDate = (period != null) ? period.getEnd() : null;
    final AccountDateDTO balanceParams = new AccountDateDTO(member, accountType, endDate);
    if (chargeMode.isFixed()) {
        boolean charge = true;
        if (freeBase != null) {
            final BigDecimal balance = accountService.getBalance(balanceParams);
            if (balance.compareTo(freeBase) <= 0) {
                charge = false;
            }
        }
        // Fixed fee amount
        if (charge) {
            amount = feeLog.getAmount();
        }
    } else if (chargeMode.isBalance()) {
        // Percentage over balance
        final boolean positiveBalance = !chargeMode.isNegative();
        BigDecimal balance = accountService.getBalance(balanceParams);
        // Skip if balance is out of range
        boolean charge = true;
        // Apply the free base
        if (freeBase != null) {
            if (positiveBalance) {
                balance = balance.subtract(freeBase);
            } else {
                balance = balance.add(freeBase);
            }
        }
        // Check if something will be charged
        if ((positiveBalance && balance.compareTo(BigDecimal.ZERO) <= 0)
                || (!positiveBalance && balance.compareTo(BigDecimal.ZERO) >= 0)) {
            charge = false;
        }
        if (charge) {
            // Get the charged amount
            chargedAmount = feeLog.getAmountValue().apply(balance.abs());
            amount = settingsService.getLocalSettings().round(chargedAmount);
        }
    } else if (chargeMode.isVolume()) {
        // Percentage over average transactioned volume
        amount = calculateChargeOverTransactionedVolume(feeLog, member);
    }

    // Ensure the amount is valid
    final BigDecimal minPayment = paymentService.getMinimumPayment();
    if (amount.compareTo(minPayment) < 0) {
        amount = BigDecimal.ZERO;
    }
    return amount;
}

From source file:ejb.session.loan.LoanPaymentSessionBean.java

@Override
public String loanLumsumPaymentFromAccount(String loanAccountNumber, String depositAccountNumber,
        BigDecimal amount) {

    try {// w  w w.j  ava  2s.  co m

        DepositAccount fromAccount = depositBean.getAccountFromId(depositAccountNumber);
        LoanAccount loanAccount = loanAccountBean.getLoanAccountByAccountNumber(loanAccountNumber);
        if (fromAccount.getBalance().compareTo(amount) < 0) {
            // not enough money
            return "FAIL1";
        } else {
            System.out.println("success" + amount);
            depositBean.transferFromAccount(fromAccount, amount);
            BigDecimal outPrin = new BigDecimal(loanAccount.getOutstandingPrincipal());
            if (amount.compareTo(outPrin) == 1) {
                return "FAIL2";
            }
            LoanAccount la = loanAccountLumsumPayment(loanAccountNumber, amount.doubleValue());
            futurePaymentBreakdown(la);
            return "SUCCESS";
        }

    } catch (DepositAccountNotFoundException e) {
        System.out.println(
                "DepositAccountNotFoundException LoanRepaymentSessionBean loanLumsumPaymentFromAccount()");
        return "FAIL0";
    }

}

From source file:com.heliumv.api.inventory.InventoryApi.java

private boolean updateInventurliste(ArtikelDto itemDto, BigDecimal newAmount, Boolean changeAmountTo,
        InventurlisteDto workListeDto) throws NamingException, RemoteException {
    if (!changeAmountTo) {
        BigDecimal oldAmount = workListeDto.getNInventurmenge();
        newAmount = oldAmount.add(newAmount);
    }//from w w w .j  ava  2s  .co  m

    if (newAmount.signum() < 0) {
        respondBadRequest("amount", "<0");
        return false;
    }

    if (newAmount.signum() == 0) {
        inventurCall.removeInventurListe(workListeDto);
    } else {
        if (itemDto.isSeriennrtragend() && newAmount.compareTo(BigDecimal.ONE) > 0) {
            respondBadRequest("serialnr", "amount has to be 1");
            return false;
        }

        workListeDto.setNInventurmenge(newAmount);
        inventurCall.updateInventurliste(workListeDto, false);
    }

    return true;
}

From source file:nl.strohalm.cyclos.services.elements.MemberServiceImpl.java

@SuppressWarnings("unchecked")
private ActivitiesVO doGetActivities(final Member member) {
    final ActivitiesVO vo = new ActivitiesVO();

    // Check if account information will be retrieved
    boolean showAccountInformation;
    boolean showAdsInformation = adService.visibleGroupsForAds().contains(member.getGroup());
    boolean showNonActiveAdsInformation = false;

    final Element loggedElement = LoggedUser.element();
    if (permissionService.manages(member)) {
        // A managed member
        showAccountInformation = permissionService.permission(member)
                .admin(AdminMemberPermission.REPORTS_SHOW_ACCOUNT_INFORMATION)
                .broker(BrokerPermission.ACCOUNTS_INFORMATION).member()
                .operator(OperatorPermission.ACCOUNT_ACCOUNT_INFORMATION).hasPermission();
        showNonActiveAdsInformation = showAdsInformation;
    } else {/*from   ww w .j a v a2 s  .c  o  m*/
        // Another related member
        showAccountInformation = permissionService.permission()
                .member(MemberPermission.REPORTS_SHOW_ACCOUNT_INFORMATION)
                .operator(MemberPermission.REPORTS_SHOW_ACCOUNT_INFORMATION).hasPermission();
    }

    boolean showReferencesInformation = permissionService.permission()
            .admin(AdminMemberPermission.REFERENCES_VIEW).member(MemberPermission.REFERENCES_VIEW)
            .operator(OperatorPermission.REFERENCES_VIEW).hasPermission();

    boolean showInvoicesInformation = showAccountInformation && permissionService.permission()
            .admin(AdminMemberPermission.INVOICES_VIEW).member(MemberPermission.INVOICES_VIEW)
            .operator(OperatorPermission.INVOICES_VIEW).hasPermission();

    vo.setShowAccountInformation(showAccountInformation);
    vo.setShowInvoicesInformation(showInvoicesInformation);
    vo.setShowReferencesInformation(showReferencesInformation);
    vo.setShowAdsInformation(showAdsInformation);
    vo.setShowNonActiveAdsInformation(showNonActiveAdsInformation);

    // Since active
    vo.setSinceActive(member.getActivationDate());

    // Number of brokered members
    boolean isBroker = member.getGroup().getNature() == Nature.BROKER;
    if (isBroker) {
        final BrokeringQuery query = new BrokeringQuery();
        query.setBroker(member);
        query.setStatus(BrokeringQuery.Status.ACTIVE);
        query.setPageForCount();
        vo.setNumberBrokeredMembers(PageHelper.getTotalCount(brokeringService.search(query)));
    }

    // References
    if (showReferencesInformation) {
        vo.setReceivedReferencesByLevel(
                referenceService.countReferencesByLevel(Reference.Nature.GENERAL, member, true));
        vo.setGivenReferencesByLevel(
                referenceService.countReferencesByLevel(Reference.Nature.GENERAL, member, false));
    }

    // Ads
    if (vo.isShowAdsInformation()) {
        vo.setAdsByStatus(adService.getNumberOfAds(null, member));
    }

    final List<MemberAccount> accounts = (List<MemberAccount>) accountService.getAccounts(member);

    // Get invoice information
    if (showInvoicesInformation) {
        // Incoming invoices
        final InvoiceSummaryDTO incomingInvoicesDTO = new InvoiceSummaryDTO();
        incomingInvoicesDTO.setOwner(member);
        incomingInvoicesDTO.setDirection(InvoiceQuery.Direction.INCOMING);
        incomingInvoicesDTO.setStatus(Invoice.Status.OPEN);
        vo.setIncomingInvoices(invoiceService.getSummary(incomingInvoicesDTO));

        // Outgoing invoices
        final InvoiceSummaryDTO summaryDTO = new InvoiceSummaryDTO();
        summaryDTO.setOwner(member);
        summaryDTO.setDirection(InvoiceQuery.Direction.OUTGOING);
        summaryDTO.setStatus(Invoice.Status.OPEN);
        vo.setOutgoingInvoices(invoiceService.getSummary(summaryDTO));
    }

    // 30 days ago
    final Calendar days30 = DateHelper.truncate(Calendar.getInstance());
    days30.add(Calendar.DATE, -30);

    // Account activities; as rate info is NOT subject to permissions, always do the loop
    for (final MemberAccount account : accounts) {
        boolean hasRateInfo = false;

        final GetTransactionsDTO allTime = new GetTransactionsDTO(account);
        // final GetTransactionsDTO last30Days = new GetTransactionsDTO(account, Period.begginingAt(days30));

        // Build an account activities VO
        final AccountActivitiesVO activities = new AccountActivitiesVO();

        // Get the account status
        AccountStatus accountStatus = accountService.getRatedStatus(account, null);
        activities.setAccountStatus(accountStatus);

        // as AccountStatus contains rate info, no need to get it separately
        hasRateInfo = rateService.isAnyRateEnabled(account, null);
        activities.setHasRateInfo(hasRateInfo);

        // get the conversion result
        if (hasRateInfo) {
            // get the relevant transfer type for conversions
            final Collection<TransferType> currencyConversionTTs = transferTypeService
                    .getConversionTTs(account.getType().getCurrency());
            final Collection<TransferType> accountConversionTTs = transferTypeService
                    .getConversionTTs(account.getType());
            TransferType conversionTT = null;
            // there must be only 1 TT available on the account. if more than one, we don't know which to choose so show nothing.
            if (accountConversionTTs.size() == 1) {
                final Object[] ttArray = accountConversionTTs.toArray();
                conversionTT = (TransferType) ttArray[0];
            } else if (accountConversionTTs.size() == 0 && currencyConversionTTs.size() == 1) {
                // OR in case there is none on the account, we will take the only one available on the currency.
                final Object[] ttArray = currencyConversionTTs.toArray();
                conversionTT = (TransferType) ttArray[0];
            }
            // if no balance or no TT, there's nothing to convert.
            final BigDecimal balance = accountStatus.getBalance();
            if (balance.compareTo(BigDecimal.ZERO) > 0 && conversionTT != null) {
                final ConversionSimulationDTO dto = new ConversionSimulationDTO();
                dto.setTransferType(conversionTT);
                dto.setAccount(account);
                dto.setAmount(balance);
                dto.setUseActualRates(true);
                dto.setDate(Calendar.getInstance());
                final TransactionFeePreviewForRatesDTO result = paymentService.simulateConversion(dto);
                activities.setTotalFeePercentage(result.getRatesAsFeePercentage());
            }
        }

        // rest of the activities info is subject to permissions
        if (showAccountInformation) {
            // Check if user has permission to view information of that account
            if (account.getMember().equals(loggedElement)
                    || canViewAccountInformation(loggedElement, account)) {

                activities.setShowAccountInfo(true);

                GetTransactionsDTO txAllTime = new GetTransactionsDTO(account);
                txAllTime.setRootOnly(true);
                GetTransactionsDTO tx30Days = new GetTransactionsDTO(account, Period.begginingAt(days30));
                tx30Days.setRootOnly(true);

                activities.setCreditsAllTime(accountService.getCredits(txAllTime));
                activities.setDebitsAllTime(accountService.getDebits(txAllTime));
                activities.setCreditsLast30Days(accountService.getCredits(tx30Days));
                activities.setDebitsLast30Days(accountService.getDebits(tx30Days));

                // Get the broker commission
                if (isBroker) {
                    activities.setBrokerCommission(accountService.getBrokerCommissions(allTime));
                }

                // Calculate the total of remaining loans
                final LoanQuery loanQuery = new LoanQuery();
                loanQuery.setMember(member);
                loanQuery.setStatus(Loan.Status.OPEN);
                loanQuery.setAccountType(account.getType());
                int remainingLoans = 0;
                BigDecimal remainingLoanAmount = BigDecimal.ZERO;
                final List<Loan> loans = loanService.search(loanQuery);
                for (final Loan loan : loans) {
                    remainingLoans++;
                    remainingLoanAmount = remainingLoanAmount.add(loan.getRemainingAmount());
                }
                activities.setRemainingLoans(new TransactionSummaryVO(remainingLoans, remainingLoanAmount));

            }
        }
        // Store this one, but only if there is info
        if (activities.isShowAccountInfo() || activities.isHasRateInfo()) {
            vo.addAccountActivities(account.getType().getName(), activities);
        }
    }
    return vo;
}

From source file:net.groupbuy.entity.Promotion.java

/**
 * /*  w w w .ja va  2s .c  o  m*/
 * 
 * @param quantity
 *            ??
 * @param price
 *            ?
 * @return 
 */
@Transient
public BigDecimal calculatePrice(Integer quantity, BigDecimal price) {
    if (price == null || StringUtils.isEmpty(getPriceExpression())) {
        return price;
    }
    BigDecimal result = new BigDecimal(0);
    try {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("quantity", quantity);
        model.put("price", price);
        result = new BigDecimal(FreemarkerUtils.process("#{(" + getPriceExpression() + ");M50}", model));
    } catch (IOException e) {
        e.printStackTrace();
    } catch (TemplateException e) {
        e.printStackTrace();
    }
    if (result.compareTo(price) > 0) {
        return price;
    }
    return result.compareTo(new BigDecimal(0)) > 0 ? result : new BigDecimal(0);
}

From source file:org.neo4j.ogm.auth.AuthenticationTest.java

private boolean isRunningWithNeo4j2Dot2OrLater() throws Exception {
    Class<?> versionClass = null;
    BigDecimal version = new BigDecimal(2.1);
    try {/*from ww  w.  ja  v a 2s.  c om*/
        versionClass = Class.forName("org.neo4j.kernel.Version");
        Method kernelVersion23x = versionClass.getDeclaredMethod("getKernelVersion", null);
        version = new BigDecimal(((String) kernelVersion23x.invoke(null)).substring(0, 3));
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        try {
            Method kernelVersion22x = versionClass.getDeclaredMethod("getKernelRevision", null);
            version = new BigDecimal(((String) kernelVersion22x.invoke(null)).substring(0, 3));
        } catch (NoSuchMethodException e1) {
            throw new RuntimeException("Unable to find a method to get Neo4js kernel version");
        }

    }
    return version.compareTo(new BigDecimal("2.1")) > 0;
}

From source file:org.efaps.esjp.accounting.transaction.Transaction_Base.java

/**
 * @param _oldValue old Value//  w  w w . jav  a 2s  .  c o  m
 * @param _oldRate old Rate
 * @param _newRate new Rate
 * @return new Value
 */
protected BigDecimal getNewValue(final BigDecimal _oldValue, final BigDecimal _oldRate,
        final BigDecimal _newRate) {
    BigDecimal ret = BigDecimal.ZERO;
    if (_oldValue.compareTo(BigDecimal.ZERO) != 0) {
        ret = _oldValue.multiply(_oldRate).divide(_newRate, BigDecimal.ROUND_HALF_UP).setScale(2,
                BigDecimal.ROUND_HALF_UP);
    }
    return ret;
}