Example usage for java.math BigDecimal add

List of usage examples for java.math BigDecimal add

Introduction

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

Prototype

public BigDecimal add(BigDecimal augend) 

Source Link

Document

Returns a BigDecimal whose value is (this + augend) , and whose scale is max(this.scale(), augend.scale()) .

Usage

From source file:com.gst.portfolio.loanaccount.service.LoanReadPlatformServiceImpl.java

private void updateInterestRatePeriodData(InterestRatePeriodData rate, LoanAccountData loan) {
    LoanProductData loanProductData = loanProductReadPlatformService
            .retrieveLoanProductFloatingDetails(loan.loanProductId());
    rate.setLoanProductDifferentialInterestRate(loanProductData.getInterestRateDifferential());
    rate.setLoanDifferentialInterestRate(loan.getInterestRateDifferential());

    BigDecimal effectiveInterestRate = BigDecimal.ZERO;
    effectiveInterestRate = effectiveInterestRate.add(rate.getLoanDifferentialInterestRate());
    effectiveInterestRate = effectiveInterestRate.add(rate.getLoanProductDifferentialInterestRate());
    effectiveInterestRate = effectiveInterestRate.add(rate.getInterestRate());
    if (rate.getBlrInterestRate() != null && rate.isDifferentialToBLR()) {
        effectiveInterestRate = effectiveInterestRate.add(rate.getBlrInterestRate());
    }/* ww w. j av a2s.  c  o  m*/
    rate.setEffectiveInterestRate(effectiveInterestRate);

    if (rate.getFromDate().compareTo(loan.getDisbursementDate().toDate()) < 0) {
        rate.setFromDate(loan.getDisbursementDate().toDate());
    }
}

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

/**
 * Apply charges with tax.//from   ww w.ja v  a 2 s .  co  m
 *
 * @param apiYear the api year
 * @param apiMonth the api month
 * @param application the application
 * @param apiName the api name
 * @param apiVersion the api version
 * @param operatorSub the operator sub
 * @param CatEntry the cat entry
 * @param rate the rate
 * @throws Exception 
 */
private static void applyChargesWithTax(String apiYear, String apiMonth, Application application,
        String apiName, String apiVersion, BillingSubscription.OperatorSubscription operatorSub,
        Map.Entry<CategoryCharge, BilledCharge> CatEntry, ChargeRate rate) throws Exception {
    String month = apiMonth;
    String year = apiYear;
    boolean isSurcharge = false;

    if (application == null) {
        throw new APIManagementException("no key generated for this api");
    }
    APIKey prodKey = getAppKey(application, APIConstants.API_KEY_TYPE_PRODUCTION);

    Set<APIRequestDTO> requestTimes = new HashSet<APIRequestDTO>();
    if (prodKey != null) {
        String api_version = apiName + ":v" + apiVersion;

        TaxDAO taxDAO = new TaxDAO();
        requestTimes = taxDAO.getAPIRequestTimesForSubscription(Short.parseShort(year), Short.parseShort(month),
                apiName, api_version, prodKey.getConsumerKey(), operatorSub.getOperator(),
                operatorSub.getOperationId(), CatEntry.getKey().getCategory(),
                CatEntry.getKey().getSubcategory());

    }

    String billCategory = CatEntry.getKey().getCategory();
    String billSubCategory = CatEntry.getKey().getSubcategory();
    BigDecimal billRate = rate.getValue();
    BigDecimal OpscomPercnt = null;

    Object SubsRate = getRateSubcategory(rate, billCategory, billSubCategory);
    if (SubsRate != null) {
        billRate = new BigDecimal((String) SubsRate);
    }

    // Surcharge value
    if (rate.getSurchargeEntity() != null) {
        billRate = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementValue());
        OpscomPercnt = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementOpco())
                .divide(new BigDecimal(100));
        isSurcharge = true;
    }

    TaxDAO taxDAO = new TaxDAO();
    List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList());
    BigDecimal totalCharge = BigDecimal.ZERO;
    BigDecimal totalTax = BigDecimal.ZERO;
    BigDecimal totalOpcom = BigDecimal.ZERO;
    BigDecimal totalAdscom = BigDecimal.ZERO;

    int reqCount = 0;
    for (APIRequestDTO req : requestTimes) {

        if (reqCount >= CatEntry.getValue().getCount()) {
            break;
        }

        BigDecimal charge = billRate.multiply(new BigDecimal(req.getRequestCount()));
        if (isSurcharge) {
            BigDecimal opcoCommision = billRate.multiply(OpscomPercnt);
            totalOpcom = totalOpcom.add(opcoCommision);
            totalAdscom = totalAdscom.add(charge.subtract(opcoCommision));
        } else {
            totalCharge = totalCharge.add(charge);
        }

        Date date = req.getDate();
        for (Tax tax : taxList) {

            // check if the date of payment request falls between this tax
            // validity period
            if (!date.before(tax.getEffective_from()) && !date.after(tax.getEffective_to())) {
                totalTax = totalTax.add(tax.getValue().multiply(charge));
            }
        }
        reqCount++;
    }

    CatEntry.getValue().addPrice(totalCharge);
    CatEntry.getValue().addTax(totalTax);
    CatEntry.getValue().addOpcom(totalOpcom);
    CatEntry.getValue().addAdscom(totalAdscom);

}

