Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

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

Prototype

public BigDecimal multiply(BigDecimal multiplicand) 

Source Link

Document

Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()) .

Usage

From source file:com.fujitsu.dc.test.setup.Setup.java

/**
 * $filter??(Edm.Double)????.//from w  w w  .  j  a  va2  s  .c  o m
 * @param index ???
 * @return ???
 */
private String getDoubleArray(int index) {
    final BigDecimal doubleData = new BigDecimal(1111111.1111111d);
    StringBuilder sbuf = new StringBuilder("[");
    for (int i = 0; i < index; i++) {
        if (i == 0) {
            sbuf.append(String.format("%f", doubleData.multiply(new BigDecimal(i))));
        } else {
            sbuf.append(String.format(",%f", doubleData.multiply(new BigDecimal(i))));
        }
    }
    sbuf.append("]");
    return sbuf.toString();
}

From source file:org.kuali.ole.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * calculates values for a list of accounting lines based on an amount taking discount into account
 *
 * @param sourceAccountingLines//from  w ww . j a v  a2  s . com
 * @param totalAmount
 * @param discountAmount
 */
@Override
public <T extends PurApAccountingLine> void updateAccountAmountsWithTotal(List<T> sourceAccountingLines,
        KualiDecimal totalAmount, KualiDecimal discountAmount) {

    // if we have a discount, then we need to base the amounts on the discount, but the percent on the total
    boolean noDiscount = true;
    if ((discountAmount != null) && KualiDecimal.ZERO.compareTo(discountAmount) != 0) {
        noDiscount = false;
    }

    if ((totalAmount != null) && KualiDecimal.ZERO.compareTo(totalAmount) != 0) {

        KualiDecimal accountTotal = KualiDecimal.ZERO;
        BigDecimal accountTotalPercent = BigDecimal.ZERO;
        T lastAccount = null;

        for (T account : sourceAccountingLines) {
            if (ObjectUtils.isNotNull(account.getAccountLinePercent())
                    || ObjectUtils.isNotNull(account.getAmount())) {
                if (ObjectUtils.isNotNull(account.getAmount())
                        && account.getAmount().isGreaterThan(KualiDecimal.ZERO)) {
                    KualiDecimal amt = account.getAmount();
                    KualiDecimal calculatedPercent = new KualiDecimal(
                            amt.multiply(new KualiDecimal(100)).divide(totalAmount).toString());
                    account.setAccountLinePercent(
                            calculatedPercent.bigDecimalValue().setScale(BIG_DECIMAL_SCALE));
                }

                if (ObjectUtils.isNotNull(account.getAccountLinePercent())) {
                    BigDecimal pct = new BigDecimal(account.getAccountLinePercent().toString())
                            .divide(new BigDecimal(100));
                    if (noDiscount) {
                        if (ObjectUtils.isNull(account.getAmount()) || account.getAmount().isZero()) {
                            account.setAmount(
                                    new KualiDecimal(pct.multiply(new BigDecimal(totalAmount.toString()))
                                            .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
                        }
                    } else {
                        account.setAmount(
                                new KualiDecimal(pct.multiply(new BigDecimal(discountAmount.toString()))
                                        .setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
                    }
                }
            }

            if (ObjectUtils.isNotNull(account.getAmount())) {
                accountTotal = accountTotal.add(account.getAmount());
            }

            if (ObjectUtils.isNotNull(account.getAccountLinePercent())) {
                accountTotalPercent = accountTotalPercent.add(account.getAccountLinePercent());
            }

            lastAccount = account;
        }

        // put excess on last account
        if (lastAccount != null) {
            KualiDecimal difference = new KualiDecimal(0);
            if (noDiscount) {
                difference = totalAmount.subtract(accountTotal);
            } else {
                difference = discountAmount.subtract(accountTotal);
            }
            if (ObjectUtils.isNotNull(lastAccount.getAmount())) {
                if ((difference.abs()).isLessEqual(new KualiDecimal(1).multiply(
                        new KualiDecimal(sourceAccountingLines.size()).divide(new KualiDecimal(2))))) {
                    lastAccount.setAmount(lastAccount.getAmount().add(difference));
                } else {
                    lastAccount.setAmount(lastAccount.getAmount());
                }
            }
            BigDecimal percentDifference = new BigDecimal(100).subtract(accountTotalPercent)
                    .setScale(BIG_DECIMAL_SCALE, BigDecimal.ROUND_CEILING);
            if (ObjectUtils.isNotNull(lastAccount.getAccountLinePercent())) {

                KualiDecimal differencePercent = (((new KualiDecimal(accountTotalPercent))
                        .subtract(new KualiDecimal(100))).abs());
                if ((differencePercent.abs()).isLessEqual(new KualiDecimal(1).multiply(
                        (new KualiDecimal(sourceAccountingLines.size()).divide(new KualiDecimal(2)))))) {
                    lastAccount
                            .setAccountLinePercent(lastAccount.getAccountLinePercent().add(percentDifference));
                } else {
                    lastAccount.setAccountLinePercent(lastAccount.getAccountLinePercent());
                }
            }
        }
    } else {
        // zero out if extended price is zero
        for (T account : sourceAccountingLines) {
            if (ObjectUtils.isNotNull(account.getAmount())) {
                account.setAmount(KualiDecimal.ZERO);
            }
        }
    }
}

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

/**
 * @param _parameter Parameter as passed from the eFaps API
 * @param _doc          Document//from w w  w  .j  a  v  a2  s . c  o  m
 * @param _transInst    Transaction Instance
 * @param _type         CITYpe
 * @param _account      TargetAccount
 * @return Instance of the new position
 * @throws EFapsException   on error
 */
protected Instance insertPosition4Massiv(final Parameter _parameter, final DocumentInfo _doc,
        final Instance _transInst, final CIType _type, final AccountInfo _account) throws EFapsException {
    final boolean isDebitTrans = _type.equals(CIAccounting.TransactionPositionDebit);
    final Instance accInst = _account.getInstance();
    Instance periodInst = _parameter.getCallInstance();
    if (_parameter.getCallInstance().getType().isKindOf(CIAccounting.SubPeriod.getType())) {
        final PrintQuery print = new CachedPrintQuery(_parameter.getCallInstance(), SubPeriod_Base.CACHEKEY);
        final SelectBuilder selPeriodInst = SelectBuilder.get().linkto(CIAccounting.SubPeriod.PeriodLink)
                .instance();
        print.addSelect(selPeriodInst);
        print.execute();
        periodInst = print.<Instance>getSelect(selPeriodInst);
    }
    final Instance curInstance = new Period().getCurrency(periodInst).getInstance();
    final Insert insert = new Insert(_type);
    insert.add(CIAccounting.TransactionPositionAbstract.TransactionLink, _transInst.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.AccountLink, accInst.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curInstance);
    insert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink,
            _account.getRateInfo().getCurrencyInstance());
    insert.add(CIAccounting.TransactionPositionAbstract.Rate,
            new Object[] { _doc.getRateInfo().getRate(), _account.getRateInfo().getRate() });
    final BigDecimal rateAmount = _account.getAmount();
    insert.add(CIAccounting.TransactionPositionAbstract.RateAmount,
            isDebitTrans ? rateAmount.negate() : rateAmount);
    final BigDecimal amount = _account.getAmountRate(_parameter).setScale(2, BigDecimal.ROUND_HALF_UP);
    insert.add(CIAccounting.TransactionPositionAbstract.Amount, isDebitTrans ? amount.negate() : amount);
    insert.execute();

    final QueryBuilder queryBldr = new QueryBuilder(CIAccounting.Account2AccountAbstract);
    queryBldr.addWhereAttrEqValue(CIAccounting.Account2AccountAbstract.FromAccountLink, accInst.getId());
    final MultiPrintQuery multi = queryBldr.getPrint();
    multi.addAttribute(CIAccounting.Account2AccountAbstract.Numerator,
            CIAccounting.Account2AccountAbstract.Denominator,
            CIAccounting.Account2AccountAbstract.ToAccountLink, CIAccounting.Account2AccountAbstract.Config);
    multi.execute();
    while (multi.next()) {
        final Instance instance = multi.getCurrentInstance();
        boolean add = false;
        Insert insert3 = null;
        BigDecimal amount2 = amount.multiply(
                new BigDecimal(multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Numerator))
                        .divide(new BigDecimal(
                                multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Denominator)),
                                BigDecimal.ROUND_HALF_UP));
        BigDecimal rateAmount2 = rateAmount.multiply(
                new BigDecimal(multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Numerator))
                        .divide(new BigDecimal(
                                multi.<Integer>getAttribute(CIAccounting.Account2AccountAbstract.Denominator)),
                                BigDecimal.ROUND_HALF_UP));
        if (instance.getType().getUUID().equals(CIAccounting.Account2AccountCosting.uuid)) {
            add = true;
            insert3 = new Insert(_type);
        } else if (instance.getType().getUUID().equals(CIAccounting.Account2AccountCostingInverse.uuid)) {
            if (_type.equals(CIAccounting.TransactionPositionDebit)) {
                insert3 = new Insert(CIAccounting.TransactionPositionCredit);
            } else {
                insert3 = new Insert(CIAccounting.TransactionPositionDebit);
            }
            amount2 = amount2.negate();
            rateAmount2 = rateAmount2.negate();
            add = true;
        } else if (instance.getType().getUUID().equals(CIAccounting.Account2AccountCredit.uuid)) {
            if (isDebitTrans) {
                insert3 = new Insert(CIAccounting.TransactionPositionCredit);
            } else {
                insert3 = new Insert(CIAccounting.TransactionPositionDebit);
                amount2 = amount2.negate();
                rateAmount2 = rateAmount2.negate();
            }
            add = true;
        } else if (instance.getType().getUUID().equals(CIAccounting.Account2AccountDebit.uuid)) {
            if (isDebitTrans) {
                insert3 = new Insert(CIAccounting.TransactionPositionDebit);
                amount2 = amount2.negate();
                rateAmount2 = rateAmount2.negate();
            } else {
                insert3 = new Insert(CIAccounting.TransactionPositionCredit);
            }
            add = true;
        }
        final Collection<Accounting.Account2AccountConfig> configs = multi
                .getAttribute(CIAccounting.Account2AccountAbstract.Config);

        add = add && (isDebitTrans && configs != null
                && configs.contains(Accounting.Account2AccountConfig.APPLY4DEBIT)
                || !isDebitTrans && configs != null
                        && configs.contains(Accounting.Account2AccountConfig.APPLY4CREDIT));

        if (add) {
            insert3.add(CIAccounting.TransactionPositionAbstract.TransactionLink, _transInst.getId());
            insert3.add(CIAccounting.TransactionPositionAbstract.AccountLink,
                    multi.<Long>getAttribute(CIAccounting.Account2AccountAbstract.ToAccountLink));
            insert3.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curInstance);
            insert3.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink,
                    _account.getRateInfo().getCurrencyInstance());
            insert3.add(CIAccounting.TransactionPositionAbstract.Rate,
                    new Object[] { _doc.getRateInfo().getRate(), _account.getRateInfo().getRate() });
            insert3.add(CIAccounting.TransactionPositionAbstract.Amount, amount2);
            insert3.add(CIAccounting.TransactionPositionAbstract.RateAmount, rateAmount2);
            insert3.execute();
        }
    }
    return insert.getInstance();
}

