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.wso2telco.dep.reportingservice.southbound.SbHostObjectUtils.java

/**
 * Apply tax for block charging./*from   w ww .j ava 2 s .  c o m*/
 *
 * @param CatEntry the cat entry
 * @param rate the rate
 * @param year the year
 * @param month the month
 * @throws Exception 
 */
private static void applyTaxForBlockCharging(Map.Entry<CategoryCharge, BilledCharge> CatEntry, ChargeRate rate,
        String year, String month) throws Exception {

    TaxDAO taxDAO = new TaxDAO();
    List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList());
    CategoryCharge categorycharge = CatEntry.getKey();
    BilledCharge billed = CatEntry.getValue();

    BigDecimal totalTax = BigDecimal.ZERO;
    Date billingDate = Date.valueOf(year + "-" + month + "-01"); // start of
    // the
    // month

    for (Tax tax : taxList) {
        // select the taxes applicable at the billing date
        if (!billingDate.before(tax.getEffective_from()) && !billingDate.after(tax.getEffective_to())) {
            totalTax = totalTax.add(tax.getValue().multiply(billed.getPrice()));
        }
    }

    CatEntry.getValue().setTax(totalTax);
}

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

/**
 * Apply tax for block charging./*from  ww  w  . ja  v  a2  s.  c  om*/
 *
 * @param CatEntry the cat entry
 * @param rate the rate
 * @param year the year
 * @param month the month
 * @throws Exception 
 */
private static void applyTaxForBlockCharging(Map.Entry<CategoryCharge, BilledCharge> CatEntry, ChargeRate rate,
        String year, String month) throws Exception {
    TaxDAO taxDAO = new TaxDAO();
    List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList());
    CategoryCharge categorycharge = CatEntry.getKey();
    BilledCharge billed = CatEntry.getValue();

    BigDecimal totalTax = BigDecimal.ZERO;
    Date billingDate = Date.valueOf(year + "-" + month + "-01"); // start of
    // the
    // month

    for (Tax tax : taxList) {
        // select the taxes applicable at the billing date
        if (!billingDate.before(tax.getEffective_from()) && !billingDate.after(tax.getEffective_to())) {
            // totalTax += taxFraction x charge
            totalTax = totalTax.add(tax.getValue().multiply(billed.getPrice()));
        }
    }

    CatEntry.getValue().setTax(totalTax);
}

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

/**
 * ??/*from  w ww  .ja  v a  2 s .c om*/
 *
 * @param thirdId
 * @param cityId
 * @param cartList
 * @return
 */

