Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:org.kuali.kpme.core.earncode.service.EarnCodeServiceImpl.java

@Override
public BigDecimal roundHrsWithEarnCode(BigDecimal hours, EarnCodeContract earnCode) {
    String roundOption = HrConstants.ROUND_OPTION_MAP.get(earnCode.getRoundingOption());
    BigDecimal fractScale = new BigDecimal(earnCode.getFractionalTimeAllowed());
    if (roundOption == null) {
        LOG.error("Rounding option of Earn Code " + earnCode.getEarnCode() + " is not recognized.");
        return null;
        //         throw new RuntimeException("Rounding option of Earn Code " + earnCode.getEarnCode() + " is not recognized.");
    }/*from w w w  .j a  v a 2s .  c om*/
    BigDecimal roundedHours = hours;
    if (roundOption.equals("Traditional")) {
        roundedHours = hours.setScale(fractScale.scale(), BigDecimal.ROUND_HALF_EVEN);
    } else if (roundOption.equals("Truncate")) {
        roundedHours = hours.setScale(fractScale.scale(), BigDecimal.ROUND_DOWN);
    }
    return roundedHours;
}

From source file:ch.elexis.data.TarmedOptifier.java

/**
 * Get double as int rounded half up.//from  w  w w . ja v  a  2s  .c o  m
 * 
 * @param value
 * @return
 */
private int doubleToInt(double value) {
    BigDecimal bd = new BigDecimal(value);
    bd = bd.setScale(0, RoundingMode.HALF_UP);
    return bd.intValue();
}

From source file:com.zl.bgec.basicapi.shop.service.impl.ShopServiceImpl.java