From source file:org.libreplan.business.orders.entities.OrderElement.java

public BigDecimal calculateBudgetFromCriteriaAndCostCategories() {
    BigDecimal totalBudget = new BigDecimal(0);

    Configuration configuration = Registry.getConfigurationDAO().getConfiguration();
    TypeOfWorkHours typeofWorkHours = configuration.getBudgetDefaultTypeOfWorkHours();

    if (!configuration.isEnabledAutomaticBudget()
            || (configuration.getBudgetDefaultTypeOfWorkHours() == null)) {
        return totalBudget;
    }//from  w ww  .j  av a2s  .c  o  m

    BigDecimal costPerHour = new BigDecimal(0);
    BigDecimal hours;

    for (HoursGroup hoursGroup : getHoursGroups()) {
        hours = new BigDecimal(hoursGroup.getWorkingHours());

        for (CriterionRequirement crit : hoursGroup.getCriterionRequirements()) {
            CostCategory costcat = crit.getCriterion().getCostCategory();

            if (costcat != null) {

                IHourCostDAO hourCostDAO = Registry.getHourCostDAO();
                costPerHour = hourCostDAO.getPriceCostFromCriterionAndType(costcat, typeofWorkHours);

            }
            totalBudget = totalBudget.add(costPerHour.multiply(hours));
        }
        if (hoursGroup.getCriterionRequirements().size() > 1) {
            totalBudget = totalBudget.divide(new BigDecimal(hoursGroup.getCriterionRequirements().size()));
        }
    }

    return totalBudget;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hyperbolic sine.//from  www. j a va  2s . c om
 *
 * @param x the argument.
 * @return the sinh(x) = (exp(x)-exp(-x))/2 .
 */
static public BigDecimal sinh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return sinh(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        if (x.doubleValue() > 2.4) {
            /* Move closer to zero with sinh(2x)= 2*sinh(x)*cosh(x).
             */
            BigDecimal two = new BigDecimal(2);
            BigDecimal xhalf = x.divide(two);

            BigDecimal resul = sinh(xhalf).multiply(cosh(xhalf)).multiply(two);
            /* The error in the result is set by the error in x itself.
             * The first derivative of sinh(x) is cosh(x), so the absolute error
             * in the result is cosh(x)*errx, and the relative error is coth(x)*errx = errx/tanh(x)
             */

            double eps = Math.tanh(x.doubleValue());
            MathContext mc = new MathContext(err2prec(0.5 * x.ulp().doubleValue() / eps));

            return resul.round(mc);

        } else {
            BigDecimal xhighpr = scalePrec(x, 2);
            /* Simple Taylor expansion, sum_{i=0..infinity} x^(2i+1)/(2i+1)! */
            BigDecimal resul = xhighpr;
            /* x^i */
            BigDecimal xpowi = xhighpr;
            /* 2i+1 factorial */
            BigInteger ifac = BigInteger.ONE;
            /* The error in the result is set by the error in x itself.
             */

            double xUlpDbl = x.ulp().doubleValue();
            /* The error in the result is set by the error in x itself.
             * We need at most k terms to squeeze x^(2k+1)/(2k+1)! below this value.
             * x^(2k+1) < x.ulp; (2k+1)*log10(x) < -x.precision; 2k*log10(x)< -x.precision;
             * 2k*(-log10(x)) > x.precision; 2k*log10(1/x) > x.precision
             */

            int k = (int) (x.precision() / Math.log10(1.0 / xhighpr.doubleValue())) / 2;
            MathContext mcTay = new MathContext(err2prec(x.doubleValue(), xUlpDbl / k));

            for (int i = 1;; i++) {
                /* TBD: at which precision will 2*i or 2*i+1 overflow?
                 */
                ifac = ifac.multiply(new BigInteger("" + (2 * i)));
                ifac = ifac.multiply(new BigInteger("" + (2 * i + 1)));
                xpowi = xpowi.multiply(xhighpr).multiply(xhighpr);
                BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay);
                resul = resul.add(corr);

                if (corr.abs().doubleValue() < 0.5 * xUlpDbl) {
                    break;
                }

            } /* The error in the result is set by the error in x itself.
              */
            MathContext mc = new MathContext(x.precision());

            return resul.round(mc);

        }
    }
}