@Override
public BigDecimal getEverythirdExpressPrice(Long thirdId, Long cityId, List<ShoppingCart> cartList) {
    // ??? ?thirdId ?
    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("freightIsDefault", "1");
    paramMap.put("freightThirdId", thirdId);
    BigDecimal freightmoney = BigDecimal.ZERO;
    Integer goodsnum = 0;
    BigDecimal goodsweight = BigDecimal.valueOf(0);

    for (ShoppingCart sc : cartList) {
        if (sc.getThirdId().equals(thirdId)) {
            // ?
            if (sc.getFitId() == null) {
                // ??
                GoodsProductVo goodsProduct = goodsProductService.queryProductByProductId(sc.getGoodsInfoId());
                goodsweight = goodsweight
                        .add(goodsProduct.getGoodsInfoWeight().multiply(new BigDecimal(sc.getGoodsNum())));
                goodsnum += Integer.parseInt(sc.getGoodsNum().toString());

            } else {
                // ?
                // ??
                List<GoodsProductVo> goodsProducts = goodsProductMapper.queryDetailByGroupId(sc.getFitId());
                // ???
                for (int j = 0; j < goodsProducts.size(); j++) {

                    goodsweight = goodsweight.add(goodsProducts.get(j).getGoodsInfoWeight()
                            .multiply(new BigDecimal(sc.getGoodsNum())));
                    goodsnum += Integer.parseInt(sc.getGoodsNum().toString());

                }

            }
        }

    }
    // ??
    FreightTemplate ft = freightTemplateMapper.selectFreightTemplateSubOrder(paramMap);

    if (ft != null) {
        // 
        List<FreightExpress> fe = freightExpressMapper.selectTemplateExpress(ft.getFreightTemplateId());

        // ?
        if (fe != null && !fe.isEmpty()) {
            for (int i = 0; i < fe.size(); i++) {

                // ?
                List<FreightExpressAll> fall = fe.get(i).getFreightExpressAll();
                // ?
                if (fall != null && !fall.isEmpty()) {
                    for (int j = 0; j < fall.size(); j++) {
                        // ?
                        String area = fall.get(j).getExpressArea();
                        String[] cityIds = area.split(",");
                        // 
                        int flag = 0;
                        // ??
                        for (String ciId : cityIds) {
                            if (ciId.equals(cityId.toString())) {
                                flag = 1;
                                break;
                            } else {
                                continue;
                            }

                        }
                        // ??
                        if (flag == 1) {
                            freightmoney = computeFreightAll(ft.getFreightMethods(), fall.get(j), goodsnum,
                                    goodsweight);
                            break;
                            // ?
                        } else {
                            // return
                            // 
                            freightmoney = computeFreight(ft.getFreightMethods(), fe.get(i), goodsnum,
                                    goodsweight);
                            continue;
                        }

                    }
                } else {
                    // 
                    freightmoney = computeFreight(ft.getFreightMethods(), fe.get(i), goodsnum, goodsweight);
                }

            }

        }

    }

    return freightmoney;
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.RRSF424V1_1Generator.java

/**
 * //from w w w .  java  2 s .  c  o m
 * This method is to get estimated project funds for RRSF424
 * 
 * @return EstimatedProjectFunding estimated total cost for the project.
 */
private EstimatedProjectFunding getProjectFunding() throws S2SException {
    ProposalDevelopmentBudgetExtContract budget = s2SCommonBudgetService
            .getBudget(pdDoc.getDevelopmentProposal());
    EstimatedProjectFunding funding = EstimatedProjectFunding.Factory.newInstance();
    funding.setTotalEstimatedAmount(BigDecimal.ZERO);
    funding.setTotalfedNonfedrequested(BigDecimal.ZERO);
    funding.setEstimatedProgramIncome(BigDecimal.ZERO);
    boolean hasBudgetLineItem = false;
    if (budget != null) {
        ScaleTwoDecimal totalCost = ScaleTwoDecimal.ZERO;

        if (budget.getModularBudgetFlag()) {
            ScaleTwoDecimal fundsRequested = ScaleTwoDecimal.ZERO;
            ScaleTwoDecimal totalDirectCost = ScaleTwoDecimal.ZERO;

            // get modular budget amounts instead of budget detail amounts
            for (BudgetPeriodContract budgetPeriod : budget.getBudgetPeriods()) {
                totalDirectCost = totalDirectCost.add(budgetPeriod.getBudgetModular().getTotalDirectCost());
                for (BudgetModularIdcContract budgetModularIdc : budgetPeriod.getBudgetModular()
                        .getBudgetModularIdcs()) {
                    fundsRequested = fundsRequested.add(budgetModularIdc.getFundsRequested());
                }
            }
            totalCost = totalCost.add(totalDirectCost);
            totalCost = totalCost.add(fundsRequested);
        } else {
            totalCost = budget.getTotalCost();
        }
        ScaleTwoDecimal fedNonFedCost = totalCost;

        BigDecimal totalProjectIncome = BigDecimal.ZERO;

        ScaleTwoDecimal costSharingAmount = ScaleTwoDecimal.ZERO;

        for (BudgetPeriodContract budgetPeriod : budget.getBudgetPeriods()) {
            for (BudgetLineItemContract lineItem : budgetPeriod.getBudgetLineItems()) {
                hasBudgetLineItem = true;
                if (budget.getSubmitCostSharingFlag() && lineItem.getSubmitCostSharingFlag()) {
                    costSharingAmount = costSharingAmount.add(lineItem.getCostSharingAmount());
                    List<? extends BudgetLineItemCalculatedAmountContract> calculatedAmounts = lineItem
                            .getBudgetLineItemCalculatedAmounts();
                    for (BudgetLineItemCalculatedAmountContract budgetLineItemCalculatedAmount : calculatedAmounts) {
                        costSharingAmount = costSharingAmount
                                .add(budgetLineItemCalculatedAmount.getCalculatedCostSharing());
                    }

                }
            }
        }
        if (!hasBudgetLineItem && budget.getSubmitCostSharingFlag()) {
            costSharingAmount = budget.getCostSharingAmount();
        }
        fedNonFedCost = fedNonFedCost.add(costSharingAmount);

        for (BudgetProjectIncomeContract budgetProjectIncome : budget.getBudgetProjectIncomes()) {
            totalProjectIncome = totalProjectIncome
                    .add(budgetProjectIncome.getProjectIncome().bigDecimalValue());
        }

        funding = EstimatedProjectFunding.Factory.newInstance();
        funding.setTotalEstimatedAmount(totalCost.bigDecimalValue());
        funding.setTotalfedNonfedrequested(fedNonFedCost.bigDecimalValue());
        funding.setEstimatedProgramIncome(totalProjectIncome);
    }
    return funding;
}

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

/**
 * Apply charges for payment api.//from www  . ja  va2 s  .  co m
 *
 * @param opSubscription the op subscription
 * @param paymentRequestSet the payment request set
 * @param categoryEntry the category entry
 * @param appId the app id
 * @param apiId the api id
 * @param subId the sub id
 * @throws Exception 
 */
private static void applyChargesForPaymentApi(BillingSubscription.OperatorSubscription opSubscription,
        Set<PaymentRequestDTO> paymentRequestSet, Map.Entry<CategoryCharge, BilledCharge> categoryEntry,
        int appId, int apiId, String subId) throws Exception {

    ChargeRate rate = opSubscription.getRate();
    String billCategory = categoryEntry.getKey().getCategory();
    String billSubCategory = categoryEntry.getKey().getSubcategory();
    BigDecimal billRate = rate.getValue();

    boolean CategoryBased = rate.getCategoryBasedVal();
    BillingDAO billingDAO = new BillingDAO();
    TaxDAO taxDAO = new TaxDAO();
    List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList());
    Map<String, CommissionPercentagesDTO> commisionMap = null;

    if (!CategoryBased) {
        commisionMap = billingDAO.getCommissionPercentages(subId, appId);
    }

    BigDecimal totalspcom = BigDecimal.ZERO;
    BigDecimal totalCharge = BigDecimal.ZERO;
    BigDecimal totaladscom = BigDecimal.ZERO;
    BigDecimal totalopcom = BigDecimal.ZERO;
    BigDecimal totalTax = BigDecimal.ZERO;

    // get this flag from rate card

    for (PaymentRequestDTO paymentRequest : paymentRequestSet) {
        totalCharge = totalCharge.add(paymentRequest.getAmount());
        BigDecimal spcom = BigDecimal.ZERO;
        BigDecimal adscom = BigDecimal.ZERO;
        BigDecimal opcom = BigDecimal.ZERO;

        String category = paymentRequest.getCategory();
        String subcategory = paymentRequest.getSubcategory();
        String merchant = paymentRequest.getMerchant();

        BigDecimal adscomPercnt = rate.getCommission().getAdsCommission().divide(new BigDecimal(100));
        BigDecimal spcomPercnt = rate.getCommission().getSpCommission().divide(new BigDecimal(100));
        BigDecimal opcomPercnt = rate.getCommission().getOpcoCommission().divide(new BigDecimal(100));

        if (CategoryBased) {
            Object SubsRate = getRateSubcategory(rate, billCategory, billSubCategory);
            if (SubsRate != null) {
                RateCommission commisionRates = (RateCommission) SubsRate;
                adscomPercnt = commisionRates.getAdsCommission().divide(new BigDecimal(100));
                spcomPercnt = commisionRates.getSpCommission().divide(new BigDecimal(100));
                opcomPercnt = commisionRates.getOpcoCommission().divide(new BigDecimal(100));
            }

        } else {
            if (commisionMap.containsKey(merchant)) {
                adscomPercnt = commisionMap.get(merchant).getAdsCommission().divide(new BigDecimal(100));
                spcomPercnt = commisionMap.get(merchant).getSpCommission().divide(new BigDecimal(100));
                opcomPercnt = commisionMap.get(merchant).getOpcoCommission().divide(new BigDecimal(100));
            } else {
                throw new APIManagementException(
                        "Payment Categoreis required for MERCHANT based charging are not specified in rate-card.xml");
            }
        }

        spcom = paymentRequest.getAmount().multiply(spcomPercnt);
        totalspcom = totalspcom.add(spcom);

        opcom = paymentRequest.getAmount().multiply(opcomPercnt);
        totalopcom = totalopcom.add(opcom);

        adscom = paymentRequest.getAmount().multiply(adscomPercnt);
        totaladscom = totaladscom.add(adscom);

        Date date = new Date(paymentRequest.getDate().getTime());
        BigDecimal totalReqTax = BigDecimal.ZERO;
        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())) {
                totalReqTax = totalReqTax.add(tax.getValue().multiply(paymentRequest.getAmount()));
            }
        }
        totalTax = totalTax.add(totalReqTax);

        if (!CategoryBased) {
            if (opSubscription.getMerchantCharges().containsKey(merchant)) {
                opSubscription.getMerchantCharges().get(merchant).addAdscom(adscom);
                opSubscription.getMerchantCharges().get(merchant).addOpcom(opcom);
                opSubscription.getMerchantCharges().get(merchant).addSpcom(spcom);
                opSubscription.getMerchantCharges().get(merchant).addPrice(spcom);
                opSubscription.getMerchantCharges().get(merchant).addTax(totalReqTax);
                opSubscription.getMerchantCharges().get(merchant).addCount(1);
            } else {
                BilledCharge billedCharge = new BilledCharge(0);
                billedCharge.addAdscom(adscom);
                billedCharge.addOpcom(opcom);
                billedCharge.addSpcom(spcom);
                billedCharge.addPrice(spcom);
                billedCharge.addTax(totalReqTax);
                billedCharge.addCount(1);
                opSubscription.getMerchantCharges().put(merchant, billedCharge);
            }
        }
    }

    // Get the percentage from the rate value

    // apply category wise charge percentage

    categoryEntry.getValue().addAdscom(totaladscom);
    categoryEntry.getValue().addOpcom(totalopcom);
    categoryEntry.getValue().addSpcom(totalspcom);
    categoryEntry.getValue().addPrice(totalspcom);
    categoryEntry.getValue().setTax(totalTax);
}

