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:jgnash.ui.report.compiled.PayeePieChart.java

private PieDataset[] createPieDataSet(final Account a) {
    DefaultPieDataset[] returnValue = new DefaultPieDataset[2];
    returnValue[0] = new DefaultPieDataset();
    returnValue[1] = new DefaultPieDataset();

    if (a != null) {
        //System.out.print("Account = "); System.out.println(a);
        Map<String, BigDecimal> names = new HashMap<>();

        List<TranTuple> list = getTransactions(a, new ArrayList<>(), startField.getLocalDate(),
                endField.getLocalDate());

        CurrencyNode currency = a.getCurrencyNode();

        for (final TranTuple tranTuple : list) {

            Transaction tran = tranTuple.transaction;
            Account account = tranTuple.account;

            String payee = tran.getPayee();
            BigDecimal sum = tran.getAmount(account);

            sum = sum.multiply(account.getCurrencyNode().getExchangeRate(currency));

            //System.out.print("   Transaction = "); System.out.print(payee); System.out.print(" "); System.out.println(sum);

            if (useFilters.isSelected()) {
                for (String aFilterList : filterList) {

                    PayeeMatcher pm = new PayeeMatcher(aFilterList, false);

                    if (pm.matches(tran)) {
                        payee = aFilterList;
                        //System.out.println(filterList.get(i));
                        break;
                    }/*from www . j  av a  2 s.co  m*/
                }
            }

            if (names.containsKey(payee)) {
                sum = sum.add(names.get(payee));
            }

            names.put(payee, sum);
        }

        for (final Map.Entry<String, BigDecimal> entry : names.entrySet()) {
            BigDecimal value = entry.getValue();

            if (value.compareTo(BigDecimal.ZERO) == -1) {
                value = value.negate();
                returnValue[1].setValue(entry.getKey(), value);
            } else {
                returnValue[0].setValue(entry.getKey(), value);
            }
        }
    }
    return returnValue;
}

From source file:org.egov.adtax.web.controller.mobile.AdtaxMobilePaymentController.java

/**
 * API to process payments from Mobile App
 *
 * @param model//from   w  ww  .  j  a  va2  s . c  o  m
 * @param advertisementNo
 * @param ulbCode
 * @param amountToBePaid
 * @param request
 * @return
 */
@RequestMapping(value = "/payAdtax/{advertisementNo},{ulbCode},{amountToBePaid},{mobileNumber},{emailId}", method = RequestMethod.GET)
public String collectTax(final Model model, @PathVariable final String advertisementNo,
        @PathVariable final String ulbCode, @PathVariable final BigDecimal amountToBePaid,
        @PathVariable final String mobileNumber, @PathVariable final String emailId,
        final HttpServletRequest request) {
    String redirectUrl = StringUtils.EMPTY;
    Advertisement advertisement = null;
    if (advertisementNo != null)
        advertisement = advertisementService.findByAdvertisementNumber(advertisementNo);

    if (amountToBePaid.compareTo(advertisementDemandService.getPendingTaxAmount(advertisement)) > 0) {
        model.addAttribute(MESSAGE, "msg.PaidAmount.greaterthan.Total");
        return COLLECT_ADVTAX_ERROR;
    }

    final BillInfoImpl billInfo = advertisementBillServiceImpl.getBillInfo(amountToBePaid, advertisement);
    if (billInfo != null) {
        final PaymentRequest paymentRequest = SpringBeanUtil.getCollectionIntegrationService()
                .processMobilePayments(billInfo);
        if (paymentRequest != null) {
            for (final Object obj : paymentRequest.getRequestParameters().values())
                redirectUrl = obj.toString();
            model.addAttribute("redirectUrl", redirectUrl);
        }
    } else {
        model.addAttribute(MESSAGE, "Bill data is incorrect");
        return COLLECT_ADVTAX_ERROR;
    }
    return PAYTAX_FORM;
}

From source file:com.nkapps.billing.dao.PaymentDaoImpl.java