From source file:logic.EntityCar.java

private void estimate() {
    //BigDecimal pq = BigDecimal.valueOf(ie.params.size());
    //BigDecimal pq = BigDecimal.valueOf(0);
    for (EntityPropertyHolder eph : aprops.values()) {
        //pq = pq.add(BigDecimal.valueOf(1));
        dinamicRateA = dinamicRateA.add(eph.dinamicRate);
        //staticRate = staticRate.add(eph.staticRate);
        //suplog+="--"+eph.supLog+"--";
    }//from w  w  w  . ja  v a2  s . c om
    for (EntityPropertyHolder eph : bprops.values()) {
        //pq = pq.add(BigDecimal.valueOf(1));
        dinamicRateB = dinamicRateB.add(eph.dinamicRate);
        //staticRate = staticRate.add(eph.staticRate);
        //suplog += "=--" + eph.supLog + "--;";
        if (!eph.activeProperty.isEmpty()) {
            suplog += eph.activeProperty.get(0).uid + "-" + eph.activeProperty.get(0).price + ";";
        }

    }

    if (staticProps.keySet().size() > 0) {
        BigDecimal supsr = BigDecimal.valueOf(0);
        //BigDecimal divisor = BigDecimal.valueOf(staticProps.keySet().size());
        for (String uid : staticProps.keySet()) {
            if (!staticProps.get(uid).isEmpty()) {
                supsr = supsr.add(staticProps.get(uid).get(0).value);
            }
        }
        staticRate = supsr;
        ///staticRate = supsr.divide(divisor, 2, RoundingMode.HALF_UP);
    } else {
        staticRate = BigDecimal.valueOf(0);
    }
    fullPrice = fullPrice.add(aFund2).add(bFund2);
    //suplog+="!stats: "+staticProps.keySet().size();
    //staticRate = pq;
    //dinamicRate = dinamicRate.divide(pq,2, RoundingMode.HALF_UP);
    //staticRate = staticRate.divide(pq,2, RoundingMode.HALF_UP);
}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * ???id id????-//from w w w.  j  av  a  2  s  . co m
 *
 * @param cityId
 * @return
 */

