Example usage for java.math BigDecimal abs

List of usage examples for java.math BigDecimal abs

Introduction

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

Prototype

public BigDecimal abs() 

Source Link

Document

Returns a BigDecimal whose value is the absolute value of this BigDecimal , and whose scale is this.scale() .

Usage

From source file:org.yes.cart.service.domain.impl.SkuWarehouseServiceImpl.java

/**
 * {@inheritDoc}/*from  ww  w  .  ja v a 2 s  . co m*/
 */
@CacheEvict(value = { "skuWarehouseService-productOnWarehouse",
        "skuWarehouseService-productSkusOnWarehouse" }, allEntries = true)
public BigDecimal voidReservation(final Warehouse warehouse, final String productSkuCode,
        final BigDecimal voidQty) {
    final SkuWarehouse skuWarehouse = findByWarehouseSkuForUpdate(warehouse, productSkuCode);

    if (skuWarehouse == null) {
        return voidQty.setScale(Constants.DEFAULT_SCALE);
    } else {
        BigDecimal canVoid = MoneyUtils
                .notNull(skuWarehouse.getReserved(), BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE))
                .min(voidQty);
        BigDecimal rest = MoneyUtils
                .notNull(skuWarehouse.getReserved(), BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE))
                .subtract(voidQty);
        skuWarehouse.setReserved(MoneyUtils
                .notNull(skuWarehouse.getReserved(), BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE))
                .subtract(canVoid));
        update(skuWarehouse);
        if (MoneyUtils.isFirstBiggerThanOrEqualToSecond(rest, BigDecimal.ZERO)) {
            return BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE);
        } else {
            return rest.abs().setScale(Constants.DEFAULT_SCALE);
        }

    }
}

From source file:org.fineract.module.stellar.horizonadapter.HorizonServerUtilities.java

public BigDecimal adjustVaultIssuedAssets(final StellarAccountId stellarAccountId,
        final char[] stellarAccountPrivateKey, final StellarAccountId stellarVaultAccountId,
        final char[] stellarVaultAccountPrivateKey, final String assetCode, final BigDecimal amount)
        throws InvalidConfigurationException, StellarPaymentFailedException,
        StellarTrustlineAdjustmentFailedException {
    final BigDecimal currentVaultIssuedAssets = currencyTrustSize(stellarAccountId, assetCode,
            stellarVaultAccountId);/*from w  ww .ja  v a2s .c o m*/

    final BigDecimal adjustmentRequired = amount.subtract(currentVaultIssuedAssets);

    if (adjustmentRequired.compareTo(BigDecimal.ZERO) < 0) {
        final BigDecimal currentVaultIssuedAssetsHeldByTenant = getBalanceByIssuer(stellarAccountId, assetCode,
                stellarVaultAccountId);

        final BigDecimal adjustmentPossible = currentVaultIssuedAssetsHeldByTenant
                .min(adjustmentRequired.abs());

        final BigDecimal finalBalance = currentVaultIssuedAssets.subtract(adjustmentPossible);

        simplePay(stellarVaultAccountId, adjustmentPossible, assetCode, stellarVaultAccountId,
                stellarAccountPrivateKey);

        setTrustLineSize(stellarAccountPrivateKey, stellarVaultAccountId, assetCode, finalBalance);

        return finalBalance;
    } else if (adjustmentRequired.compareTo(BigDecimal.ZERO) > 0) {
        setTrustLineSize(stellarAccountPrivateKey, stellarVaultAccountId, assetCode, amount);

        simplePay(stellarAccountId, adjustmentRequired, assetCode, stellarVaultAccountId,
                stellarVaultAccountPrivateKey);

        return amount;
    } else {
        return currentVaultIssuedAssets;
    }
}

From source file:org.openbravo.erpCommon.ad_forms.Fact.java

/**
 * Create and convert Fact Line. Used to create either a DR or CR entry
 * // www. ja  v  a 2  s  .  c om
 * @param docLine
 *          Document line or null
 * @param account
 *          Account to be used
 * @param C_Currency_ID
 *          Currency
 * @param Amt
 *          if negative Cr else Dr
 * @return FactLine
 */