From source file:org.kuali.kfs.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * @see org.kuali.kfs.module.purap.service.PurapAccountingService#convertMoneyToPercent(org.kuali.kfs.module.purap.document.PaymentRequestDocument)
 *///from w  w w  . ja  v a 2 s.c  o  m
@Override
public void convertMoneyToPercent(PaymentRequestDocument pr) {
    LOG.debug("convertMoneyToPercent() started");

    int itemNbr = 0;

    for (Iterator<PaymentRequestItem> iter = pr.getItems().iterator(); iter.hasNext();) {
        PaymentRequestItem item = iter.next();

        itemNbr++;
        String identifier = item.getItemIdentifierString();

        if (item.getTotalAmount() != null && item.getTotalAmount().isNonZero()) {
            int numOfAccounts = item.getSourceAccountingLines().size();
            BigDecimal percentTotal = BigDecimal.ZERO;
            BigDecimal percentTotalRoundUp = BigDecimal.ZERO;
            KualiDecimal accountTotal = KualiDecimal.ZERO;
            int accountIdentifier = 0;

            for (Iterator<PurApAccountingLine> iterator = item.getSourceAccountingLines().iterator(); iterator
                    .hasNext();) {
                accountIdentifier++;
                PaymentRequestAccount account = (PaymentRequestAccount) iterator.next();

                // account.getAmount returns the wrong value for trade in source accounting lines...
                KualiDecimal accountAmount = KualiDecimal.ZERO;
                if (ObjectUtils.isNotNull(account.getAmount())) {
                    accountAmount = account.getAmount();
                }

                BigDecimal tmpPercent = BigDecimal.ZERO;
                KualiDecimal extendedPrice = item.getTotalAmount();
                tmpPercent = accountAmount.bigDecimalValue().divide(extendedPrice.bigDecimalValue(),
                        PurapConstants.CREDITMEMO_PRORATION_SCALE.intValue(), KualiDecimal.ROUND_BEHAVIOR);

                if (accountIdentifier == numOfAccounts) {
                    // if on last account, calculate the percent by subtracting current percent total from 1
                    tmpPercent = BigDecimal.ONE.subtract(percentTotal);
                }

                // test that the above amount is correct, if so just check that the total of all these matches the item total
                BigDecimal calcAmountBd = tmpPercent.multiply(extendedPrice.bigDecimalValue());
                calcAmountBd = calcAmountBd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR);
                KualiDecimal calcAmount = new KualiDecimal(calcAmountBd);
                if (calcAmount.compareTo(accountAmount) != 0) {
                    // rounding error
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("convertMoneyToPercent() Rounding error on " + account);
                    }
                    String param1 = identifier + "." + accountIdentifier;
                    String param2 = calcAmount.bigDecimalValue().subtract(accountAmount.bigDecimalValue())
                            .toString();
                    GlobalVariables.getMessageMap().putError(item.getItemIdentifierString(),
                            PurapKeyConstants.ERROR_ITEM_ACCOUNTING_ROUNDING, param1, param2);
                    account.setAmount(calcAmount);
                }

                // update percent
                if (LOG.isDebugEnabled()) {
                    LOG.debug("convertMoneyToPercent() updating percent to " + tmpPercent);
                }
                account.setAccountLinePercent(tmpPercent.multiply(new BigDecimal(100)));
                // handle 33.33% issue
                if (accountIdentifier == numOfAccounts) {
                    account.setAccountLinePercent(new BigDecimal(100).subtract(percentTotalRoundUp));
                }

                // check total based on adjusted amount
                accountTotal = accountTotal.add(calcAmount);
                percentTotal = percentTotal.add(tmpPercent);
                percentTotalRoundUp = percentTotalRoundUp.add(account.getAccountLinePercent());
            }
        }
    }
}