@Override
@Transactional(readOnly = true)//from  www.  j  av  a2  s  . co m
public Map<String, Object> getShopIndexInfo(String memberNo) throws Exception {
    String sql = "select tsi.shop_name shopName," + "tsi.shop_address shopAddress," + "tsi.shop_logo shopLogo,"
            + "tsi.status status, " + "tsi.shop_no shopNo "
            + "from tbl_shop_info tsi where tsi.merch_no=:shopNo and tsi.status!='3'";
    Query query = shopDao.createSQLQuery(sql);
    query.setParameter("shopNo", memberNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> results = query.list();
    Map<String, Object> result = new HashMap<String, Object>();
    if (results != null && !results.isEmpty()) {
        result = results.get(0);
    } else {
        return null;
    }
    String shopNo = String.valueOf(result.get("shopNo"));
    Criteria criteria = commodityDao.createCriteria(Restrictions.eq("sellerNo", shopNo));
    criteria.add(Restrictions.eq("deleteFlag", (byte) 0));//
    criteria.add(Restrictions.eq("publishState", "1"));//
    int commodityCount = commodityDao.getRowCount(criteria);// ??
    result.put("commodityCount", String.valueOf(commodityCount));
    criteria = shopCollectDao.createCriteria(Restrictions.eq("shopNo", shopNo));
    int collectCount = shopCollectDao.getRowCount(criteria);
    result.put("collectCount", String.valueOf(collectCount));
    Criteria promotionCriteria = promotionDao.createCriteria(Restrictions.eq("shopNo", shopNo));
    promotionCriteria.add(Restrictions.ge("endTime", new Date()));//
    promotionCriteria.add(Restrictions.eq("status", "2"));//
    promotionCriteria.add(Restrictions.eq("lockFlag", "0"));//?
    promotionCriteria.add(Restrictions.ne("promotionType", "2"));//?
    int count = promotionDao.getRowCount(promotionCriteria);
    result.put("promotionCount", count);
    List<String> values = new ArrayList<String>();
    //      values.add(OrderConstants.BASIC_STATE_REFUND);
    //      values.add(OrderConstants.BASIC_STATE_ALREADY_RECEIVE);
    //      values.add(OrderConstants.BASIC_STATE_REFUND_APPLY);
    values.add(OrderConstants.BASIC_STATE_WAITING_DELIVERY);
    //      values.add(OrderConstants.BASIC_STATE_WAITING_RETURN);
    //      values.add(OrderConstants.BASIC_STATE_WAITING_PAY);
    //      values.add(OrderConstants.BASIC_STATE_ALREADY_DELIVERY);
    Criteria criteriaOrder = orderDao.createCriteria(Restrictions.in("basicState", values));
    criteriaOrder.add(Restrictions.eq("deleteFlag", (byte) 0));
    criteriaOrder.add(Restrictions.eq("shopNo", shopNo));
    String sqlGroupBuy = "select count(*) " + "  from tbl_promotion tp "
            + " left join tbl_product tpr on tp.ref_commo_no = tpr.commo_no"
            + " where tp.promotion_type='2' and tp.delete_flag='0' and tp.shop_no=:shopNo  and :curentTime between tp.start_time and tp.end_time ";
    Query groupBuyQuery = promotionDao.createSQLQuery(sqlGroupBuy);
    groupBuyQuery.setParameter("shopNo", shopNo);
    groupBuyQuery.setParameter("curentTime", new Date());
    BigInteger totalRows = (BigInteger) groupBuyQuery.uniqueResult();
    result.put("groupBuyCount", totalRows.intValue());
    result.put("orderCount", orderDao.getRowCount(criteriaOrder));
    String gradeSql = "select  avg(tcc.service_grade) serviceGrade," + " avg(tcc.delivery_grade) deliveryGrade"
            + " from tbl_commodity_comment tcc " + " where tcc.shop_no = :shopNo " + " group by(tcc.shop_no) ";
    Query queryGrade = shopDao.createSQLQuery(gradeSql);
    queryGrade.setParameter("shopNo", shopNo);
    queryGrade.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> list = queryGrade.list();
    if (list != null && !list.isEmpty()) {
        Double servGrade = list.get(0).get("serviceGrade") == null ? 0
                : Double.valueOf(list.get(0).get("serviceGrade").toString());
        BigDecimal serviceGrade = new BigDecimal(servGrade);
        serviceGrade = serviceGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
        result.put("serviceGrade", serviceGrade.doubleValue());
        Double delGrade = list.get(0).get("deliveryGrade") == null ? 0
                : Double.valueOf(list.get(0).get("deliveryGrade").toString());
        BigDecimal deliveryGrade = new BigDecimal(delGrade);
        deliveryGrade = deliveryGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
        result.put("deliveryGrade", deliveryGrade.doubleValue());
    } else {
        result.put("serviceGrade", "0");
        result.put("deliveryGrade", "0");
    }

    return result;
}

From source file:com.salesmanager.core.service.tax.TaxService.java

/**
 * Calculates tax on an OrderTotalSummary object (products applicable,
 * shipping...), creates and set the shopping cart lines. Returns the amount
 * with tax// w  w  w .j a va 2 s . co m
 * 
 * @param summary
 * @param amount
 * @param customer
 * @param merchantId
 * @return
 * @throws Exception
 */
@Transactional
public OrderTotalSummary calculateTax(OrderTotalSummary summary, Collection<OrderProduct> products,
        Customer customer, int merchantId, Locale locale, String currency) throws Exception {

    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore store = mservice.getMerchantStore(merchantId);

    Map productsTax = new HashMap();

    //rounding definition
    BigDecimal totalTaxAmount = new BigDecimal(0);
    //totalTaxAmount.setScale(2, BigDecimal.ROUND_DOWN);

    // check if tax is applicable and build a map
    // of tax class - product
    if (products != null) {
        Iterator prodIt = products.iterator();
        while (prodIt.hasNext()) {
            OrderProduct prod = (OrderProduct) prodIt.next();
            if (prod.getTaxClassId() > -1) {

                BigDecimal groupBeforeTaxAmount = (BigDecimal) productsTax.get(prod.getTaxClassId());

                if (groupBeforeTaxAmount == null) {
                    groupBeforeTaxAmount = new BigDecimal("0");
                }

                BigDecimal finalPrice = prod.getFinalPrice();// unit price +
                // attribute
                // * qty
                // finalPrice = finalPrice.multiply(new
                // BigDecimal(prod.getProductQuantity()));

                groupBeforeTaxAmount = groupBeforeTaxAmount.add(finalPrice);

                // getPrices
                Set prices = prod.getPrices();
                // List prices = prod.getRelatedPrices();
                if (prices != null) {
                    Iterator ppriceIter = prices.iterator();
                    while (ppriceIter.hasNext()) {
                        OrderProductPrice pprice = (OrderProductPrice) ppriceIter.next();
                        if (!pprice.isDefaultPrice()) {// related price
                            // activation...
                            // PriceModule module =
                            // (PriceModule)SpringUtil.getBean(pprice.getProductPriceModuleName());
                            // if(module.isTaxApplicable()) {//related price
                            // becomes taxeable
                            // if(pprice.isProductHasTax()) {
                            // groupBeforeTaxAmount =
                            // groupBeforeTaxAmount.add(ProductUtil.determinePrice(pprice));

                            BigDecimal ppPrice = pprice.getProductPriceAmount();
                            ppPrice = ppPrice.multiply(new BigDecimal(prod.getProductQuantity()));

                            groupBeforeTaxAmount = groupBeforeTaxAmount.add(ppPrice);
                            // }
                        }
                    }
                }

                BigDecimal credits = prod.getApplicableCreditOneTimeCharge();
                groupBeforeTaxAmount = groupBeforeTaxAmount.subtract(credits);

                productsTax.put(prod.getTaxClassId(), groupBeforeTaxAmount);

            }
        }
    }

    if (productsTax.size() == 0) {
        return summary;
    }

    // determine if tax applies on billing or shipping address

    // get shipping & tax informations
    ConfigurationRequest request = new ConfigurationRequest(merchantId);
    ConfigurationResponse response = mservice.getConfiguration(request);

    String taxBasis = TaxConstants.SHIPPING_TAX_BASIS;

    // get tax basis
    MerchantConfiguration taxConf = response.getMerchantConfiguration(TaxConstants.MODULE_TAX_BASIS);
    if (taxConf != null && !StringUtils.isBlank(taxConf.getConfigurationValue())) {// tax
        // basis
        taxBasis = taxConf.getConfigurationValue();
    }

    // tax on shipping
    if (summary.getShippingTotal() != null && summary.getShippingTotal().floatValue() > 0) {
        MerchantConfiguration shippingTaxConf = response
                .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_TAX_CLASS);
        if (shippingTaxConf != null && !StringUtils.isBlank(shippingTaxConf.getConfigurationValue())) {// tax on shipping

            long taxClass = Long.parseLong(shippingTaxConf.getConfigurationValue());
            BigDecimal groupSubTotal = (BigDecimal) productsTax.get(taxClass);
            if (groupSubTotal == null) {
                groupSubTotal = new BigDecimal("0");
                productsTax.put(taxClass, groupSubTotal);
            }
            groupSubTotal = groupSubTotal.add(summary.getShippingTotal());
            productsTax.put(taxClass, groupSubTotal);
        }
    }

    Map taxDescriptionsHolder = new TreeMap();

    Iterator taxMapIter = productsTax.keySet().iterator();
    while (taxMapIter.hasNext()) {// get each tax class

        long key = (Long) taxMapIter.next();
        // List taxClassGroup = (List)productsTax.get(key);

        int countryId = 0;

        Collection taxCollection = null;
        if (taxBasis.equals(TaxConstants.SHIPPING_TAX_BASIS)) {

            if (store.getCountry() != customer.getCustomerCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerCountryId(),
                    customer.getCustomerZoneId(), key, merchantId);
            countryId = customer.getCustomerCountryId();
        } else { // BILLING

            if (store.getCountry() != customer.getCustomerBillingCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerBillingCountryId(),
                    customer.getCustomerBillingZoneId(), key, merchantId);
            countryId = customer.getCustomerBillingCountryId();
        }

        if (taxCollection == null || taxCollection.size() == 0) {// no tax
            continue;
        }

        Map countries = RefCache.getCountriesMap();
        Country c = (Country) countries.get(countryId);

        if (c != null) {// tax adjustment rules
            TaxModule module = (TaxModule) SpringUtil.getBean(c.getCountryIsoCode2());
            if (module != null) {
                taxCollection = module.adjustTaxRate(taxCollection, store);
            }
        }

        //BigDecimal beforeTaxAmount = new BigDecimal("0");
        //beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal groupSubTotal = (BigDecimal) productsTax.get(key);

        //beforeTaxAmount = beforeTaxAmount.add(groupSubTotal);
        BigDecimal beforeTaxAmount = groupSubTotal;
        beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);

        // iterate through tax collection and calculate tax lines
        if (taxCollection != null) {

            Iterator i = taxCollection.iterator();
            while (i.hasNext()) {

                TaxRate trv = (TaxRate) i.next();
                // double value = ((trv.getTaxRate().doubleValue() *
                // beforeTaxAmount.doubleValue())/100)+beforeTaxAmount.doubleValue();
                double trDouble = trv.getTaxRate().doubleValue();

                // if piggy back, add tax to subtotal
                BigDecimal amount = beforeTaxAmount;
                if (trv.isPiggyback()) {
                    // add previous calculated tax on top of subtotal
                    amount = amount.add(totalTaxAmount);
                }

                // commented for piggyback
                // double beforeTaxDouble = beforeTaxAmount.doubleValue();
                double beforeTaxDouble = amount.doubleValue();

                double value = ((trDouble * beforeTaxDouble) / 100);

                BigDecimal nValue = BigDecimal.valueOf(value);

                //BigDecimal nValue = new BigDecimal(value);
                nValue.setScale(2, BigDecimal.ROUND_HALF_UP);

                //nValue = nValue.add(new BigDecimal(value));

                // commented for piggyback
                // beforeTaxAmount = beforeTaxAmount.add(nValue);

                //BigDecimal bdValue = nValue;
                String am = CurrencyUtil.getAmount(nValue, store.getCurrency());

                /** this one **/
                totalTaxAmount = totalTaxAmount.add(new BigDecimal(am));

                String name = LabelUtil.getInstance().getText(locale, "label.generic.tax");

                OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder
                        .get(trv.getZoneToGeoZone().getGeoZoneId());

                if (line == null) {
                    // tax description
                    line = new OrderTotalLine();
                    Set descriptionsSet = trv.getDescriptions();
                    if (descriptionsSet != null) {
                        Iterator li = descriptionsSet.iterator();
                        while (li.hasNext()) {
                            TaxRateDescription description = (TaxRateDescription) li.next();
                            if (description.getId().getLanguageId() == LanguageUtil
                                    .getLanguageNumberCode(locale.getLanguage())) {
                                name = description.getTaxDescription();
                                break;
                            }
                        }
                    }

                    line.setText(name);
                    line.setCost(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(nValue, currency));
                    taxDescriptionsHolder.put(trv.getZoneToGeoZone().getGeoZoneId(), line);
                } else {// needs to re-use the same shopping cart line
                    BigDecimal cost = line.getCost();
                    cost = cost.add(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(cost, currency));
                }

                // now set tax on producs
                Iterator prodIt = products.iterator();
                while (prodIt.hasNext()) {
                    OrderProduct prod = (OrderProduct) prodIt.next();
                    if (prod.getTaxClassId() == key) {
                        // calculate tax for this product
                        BigDecimal price = prod.getProductPrice();
                        BigDecimal productTax = prod.getProductTax();
                        if (productTax == null) {
                            productTax = new BigDecimal("0");
                        }
                        price = price.add(productTax);
                        double pTax = ((trDouble * price.doubleValue()) / 100);

                        prod.setProductTax(new BigDecimal(pTax));

                    }
                }

            } // end while

        }

        Iterator titer = taxDescriptionsHolder.keySet().iterator();
        while (titer.hasNext()) {
            long lineKey = (Long) titer.next();
            OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder.get(lineKey);
            summary.addTaxPrice(line);
        }

    }

    summary.setTaxTotal(totalTaxAmount);

    return summary;

}

