List of usage examples for java.math BigDecimal doubleValue
@Override public double doubleValue()
From source file:com.github.jessemull.microflexbigdecimal.stat.PopulationVarianceWeightsTest.java
/** * Tests set calculation using indices.//from www. j ava2 s . c o m */ @Test public void testSetIndices() { for (Plate plate : arrayIndices) { int begin = random.nextInt(plate.first().size() - 4); int end = begin + random.nextInt(3) + 3; Map<Well, BigDecimal> resultMap = new TreeMap<Well, BigDecimal>(); Map<Well, BigDecimal> returnedMap = variance.set(plate.dataSet(), ArrayUtils.subarray(weightsIndices, begin, end), begin, end - begin, mc); for (Well well : plate) { double[] input = new double[well.size()]; int index = 0; for (BigDecimal bd : well) { input[index] = bd.doubleValue() * weightsIndices[index]; index++; } DescriptiveStatistics stat = new DescriptiveStatistics(ArrayUtils.subarray(input, begin, end)); double resultDouble = stat.getPopulationVariance(); BigDecimal result = new BigDecimal(resultDouble, mc); resultMap.put(well, result); } for (Well well : plate) { BigDecimal result = resultMap.get(well); BigDecimal returned = returnedMap.get(well); BigDecimal[] corrected = correctRoundingErrors(result, returned); assertEquals(corrected[0], corrected[1]); } } }
From source file:com.salesmanager.checkout.cart.AjaxShoppingCartUtil.java
/** * Synchronize Session objects with passed parameters Validates input * parameters Then delegates to OrderService for OrderTotalSummary * calculation. Invoked when recalculate, remove product and changing quantities * //from w ww.ja va 2 s . c o m * @param products */ public OrderTotalSummary calculate(OrderProduct[] products, ShippingInformation shippingMethodLine) { // subtotal // quantity // tax // shipping // handling // other prices HttpServletRequest req = WebContextFactory.get().getHttpServletRequest(); MerchantStore store = SessionUtil.getMerchantStore(req); String currency = store.getCurrency(); // requires order from http session Order order = SessionUtil.getOrder(req); if (order != null && !StringUtils.isBlank(order.getCurrency())) { currency = order.getCurrency(); } OrderTotalSummary total = new OrderTotalSummary(currency); Customer customer = SessionUtil.getCustomer(req); // Shipping ShippingInformation shippingInfo = SessionUtil.getShippingInformation(req); Shipping shipping = null; if (shippingInfo == null) { shippingInfo = new ShippingInformation(); } if (shippingMethodLine != null && shippingMethodLine.getShippingMethodId() == null) {// reset // shipping // shippingMethodLine = new ShippingInformation(); if (req.getSession().getAttribute("PRODUCTLOADED") != null) { shipping = new Shipping(); shipping.setHandlingCost(shippingInfo.getHandlingCost()); shipping.setShippingCost(shippingInfo.getShippingCost()); shipping.setShippingDescription(shippingInfo.getShippingMethod()); shipping.setShippingModule(shippingInfo.getShippingModule()); req.getSession().removeAttribute("PRODUCTLOADED"); } else { shippingInfo.setShippingCostText( CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal("0"), store.getCurrency())); shippingInfo.setShippingMethodId(null); shippingInfo.setShippingMethod(null); shippingInfo.setShippingCost(new BigDecimal("0")); try { SessionUtil.removeShippingInformation(req); } catch (Exception e) { log.error(e); } } } else { // retreive shipping info in http session shipping = new Shipping(); Map shippingOptionsMap = SessionUtil.getShippingMethods(req); String method = shippingMethodLine.getShippingMethodId(); if (shippingInfo.getShippingCost() != null && shippingInfo.getShippingMethod() != null) { shipping.setHandlingCost(shippingInfo.getHandlingCost()); shipping.setShippingCost(shippingInfo.getShippingCost()); shipping.setShippingDescription(shippingInfo.getShippingMethod()); shipping.setShippingModule(shippingInfo.getShippingModule()); } else { if (shippingOptionsMap == null || method == null) { shippingMethodLine.setShippingCostText(CurrencyUtil .displayFormatedAmountWithCurrency(new BigDecimal("0"), store.getCurrency())); // total.setShippingLine(shippingMethodLine); shippingInfo = shippingMethodLine; } else {// after a selection // retreive shipping option ShippingOption option = (ShippingOption) shippingOptionsMap.get(method); // get the latest shipping information (handling, free ...) shippingInfo.setShippingMethodId(option.getOptionId()); shippingInfo.setShippingOptionSelected(option); shippingInfo.setShippingMethod(option.getDescription()); shippingInfo.setShippingCost(option.getOptionPrice()); shippingInfo.setShippingModule(option.getModule()); shipping.setHandlingCost(shippingInfo.getHandlingCost()); shipping.setShippingCost(shippingInfo.getShippingCost()); shipping.setShippingDescription(option.getDescription()); shipping.setShippingModule(option.getModule()); // total.setShipping(true); } } } List productList = new ArrayList(); try { // validate numeric quantity // validate numeric price if (products != null) { // get products from httpsession Map savedOrderProducts = SessionUtil.getOrderProducts(req); Map currentProducts = new HashMap(); if (savedOrderProducts == null) { savedOrderProducts = SessionUtil.createSavedOrderProducts(req); } total.setOrderProducts(products); if (order == null) { log.error("No order exist for the price calculation"); total.setErrorMessage( LabelUtil.getInstance().getText(req.getLocale(), "messages.genericmessage")); return total; } // validates amounts BigDecimal oneTimeSubTotal = total.getOneTimeSubTotal(); List prdscart = null; ShoppingCart cart = SessionUtil.getMiniShoppingCart(req); for (int i = 0; i < products.length; i++) { //get product submited OrderProduct product = products[i]; currentProducts.put(String.valueOf(product.getLineId()), product); // get the original line OrderProduct oproduct = (OrderProduct) savedOrderProducts .get(String.valueOf(product.getLineId())); oproduct.setPriceErrorMessage(null); oproduct.setErrorMessage(null); productList.add(oproduct); // check that productid match if (product.getProductId() != oproduct.getProductId()) {// set // an // error // message oproduct.setErrorMessage(LabelUtil.getInstance().getText(req.getLocale(), "messages.invoice.product.invalid")); //oproduct.setPriceText("0"); //oproduct.setProductPrice(new BigDecimal(0)); oproduct.setPriceFormated(CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal(0), store.getCurrency())); continue; } //validate if quantity is valid if (product.getProductQuantity() > oproduct.getProductQuantityOrderMax()) { oproduct.setErrorMessage( LabelUtil.getInstance().getText(req.getLocale(), "messages.invalid.quantity")); product.setProductQuantity(product.getProductQuantityOrderMax()); continue; } // validate and set the final price try { product.setPriceErrorMessage(null);// reset any error // message product.setErrorMessage(null); // set price submited BigDecimal price = oproduct.getProductPrice(); oproduct.setPriceText(product.getPriceText()); oproduct.setProductPrice(price); oproduct.setProductQuantity(product.getProductQuantity()); double finalPrice = price.doubleValue() * product.getProductQuantity(); BigDecimal bdFinalPrice = new BigDecimal(finalPrice); // price calculated @todo can remove, use priceFormated oproduct.setCostText( CurrencyUtil.displayFormatedAmountWithCurrency(bdFinalPrice, store.getCurrency())); oproduct.setPriceFormated( CurrencyUtil.displayFormatedAmountWithCurrency(bdFinalPrice, store.getCurrency())); // final price is price * quantity oproduct.setFinalPrice(bdFinalPrice); } catch (NumberFormatException nfe) { oproduct.setPriceErrorMessage( LabelUtil.getInstance().getText(req.getLocale(), "messages.price.invalid")); oproduct.setPriceText("0"); oproduct.setProductPrice(new BigDecimal(0)); oproduct.setCostText(CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal(0), store.getCurrency())); oproduct.setPriceFormated(CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal(0), store.getCurrency())); // set shipping to 0 ShippingInformation info = new ShippingInformation(); shippingMethodLine.setShippingCostText(CurrencyUtil .displayFormatedAmountWithCurrency(new BigDecimal("0"), store.getCurrency())); total.setShippingLine(info); total.setShippingTotal(new BigDecimal("0")); } // check mini cart products and adjust quantity if (cart != null) { Collection prds = cart.getProducts(); if (prds != null) { Iterator iprd = prds.iterator(); while (iprd.hasNext()) { ShoppingCartProduct scp = (ShoppingCartProduct) iprd.next(); if (scp.getMainCartLine() != null && scp.getMainCartLine().equals(String.valueOf(products[i].getLineId()))) { scp.setQuantity(products[i].getProductQuantity()); } } } } } // save mini cart if (cart != null) { MiniShoppingCartUtil.calculateTotal(cart, store); } List removable = null; // cleanup http session Iterator it = savedOrderProducts.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); if (!currentProducts.containsKey(key)) { if (removable == null) { removable = new ArrayList(); } removable.add(key); } } if (removable != null) { Iterator removIt = removable.iterator(); while (removIt.hasNext()) { String key = (String) removIt.next(); SessionUtil.removeOrderTotalLine(key, req); } } OrderService oservice = (OrderService) ServiceFactory.getService(ServiceFactory.OrderService); total = oservice.calculateTotal(order, productList, customer, shipping, store.getCurrency(), LocaleUtil.getLocale(req)); OrderProduct[] opArray = new OrderProduct[productList.size()]; OrderProduct[] o = (OrderProduct[]) productList.toArray(opArray); total.setOrderProducts(o); total.setShippingLine(shippingInfo); Order savedOrder = SessionUtil.getOrder(req); savedOrder.setTotal(total.getTotal()); savedOrder.setOrderTax(total.getTaxTotal()); savedOrder.setRecursiveAmount(total.getRecursiveSubTotal()); SessionUtil.setOrder(savedOrder, req); Map totals = OrderUtil.getOrderTotals(order.getOrderId(), total, store.getCurrency(), LocaleUtil.getLocale(req)); // transform totals to a list List totalsList = new ArrayList(); if (totals != null) { Iterator totalsIterator = totals.keySet().iterator(); while (totalsIterator.hasNext()) { String key = (String) totalsIterator.next(); OrderTotal t = (OrderTotal) totals.get(key); totalsList.add(t); } } SessionUtil.setOrderTotals(totalsList, req); } } catch (Exception e) { log.error(e); total = new OrderTotalSummary(store.getCurrency()); total.setErrorMessage(LabelUtil.getInstance().getText(req.getLocale(), "messages.genericmessage")); } ShippingInformation shippingLine = total.getShippingLine(); if (shippingLine != null) { shippingLine.setShippingCostText(CurrencyUtil .displayFormatedAmountWithCurrency(shippingLine.getShippingCost(), store.getCurrency())); } else { shippingLine = new ShippingInformation(); shippingLine.setShippingCostText( CurrencyUtil.displayFormatedAmountWithCurrency(new BigDecimal("0"), store.getCurrency())); } if (shippingLine.getHandlingCost() != null) { shippingLine.setHandlingCostText(CurrencyUtil .displayFormatedAmountWithCurrency(shippingMethodLine.getHandlingCost(), store.getCurrency())); } if (total.getShippingTotal() != null) { total.setShippingTotalText( CurrencyUtil.displayFormatedAmountWithCurrency(total.getShippingTotal(), store.getCurrency())); } if (total.getOneTimeSubTotal() != null) { total.setOneTimeSubTotalText(CurrencyUtil.displayFormatedAmountWithCurrency(total.getOneTimeSubTotal(), store.getCurrency())); } if (total.getRecursiveSubTotal() != null) { total.setRecursiveSubTotalText(CurrencyUtil .displayFormatedAmountWithCurrency(total.getRecursiveSubTotal(), store.getCurrency())); } if (total.getTotal() != null) { total.setTotalText( CurrencyUtil.displayFormatedAmountWithCurrency(total.getTotal(), store.getCurrency())); } synchronizeProductList(req); return total; }
From source file:com.zl.bgec.basicapi.shop.service.impl.ShopServiceImpl.java
@Override @Transactional(readOnly = true)/*from www . j a v a 2s . c o m*/ public List<Map<String, Object>> getShop(String shopName, String shopTypeNo, String memberNo) throws Exception { String sql = "select " + " tsi.shop_no shopNo, " + " tsi.shop_name shopName, " + " tsi.shop_logo shopLogo, " + " tsi.shop_summary shopSummary, " + " tsi.is_recommend isRecommend, " + " tcc.serviceGrade serviceGrade, " + " tcc.deliveryGrade deliveryGrade, " + " if(tcs.shop_no is null,'0','1') isCollect " + " from tbl_shop_info tsi left join " + " (select avg(tcc.service_grade) serviceGrade,avg(tcc.delivery_grade) deliveryGrade , " + " tcc.shop_no from tbl_commodity_comment tcc group by(tcc.shop_no) ) tcc on tsi.shop_no = tcc.shop_no " + " left join (select * from tbl_shop_collect tcs where tcs.member_no = :memberNo) tcs on tsi.shop_no = tcs.shop_no " + "where tsi.status=2 "; if (shopTypeNo != null && !shopTypeNo.equals("")) { sql = sql + "and tsi.shop_type_no=:shopTypeNo "; } if (shopName != null && !shopName.equals("")) { sql = sql + "and tsi.shop_name like :shopName "; } Query query = shopDao.createSQLQuery(sql); if (shopTypeNo != null && !shopTypeNo.equals("")) { query.setParameter("shopTypeNo", shopTypeNo); } if (shopName != null && !shopName.equals("")) { query.setParameter("shopName", "%" + shopName + "%"); } query.setParameter("memberNo", memberNo); query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP); List<Map<String, Object>> results = query.list(); if (results != null && !results.isEmpty()) { for (Map<String, Object> result : results) { Double servGrade = result.get("serviceGrade") == null ? 0 : Double.valueOf(result.get("serviceGrade").toString()); BigDecimal serviceGrade = new BigDecimal(servGrade); serviceGrade = serviceGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN); result.put("serviceGrade", serviceGrade.doubleValue()); Double delGrade = result.get("deliveryGrade") == null ? 0 : Double.valueOf(result.get("deliveryGrade").toString()); BigDecimal deliveryGrade = new BigDecimal(delGrade); deliveryGrade = deliveryGrade.setScale(1, BigDecimal.ROUND_HALF_EVEN); result.put("deliveryGrade", deliveryGrade.doubleValue()); } } return results; }
From source file:com.griddynamics.jagger.engine.e1.scenario.DefaultWorkloadSuggestionMaker.java
private static Integer findClosestPoint(BigDecimal desiredTps, Map<Integer, Pair<Long, BigDecimal>> stats) { final int MAX_POINTS_FOR_REGRESSION = 10; SortedMap<Long, Integer> map = Maps.newTreeMap(new Comparator<Long>() { @Override// www . j ava2 s . c o m public int compare(Long first, Long second) { return second.compareTo(first); } }); for (Map.Entry<Integer, Pair<Long, BigDecimal>> entry : stats.entrySet()) { map.put(entry.getValue().getFirst(), entry.getKey()); } if (map.size() < 2) { throw new IllegalArgumentException("Not enough stats to calculate point"); } // <time><number of threads> - sorted by time Iterator<Map.Entry<Long, Integer>> iterator = map.entrySet().iterator(); SimpleRegression regression = new SimpleRegression(); Integer tempIndex; double previousValue = -1.0; double value; double measuredTps; log.debug("Selecting next point for balancing"); int indx = 0; while (iterator.hasNext()) { tempIndex = iterator.next().getValue(); if (previousValue < 0.0) { previousValue = tempIndex.floatValue(); } value = tempIndex.floatValue(); measuredTps = stats.get(tempIndex).getSecond().floatValue(); regression.addData(value, measuredTps); log.debug(String.format(" %7.2f %7.2f", value, measuredTps)); indx++; if (indx > MAX_POINTS_FOR_REGRESSION) { break; } } double intercept = regression.getIntercept(); double slope = regression.getSlope(); double approxPoint; // if no slope => use previous number of threads if (Math.abs(slope) > 1e-12) { approxPoint = (desiredTps.doubleValue() - intercept) / slope; } else { approxPoint = previousValue; } // if approximation point is negative - ignore it if (approxPoint < 0) { approxPoint = previousValue; } log.debug(String.format("Next point %7d (target tps: %7.2f)", (int) Math.round(approxPoint), desiredTps.doubleValue())); return (int) Math.round(approxPoint); }
From source file:it.govpay.web.rs.dars.monitoraggio.rendicontazioni.RendicontazioniHandler.java
@Override public Dettaglio getDettaglio(long id, UriInfo uriInfo, BasicBD bd) throws WebApplicationException, ConsoleException { String methodName = "dettaglio " + this.titoloServizio + "." + id; try {//from w w w. j av a2 s .c o m this.log.info("Esecuzione " + methodName + " in corso..."); // Operazione consentita solo ai ruoli con diritto di lettura this.darsService.checkDirittiServizioLettura(bd, this.funzionalita); RendicontazioniBD frBD = new RendicontazioniBD(bd); Set<Long> setDomini = this.darsService.getIdDominiAbilitatiLetturaServizio(bd, this.funzionalita); boolean eseguiRicerca = !setDomini.isEmpty(); if (eseguiRicerca && !setDomini.contains(-1L)) { List<Long> idDomini = new ArrayList<Long>(); RendicontazioneFilter filter = frBD.newFilter(); List<Long> lstCodDomini = new ArrayList<Long>(); lstCodDomini.addAll(setDomini); idDomini.addAll(setDomini); filter.setIdDomini(toListCodDomini(idDomini, bd)); List<Long> idRendL = new ArrayList<Long>(); idRendL.add(id); filter.setIdRendicontazione(idRendL); long count = eseguiRicerca ? frBD.count(filter) : 0; eseguiRicerca = eseguiRicerca && count > 0; } // recupero oggetto Rendicontazione rendicontazione = eseguiRicerca ? frBD.getRendicontazione(id) : null; InfoForm infoModifica = null; InfoForm infoCancellazione = rendicontazione != null ? this.getInfoCancellazioneDettaglio(uriInfo, bd, rendicontazione) : null; InfoForm infoEsportazione = rendicontazione != null ? this.getInfoEsportazioneDettaglio(uriInfo, bd, rendicontazione) : null; String titolo = rendicontazione != null ? this.getTitolo(rendicontazione, bd) : ""; Dettaglio dettaglio = new Dettaglio(titolo, infoEsportazione, infoCancellazione, infoModifica); it.govpay.web.rs.dars.model.Sezione root = dettaglio.getSezioneRoot(); String codDominio = null; if (rendicontazione != null) { Pagamento pagamento = rendicontazione.getPagamento(bd); if (pagamento != null) { codDominio = pagamento.getCodDominio(); } else { Fr fr = rendicontazione.getFr(bd); codDominio = fr.getCodDominio(); } // dominio if (StringUtils.isNotEmpty(codDominio)) { try { Dominio dominio = AnagraficaManager.getDominio(bd, codDominio); Domini dominiDars = new Domini(); DominiHandler dominiDarsHandler = (DominiHandler) dominiDars.getDarsHandler(); Elemento elemento = dominiDarsHandler.getElemento(dominio, dominio.getId(), dominiDars.getPathServizio(), bd); root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".dominio.label"), elemento.getTitolo(), elemento.getUri()); } catch (NotFoundException e) { } } // iur if (StringUtils.isNotEmpty(rendicontazione.getIur())) { root.addVoce(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".iur.label"), rendicontazione.getIur()); } if (StringUtils.isNotEmpty(rendicontazione.getIuv())) { root.addVoce(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".iuv.label"), rendicontazione.getIuv()); } if (rendicontazione.getData() != null) { root.addVoce(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".data.label"), this.sdf.format(rendicontazione.getData())); } BigDecimal importoPagato = rendicontazione.getImporto() != null ? rendicontazione.getImporto() : BigDecimal.ZERO; root.addVoce(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle( this.nomeServizio + ".importo.label"), importoPagato.doubleValue() + ""); StatoRendicontazione stato = rendicontazione.getStato(); if (stato != null) { root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".stato.label"), Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".stato." + stato.name())); } EsitoRendicontazione esito = rendicontazione.getEsito(); if (esito != null) { root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esito.label"), Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".esito." + esito.name())); } if (pagamento != null) { Pagamenti pagamentiDars = new Pagamenti(); PagamentiHandler pagamentiDarsHandler = (PagamentiHandler) pagamentiDars.getDarsHandler(); SingoloVersamento singoloVersamento = pagamento.getSingoloVersamento(bd); if (singoloVersamento != null) { Elemento elemento = pagamentiDarsHandler.getElemento(pagamento, pagamento.getId(), pagamentiDars.getPathServizio(), bd); root.addVoce( Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".idPagamento.label"), singoloVersamento.getCodSingoloVersamentoEnte(), elemento.getUri()); } } if (rendicontazione.getAnomalie() != null && rendicontazione.getAnomalie().size() > 0) { String etichettaSezioneAnomalie = Utils.getInstance(this.getLanguage()) .getMessageFromResourceBundle(this.nomeServizio + ".sezioneAnomalie.label"); it.govpay.web.rs.dars.model.Sezione sezioneAnomalie = dettaglio .addSezione(etichettaSezioneAnomalie); for (Anomalia anomalia : rendicontazione.getAnomalie()) { sezioneAnomalie.addVoce(anomalia.getCodice(), anomalia.getDescrizione()); } } } this.log.info("Esecuzione " + methodName + " completata."); return dettaglio; } catch (WebApplicationException e) { throw e; } catch (Exception e) { throw new ConsoleException(e); } }
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); }//from ww w .ja va 2 s. c o m 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(readOnly = true)/*from w w w .j a v a 2s . 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.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java
/** * Returns the average execution time//from w w w . j a va 2 s .c o 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.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java
/** * Returns the push listener load factor computed as completedTaskCount/runningTime * in minutes (that is number of completed tasks in a minute) * @return the push listener load factor computed as completedTaskCount/runningTime *//*from w w w. j a v a 2 s .com*/ public double getLoadFactor() { double runningTime = ((double) System.currentTimeMillis() - startingTime) / 60000; // in minutes if (runningTime == 0) { return 0; } long completedTask = getCompletedTaskCount(); if (completedTask == 0) { return 0; } double loadFactor = (double) completedTask / runningTime; BigDecimal bd = new BigDecimal(loadFactor); bd = bd.setScale(1, BigDecimal.ROUND_HALF_EVEN); return bd.doubleValue(); }
From source file:com.zl.bgec.basicapi.shop.service.impl.ShopServiceImpl.java
@Override @Transactional//from w w w . j a v a 2 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; }