From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java

private void prepareResponseDataForConnectionType(final WaterChargeDashBoardRequest collectionDetailsRequest,
        final List<WaterChargeConnectionTypeResponse> waterchargeConndemandList, final String aggregationField,
        final Map<String, BigDecimal> connectionResidentialTotalDemandMap,
        final Map<String, Long> connectionCommercialcountMap,
        final Map<String, BigDecimal> connectionCOmmercialTotalDemandMap, final Map.Entry<String, Long> entry,
        final Map<String, BigDecimal> connectionResidentialTotalCollectionMap,
        final Map<String, BigDecimal> connectionCOmmercialTotalCollectionMap) {
    String name;// ww  w  .  j a  v  a 2 s  . c om
    final WaterChargeConnectionTypeResponse receiptData = new WaterChargeConnectionTypeResponse();
    name = entry.getKey();

    if (WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD.equals(aggregationField))
        receiptData.setRegionName(name);
    else if (WaterTaxConstants.DISTRICTNAMEAGGREGATIONFIELD.equals(aggregationField)) {
        receiptData.setRegionName(collectionDetailsRequest.getRegionName());
        receiptData.setDistrictName(name);
    } else if (WaterTaxConstants.CITYNAMEAGGREGATIONFIELD.equals(aggregationField)) {
        receiptData.setUlbName(name);
        receiptData.setDistrictName(collectionDetailsRequest.getDistrictName());
        receiptData.setUlbGrade(collectionDetailsRequest.getUlbGrade());
    } else if (WaterTaxConstants.CITYGRADEAGGREGATIONFIELD.equals(aggregationField))
        receiptData.setUlbGrade(name);
    else if (WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD.equals(aggregationField))
        receiptData.setWardName(name);
    final Date fromDate = new DateTime().withMonthOfYear(4).dayOfMonth().withMinimumValue().toDate();
    final Date toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);

    final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1;
    final BigDecimal totalResDemandValue = !connectionResidentialTotalDemandMap.isEmpty()
            && connectionResidentialTotalDemandMap.get(name) != null
                    ? connectionResidentialTotalDemandMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO;
    final BigDecimal totalResCollections = !connectionResidentialTotalCollectionMap.isEmpty()
            && connectionResidentialTotalCollectionMap.get(name) != null
                    ? connectionResidentialTotalCollectionMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO;
    final BigDecimal proportionalDemand = totalResDemandValue
            .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(noOfMonths));
    receiptData.setResidentialAchievement(totalResCollections.multiply(WaterTaxConstants.BIGDECIMAL_100)
            .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP));

    final BigDecimal totalCommDemandValue = !connectionCOmmercialTotalDemandMap.isEmpty()
            && connectionCOmmercialTotalDemandMap.get(name) != null
                    ? connectionCOmmercialTotalDemandMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO;
    final BigDecimal totalCommCollections = !connectionCOmmercialTotalCollectionMap.isEmpty()
            && connectionCOmmercialTotalCollectionMap.get(name) != null
                    ? connectionCOmmercialTotalCollectionMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO;
    final BigDecimal commproportionalDemand = totalCommDemandValue
            .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(noOfMonths));
    receiptData.setCommercialAchievement(commproportionalDemand.compareTo(BigDecimal.ZERO) > 0
            ? totalCommCollections.multiply(WaterTaxConstants.BIGDECIMAL_100).divide(commproportionalDemand, 1,
                    BigDecimal.ROUND_HALF_UP)
            : BigDecimal.ZERO);

    receiptData
            .setWaterChargeCommercialaverage(connectionCommercialcountMap.get(name) != null
                    ? totalCommDemandValue.divide(BigDecimal.valueOf(connectionCommercialcountMap.get(name)), 1,
                            BigDecimal.ROUND_HALF_UP)
                    : BigDecimal.ZERO);

    receiptData.setWaterChargeResidentialaverage(
            totalResDemandValue.divide(BigDecimal.valueOf(entry.getValue()), 1, BigDecimal.ROUND_HALF_UP));

    receiptData.setResidentialConnectionCount(entry.getValue());
    receiptData.setUlbName(name);
    receiptData.setResidentialtotalCollection(!connectionResidentialTotalCollectionMap.isEmpty()
            && connectionResidentialTotalCollectionMap.get(name) != null
                    ? connectionResidentialTotalCollectionMap.get(name)
                    : BigDecimal.ZERO);
    receiptData.setCommercialConnectionCount(connectionCommercialcountMap.get(name));
    receiptData.setComercialtotalCollection(!connectionCOmmercialTotalCollectionMap.isEmpty()
            && connectionCOmmercialTotalCollectionMap.get(name) != null
                    ? connectionCOmmercialTotalCollectionMap.get(name)
                    : BigDecimal.ZERO);

    waterchargeConndemandList.add(receiptData);
}