public FactLine createLine(DocLine docLine, Account account, String C_Currency_ID, String Amt,
        String Fact_Acct_Group_ID, String SeqNo, String DocBaseType, ConnectionProvider conn) {
    BigDecimal m_Amt = ZERO;
    try {
        if (!Amt.equals(""))
            m_Amt = new BigDecimal(Amt);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (m_Amt.compareTo(ZERO) < 0)
        return createLine(docLine, account, C_Currency_ID, "", m_Amt.abs().toString(), Fact_Acct_Group_ID,
                SeqNo, DocBaseType, conn);
    else
        return createLine(docLine, account, C_Currency_ID, Amt.toString(), "", Fact_Acct_Group_ID, SeqNo,
                DocBaseType, conn);
}

From source file:org.openbravo.erpCommon.ad_forms.Fact.java

/**
 * Create and convert Fact Line. Used to create either a DR or CR entry
 * // w  ww.  java2 s  . com
 * @param docLine
 *          Document Line or null
 * @param accountDr
 *          Account to be used if Amt is DR balance
 * @param accountCr
 *          Account to be used if Amt is CR balance
 * @param C_Currency_ID
 *          Currency
 * @param Amt
 *          if negative Cr else Dr
 * @return FactLine
 */
public FactLine createLine(DocLine docLine, Account accountDr, Account accountCr, String C_Currency_ID,
        String Amt, String Fact_Acct_Group_ID, String SeqNo, String DocBaseType, ConnectionProvider conn) {
    BigDecimal m_Amt = ZERO;
    try {
        if (!Amt.equals(""))
            m_Amt = new BigDecimal(Amt);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (m_Amt.compareTo(ZERO) < 0)
        return createLine(docLine, accountCr, C_Currency_ID, "", m_Amt.abs().toString(), Fact_Acct_Group_ID,
                SeqNo, DocBaseType, conn);
    else
        return createLine(docLine, accountDr, C_Currency_ID, m_Amt.toString(), "", Fact_Acct_Group_ID, SeqNo,
                DocBaseType, conn);
}

From source file:org.kuali.kpme.tklm.leave.payout.LeavePayout.java

public LeavePayout adjust(BigDecimal payoutAmount) {
    BigDecimal difference = this.payoutAmount.subtract(payoutAmount);
    //technically if there is forfeiture, then the transfer amount has already been maximized
    //via BalanceTransferService::initializeTransfer(...)
    //i.o.w. transfer amount cannot be increased.
    //this method is written with the intention of eventually allowing end user to adjust the transfer
    //amount as many times as they wish before submitting. Currently they cannot.
    if (difference.signum() < 0) {
        //transfer amount is being increased.
        if (forfeitedAmount.compareTo(BigDecimal.ZERO) > 0) {
            //transfer amount has already been maximized.
            if (forfeitedAmount.compareTo(difference.abs()) >= 0)
                // there is enough leave in the forfeited amount to take out the difference.
                forfeitedAmount = forfeitedAmount.subtract(difference.abs());
            else/*from   w w w . j  av  a 2s .  co m*/
                // the difference zero's the forfeited amount.
                forfeitedAmount = BigDecimal.ZERO;
        }
        // a forfeited amount equal to zero with an increase in the transfer amount
        // does not produce forfeiture.
        // forfeiture cannot be negative.
    } else if (difference.signum() > 0) {
        //transfer amount is being decreased
        forfeitedAmount = forfeitedAmount.add(difference);
    }

    this.payoutAmount = payoutAmount;

    return this;
}

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

private Transfer doRepay(final RepayLoanDTO params) {
    BigDecimal amount = params.getAmount();

    // Check if the amount is valid
    if (amount.compareTo(paymentService.getMinimumPayment()) < 0) {
        throw new ValidationException("amount", "loan.amount", new InvalidError());
    }/*from  ww  w .  j a v a  2  s.  c  om*/

    // Get the loan payment to repay
    Calendar date = params.getDate();
    if (date == null) {
        date = Calendar.getInstance();
        params.setDate(date);
    }
    final LoanRepaymentAmountsDTO amountsDTO = getLoanPaymentAmount(params);
    final LoanPayment payment = amountsDTO.getLoanPayment();
    if (payment == null) {
        throw new UnexpectedEntityException();
    }

    // Validate the amount
    final BigDecimal remainingAmount = amountsDTO.getRemainingAmountAtDate();
    final BigDecimal diff = remainingAmount.subtract(amount);
    final MutableBoolean totallyRepaid = new MutableBoolean();
    // If the amount is on an acceptable delta, set the transfer value = parcel value
    if (diff.abs().floatValue() < PRECISION_DELTA) {
        amount = remainingAmount;
        totallyRepaid.setValue(true);
    } else if (diff.compareTo(BigDecimal.ZERO) < 0
            || !params.getLoan().getTransfer().getType().getLoan().getType().allowsPartialRepayments()) {
        throw new ValidationException("amount", "loan.amount", new InvalidError());
    }
    final LocalSettings localSettings = settingsService.getLocalSettings();
    Loan loan = fetchService.fetch(params.getLoan(), Loan.Relationships.PAYMENTS, RelationshipHelper
            .nested(Loan.Relationships.TRANSFER, Payment.Relationships.TO, MemberAccount.Relationships.MEMBER),
            Loan.Relationships.TO_MEMBERS);

    // Build the transfers for repayment
    final List<TransferDTO> transfers = handlersByType.get(loan.getParameters().getType())
            .buildTransfersForRepayment(params, amountsDTO);
    Transfer root = null;
    BigDecimal totalAmount = BigDecimal.ZERO;
    for (final TransferDTO dto : transfers) {
        if (dto.getAmount().floatValue() < PRECISION_DELTA) {
            // If the root amount is zero, it means that the parent transfer should be the last transfer for this loan payment
            final TransferQuery tq = new TransferQuery();
            tq.setLoanPayment(payment);
            tq.setReverseOrder(true);
            tq.setUniqueResult();
            final List<Transfer> paymentTransfers = paymentService.search(tq);
            if (paymentTransfers.isEmpty()) {
                throw new IllegalStateException(
                        "The root transfer has amount 0 and there is no other transfers for this payment");
            }
            root = paymentTransfers.iterator().next();
        } else {
            totalAmount = totalAmount.add(dto.getAmount());
            dto.setParent(root);
            dto.setLoanPayment(payment);
            final Transfer transfer = (Transfer) paymentService.insertWithoutNotification(dto);
            if (root == null) {
                // The first will be the root. All others are it's children
                root = transfer;
            }
        }
    }

    // Update the loan payment
    final BigDecimal totalRepaid = localSettings.round(payment.getRepaidAmount().add(totalAmount));
    payment.setRepaidAmount(totalRepaid);
    if (totallyRepaid.booleanValue()) {
        // Mark the payment as repaid, if is the case
        payment.setStatus(LoanPayment.Status.REPAID);
        payment.setRepaymentDate(params.getDate());
    }
    payment.setTransfers(null); // Avoid 2 representations of the transfers collection. It's inverse="true", no problem setting null
    loanPaymentDao.update(payment);

    // Return the generated root transfer
    return root;
}

From source file:org.apache.calcite.runtime.SqlFunctions.java

/** SQL <code>ABS</code> operator applied to BigDecimal values. */
public static BigDecimal abs(BigDecimal b0) {
    return b0.abs();
}

From source file:org.kuali.kpme.tklm.leave.transfer.web.BalanceTransferAction.java

private void buildBalanceTransferForLeaveBlock(BalanceTransferForm btf, String lbId) {
    LeaveBlock lb = LmServiceLocator.getLeaveBlockService().getLeaveBlock(lbId);
    // this leave block is a ssto usage block, need to use it fo find the accrualed leave block which has a positive amount
    if (lb == null || StringUtils.isEmpty(lb.getScheduleTimeOffId())) {
        LOG.error("could not find the System Scheduled Time Off leave block that needs to be transferred!");
        GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "error.SSTOlb.nonExist");
        return;/*from w  w  w  . j  av a 2s  .  c om*/
        //         throw new RuntimeException("could not find the System Scheduled Time Off leave block that needs to be transferred!");   
    }
    SystemScheduledTimeOffContract ssto = LmServiceLocator.getSysSchTimeOffService()
            .getSystemScheduledTimeOff(lb.getScheduleTimeOffId());
    BigDecimal amountTransferred = ssto.getTransferConversionFactor() == null ? lb.getLeaveAmount()
            : lb.getLeaveAmount().multiply(ssto.getTransferConversionFactor());
    EarnCode ec = HrServiceLocator.getEarnCodeService().getEarnCode(ssto.getTransfertoEarnCode(),
            lb.getLeaveLocalDate());

    BalanceTransfer bt = new BalanceTransfer();
    bt.setTransferAmount(lb.getLeaveAmount().abs()); // the usage leave block's leave amount is negative
    bt.setFromAccrualCategory(lb.getAccrualCategory());
    bt.setAmountTransferred(amountTransferred.abs());
    bt.setToAccrualCategory(ec.getAccrualCategory());
    bt.setSstoId(lb.getScheduleTimeOffId());
    bt.setEffectiveLocalDate(lb.getLeaveLocalDate());
    bt.setPrincipalId(lb.getPrincipalId());

    btf.setBalanceTransfer(bt);
    btf.setTransferAmount(bt.getTransferAmount());
    GlobalVariables.getMessageMap().putWarning("document.newMaintainableObj.transferAmount",
            "balanceTransfer.transferSSTO", bt.getTransferAmount().toString(),
            bt.getAmountTransferred().toString());
}

From source file:org.yes.cart.service.domain.impl.SkuWarehouseServiceImpl.java

/**
 * {@inheritDoc}/*w  w  w.j a  v  a  2 s . co m*/
 */
@CacheEvict(value = { "skuWarehouseService-productOnWarehouse",
        "skuWarehouseService-productSkusOnWarehouse" }, allEntries = true)
public BigDecimal reservation(final Warehouse warehouse, final String productSkuCode,
        final BigDecimal reserveQty, final boolean allowBackorder) {

    final SkuWarehouse skuWarehouse = findByWarehouseSkuForUpdate(warehouse, productSkuCode);

    if (skuWarehouse == null) {

        if (allowBackorder) {
            final SkuWarehouse newSkuEntry = getGenericDao().getEntityFactory().getByIface(SkuWarehouse.class);
            newSkuEntry.setWarehouse(warehouse);
            newSkuEntry.setSkuCode(productSkuCode);
            newSkuEntry.setQuantity(BigDecimal.ZERO);
            newSkuEntry.setReserved(reserveQty);
            create(newSkuEntry);
            return BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE);
        }
        return reserveQty.setScale(Constants.DEFAULT_SCALE);

    } else {

        final BigDecimal rest;
        if (allowBackorder) {
            rest = BigDecimal.ZERO; // the remainder is zero
        } else {
            BigDecimal canReserve = skuWarehouse.getAvailableToSell();
            rest = canReserve.subtract(reserveQty);
        }

        if (MoneyUtils.isFirstBiggerThanOrEqualToSecond(rest, BigDecimal.ZERO)) {
            skuWarehouse.setReserved(MoneyUtils
                    .notNull(skuWarehouse.getReserved(), BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE))
                    .add(reserveQty));
            update(skuWarehouse);
            return BigDecimal.ZERO.setScale(Constants.DEFAULT_SCALE);
        } else {
            skuWarehouse.setReserved(skuWarehouse.getQuantity());
            update(skuWarehouse);
            return rest.abs().setScale(Constants.DEFAULT_SCALE);
        }
    }

}