From source file:mx.edu.um.mateo.inventario.web.EntradaController.java

@RequestMapping("/ver/{id}")
public String ver(@PathVariable Long id, Model modelo) {
    log.debug("Mostrando entrada {}", id);
    Entrada entrada = entradaDao.obtiene(id);
    switch (entrada.getEstatus().getNombre()) {
    case Constantes.ABIERTA:
        modelo.addAttribute("puedeEditar", true);
        modelo.addAttribute("puedeEliminar", true);
        modelo.addAttribute("puedeCerrar", true);
        modelo.addAttribute("puedePendiente", true);
        break;//from  w  w w .j  a  v a2s  . c  om
    case Constantes.PENDIENTE:
        modelo.addAttribute("puedeEditarPendiente", true);
        break;
    case Constantes.CERRADA:
        modelo.addAttribute("puedeCancelar", true);
        break;
    }

    modelo.addAttribute("entrada", entrada);

    BigDecimal subtotal = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    BigDecimal iva = new BigDecimal("0").setScale(2, RoundingMode.HALF_UP);
    for (LoteEntrada lote : entrada.getLotes()) {
        subtotal = subtotal.add(lote.getPrecioUnitario().multiply(lote.getCantidad()));
        iva = iva.add(lote.getIva());
    }
    BigDecimal total = subtotal.add(iva);
    modelo.addAttribute("subtotal", subtotal.setScale(2, RoundingMode.HALF_UP));
    modelo.addAttribute("iva", iva);
    modelo.addAttribute("total", total.setScale(2, RoundingMode.HALF_UP));
    if (iva.compareTo(entrada.getIva()) == 0 && total.compareTo(entrada.getTotal()) == 0) {
        modelo.addAttribute("estiloTotales", "label label-success");
    } else {
        BigDecimal variacion = new BigDecimal("0.05");
        BigDecimal topeIva = entrada.getIva().multiply(variacion);
        BigDecimal topeTotal = entrada.getTotal().multiply(variacion);
        log.debug("Estilos {} {} {} {} {} {}",
                new Object[] { iva, entrada.getIva(), topeIva, total, entrada.getTotal(), topeTotal });
        if (iva.compareTo(entrada.getIva()) < 0 || total.compareTo(entrada.getTotal()) < 0) {
            log.debug("La diferencia es menor");
            if (iva.compareTo(entrada.getIva().subtract(topeIva)) >= 0
                    && total.compareTo(entrada.getTotal().subtract(topeTotal)) >= 0) {
                modelo.addAttribute("estiloTotales", "label label-warning");
            } else {
                modelo.addAttribute("estiloTotales", "label label-important");
            }
        } else {
            log.debug("La diferencia es mayor {} {}",
                    new Object[] { iva.compareTo(entrada.getIva().add(topeIva)),
                            total.compareTo(entrada.getTotal().add(topeTotal)) });
            if (iva.compareTo(entrada.getIva().add(topeIva)) <= 0
                    && total.compareTo(entrada.getTotal().add(topeTotal)) <= 0) {
                log.debug("estilo warning");
                modelo.addAttribute("estiloTotales", "label label-warning");
            } else {
                log.debug("estilo error");
                modelo.addAttribute("estiloTotales", "label label-important");
            }
        }
    }

    return "inventario/entrada/ver";
}