From source file:com.wso2telco.dep.reportingservice.northbound.NbHostObjectUtils.java

/**
 * Bill component./*from  w w  w  .  j a v a2  s.c om*/
 *
 * @param rate the rate
 * @param rateCard the rate card
 * @param operatorSubscription the operator subscription
 * @param subsYear the subs year
 * @param subsMonth the subs month
 * @param application the application
 * @param ApiName the api name
 * @param apiVersion the api version
 * @param categoryEntry the category entry
 * @param appId the app id
 * @param apiId the api id
 * @param subsId the subs id
 * @throws Exception 
 */
private static void billComponent(ChargeRate rate, Map<RateKey, ChargeRate> rateCard,
        BillingSubscription.OperatorSubscription operatorSubscription, String subsYear, String subsMonth,
        Application application, String ApiName, String apiVersion,
        Map.Entry<CategoryCharge, BilledCharge> categoryEntry, int appId, int apiId, String subsId)
        throws Exception {

    String billCategory = categoryEntry.getKey().getCategory();
    String billSubCategory = categoryEntry.getKey().getSubcategory();
    BigDecimal billRate = rate.getValue();
    Object SubsRate = null;

    switch (rate.getType()) {

    case CONSTANT:

        SubsRate = getRateSubcategory(rate, billCategory, billSubCategory);
        if (SubsRate != null) {
            billRate = new BigDecimal((String) SubsRate);
        }
        categoryEntry.getValue().setPrice(billRate);
        applyTaxForBlockCharging(categoryEntry, rate, subsYear, subsMonth);
        break;

    case QUOTA:

        Map<String, String> rateAttributes = (Map<String, String>) rate.getRateAttributes();
        SubsRate = getRateSubcategory(rate, billCategory, billSubCategory);
        if (SubsRate != null) {
            rateAttributes = (Map<String, String>) SubsRate;
        }

        if (rateAttributes == null
                || !rateAttributes.containsKey(HostObjectConstants.RATE_ATTRIBUTE_MAX_COUNT.toString())
                || !rateAttributes.containsKey(HostObjectConstants.RATE_ATTRIBUTE_EXCESS_RATE.toString())
                || !rateAttributes.containsKey(HostObjectConstants.RATE_ATTRIBUTE_DEFAULT_RATE.toString())) {
            throw new APIManagementException(
                    "Attributes required for QUOTA charging are not specified in rate-card.xml");
        }
        int maxCount = Integer
                .parseInt(rateAttributes.get(HostObjectConstants.RATE_ATTRIBUTE_MAX_COUNT.toString()));
        BigDecimal excessRate = new BigDecimal(
                rateAttributes.get(HostObjectConstants.RATE_ATTRIBUTE_EXCESS_RATE.toString()));
        BigDecimal defaultRate = new BigDecimal(
                rateAttributes.get(HostObjectConstants.RATE_ATTRIBUTE_DEFAULT_RATE.toString()));

        if (categoryEntry.getValue().getCount() > maxCount) {
            int excess = categoryEntry.getValue().getCount() - maxCount;
            BigDecimal charge = excessRate.multiply(BigDecimal.valueOf(excess)).add(defaultRate);
            categoryEntry.getValue().setPrice(charge);
        } else {
            categoryEntry.getValue().setPrice(defaultRate);
        }
        applyTaxForBlockCharging(categoryEntry, rate, subsYear, subsMonth);
        break;

    case MULTITIER:
        int totalRequestCount = categoryEntry.getValue().getCount();

        BigDecimal price = BigDecimal.ZERO;
        int tierCount = 0;
        List<UsageTiers> usageTier = rate.getUsageTiers();
        SubsRate = getRateSubcategory(rate, billCategory, billSubCategory);
        if (SubsRate != null) {
            usageTier = (List<UsageTiers>) SubsRate;
        }

        calculateTiersCharges(usageTier, rateCard, totalRequestCount, tierCount, operatorSubscription, subsYear,
                subsMonth, application, ApiName, apiVersion, categoryEntry, appId, apiId, subsId);
        break;

    case PERCENTAGE:
        APIKey prodKey = getAppKey(application, APIConstants.API_KEY_TYPE_PRODUCTION);
        if (prodKey != null) {
            String consumerKey = prodKey.getConsumerKey();
            String api_version = ApiName + ":v" + apiVersion;
            BillingDAO billingDAO = new BillingDAO();
            Set<PaymentRequestDTO> paymentRequestSet = billingDAO.getNbPaymentAmounts(
                    Short.parseShort(subsYear), Short.parseShort(subsMonth), consumerKey, api_version,
                    operatorSubscription.getOperationId(), categoryEntry.getKey().getCategory(),
                    categoryEntry.getKey().getSubcategory());
            applyChargesForPaymentApi(operatorSubscription, paymentRequestSet, categoryEntry, appId, apiId,
                    subsId);
        }
        break;

    case SUBSCRIPTION:
        int noOfSubscribers = categoryEntry.getValue().getCount();
        if (SubsRate != null) {
            billRate = new BigDecimal((String) SubsRate);
        }
        categoryEntry.getValue().setPrice(billRate.multiply(new BigDecimal(noOfSubscribers)));
        applyTaxForBlockCharging(categoryEntry, rate, subsYear, subsMonth);
        break;

    case PER_REQUEST:
        applyChargesWithTax(subsYear, subsMonth, application, ApiName, apiVersion, operatorSubscription,
                categoryEntry, rate);
        break;

    default:
        break;
    }

}