@Override
public void savePaymentManual(String bankStatementId, List<Payment> paymentList, Long issuerSerialNumber,
        String issuerIp) throws Exception {
    Session session = getSession();/*from   w  ww.  j av  a  2 s  . c o  m*/
    Transaction transaction = session.beginTransaction();
    BankStatement bs = (BankStatement) session.get(BankStatement.class, bankStatementId);
    if (bs == null) {
        throw new Exception(messageSource.getMessage("bank_statement.editable.bs_not_found", null,
                LocaleContextHolder.getLocale()));
    }

    String q = "SELECT COALESCE(bs.paymentSum,0) - COALESCE(bs.returnSum,0) - (SELECT COALESCE(SUM(kp.paidSum),0) FROM bs.bankStatementPayments bsp JOIN bsp.id.payment p JOIN p.keyPayments kp WHERE p.claim = 0) AS overpaymentSum"
            + " FROM BankStatement bs" + " WHERE bs = :bs";
    Query query = session.createQuery(q);
    query.setParameter("bs", bs);
    BigDecimal overpaymentSum = (BigDecimal) query.uniqueResult();

    if (overpaymentSum.compareTo(BigDecimal.ZERO) > 0) {
        LocalDateTime dateTime = LocalDateTime.now();

        overpaymentDao.returnStateCommit(session, bs, overpaymentSum, issuerSerialNumber, issuerIp, dateTime); // if bankstatement already converted to payment, then them must revert

        for (Payment payment : paymentList) {
            BigDecimal paymentSum = payment.getPaymentSum();
            if (paymentSum.compareTo(overpaymentSum) > 0) {
                paymentSum = overpaymentSum;
                overpaymentSum = BigDecimal.ZERO;
            } else {
                overpaymentSum = overpaymentSum.subtract(paymentSum);
            }
            payment.setPaymentSum(paymentSum);
            payment.setIssuerSerialNumber(issuerSerialNumber);
            payment.setIssuerIp(issuerIp);
            payment.setDateCreated(dateTime);
            payment.setDateUpdated(dateTime);

            session.save(payment);

            BankStatementPayment bsp = new BankStatementPayment();
            BankStatementPaymentId bspId = new BankStatementPaymentId();
            bspId.setBankStatement(bs);
            bspId.setPayment(payment);
            bsp.setId(bspId);

            session.save(bsp);

            if (overpaymentSum.compareTo(BigDecimal.ZERO) <= 0) {
                break;
            }
        }
    }

    transaction.commit();
    session.close();
}

From source file:com.streamsets.pipeline.lib.salesforce.SobjectRecordCreator.java

protected String fixOffset(String offsetColumn, String offset) {
    com.sforce.soap.partner.Field sfdcField = 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";
        }// ww  w.j a  v a  2  s  .c  om
    }
    return offset;
}

From source file:net.groupbuy.service.impl.MemberServiceImpl.java

public void update(Member member, Integer modifyPoint, BigDecimal modifyBalance, String depositMemo,
        Admin operator) {/*from  w w  w .java 2s  . c om*/
    Assert.notNull(member);

    memberDao.lock(member, LockModeType.PESSIMISTIC_WRITE);

    if (modifyPoint != null && modifyPoint != 0 && member.getPoint() + modifyPoint >= 0) {
        member.setPoint(member.getPoint() + modifyPoint);
    }

    if (modifyBalance != null && modifyBalance.compareTo(new BigDecimal(0)) != 0
            && member.getBalance().add(modifyBalance).compareTo(new BigDecimal(0)) >= 0) {
        member.setBalance(member.getBalance().add(modifyBalance));
        Deposit deposit = new Deposit();
        if (modifyBalance.compareTo(new BigDecimal(0)) > 0) {
            deposit.setType(operator != null ? Deposit.Type.adminRecharge : Deposit.Type.memberRecharge);
            deposit.setCredit(modifyBalance);
            deposit.setDebit(new BigDecimal(0));
        } else {
            deposit.setType(operator != null ? Deposit.Type.adminChargeback : Deposit.Type.memberPayment);
            deposit.setCredit(new BigDecimal(0));
            deposit.setDebit(modifyBalance);
        }
        deposit.setBalance(member.getBalance());
        deposit.setOperator(operator != null ? operator.getUsername() : null);
        deposit.setMemo(depositMemo);
        deposit.setMember(member);
        depositDao.persist(deposit);
    }
    memberDao.merge(member);
}

From source file:com.opensky.osis.BraintreeConnector.java

/**
 * Custom processor//from   w w  w .  java 2  s  .  c  o  m
 *
 * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:settle}
 *
 * @param id The transaction id
 * @param amount the amount of the transaction
 * @return The transaction
 */
@Processor
public Result settle(String id, BigDecimal amount) {
    log.info("Settling transaction {} amount {}", id, amount);

    Validate.notNull(id, "token should not be null");
    Validate.notNull(amount, "amount should not be null");
    Validate.isTrue(amount.compareTo(BigDecimal.ZERO) >= 0, "amount must be >= 0");

    try {
        Result<Transaction> res = getGateway().transaction().submitForSettlement(id, amount);
        return res;
    } catch (BraintreeException e) {
        return new ExceptionResult(e.getClass().getCanonicalName());
    }
}

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

private boolean isDifferenceToLarge(BigDecimal baseAmount, BigDecimal newAmount) {
    BigDecimal percentAllowed = new BigDecimal(10);
    BigDecimal amplitude = baseAmount.movePointLeft(2).multiply(percentAllowed);
    if (amplitude.compareTo(BigDecimal.ONE) <= 0) {
        amplitude = BigDecimal.ONE;
    }/*from  w  ww.j  ava 2  s.  c o m*/
    return baseAmount.subtract(newAmount).abs().compareTo(amplitude) > 0;
}

From source file:net.shopxx.service.impl.MerchantServiceImpl.java