From source file:org.kalypso.ui.wizards.results.ResultSldHelper.java

private static void configurePolygonSymbolizer(final SurfacePolygonSymbolizer symbolizer,
        final BigDecimal minValue, final BigDecimal maxValue) throws FilterEvaluationException {
    final PolygonColorMap templateColorMap = symbolizer.getColorMap();
    final PolygonColorMap newColorMap = new PolygonColorMap_Impl();

    // retrieve stuff from template-entries
    final PolygonColorMapEntry fromEntry = templateColorMap.findEntry("from", null); //$NON-NLS-1$
    final PolygonColorMapEntry toEntry = templateColorMap.findEntry("to", null); //$NON-NLS-1$

    // Fill//  w w  w .  j  av  a 2 s .  c  o  m
    final Color fromPolygonColor = fromEntry.getFill().getFill(null);
    final Color toPolygonColor = toEntry.getFill().getFill(null);
    final double polygonOpacity = fromEntry.getFill().getOpacity(null);

    // Stroke
    final Color fromLineColor = fromEntry.getStroke().getStroke(null);
    final Color toLineColor = toEntry.getStroke().getStroke(null);
    final double lineOpacity = fromEntry.getStroke().getOpacity(null);

    // step width
    final double stepWidth = fromEntry.getTo(null);

    // scale of the step width
    final BigDecimal setScale = new BigDecimal(fromEntry.getFrom(null)).setScale(0, BigDecimal.ROUND_FLOOR);
    final int stepWidthScale = setScale.intValue();

    // get rounded values below min and above max (rounded by first decimal)
    // as a first try we will generate isareas by using class steps of 0.1
    // later, the classes will be created by using user defined class steps.
    // for that we fill an array of calculated (later user defined values) from max to min
    final BigDecimal minDecimal = minValue.setScale(1, BigDecimal.ROUND_FLOOR);
    final BigDecimal maxDecimal = maxValue.setScale(1, BigDecimal.ROUND_CEILING);

    final BigDecimal polygonStepWidth = new BigDecimal(stepWidth).setScale(stepWidthScale,
            BigDecimal.ROUND_FLOOR);
    int numOfClasses = (maxDecimal.subtract(minDecimal).divide(polygonStepWidth)).intValue();
    // set to provide more them 1 or 0 classes. in such cases the color map will not be created, that results error.  
    if (numOfClasses < 2) {
        numOfClasses = (maxDecimal.subtract(minDecimal).divide(polygonStepWidth.divide(new BigDecimal(4))))
                .intValue();
    }
    for (int currentClass = 0; currentClass < numOfClasses; currentClass++) {
        final double fromValue = minDecimal.doubleValue() + currentClass * polygonStepWidth.doubleValue();
        final double toValue = minDecimal.doubleValue() + (currentClass + 1) * polygonStepWidth.doubleValue();

        // Stroke
        Color lineColor;
        if (fromLineColor == toLineColor)
            lineColor = fromLineColor;
        else
            lineColor = interpolateColor(fromLineColor, toLineColor, currentClass, numOfClasses);

        // Fill
        final Color polygonColor = interpolateColor(fromPolygonColor, toPolygonColor, currentClass,
                numOfClasses);
        lineColor = polygonColor;

        final Stroke stroke = StyleFactory.createStroke(lineColor, lineOpacity, 1);

        final Fill fill = StyleFactory.createFill(polygonColor, polygonOpacity);

        final ParameterValueType label = StyleFactory.createParameterValueType("Isoflche " + currentClass); //$NON-NLS-1$
        final ParameterValueType from = StyleFactory.createParameterValueType(fromValue);
        final ParameterValueType to = StyleFactory.createParameterValueType(toValue);

        final PolygonColorMapEntry colorMapEntry = new PolygonColorMapEntry_Impl(fill, stroke, label, from, to);
        newColorMap.addColorMapClass(colorMapEntry);
    }

    symbolizer.setColorMap(newColorMap);
}