From source file:org.kuali.kfs.module.endow.document.service.impl.CurrentTaxLotServiceImpl.java

/**
 * calculates the remainder of fiscal year estimated income for cash
 * /*from   w w  w  .  j  a va2s .  com*/
 * @param security
 * @param holdingTaxLot
 * @return amount
 */
protected BigDecimal getRemainderOfFiscalYearEstimatedIncomeForCash(Security security,
        HoldingTaxLot holdingTaxLot) {
    BigDecimal amount = BigDecimal.ZERO;

    if (ObjectUtils.isNull(security.getIncomeRate())
            || security.getIncomeRate().compareTo(BigDecimal.ZERO) == 0) {
        return amount;
    }

    Date nextIncomeDueDate = security.getIncomeNextPayDate();
    Date fiscalYearEndDate = getFiscalYearEndDate();
    String incomePayFrequency = security.getIncomePayFrequency();

    if (ObjectUtils.isNull(nextIncomeDueDate) || ObjectUtils.isNull(incomePayFrequency)) {
        return amount;
    }

    // BONDS - rule 3.a
    if (nextIncomeDueDate.after(fiscalYearEndDate)) {
        return BigDecimal.ZERO;
    }

    // rule 3.b
    if (nextIncomeDueDate.before(fiscalYearEndDate)) {
        Date lastPaymentDate = getLastPaymentDate(incomePayFrequency, fiscalYearEndDate);
        long daysToLastPayment = getTotalDaysToLastPayment(lastPaymentDate, nextIncomeDueDate);

        amount = KEMCalculationRoundingHelper.multiply(holdingTaxLot.getUnits(), security.getIncomeRate(),
                EndowConstants.Scale.SECURITY_MARKET_VALUE);
        amount = amount.multiply(BigDecimal.valueOf(daysToLastPayment));
        amount = KEMCalculationRoundingHelper.divide(amount,
                BigDecimal.valueOf(EndowConstants.NUMBER_OF_DAYS_IN_YEAR),
                EndowConstants.Scale.SECURITY_MARKET_VALUE);
        amount = amount.add(holdingTaxLot.getCurrentAccrual());
    }

    return amount;
}