From source file:com.selfsoft.business.action.TbFixEntrustAction.java

public String findTbFixEntrust() {
    if (null == tbFixEntrust) {

        tbFixEntrust = new TbFixEntrust();

        tbFixEntrust.setIsvalid(Constants.ISVALIDVALUE);

        tbFixEntrust.setFixDateStart(CommonMethod.parseStringToDate(
                CommonMethod.parseDateToString(CommonMethod.addDate(new Date(), -14), "yyyy-MM-dd"),
                "yyyy-MM-dd"));

        tbFixEntrust.setFixDateEnd(CommonMethod
                .parseStringToDate(CommonMethod.parseDateToString(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd"));
    }/*from  www.j av  a2  s  .  c  om*/

    String wjg = request.getParameter("wjg");

    tbFixEntrust.setWjg(wjg);

    String jsqk = request.getParameter("jsqk");

    tbFixEntrust.setJsqk(jsqk);

    List<TbFixEntrust> tbFixEntrustList = tbFixEntrustService.findByTbFixEntrust(tbFixEntrust);

    List<TbFixEntrust> tbFixEntrustListPage = new ArrayList<TbFixEntrust>();

    BigDecimal pjcbTotal = new BigDecimal("0.00");

    if (null != tbFixEntrustList && tbFixEntrustList.size() > 0) {

        for (TbFixEntrust _tbFixEntrust : tbFixEntrustList) {

            _tbFixEntrust.setFixHourTotal(new BigDecimal(
                    tbFixEntrustContentService.countTbFixEnTrustContentByTbFixEntrustId(_tbFixEntrust.getId()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP));

            List<TbMaintainPartContent> tcList = tbMaintainPartContentService
                    .getViewEntrustMaintianContent(_tbFixEntrust.getId());

            if (null != tcList && tcList.size() > 0) {

                _tbFixEntrust.setStockOutPartTotal(
                        new BigDecimal(tcList.get(0).getTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_UP));

            }

            _tbFixEntrust.setPjcb(
                    new BigDecimal(statisticsStockInOutService.sumStockDetailByEntrustId(_tbFixEntrust.getId()))
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP));

            pjcbTotal = pjcbTotal.add(_tbFixEntrust.getPjcb());

            _tbFixEntrust.setSolePartTotal(
                    new BigDecimal(tmStockOutService.getTotalPriceByEntrustCode(_tbFixEntrust.getEntrustCode()))
                            .setScale(2, BigDecimal.ROUND_HALF_UP));

            _tbFixEntrust.setAllTotal(_tbFixEntrust.getFixHourTotal()
                    .add(_tbFixEntrust.getStockOutPartTotal().add(_tbFixEntrust.getSolePartTotal())));

            _tbFixEntrust.setZlr(_tbFixEntrust.getFixHourTotal().add(_tbFixEntrust.getStockOutPartTotal()
                    .add(_tbFixEntrust.getSolePartTotal()).subtract(_tbFixEntrust.getPjcb())));

            tbFixEntrustListPage.add(_tbFixEntrust);

        }

    }

    ActionContext.getContext().put("pjcbTotal",
            pjcbTotal.divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP));

    ActionContext.getContext().put("tmUserMap", tmUserService.findAllTmUserMap());

    ActionContext.getContext().put("tbFixEntrustList", tbFixEntrustListPage);

    ActionContext.getContext().getSession().put("tbFixEntrustListSession", tbFixEntrustListPage);

    return Constants.SUCCESS;
}

From source file:fr.hoteia.qalingo.core.web.mvc.factory.impl.ViewBeanFactoryImpl.java

/**
 * @throws Exception//from www.  jav  a  2s.c  o  m
 * 
 */
public CartViewBean buildCartViewBean(final RequestData requestData, final Cart cart) throws Exception {
    final MarketArea marketArea = requestData.getMarketArea();
    final Localization localization = requestData.getLocalization();
    final Locale locale = localization.getLocale();

    final CartViewBean cartViewBean = new CartViewBean();

    cartViewBean.setCartDetailsUrl(urlService.generateUrl(FoUrls.CART_DETAILS, requestData));
    cartViewBean.setCartAuthUrl(urlService.generateUrl(FoUrls.CART_AUTH, requestData));
    cartViewBean.setCartDeliveryAndOrderDetailsUrl(urlService.generateUrl(FoUrls.CART_DELIVERY, requestData));
    cartViewBean.setCartOrderPaymentUrl(urlService.generateUrl(FoUrls.CART_ORDER_PAYMENT, requestData));
    cartViewBean
            .setCartOrderConfirmationUrl(urlService.generateUrl(FoUrls.CART_ORDER_CONFIRMATION, requestData));

    cartViewBean.setAddNewAddressUrl(urlService.generateUrl(FoUrls.PERSONAL_ADD_ADDRESS, requestData));

    // ITEMS PART
    List<CartItemViewBean> cartItemViewBeans = new ArrayList<CartItemViewBean>();
    Set<CartItem> cartItems = cart.getCartItems();
    for (Iterator<CartItem> iterator = cartItems.iterator(); iterator.hasNext();) {
        final CartItem cartItem = (CartItem) iterator.next();
        cartItemViewBeans.add(buildCartItemViewBean(requestData, cartItem));
    }
    cartViewBean.setCartItems(cartItemViewBeans);

    // SUB PART : Subtotal
    final String currencyCode = marketArea.getCurrency().getCode();
    final NumberFormat formatter = requestUtil.getCartItemPriceNumberFormat(requestData, currencyCode);
    BigDecimal cartItemsTotal = new BigDecimal("0");
    BigDecimal cartShippingTotal = new BigDecimal("0");
    BigDecimal cartFeesTotal = new BigDecimal("0");
    BigDecimal carTotal = new BigDecimal("0");
    for (Iterator<CartItem> iterator = cartItems.iterator(); iterator.hasNext();) {
        final CartItem cartItem = (CartItem) iterator.next();
        if (cartItem.getPrice() != null) {
            cartItemsTotal = cartItemsTotal.add(cartItem.getPrice());
        }
    }

    // SUB PART : Shippings
    final List<CartShippingViewBean> cartShippingViewBeans = new ArrayList<CartShippingViewBean>();
    final Set<Shipping> shippings = cart.getShippings();
    if (shippings != null) {
        for (Iterator<Shipping> iterator = shippings.iterator(); iterator.hasNext();) {
            final Shipping shipping = (Shipping) iterator.next();
            final CartShippingViewBean cartShippingViewBean = new CartShippingViewBean();
            if (shipping.getPrice() != null) {
                cartShippingTotal = cartShippingTotal.add(shipping.getPrice());
                cartShippingViewBean.setCartShippingTotal(formatter.format(shipping.getPrice()));
            }
            Object[] params = { shipping.getName() };
            cartShippingViewBean.setCartShippingTotalLabel(getSpecificMessage(ScopeWebMessage.COMMON,
                    "shoppingcart.amount.shippings", params, locale));
            cartShippingViewBeans.add(cartShippingViewBean);
        }
        cartViewBean.setCartShippings(cartShippingViewBeans);
    }

    // SUB PART : Taxes
    final List<CartTaxViewBean> cartTaxViewBeans = new ArrayList<CartTaxViewBean>();
    final Set<Tax> taxes = cart.getTaxes();
    if (taxes != null) {
        for (Iterator<Tax> iterator = taxes.iterator(); iterator.hasNext();) {
            final Tax tax = (Tax) iterator.next();
            final CartTaxViewBean cartTaxViewBean = new CartTaxViewBean();
            BigDecimal taxesCalc = cartItemsTotal;
            taxesCalc = taxesCalc.multiply(tax.getPercent());
            taxesCalc = taxesCalc.divide(new BigDecimal("100"));
            cartFeesTotal = cartFeesTotal.add(taxesCalc);
            Object[] params = { tax.getName() };
            cartTaxViewBean.setCartTaxTotal(formatter.format(taxesCalc));
            cartTaxViewBean.setCartTaxTotalLabel(
                    getSpecificMessage(ScopeWebMessage.COMMON, "shoppingcart.amount.taxes", params, locale));
            cartTaxViewBeans.add(cartTaxViewBean);
        }
        cartViewBean.setCartTaxes(cartTaxViewBeans);
    }
    carTotal = carTotal.add(cartItemsTotal);
    carTotal = carTotal.add(cartShippingTotal);
    carTotal = carTotal.add(cartFeesTotal);
    cartViewBean.setCartItemsTotal(formatter.format(cartItemsTotal));
    cartViewBean.setCartShippingTotal(formatter.format(cartShippingTotal));
    cartViewBean.setCartFeesTotal(formatter.format(cartFeesTotal));
    cartViewBean.setCartTotal(formatter.format(carTotal));

    return cartViewBean;
}

From source file:ch.algotrader.service.PortfolioServiceImpl.java

/**
 * {@inheritDoc}/*from  w  w w.  j  a  v a  2  s  .  c  o  m*/
 */
@Override
public PortfolioValue getPortfolioValue(final String strategyName) {

    Validate.notEmpty(strategyName, "Strategy name is empty");

    Strategy strategy = this.strategyDao.findByName(strategyName);

    BigDecimal cashBalance;
    BigDecimal marketValue;
    BigDecimal realizedPL;
    BigDecimal unrealizedPL;
    int openPositions;
    if (strategy.isServer()) {
        cashBalance = getCashBalance();
        marketValue = getMarketValue();
        realizedPL = getRealizedPL();
        unrealizedPL = getUnrealizedPL();
        openPositions = getOpenPositions();
    } else {
        cashBalance = getCashBalance(strategyName);
        marketValue = getMarketValue(strategyName);
        realizedPL = getRealizedPL(strategyName);
        unrealizedPL = getUnrealizedPL(strategyName);
        openPositions = getOpenPositions(strategyName);
    }

    PortfolioValue portfolioValue = PortfolioValue.Factory.newInstance();

    portfolioValue.setStrategy(strategy);
    portfolioValue.setDateTime(this.engineManager.getCurrentEPTime());
    portfolioValue.setNetLiqValue(marketValue != null ? cashBalance.add(marketValue) : null);
    portfolioValue.setCashBalance(cashBalance);
    portfolioValue.setMarketValue(marketValue);
    portfolioValue.setRealizedPL(realizedPL);
    portfolioValue.setUnrealizedPL(unrealizedPL);
    portfolioValue.setOpenPositions(openPositions);

    return portfolioValue;

}

From source file:fr.hoteia.qalingo.core.web.mvc.factory.impl.ViewBeanFactoryImpl.java

/**
  * //from  w w w .  ja  v a  2  s .  co  m
  */
public OrderViewBean buildOrderViewBean(final RequestData requestData, final Order order) throws Exception {
    final MarketArea marketArea = requestData.getMarketArea();
    final Localization localization = requestData.getLocalization();
    final Locale locale = localization.getLocale();
    final String orderId = order.getId().toString();
    final OrderViewBean orderViewBean = new OrderViewBean();

    // ITEMS PART
    final List<OrderItemViewBean> orderItemViewBeans = new ArrayList<OrderItemViewBean>();
    final Set<OrderItem> orderItems = order.getOrderItems();
    for (Iterator<OrderItem> iterator = orderItems.iterator(); iterator.hasNext();) {
        OrderItem orderItem = (OrderItem) iterator.next();
        orderItemViewBeans.add(buildOrderItemViewBean(requestData, orderItem));
    }
    orderViewBean.setOrderItems(orderItemViewBeans);

    // SUB PART : Subtotal
    final String currencyCode = marketArea.getCurrency().getCode();
    final NumberFormat formatter = requestUtil.getCartItemPriceNumberFormat(requestData, currencyCode);
    BigDecimal orderItemsTotal = new BigDecimal("0");
    BigDecimal orderShippingTotal = new BigDecimal("0");
    BigDecimal orderFeesTotal = new BigDecimal("0");
    BigDecimal orderTotal = new BigDecimal("0");
    for (Iterator<OrderItem> iterator = orderItems.iterator(); iterator.hasNext();) {
        final OrderItem orderItem = (OrderItem) iterator.next();
        if (orderItem.getPrice() != null) {
            orderItemsTotal = orderItemsTotal.add(orderItem.getPrice());
        }
    }

    // SUB PART : Shippings
    final List<OrderShippingViewBean> orderShippingViewBeans = new ArrayList<OrderShippingViewBean>();
    final Set<OrderShipment> orderShipments = order.getOrderShipments();
    if (orderShipments != null) {
        for (Iterator<OrderShipment> iterator = orderShipments.iterator(); iterator.hasNext();) {
            final OrderShipment orderShipment = (OrderShipment) iterator.next();
            final OrderShippingViewBean orderShippingViewBean = new OrderShippingViewBean();
            if (orderShipment.getPrice() != null) {
                orderShippingTotal = orderShippingTotal.add(orderShipment.getPrice());
                orderShippingViewBean.setOrderShippingTotal(formatter.format(orderShipment.getPrice()));
            }
            Object[] params = { orderShipment.getName() };
            orderShippingViewBean.setOrderShippingTotalLabel(getSpecificMessage(ScopeWebMessage.COMMON,
                    "shoppingcart.amount.shippings", params, locale));
            orderShippingViewBeans.add(orderShippingViewBean);
        }
        orderViewBean.setOrderShippings(orderShippingViewBeans);
    }

    // SUB PART : Taxes
    final List<OrderTaxViewBean> orderTaxViewBeans = new ArrayList<OrderTaxViewBean>();
    final Set<OrderTax> orderTaxes = order.getOrderTaxes();
    if (orderTaxes != null) {
        for (Iterator<OrderTax> iterator = orderTaxes.iterator(); iterator.hasNext();) {
            final OrderTax orderTax = (OrderTax) iterator.next();
            final OrderTaxViewBean orderTaxViewBean = new OrderTaxViewBean();
            BigDecimal taxesCalc = orderItemsTotal;
            taxesCalc = taxesCalc.multiply(orderTax.getPercent());
            taxesCalc = taxesCalc.divide(new BigDecimal("100"));
            orderFeesTotal = orderFeesTotal.add(taxesCalc);
            Object[] params = { orderTax.getName() };
            orderTaxViewBean.setOrderTaxTotal(formatter.format(taxesCalc));
            orderTaxViewBean.setOrderTaxTotalLabel(
                    getSpecificMessage(ScopeWebMessage.COMMON, "shoppingcart.amount.taxes", params, locale));
            orderTaxViewBeans.add(orderTaxViewBean);
        }
        orderViewBean.setOrderTaxes(orderTaxViewBeans);
    }
    orderTotal = orderTotal.add(orderItemsTotal);
    orderTotal = orderTotal.add(orderShippingTotal);
    orderTotal = orderTotal.add(orderFeesTotal);
    orderViewBean.setOrderItemsTotal(formatter.format(orderItemsTotal));
    orderViewBean.setOrderShippingTotal(formatter.format(orderShippingTotal));
    orderViewBean.setOrderFeesTotal(formatter.format(orderFeesTotal));
    orderViewBean.setOrderTotal(formatter.format(orderTotal));

    // final Object[] params = {order.getOrderNum()};
    // orderViewBean.setConfirmationMessage(getSpecificMessage(ScopeWebMessage.COMMON,
    // "order.confirmation.message", params, locale));

    Map<String, String> urlParams = new HashMap<String, String>();
    urlParams.put(RequestConstants.REQUEST_PARAMETER_CUSTOMER_ORDER_ID, orderId.toString());

    orderViewBean
            .setOrderDetailsUrl(urlService.generateUrl(FoUrls.PERSONAL_ORDER_DETAILS, requestData, urlParams));

    return orderViewBean;
}

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

/**
 * Apply charges with tax.// ww w . ja  v  a2  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);
    TaxDAO taxDAO = new TaxDAO();
    Set<APIRequestDTO> requestTimes = new HashSet<APIRequestDTO>();
    if (prodKey != null) {
        String api_version = apiName + ":v" + apiVersion;
        requestTimes = taxDAO.getNbAPIRequestTimesForSubscription(Short.parseShort(year),
                Short.parseShort(month), apiName, api_version, prodKey.getConsumerKey(),
                operatorSub.getOperationId(), CatEntry.getKey().getCategory(),
                CatEntry.getKey().getSubcategory());
    }

    // ChargeRate rate = operatorSub.getRate();
    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;
    }

    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 += taxFraction x charge
                totalTax = totalTax.add(tax.getValue().multiply(charge));
            }
        }
        reqCount++;
    }

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

}