From source file:net.sourceforge.fenixedu.domain.oldInquiries.StudentInquiriesCourseResult.java

private Double getValueForPresentation(Double value) {
    // TODO: ugly hack, refactor
    if (value == null) {
        return new Double(0);
    }/*  w  w w  .j a v  a 2s  .c  om*/
    BigDecimal round = new BigDecimal(value);
    round.setScale(2, RoundingMode.HALF_EVEN);
    return round.doubleValue();
}

From source file:com.zl.bgec.basicapi.shop.service.impl.ShopServiceImpl.java

@Override
@Transactional/*  w  w w.  j  av  a2  s .  c o m*/
public Map<String, Object> getShopDetailNoUserId(String shopNo, String memberNo) throws Exception {
    String sql = "select " + " tsi.shop_name shopName," + " tsi.status status," + " tsi.shop_logo shopLogo,"
            + " tsi.shop_address address," + " tsi.shop_summary summary,"//
            + " tsi.phone phone,"//?
            + " tsi.merch_no memberNo,"//?
            + " tsi.begin_time beginTime,"//?
            + " tsi.end_time endTime,"//??
            + " tsi.shop_sign shopSign,"//
            + " tsi.sell_scope sellScope,"//??
            + " tsi.delivery_type deliveryType,"//??
            + " tsi.company_name companyName,"//???
            + " tsi.license_regist_no licenseRegistNo,"//??
            + " if(tsi.is_recommend is null,'0',tsi.is_recommend) isRecommend "
            + " from tbl_shop_info tsi where tsi.shop_no = :shopNo";
    Query query = shopDao.createSQLQuery(sql);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    Map<String, Object> map = (Map<String, Object>) query.uniqueResult();
    String sqlComment = "select avg(tcc.service_grade) serviceGrade,avg(tcc.delivery_grade) deliveryGrade "
            + " from tbl_commodity_comment tcc where tcc.shop_no=:shopNo";
    query = shopDao.createSQLQuery(sqlComment);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    if (map != null) {
        Map<String, Object> mapComment = (Map<String, Object>) query.uniqueResult();
        if (mapComment != null) {
            Double servGrade = mapComment.get("serviceGrade") == null ? 0
                    : Double.valueOf(mapComment.get("serviceGrade").toString());
            BigDecimal serviceGrade = new BigDecimal(servGrade);
            serviceGrade = serviceGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
            map.put("serviceGrade", serviceGrade.doubleValue());
            Double delGrade = mapComment.get("deliveryGrade") == null ? 0
                    : Double.valueOf(mapComment.get("deliveryGrade").toString());
            BigDecimal deliveryGrade = new BigDecimal(delGrade);
            deliveryGrade = deliveryGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN);
            map.put("deliveryGrade", deliveryGrade.doubleValue());
        } else {
            map.put("serviceGrade", 0);
            map.put("deliveryGrade", 0);
        }
    }

    if (map != null) {
        map.put("promotions", "");
    }
    String sqlProduct = "select IF(tp.prod_name is null,'',tp.prod_name) prodName,"
            + " IF(tp.default_pic is null,'',tp.default_pic) prodPic," + " tp.price prodPrice,"
            + " tp.prod_no prodNo," + " tp.sort sort," + " ifnull(tp.stock,0) stock,"
            + " ifnull(tp.stock_preemption,0) stockPreemption,"
            + " IF(tp.sell_num is null,0,tp.sell_num) sellNum "
            + " from tbl_product tp left join tbl_commodity tc on tc.commo_no = tp.commo_no"
            + " where tc.seller_no = :shopNo and tc.publish_state ='1' and (tp.is_groupbuy is null or tp.is_groupbuy='1') and tp.delete_flag ='0' order by ifnull(tp.sort,2147483647) asc,tc.publish_time desc";
    query = productDao.createSQLQuery(sqlProduct);
    //      query.setMaxResults(10);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> prods = query.list();
    if (map != null) {
        map.put("products", prods);
    }
    String sqlGroupBuyProduct = "select IF(tp.prod_name is null,'',tp.prod_name) prodName,"
            + " IF(tp.default_pic is null,'',tp.default_pic) prodPic," + " tp.price prodPrice,"
            + " tp.prod_no prodNo," + " tp.sort sort," + " ifnull(tp.stock,0) stock,"
            + " tpromotion.discount_amount groupbuyPrice," + " tpromotion.end_time endTime,"
            + " ifnull(tp.stock_preemption,0) stockPreemption,"
            + " IF(tp.sell_num is null,0,tp.sell_num) sellNum "
            + " from tbl_product tp left join tbl_commodity tc on tc.commo_no = tp.commo_no"
            + " left join tbl_promotion tpromotion on tpromotion.ref_commo_no = tc.commo_no"
            + " where tc.seller_no = :shopNo and tc.publish_state ='1'  and tp.is_groupbuy='2' and tpromotion.status='2' "
            + " and now() between tpromotion.start_time and tpromotion.end_time "
            + " and tpromotion.delete_flag ='0' and tp.delete_flag ='0' order by ifnull(tp.sort,2147483647) asc,tc.publish_time desc";
    query = productDao.createSQLQuery(sqlGroupBuyProduct);
    //      query.setMaxResults(10);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> groupBuyProds = query.list();
    if (map != null) {
        map.put("groupBuyProds", groupBuyProds);
    }
    String sqlCollect = "select * from tbl_shop_collect tsc where tsc.shop_no = :shopNo ";
    Query queryC = shopCollectDao.createSQLQuery(sqlCollect);
    queryC.setParameter("shopNo", shopNo);
    List listCollect = queryC.list();
    if (map != null) {
        map.put("collectNum", listCollect == null ? 0 : listCollect.size());
    }
    //      Query queryCollect = shopCollectDao.createSQLQuery(sqlCollect+"and tsc.member_no = :memberNo");
    //      queryCollect.setParameter("shopNo", shopNo);
    //      queryCollect.setParameter("memberNo", memberNo);
    //      List list = queryCollect.list();
    //      map.put("isCollect", list!=null&&!list.isEmpty()?"1":"0");
    String sqlCat = "select tc.cat_no catNo," + " IF(tcat.cat_name is null,'',tcat.cat_name) catName "
            + " from tbl_commodity tc " + " left join tbl_commo_category tcat "
            + " on tc.cat_no = tcat.cat_no where seller_no = :shopNo group by(tcat.cat_no)";
    query = commodityCatDao.createSQLQuery(sqlCat);
    query.setParameter("shopNo", shopNo);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map<String, Object>> cats = query.list();
    if (map != null) {
        map.put("cats", cats);
    }
    return map;
}