From source file:com.wso2telco.dep.reportingservice.southbound.SbHostObjectUtils.java

/**
 * Bill component.//from w  w  w  .  j a va2s.c  o m
 *
 * @param rate the rate
 * @param rateCard the rate card
 * @param operatorSubscription the operator subscription
 * @param subsYear the subs year
 * @param subsMonth the subs month
 * @param application the application
 * @param ApiName the api name
 * @param apiVersion the api version
 * @param categoryEntry the category entry
 * @param appId the app id
 * @param apiId the api id
 * @param subsId the subs id
 * @throws Exception 
 */
private static void billComponent(ChargeRate rate, Map<RateKey, ChargeRate> rateCard,
        BillingSubscription.OperatorSubscription operatorSubscription, String subsYear, String subsMonth,
        Application application, String ApiName, String apiVersion,
        Map.Entry<CategoryCharge, BilledCharge> categoryEntry, int appId, int apiId, String subsId)
        throws Exception {

    String billCategory = categoryEntry.getKey().getCategory();
    String billSubCategory = categoryEntry.getKey().getSubcategory();
    BigDecimal billRate = rate.getValue();
    Object SubsRate = null;

    switch (rate.getType()) {

    case CONSTANT:
        // apply charge for category

        SubsRate = getRateSubcategory(rate, billCategory, billSubCategory);
        if (SubsRate != null) {
            billRate = new BigDecimal((String) SubsRate);
        }
        categoryEntry.getValue().setPrice(billRate);
        applyTaxForBlockCharging(categoryEntry, rate, subsYear, subsMonth);
        break;

    case QUOTA:

        Map<String, String> rateAttributes = (Map<String, String>) rate.getRateAttributes();

        SubsRate = getRateSubcategory(rate, billCategory, billSubCategory);

        if (SubsRate != null) {
            rateAttributes = (Map<String, String>) SubsRate;
        }

        if (rateAttributes == null
                || !rateAttributes.containsKey(HostObjectConstants.RATE_ATTRIBUTE_MAX_COUNT.toString())
                || !rateAttributes.containsKey(HostObjectConstants.RATE_ATTRIBUTE_EXCESS_RATE.toString())
                || !rateAttributes.containsKey(HostObjectConstants.RATE_ATTRIBUTE_DEFAULT_RATE.toString())) {
            throw new APIManagementException(
                    "Attributes required for QUOTA charging are not specified in rate-card.xml");
        }

        int maxCount = Integer
                .parseInt(rateAttributes.get(HostObjectConstants.RATE_ATTRIBUTE_MAX_COUNT.toString()));
        BigDecimal excessRate = new BigDecimal(
                rateAttributes.get(HostObjectConstants.RATE_ATTRIBUTE_EXCESS_RATE.toString()));
        BigDecimal defaultRate = new BigDecimal(
                rateAttributes.get(HostObjectConstants.RATE_ATTRIBUTE_DEFAULT_RATE.toString()));

        if (categoryEntry.getValue().getCount() > maxCount) {
            int excess = categoryEntry.getValue().getCount() - maxCount;
            BigDecimal charge = excessRate.multiply(BigDecimal.valueOf(excess)).add(defaultRate);
            categoryEntry.getValue().setPrice(charge);
        } else {
            categoryEntry.getValue().setPrice(defaultRate);
        }
        applyTaxForBlockCharging(categoryEntry, rate, subsYear, subsMonth);
        break;

    case MULTITIER:
        int totalRequestCount = categoryEntry.getValue().getCount();

        BigDecimal price = BigDecimal.ZERO;
        int tierCount = 0;
        List<UsageTiers> usageTier = rate.getUsageTiers();
        SubsRate = getRateSubcategory(rate, billCategory, billSubCategory);
        if (SubsRate != null) {
            usageTier = (List<UsageTiers>) SubsRate;
        }

        calculateTiersCharges(usageTier, rateCard, totalRequestCount, tierCount, operatorSubscription, subsYear,
                subsMonth, application, ApiName, apiVersion, categoryEntry, appId, apiId, subsId);
        break;

    case PERCENTAGE:
        APIKey prodKey = getAppKey(application, APIConstants.API_KEY_TYPE_PRODUCTION);
        if (prodKey != null) {
            String consumerKey = prodKey.getConsumerKey();
            String api_version = ApiName + ":v" + apiVersion;
            BillingDAO billingDAO = new BillingDAO();
            Set<PaymentRequestDTO> paymentRequestSet = billingDAO.getPaymentAmounts(Short.parseShort(subsYear),
                    Short.parseShort(subsMonth), consumerKey, api_version, operatorSubscription.getOperator(),
                    operatorSubscription.getOperationId(), categoryEntry.getKey().getCategory(),
                    categoryEntry.getKey().getSubcategory());
            applyChargesForPaymentApi(operatorSubscription, paymentRequestSet, categoryEntry, appId, apiId,
                    subsId);
        }
        break;

    case SUBSCRIPTION:
        // Update the Handler to count the subscribers operator wise
        int noOfSubscribers = categoryEntry.getValue().getCount();
        if (SubsRate != null) {
            billRate = new BigDecimal((String) SubsRate);
        }
        categoryEntry.getValue().setPrice(billRate.multiply(new BigDecimal(noOfSubscribers)));
        applyTaxForBlockCharging(categoryEntry, rate, subsYear, subsMonth);
        break;

    case PER_REQUEST:
        applyChargesWithTax(subsYear, subsMonth, application, ApiName, apiVersion, operatorSubscription,
                categoryEntry, rate);
        break;

    default:
        break;
    }

}