@Override
public Map<String, Object> getNewExpressPrice(Long cityId, List<Long> cartIds) {

    List<ShoppingCart> shopdata = shoppingCartMapper.shopCartListByIds(cartIds);
    // List<ShoppingCart> shopthird = new ArrayList<>();
    Map<Long, Object> thirdMap = new HashMap<>();
    BigDecimal freightmoney = BigDecimal.ZERO;
    // boss???
    BigDecimal bossfreight = BigDecimal.ZERO;
    // ??
    List<ShoppingCart> cartList = getNobaoyouShoppingcarts(shopdata);
    if (CollectionUtils.isNotEmpty(cartList)) {

        // id?
        for (ShoppingCart sh : cartList) {
            if (sh.getThirdId() != null) {
                thirdMap.put(sh.getThirdId(), "");

            } else {
                if (sh.getFitId() != null) {
                }
            }
        }
        for (Long thirdId : thirdMap.keySet()) {
            freightmoney = freightmoney.add(getEverythirdExpressPrice(thirdId, cityId, cartList));
            if (thirdId == 0) {
                bossfreight = bossfreight.add(getEverythirdExpressPrice(thirdId, cityId, cartList));
            }
        }

    }
    Map<String, Object> freightMap = new HashMap<>();
    // ?
    freightMap.put("freightmoney", freightmoney);
    // boss??
    freightMap.put("bossfreight", bossfreight);
    return freightMap;

}

From source file:com.salesmanager.core.service.order.OrderService.java