From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java

/**
 * Returns the average execution time/*from   w ww .j  a v  a2 s.  co m*/
 * @return the average execution time
 */
public double getAverageExecutionTime() {

    long completedTask = getCompletedTaskCount();

    if (completedTask == 0) {
        return 0;
    }

    double average = totalExecutionTime.doubleValue() / completedTask;

    BigDecimal bd = new BigDecimal(average);
    bd = bd.setScale(1, BigDecimal.ROUND_HALF_EVEN);

    return bd.doubleValue();
}

From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

private void addMarketingRelationUser(TradeDetail detail, Trade trade, DivsionRuleRole divsionRuleRole)
        throws Exception {
    double yxJGAmount = 0;
    BigDecimal bg = new BigDecimal(getDaysRuleRate(divsionRuleRole.getRule(), trade) * detail.getAmount());
    yxJGAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    yxJGAmount = Math.floor(yxJGAmount);

    UserBaseInfoDO curParentJjr = null;//w w w  . j a v  a 2s .c  o m
    if (curParentJjr == null) {
        try {
            curParentJjr = userBaseInfoManager.queryByUserName(detail.getUserName(),
                    SysUserRoleEnum.BROKER.getValue());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    if (curParentJjr == null) {
        Page<UserRelationDO> userRelationsPage = userRelationManager.getRelationsByConditions(null, null,
                detail.getUserId(), null);
        if (userRelationsPage.getResult() != null && userRelationsPage.getResult().size() > 0) {
            List<UserBaseInfoDO> curParentJjrs = userBaseInfoManager.queryByType(null,
                    String.valueOf(userRelationsPage.getResult().get(0).getParentId()));
            if (curParentJjrs != null && curParentJjrs.size() > 0) {
                if (UserTypeEnum.GR.code().equals(curParentJjrs.get(0).getType())) {
                    curParentJjr = curParentJjrs.get(0);
                }

            }
        }
    }
    if (curParentJjr != null) {
        //??
        UserBaseInfoDO curParentJG = null;
        int maxLength = 20;
        int index = 0;
        long curParentJjrUserId = curParentJjr.getUserId();
        while (curParentJG == null && index < maxLength) {
            index++;
            Page<UserRelationDO> userRelationsJGPage = userRelationManager.getRelationsByConditions(null, null,
                    curParentJjrUserId, null);
            if (userRelationsJGPage.getResult() != null && userRelationsJGPage.getResult().size() > 0) {
                long parentUserId = userRelationsJGPage.getResult().get(0).getParentId();
                UserBaseInfoDO parentUser = userBaseInfoManager.queryByUserId(parentUserId);
                if (parentUser != null) {
                    if (UserTypeEnum.JG.code().equals(parentUser.getType())) {
                        curParentJG = parentUser;
                        break;
                    } else {
                        curParentJjrUserId = parentUser.getUserId();
                    }
                }
            } else {
                break;
            }
        }
        if (curParentJG != null) {
            //?
            tradeDetailDao.addTradeDetail(new TradeDetail(curParentJG.getUserId(), trade.getId(),
                    (long) yxJGAmount, 10, divsionRuleRole.getPhase(), String.valueOf(detail.getId())));
        }

    }

    //      double yxJGAmount = 0;
    //      long tradeId = trade.getId();
    //      long detailId = detail.getId();
    //      BigDecimal bg = new BigDecimal(getDaysRuleRate(
    //            divsionRuleRole.getRule(), trade)
    //            * detail.getAmount());
    //      yxJGAmount = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();
    //      yxJGAmount = Math.floor(yxJGAmount);
    //      // ??
    //      Page<UserRelationDO> userRelationsPage = userRelationManager
    //            .getRelationsByConditions(null, null, detail.getUserId(), null);
    //      if (userRelationsPage.getResult() != null
    //            && userRelationsPage.getResult().size() > 0) {
    //         List<UserBaseInfoDO> curParentJjrs = userBaseInfoManager
    //               .queryByType(
    //                     null,
    //                     String.valueOf(userRelationsPage.getResult().get(0)
    //                           .getParentId()));
    //         UserBaseInfoDO curParentJjr = null;
    //         if (curParentJjrs != null && curParentJjrs.size() > 0) {
    //            curParentJjr = curParentJjrs.get(0);
    //            // ??
    //            Page<UserRelationDO> userRelationsJGPage = userRelationManager
    //                  .getRelationsByConditions(null, null,
    //                        curParentJjr.getUserId(), null);
    //            if (userRelationsJGPage.getResult() != null
    //                  && userRelationsJGPage.getResult().size() > 0) {
    //               List<UserBaseInfoDO> curParentJGs = userBaseInfoManager
    //                     .queryByType(
    //                           UserTypeEnum.JG.code(),
    //                           String.valueOf(userRelationsJGPage
    //                                 .getResult().get(0).getParentId()));
    //               UserBaseInfoDO curParentJG = null;
    //               if (curParentJGs != null && curParentJGs.size() > 0) {
    //                  curParentJG = curParentJGs.get(0);
    //                  // ?
    //                  tradeDetailDao.addTradeDetail(new TradeDetail(
    //                        curParentJG.getUserId(), tradeId,
    //                        (long) yxJGAmount, 10, divsionRuleRole
    //                              .getPhase(), String.valueOf(detailId)));
    //               }
    //            }
    //         }
    //      }
}