From source file:org.openvpms.archetype.rules.finance.till.TillRulesTestCase.java

private BigDecimal checkBalance(BigDecimal initialCashFloat, BigDecimal newCashFloat, FinancialAct balance,
        String status) {/*  w w  w  .ja va2  s . c om*/
    // make sure the balance is updated
    assertEquals(status, balance.getStatus());
    // end time should be > startTime < now
    Date startTime = balance.getActivityStartTime();
    Date endTime = balance.getActivityEndTime();
    if (TillBalanceStatus.CLEARED.equals(status)) {
        // CLEARED balances have an end time
        assertEquals(1, endTime.compareTo(startTime));
        assertEquals(-1, endTime.compareTo(new Date()));
    } else {
        // IN_PROGRESS balances do not
        assertNull(endTime);
    }

    BigDecimal total = newCashFloat.subtract(initialCashFloat);

    if (initialCashFloat.compareTo(newCashFloat) != 0) {
        // expect a till balance adjustment to have been made
        Set<ActRelationship> rels = balance.getSourceActRelationships();
        assertEquals(1, rels.size());
        ActRelationship r = rels.toArray(new ActRelationship[rels.size()])[0];
        Act target = (Act) get(r.getTarget());
        assertTrue(TypeHelper.isA(target, "act.tillBalanceAdjustment"));
        ActBean adjBean = new ActBean(target);
        BigDecimal amount = adjBean.getBigDecimal("amount");

        boolean credit = (newCashFloat.compareTo(initialCashFloat) < 0);
        BigDecimal adjustmentTotal = total.abs();
        assertTrue(adjustmentTotal.compareTo(amount) == 0);
        assertEquals(credit, adjBean.getBoolean("credit"));
    } else {
        // no till balance adjustment should have been generated
        assertTrue(balance.getSourceActRelationships().isEmpty());
    }

    // check the till balance.
    BigDecimal expectedBalance = total.negate();
    assertTrue(expectedBalance.compareTo(balance.getTotal()) == 0);

    // make sure the till is updated
    Party till = (Party) get(this.till.getObjectReference());
    IMObjectBean bean = new IMObjectBean(till);
    BigDecimal currentFloat = bean.getBigDecimal("tillFloat");
    Date lastCleared = bean.getDate("lastCleared");
    Date now = new Date();

    assertTrue(currentFloat.compareTo(newCashFloat) == 0);
    assertTrue(now.compareTo(lastCleared) == 1); // expect now > lastCleared
    return expectedBalance;
}