public void update(Merchant merchant, Integer modifyPoint, BigDecimal modifyBalance, String depositMemo,
        Admin operator) {//  ww w.  jav  a 2s.c om
    Assert.notNull(merchant);

    merchantDao.lock(merchant, LockModeType.PESSIMISTIC_WRITE);

    if (modifyPoint != null && modifyPoint != 0 && merchant.getPoint() + modifyPoint >= 0) {
        merchant.setPoint(merchant.getPoint() + modifyPoint);
    }

    if (modifyBalance != null && modifyBalance.compareTo(new BigDecimal(0)) != 0
            && merchant.getBalance().add(modifyBalance).compareTo(new BigDecimal(0)) >= 0) {
        merchant.setBalance(merchant.getBalance().add(modifyBalance));
        Deposit deposit = new Deposit();
        if (modifyBalance.compareTo(new BigDecimal(0)) > 0) {
            //            deposit.setType(operator != null ? Deposit.Type.adminRecharge : Deposit.Type.merchantRecharge);
            deposit.setCredit(modifyBalance);
            deposit.setDebit(new BigDecimal(0));
        } else {
            //            deposit.setType(operator != null ? Deposit.Type.adminChargeback : Deposit.Type.merchantPayment);
            deposit.setCredit(new BigDecimal(0));
            deposit.setDebit(modifyBalance);
        }
        deposit.setBalance(merchant.getBalance());
        deposit.setOperator(operator != null ? operator.getUsername() : null);
        deposit.setMemo(depositMemo);
        deposit.setMerchant(merchant);
        depositDao.persist(deposit);
    }
    merchantDao.merge(merchant);
}

From source file:org.apache.hadoop.hbase.io.hfile.slab.SlabCache.java

/**
 * A way of allocating the desired amount of Slabs of each particular size.
 *
 * This reads two lists from conf, hbase.offheap.slab.proportions and
 * hbase.offheap.slab.sizes.//from  ww w . j  a v  a 2s  .co m
 *
 * The first list is the percentage of our total space we allocate to the
 * slabs.
 *
 * The second list is blocksize of the slabs in bytes. (E.g. the slab holds
 * blocks of this size).
 *
 * @param conf Configuration file.
 */
public void addSlabByConf(Configuration conf) {
    // Proportions we allocate to each slab of the total size.
    String[] porportions = conf.getStrings(SLAB_CACHE_PROPORTIONS_KEY, "0.80", "0.20");
    String[] sizes = conf.getStrings(SLAB_CACHE_SIZES_KEY, Long.valueOf(avgBlockSize * 11 / 10).toString(),
            Long.valueOf(avgBlockSize * 21 / 10).toString());

    if (porportions.length != sizes.length) {
        throw new IllegalArgumentException("SlabCache conf not "
                + "initialized, error in configuration. hbase.offheap.slab.proportions specifies "
                + porportions.length + " slabs while hbase.offheap.slab.sizes specifies " + sizes.length
                + " slabs " + "offheapslabporportions and offheapslabsizes");
    }
    /*
     * We use BigDecimals instead of floats because float rounding is annoying
     */

    BigDecimal[] parsedProportions = stringArrayToBigDecimalArray(porportions);
    BigDecimal[] parsedSizes = stringArrayToBigDecimalArray(sizes);

    BigDecimal sumProportions = new BigDecimal(0);
    for (BigDecimal b : parsedProportions) {
        /* Make sure all proportions are greater than 0 */
        Preconditions.checkArgument(b.compareTo(BigDecimal.ZERO) == 1,
                "Proportions in hbase.offheap.slab.proportions must be greater than 0!");
        sumProportions = sumProportions.add(b);
    }

    /* If the sum is greater than 1 */
    Preconditions.checkArgument(sumProportions.compareTo(BigDecimal.ONE) != 1,
            "Sum of all proportions in hbase.offheap.slab.proportions must be less than 1");

    /* If the sum of all proportions is less than 0.99 */
    if (sumProportions.compareTo(new BigDecimal("0.99")) == -1) {
        LOG.warn("Sum of hbase.offheap.slab.proportions is less than 0.99! Memory is being wasted");
    }
    for (int i = 0; i < parsedProportions.length; i++) {
        int blockSize = parsedSizes[i].intValue();
        int numBlocks = new BigDecimal(this.size).multiply(parsedProportions[i])
                .divide(parsedSizes[i], BigDecimal.ROUND_DOWN).intValue();
        addSlab(blockSize, numBlocks);
    }
}

From source file:nl.strohalm.cyclos.controls.mobile.MobileDoPaymentAction.java

/**
 * Validate the typed amount//from www . ja v  a2 s  .co  m
 */
private BigDecimal validateAmount(final MobileActionContext context) {
    final MobileDoPaymentForm form = context.getForm();
    final UnitsConverter converter = getUnitsConverter(context);
    BigDecimal amount = null;
    try {
        amount = converter.valueOf(form.getAmount());
    } catch (final Exception e) {
        throw new MobileException("errors.invalid", context.message("mobile.payment.amount"));
    }
    if (amount == null) {
        throw new MobileException("errors.required", context.message("mobile.payment.amount"));
    }
    if (amount.compareTo(paymentService.getMinimumPayment()) == -1) {
        throw new MobileException("errors.invalid", context.message("mobile.payment.amount"));
    }
    return amount;
}