@Transactional
private OrderTotalSummary calculateOrderTotal(Order order, Collection<OrderProduct> products, Customer customer,
        Shipping shipping, String currency, Locale locale) throws Exception {

    OrderTotalSummary summary = new OrderTotalSummary(order.getCurrency());

    if (products != null) {
        Iterator i = products.iterator();

        // calculates oneTimeSubTotal
        // BigDecimal oneTimeSubTotal = summary.getOneTimeSubTotal();

        while (i.hasNext()) {
            OrderProduct product = (OrderProduct) i.next();
            product.setApplicableCreditOneTimeCharge(new BigDecimal("0"));
            product.setSoldPrice(new BigDecimal("0"));

            if (product.isShipping()) {
                summary.setShipping(true);
            }/* w  w w .  j a v  a2s . com*/

            // get unit price
            BigDecimal price = product.getProductPrice();

            // get the prices for each
            Set productPrices = product.getPrices();
            boolean defaultPriceMet = false;

            if (productPrices != null && productPrices.size() > 0) {
                Iterator it = productPrices.iterator();

                while (it.hasNext()) {
                    OrderProductPrice pp = (OrderProductPrice) it.next();
                    PriceModule priceModule = (PriceModule) SpringUtil.getBean(pp.getProductPriceModuleName());
                    if (priceModule == null) {
                        log.warn("Price Module " + pp.getProductPriceModuleName()
                                + " is not defined in sm-core-beans.xml");
                        continue;
                    }

                    // price module will set the price in order summary
                    summary = priceModule.calculateOrderPrice(order, summary, product, pp, currency, locale);

                    if (pp.isDefaultPrice()) {
                        defaultPriceMet = true;
                        // BigDecimal t = summary.getOneTimeSubTotal();
                        // t = t.add(product.getProductPrice()).multiply(
                        // new BigDecimal(product.getProductQuantity()));
                        // summary.setOneTimeSubTotal(t);
                    }

                }
            } else {// consider the price submited as one time
                if (summary.getOneTimeSubTotal() == null) {

                    BigDecimal oneTimeSubTotal = new BigDecimal(0);
                    //oneTimeSubTotal.setScale(0, BigDecimal.ROUND_DOWN);

                    summary.setOneTimeSubTotal(oneTimeSubTotal);
                }
                BigDecimal t = summary.getOneTimeSubTotal();
                BigDecimal subTotal = price.multiply(new BigDecimal(product.getProductQuantity()));
                t = t.add(subTotal);
                summary.setOneTimeSubTotal(t);
                defaultPriceMet = true;

                // check for regular discount
                // Special sp = product.getBasePriceSpecial();
                java.util.Date spdate = null;
                java.util.Date spenddate = null;
                BigDecimal bddiscountprice = null;
                if (product.getProductSpecialNewPrice() != null) {
                    bddiscountprice = product.getProductSpecialNewPrice();
                    spdate = product.getProductSpecialDateAvailable();
                    spenddate = product.getProductSpecialDateExpire();
                    if (spdate != null && spdate.before(new Date()) && spdate != null
                            && spenddate.after(new Date())) {

                        OrderTotalLine line = new OrderTotalLine();

                        BigDecimal st = product.getOriginalProductPrice()
                                .multiply(new BigDecimal(product.getProductQuantity()));
                        BigDecimal creditSubTotal = bddiscountprice
                                .multiply(new BigDecimal(product.getProductQuantity()));
                        BigDecimal credit = subTotal.subtract(creditSubTotal);

                        // BigDecimal credit =
                        // product.getOriginalProductPrice().subtract(bddiscountprice);

                        StringBuffer spacialNote = new StringBuffer();
                        spacialNote.append("<font color=\"red\">[");
                        spacialNote.append(product.getProductName());
                        spacialNote.append(" ");
                        spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                        spacialNote.append("]</font>");

                        line.setCost(credit);
                        line.setText(spacialNote.toString());
                        line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                        summary.addDueNowCredits(line);

                        BigDecimal oneTimeCredit = product.getApplicableCreditOneTimeCharge();
                        oneTimeCredit = oneTimeCredit.add(credit);
                        product.setApplicableCreditOneTimeCharge(oneTimeCredit);

                    }
                }

            }

            if (!defaultPriceMet) {
                BigDecimal t = summary.getOneTimeSubTotal();

                BigDecimal subTotal = price.multiply(new BigDecimal(product.getProductQuantity()));
                t = t.add(subTotal);
                /** t = t.add(price); **/
                summary.setOneTimeSubTotal(t);

                // check for regular discount
                // Special sp = product.getBasePriceSpecial();
                java.util.Date spdate = null;
                java.util.Date spenddate = null;
                BigDecimal bddiscountprice = null;
                if (product.getProductSpecialNewPrice() != null) {
                    bddiscountprice = product.getProductSpecialNewPrice();
                    spdate = product.getProductSpecialDateAvailable();
                    spenddate = product.getProductSpecialDateExpire();
                    if (spdate != null && spdate.before(new Date()) && spdate != null
                            && spenddate.after(new Date())) {

                        OrderTotalLine line = new OrderTotalLine();

                        // BigDecimal credit =
                        // product.getOriginalProductPrice().subtract(bddiscountprice);

                        BigDecimal st = product.getOriginalProductPrice()
                                .multiply(new BigDecimal(product.getProductQuantity()));

                        // BigDecimal attributes =
                        // product.getAttributeAdditionalCost();
                        // if(attributes!=null) {
                        // attributes = attributes.multiply(new
                        // BigDecimal(product.getProductQuantity()));
                        // st = st.subtract(attributes);
                        // }

                        BigDecimal creditSubTotal = bddiscountprice
                                .multiply(new BigDecimal(product.getProductQuantity()));

                        // BigDecimal credit =
                        // subTotal.subtract(creditSubTotal);
                        BigDecimal credit = st.subtract(creditSubTotal);

                        StringBuffer spacialNote = new StringBuffer();
                        spacialNote.append("<font color=\"red\">[");
                        spacialNote.append(product.getProductName());
                        spacialNote.append(" ");
                        spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                        spacialNote.append("]</font>");

                        line.setCost(credit);
                        line.setText(spacialNote.toString());
                        line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                        summary.addDueNowCredits(line);

                        BigDecimal oneTimeCredit = product.getApplicableCreditOneTimeCharge();
                        oneTimeCredit = oneTimeCredit.add(credit);
                        product.setApplicableCreditOneTimeCharge(oneTimeCredit);

                    }
                }

            }

        }

        // reajust order total with credits
        Iterator prIterator = products.iterator();
        BigDecimal credit = new BigDecimal("0");
        while (prIterator.hasNext()) {
            OrderProduct op = (OrderProduct) prIterator.next();

            credit = credit.add(op.getApplicableCreditOneTimeCharge());

        }

        BigDecimal otSummary = summary.getOneTimeSubTotal();
        otSummary = otSummary.subtract(credit);
        summary.setOneTimeSubTotal(otSummary);

        // @todo why shipping is not null for subscriptions ?

        if (shipping != null) {
            if (shipping.getShippingCost() != null) {
                BigDecimal totalShipping = shipping.getShippingCost();
                if (shipping.getHandlingCost() != null) {
                    totalShipping = totalShipping.add(shipping.getHandlingCost());
                }
                // shippingInformation.setShippingCost(totalShipping);
                summary.setShippingTotal(totalShipping);
            }
        }

        if (customer != null) {

            // calculate tax on subtotal + shipping if applies
            TaxService tservice = (TaxService) ServiceFactory.getService(ServiceFactory.TaxService);

            summary = tservice.calculateTax(summary, products, customer, order.getMerchantId(), locale,
                    currency);

        }

        // calculate total
        // subtotal + shipping + tax

        BigDecimal total = summary.getOneTimeSubTotal().add(summary.getShippingTotal())
                .add(summary.getTaxTotal());

        summary.setTotal(total);

    }

    return summary;

}

From source file:org.impotch.calcul.impot.cantonal.ge.pp.avant2010.BaremePrestationCapital2009Test.java

private void test(int revenu, String tauxEnPourcent) {
    RecepteurMultipleImpot recepteur = recepteur("IBR", "RIBR", "CAR", "RCAR", "ADR", "COR");
    FournisseurAssiettePeriodique fournisseur = this.creerAssiettes(2009, revenu);
    producteur2009.produireImpot(situationCelibataire, fournisseur, recepteur);

    BigDecimal valeurImpot = getValeur(recepteur, "TOTAL");

    // On prend les bornes Sup et Inf
    BigDecimal borneSup = valeurImpot.add(deltaSurMontantImpotCalcule);
    BigDecimal borneInf = valeurImpot.subtract(deltaSurMontantImpotCalcule);

    BigDecimal tauxCalculeSup = borneSup.multiply(new BigDecimal(20)).divide(new BigDecimal(revenu), 5,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal tauxCalculeInf = borneInf.multiply(new BigDecimal(20)).divide(new BigDecimal(revenu), 5,
            BigDecimal.ROUND_HALF_UP);
    BigDecimal tauxAttendu = new BigDecimal(tauxEnPourcent);

    assertTrue("Comparaison taux attendu : " + tauxEnPourcent + ", tauxSup " + tauxCalculeSup,
            0 >= tauxAttendu.compareTo(tauxCalculeSup));
    assertTrue("Comparaison taux attendu : " + tauxEnPourcent + ", tauxInf " + tauxCalculeInf,
            0 >= tauxCalculeInf.compareTo(tauxAttendu));
}

From source file:com.gst.portfolio.shareaccounts.serialization.ShareAccountDataSerializer.java

private void createChargeTransaction(ShareAccount account) {
    BigDecimal totalChargeAmount = BigDecimal.ZERO;
    Set<ShareAccountCharge> charges = account.getCharges();
    Date currentDate = DateUtils.getLocalDateOfTenant().toDate();
    for (ShareAccountCharge charge : charges) {
        if (charge.isActive() && charge.isShareAccountActivation()) {
            charge.deriveChargeAmount(totalChargeAmount, account.getCurrency());
            ShareAccountTransaction chargeTransaction = ShareAccountTransaction
                    .createChargeTransaction(currentDate, charge);
            ShareAccountChargePaidBy paidBy = new ShareAccountChargePaidBy(chargeTransaction, charge,
                    charge.percentageOrAmount());
            chargeTransaction.addShareAccountChargePaidBy(paidBy);
            account.addChargeTransaction(chargeTransaction);
        }//from   w  ww . j  a va 2 s .c om
    }

    Set<ShareAccountTransaction> pendingApprovalTransaction = account
            .getPendingForApprovalSharePurchaseTransactions();
    for (ShareAccountTransaction pending : pendingApprovalTransaction) {
        for (ShareAccountCharge charge : charges) {
            if (charge.isActive() && charge.isSharesPurchaseCharge()) {
                BigDecimal amount = charge.deriveChargeAmount(pending.amount(), account.getCurrency());
                ShareAccountChargePaidBy paidBy = new ShareAccountChargePaidBy(pending, charge, amount);
                pending.addShareAccountChargePaidBy(paidBy);
                totalChargeAmount = totalChargeAmount.add(amount);
            }
        }
        pending.updateChargeAmount(totalChargeAmount);
    }
}

From source file:com.oncore.calorders.rest.service.extension.OrderHistoryFacadeRESTExtension.java

/**
 * findOrderDetailById returns an order detail record for a 
 * particular order/*from  ww w . jav  a2s.  c  om*/
 * 
 * @param orderUid a valid order id
 * @return a populated OrderDetailData if data is found
 */
@GET
@Path("findOrderDetailById/{orderUid}")
@Produces({ MediaType.APPLICATION_JSON })
public OrderDetailData findOrderDetailById(@PathParam("orderUid") Integer orderUid) {
    OrderDetailData order = new OrderDetailData();
    BigDecimal productTotalPrice = new BigDecimal(0);

    OrderHistory orderHistory = super.find(orderUid);

    order.setId(orderHistory.getOrdUid());
    order.setStatusDescription(orderHistory.getOrdStatusCd().getLongDesc());
    order.setOrderDate(orderHistory.getCreateTs());
    order.setStatusCode(orderHistory.getOrdStatusCd().getCode());

    if (orderHistory.getDepUidFk().getAddressCollection() != null
            && !orderHistory.getDepUidFk().getAddressCollection().isEmpty()) {
        Address address = orderHistory.getDepUidFk().getAddressCollection().iterator().next();

        order.setShippingAddressLine1(address.getAdrLine1());
        order.setShippingAddressLine2(address.getAdrLine2());
        order.setShippingAddressCity(address.getAdrCity());
        order.setShippingAddressStateCode(address.getAdrStateCd().getCode());
        order.setShippingAddressZipCode(address.getAdrZip5());

        if (StringUtils.isNotBlank(address.getAdrZip4())) {
            order.setShippingAddressZipCode(order.getShippingAddressZipCode() + "-" + address.getAdrZip4());
        }
    }

    for (OrderProductAssoc productAssoc : orderHistory.getOrderProductAssocCollection()) {
        OrderDetailProductData orderProduct = new OrderDetailProductData();
        orderProduct.setPrdUid(productAssoc.getPrdUidFk().getPrdUid());
        orderProduct.setPrdName(productAssoc.getPrdUidFk().getPrdName());
        orderProduct.setPrdImgImage(productAssoc.getPrdUidFk().getPrdImgImage());
        orderProduct.setPrdPrice(productAssoc.getOpaPrice());
        orderProduct.setPrdEachPrice(
                productAssoc.getOpaPrice().divide(new BigDecimal(productAssoc.getOpaQuantity())));

        orderProduct.setPrdQuantity(productAssoc.getOpaQuantity());
        orderProduct.setPrdImgTypeCd(productAssoc.getPrdUidFk().getPrdImgTypeCd());

        productTotalPrice = productTotalPrice.add(productAssoc.getOpaPrice());

        order.getOrderDetailProductDataList().add(orderProduct);
    }

    // Set pricing
    order.setShippingPrice(SHIPPING_PRICE);
    order.setProductTotalPrice(productTotalPrice);
    order.setTotalPrice(order.getShippingPrice().add(order.getProductTotalPrice()));

    System.out.println("total product: " + order.getProductTotalPrice());

    return order;
}

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

/**
 * Generates a PurAP accounting line and adds to the specified tax item.
 *
 * @param taxItem The specified tax item the accounting line will be associated with.
 * @param taxableAmount The amount to which tax is computed against.
 * @return A fully populated PurApAccountingLine instance for the specified tax item.
 *///w w  w  .j a  va 2 s. co m
protected PurApAccountingLine addTaxAccountingLine(PurApItem taxItem, BigDecimal taxableAmount) {
    PaymentRequestDocument preq = taxItem.getPurapDocument();
    PurApAccountingLine taxLine = null;

    try {
        taxLine = (PurApAccountingLine) taxItem.getAccountingLineClass().newInstance();
    } catch (IllegalAccessException e) {
        throw new InfrastructureException("Unable to access sourceAccountingLineClass", e);
    } catch (InstantiationException e) {
        throw new InfrastructureException("Unable to instantiate sourceAccountingLineClass", e);
    }

    // tax item type indicators
    boolean isFederalTax = ItemTypeCodes.ITEM_TYPE_FEDERAL_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederalGross = ItemTypeCodes.ITEM_TYPE_FEDERAL_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateTax = ItemTypeCodes.ITEM_TYPE_STATE_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateGross = ItemTypeCodes.ITEM_TYPE_STATE_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederal = isFederalTax || isFederalGross; // true for federal tax/gross; false for state tax/gross
    boolean isGross = isFederalGross || isStateGross; // true for federal/state gross, false for federal/state tax

    // obtain accounting line info according to tax item type code
    String taxChart = null;
    String taxAccount = null;
    String taxObjectCode = null;

    if (isGross) {
        // for gross up tax items, use preq's first item's first accounting line, which shall exist at this point
        AccountingLine line1 = preq.getFirstAccount();
        taxChart = line1.getChartOfAccountsCode();
        taxAccount = line1.getAccountNumber();
        taxObjectCode = line1.getFinancialObjectCode();
    } else if (isFederalTax) {
        // for federal tax item, get chart, account, object code info from parameters
        taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                preq.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve federal tax parameters.");
            throw new RuntimeException("Unable to retrieve federal tax parameters.");
        }
    } else if (isStateTax) {
        // for state tax item, get chart, account, object code info from parameters
        taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                preq.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve state tax parameters.");
            throw new RuntimeException("Unable to retrieve state tax parameters.");
        }
    }

    // calculate tax amount according to gross up indicator and federal/state tax type
    /*
     * The formula of tax and gross up amount are as follows: if (not gross up) gross not existing taxFederal/State = - amount *
     * rateFederal/State otherwise gross up grossFederal/State = amount * rateFederal/State / (1 - rateFederal - rateState) tax
     * = - gross
     */

    // pick federal/state tax rate
    BigDecimal taxPercentFederal = preq.getTaxFederalPercent();
    BigDecimal taxPercentState = preq.getTaxStatePercent();
    BigDecimal taxPercent = isFederal ? taxPercentFederal : taxPercentState;

    // divider value according to gross up or not
    BigDecimal taxDivider = new BigDecimal(100);
    if (preq.getTaxGrossUpIndicator()) {
        taxDivider = taxDivider.subtract(taxPercentFederal.add(taxPercentState));
    }

    // tax = amount * rate / divider
    BigDecimal taxAmount = taxableAmount.multiply(taxPercent);
    taxAmount = taxAmount.divide(taxDivider, 5, BigDecimal.ROUND_HALF_UP);

    // tax is always negative, since it reduces the total amount; while gross up is always the positive of tax
    if (!isGross) {
        taxAmount = taxAmount.negate();
    }

    // populate necessary accounting line fields
    taxLine.setDocumentNumber(preq.getDocumentNumber());
    taxLine.setSequenceNumber(preq.getNextSourceLineNumber());
    taxLine.setChartOfAccountsCode(taxChart);
    taxLine.setAccountNumber(taxAccount);
    taxLine.setFinancialObjectCode(taxObjectCode);
    taxLine.setAmount(new KualiDecimal(taxAmount));

    // add the accounting line to the item
    taxLine.setItemIdentifier(taxItem.getItemIdentifier());
    taxLine.setPurapItem(taxItem);
    taxItem.getSourceAccountingLines().add(taxLine);

    return taxLine;
}