List of usage examples for java.math BigDecimal setScale
@Deprecated(since = "9") public BigDecimal setScale(int newScale, int roundingMode)
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 ava 2s. 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:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.java
public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); HttpServletRequest request = (HttpServletRequest) context.get("request"); HttpServletResponse response = (HttpServletResponse) context.get("response"); Map<String, Object> paramMap = UtilHttp.getParameterMap(request); String token = (String) paramMap.get("TOKEN"); WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token)); ShoppingCart cart = null;// w w w .j a v a2 s . c o m if (weakCart != null) { cart = weakCart.get(); } if (cart == null) { Debug.logError("Could locate the ShoppingCart for token " + token, module); return ServiceUtil.returnSuccess(); } // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and // then delete once we're done, now is not the time to worry about updating everything String contactMechId = null; Map<String, Object> inMap = new HashMap<String, Object>(); inMap.put("address1", paramMap.get("SHIPTOSTREET")); inMap.put("address2", paramMap.get("SHIPTOSTREET2")); inMap.put("city", paramMap.get("SHIPTOCITY")); String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY"); String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator); if (countryGeoId == null) { return ServiceUtil.returnSuccess(); } inMap.put("countryGeoId", countryGeoId); inMap.put("stateProvinceGeoId", parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator)); inMap.put("postalCode", paramMap.get("SHIPTOZIP")); try { GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", "system") .cache().queryOne(); inMap.put("userLogin", userLogin); } catch (GenericEntityException e) { Debug.logError(e, module); } boolean beganTransaction = false; Transaction parentTransaction = null; try { parentTransaction = TransactionUtil.suspend(); beganTransaction = TransactionUtil.begin(); } catch (GenericTransactionException e1) { Debug.logError(e1, module); } try { Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap); contactMechId = (String) outMap.get("contactMechId"); } catch (GenericServiceException e) { Debug.logError(e.getMessage(), module); return ServiceUtil.returnSuccess(); } try { TransactionUtil.commit(beganTransaction); if (parentTransaction != null) TransactionUtil.resume(parentTransaction); } catch (GenericTransactionException e) { Debug.logError(e, module); } // clone the cart so we can modify it temporarily CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart); String oldShipAddress = cart.getShippingContactMechId(); coh.setCheckOutShippingAddress(contactMechId); ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0); int line = 0; NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "CallbackResponse"); for (GenericValue shipMethod : estWrapper.getShippingMethods()) { BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod); //Check that we have a valid estimate (allowing zero value estimates for now) if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) { continue; } cart.setAllShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId")); cart.setAllCarrierPartyId(shipMethod.getString("partyId")); try { coh.calcAndAddTax(); } catch (GeneralException e) { Debug.logError(e, module); continue; } String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description"); encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel); encoder.add("L_SHIPPINGOPTIONAMOUNT" + line, estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); // Just make this first one default for now encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false"); encoder.add("L_TAXAMT" + line, cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); line++; } String responseMsg = null; try { responseMsg = encoder.encode(); } catch (PayPalException e) { Debug.logError(e, module); } if (responseMsg != null) { try { response.setContentLength(responseMsg.getBytes("UTF-8").length); } catch (UnsupportedEncodingException e) { Debug.logError(e, module); } try { Writer writer = response.getWriter(); writer.write(responseMsg); writer.close(); } catch (IOException e) { Debug.logError(e, module); } } // Remove the temporary ship address try { GenericValue postalAddress = EntityQuery.use(delegator).from("PostalAddress") .where("contactMechId", contactMechId).queryOne(); postalAddress.remove(); GenericValue contactMech = EntityQuery.use(delegator).from("ContactMech") .where("contactMechId", contactMechId).queryOne(); contactMech.remove(); } catch (GenericEntityException e) { Debug.logError(e, module); } coh.setCheckOutShippingAddress(oldShipAddress); return ServiceUtil.returnSuccess(); }
From source file:org.egov.stms.notice.service.SewerageNoticeService.java
public ReportOutput generateReportOutputDataForEstimation( final SewerageApplicationDetails sewerageApplicationDetails) { ReportRequest reportInput = null;//w w w. j a v a 2 s . c om final Map<String, Object> reportParams = new HashMap<>(); if (sewerageApplicationDetails != null) { final AssessmentDetails assessmentDetails = sewerageTaxUtils.getAssessmentDetailsForFlag( sewerageApplicationDetails.getConnectionDetail().getPropertyIdentifier(), PropertyExternalService.FLAG_FULL_DETAILS); String[] doorNo = null; if (null != assessmentDetails.getPropertyAddress()) doorNo = assessmentDetails.getPropertyAddress().split(","); String ownerName = ""; if (null != assessmentDetails.getOwnerNames()) for (final OwnerName names : assessmentDetails.getOwnerNames()) { ownerName = names.getOwnerName(); break; } if (sewerageApplicationDetails.getApplicationType() != null) reportParams.put(APPLICATION_TYPE, WordUtils.capitalize(sewerageApplicationDetails.getApplicationType().getName())); reportParams.put("cityName", cityService.getMunicipalityName()); reportParams.put(DISTRICT, cityService.getDistrictName()); reportParams.put("estimationDate", getDefaultFormattedDate(sewerageApplicationDetails.getApplicationDate())); reportParams.put("cityLogo", cityService.getCityLogoURL()); reportParams.put("estimationNumber", sewerageApplicationDetails.getEstimationNumber()); reportParams.put(ASSESSMENT_NO, sewerageApplicationDetails.getConnectionDetail().getPropertyIdentifier()); if (sewerageApplicationDetails.getCurrentDemand() != null) for (final EgDemandDetails egDmdDetails : sewerageApplicationDetails.getCurrentDemand() .getEgDemandDetails()) if (egDmdDetails.getEgDemandReason().getEgDemandReasonMaster().getCode() .equalsIgnoreCase(SewerageTaxConstants.FEES_DONATIONCHARGE_CODE)) donationCharges = egDmdDetails.getAmount().subtract(egDmdDetails.getAmtCollected()); // TODO: CHECK THIS LOGIC AGAIN. IF FEE TYPE IS ESTIMATION FEES, // THEN WE NEED TO GROUP ALL FEESES. for (final SewerageConnectionFee scf : sewerageApplicationDetails.getConnectionFees()) { if (scf.getFeesDetail().getCode() .equalsIgnoreCase(SewerageTaxConstants.FEES_ESTIMATIONCHARGES_CODE)) estimationCharges = BigDecimal.valueOf(scf.getAmount()); if (scf.getFeesDetail().getCode().equalsIgnoreCase(SewerageTaxConstants.FEES_SEWERAGETAX_CODE)) sewerageCharges = BigDecimal.valueOf(scf.getAmount()); } final BigDecimal totalCharges = estimationCharges.add(donationCharges).add(sewerageCharges); reportParams.put(ESTIMATION_CHARGES, estimationCharges); reportParams.put(DONATION_CHARGES, donationCharges); reportParams.put("sewerageCharges", sewerageCharges); reportParams.put(TOTAL_CHARGES, totalCharges); reportParams.put("amountInWords", getTotalAmountInWords(totalCharges.setScale(2, BigDecimal.ROUND_HALF_EVEN))); reportParams.put(APPLICATION_DATE, getDefaultFormattedDate(sewerageApplicationDetails.getApplicationDate())); reportParams.put("applicantName", ownerName); reportParams.put(ADDRESS, assessmentDetails.getPropertyAddress()); reportParams.put("inspectionDetails", sewerageApplicationDetails.getFieldInspections().get(0).getFieldInspectionDetails()); reportParams.put("estimationDetails", sewerageApplicationDetails.getEstimationDetails()); reportParams.put("houseNo", doorNo != null ? doorNo[0] : ""); reportInput = new ReportRequest(ESTIMATION_NOTICE, sewerageApplicationDetails, reportParams); } return reportService.createReport(reportInput); }
From source file:nl.tudelft.stocktrader.derby.DerbyCustomerDAO.java
public void updateAccountBalance(int accountId, BigDecimal total) throws DAOException { if (logger.isDebugEnabled()) { logger.debug("MySQLCustomerDAO.updateAccoutBalance(int,BigDecimal)\n Account ID :" + accountId + "\nTotal :" + total); }/* w ww .j a va 2 s . c o m*/ PreparedStatement debitAccountStat = null; try { /* Tiago: we need to be very careful with BigDecimals. Round to 2 places */ total = total.setScale(2, RoundingMode.HALF_UP); debitAccountStat = sqlConnection.prepareStatement(SQL_DEBIT_ACCOUNT); debitAccountStat.setBigDecimal(1, total); debitAccountStat.setInt(2, accountId); debitAccountStat.executeUpdate(); } catch (SQLException e) { throw new DAOException("Excpetion is thrown when updating the account balance for accountID :" + accountId + " total :" + total, e); } finally { if (debitAccountStat != null) { try { debitAccountStat.close(); } catch (SQLException e) { logger.debug("", e); } } } }
From source file:com.zl.bgec.basicapi.shop.service.impl.ShopServiceImpl.java
@Override @Transactional(readOnly = true)//from w w w. j av a 2 s . com public Map<String, Object> getShopDetail(String shopNo, String memberNo) throws Exception { String sql = "select " + " tsi.shop_name shopName," + " tsi.status status," + " tsi.shop_logo shopLogo," + " tsi.shop_type_no shopTypeNo," + " 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,"//?? + " ifnull(tsi.delivery_fee,0) deliveryFee,"//? + " 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", promotionService.getPromotionByShopNo(shopNo, memberNo)); } String sqlProduct = "select IF(tp.prod_name is null,'',tp.prod_name) prodName," + "tp.model model," + " IF(tp.default_pic is null,'',tp.default_pic) prodPic," + " tp.price prodPrice," + " tp.is_groupbuy isGroupbuy," + " 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 (prods != null && !prods.isEmpty()) { for (Map<String, Object> r : prods) { //????+ String prodName = (String) (r.get("prodName") == null ? "" : r.get("prodName")); String model = (String) (r.get("model") == null ? "" : r.get("model")); if (model != null && !model.equals("")) { r.put("prodName", prodName + "(" + model + ")"); } } } if (map != null) { map.put("products", prods); } String sqlGroupBuyProduct = "select IF(tp.prod_name is null,'',tp.prod_name) prodName," + "tp.model model," + " IF(tp.default_pic is null,'',tp.default_pic) prodPic," + " tp.price prodPrice," + " tp.is_groupbuy isGroupbuy," + " tp.prod_no prodNo," + " tp.sort sort," + " ifnull(tp.stock,0) stock," + " tpromotion.promotion_no promotionNo," + " 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 (groupBuyProds != null && !groupBuyProds.isEmpty()) { for (Map<String, Object> gpd : groupBuyProds) { //????+ String prodName = (String) (gpd.get("prodName") == null ? "" : gpd.get("prodName")); String model = (String) (gpd.get("model") == null ? "" : gpd.get("model")); if (model != null && !model.equals("")) { gpd.put("prodName", prodName + "(" + model + ")"); } String promotionNo = (String) gpd.get("promotionNo"); Order buyerOrder = this.getOrderByBuyer(promotionNo, memberNo); if (buyerOrder != null) { if (buyerOrder.getBasicState().equals(OrderConstants.BASIC_STATE_WAITING_PAY)) gpd.put("buyed", "1");// else gpd.put("buyed", "2");// } else { gpd.put("buyed", "0"); } } } 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); } if (map != null && map.get("shopSign") == null) { map.put("shopSign", ""); } return map; }
From source file:com.cisco.dvbu.ps.deploytool.dao.jdbcapi.RegressionPerfTestDAOImpl.java
private String executePerformanceTestWorkers() throws CompositeException { try {/*from w ww . j av a 2s . c o m*/ // Create all the connections Worker[] workers = new Worker[perfTestThreads]; for (int i = 0; i < workers.length; i++) { workers[i] = new Worker(); } // Pause in between query executions Thread.sleep(perfTestSleepExec * 1000); // Start the clock long startTime = System.currentTimeMillis(); endTime = startTime + perfTestDuration * 1000; // Start the workers for (int i = 0; i < workers.length; i++) { workers[i].start(); } // Output the Header Rows String content = CommonUtils.lpad(HEADER, 7, padChar) + logDelim + CommonUtils.rpad("Threads=" + perfTestThreads, 12, padChar) + logDelim + CommonUtils.rpad("Duration (s)=" + perfTestDuration, 17, padChar) + logDelim + CommonUtils.rpad("Print Sleep (s)=" + perfTestSleepPrint, 19, padChar) + logDelim + CommonUtils.rpad("Exec Sleep (s)=" + perfTestSleepExec, 18, padChar) + logDelim + logDelim + logDelim + logDelim; RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, ""); StringBuffer buf = new StringBuffer(); buf.append(content + "\n"); content = CommonUtils.lpad(HEADER, 8, padChar) + logDelim + CommonUtils.rpad("Execs", 12, padChar) + logDelim + CommonUtils.rpad("Execs/sec", 12, padChar) + logDelim + CommonUtils.rpad("Rows/exec", 12, padChar) + logDelim + CommonUtils.rpad("Latency (ms)", 13, padChar) + logDelim + CommonUtils.rpad("1st row (ms)", 13, padChar) + logDelim + CommonUtils.rpad("Duration (ms)", 14, padChar) + logDelim + logDelim; RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, ""); buf.append(content + "\n"); // Initialize the totals before each query execution. numStatExecs.set(0); execsTotal = 0; tpsTotal = new BigDecimal(0); rptTotal = new BigDecimal(0); latTotal = new BigDecimal(0); frTotal = new BigDecimal(0); durTotal = new BigDecimal(0); /* Safeguard: determine the number of loops by taking the "total duration" divided by the "print stat sleep interval" * This is important because sometimes the timing is off when the end time is calculated and when worker threads are * still running. The issue is pointed out below (-->) when there is an extra line printed that throws off the stats. * * HEADER|Threads=1 |Duration (s)=10 |Print Sleep (s)=5 |Exec Sleep (s)=0 |||| * HEADER|Execs |Execs/sec |Rows/exec |Latency (ms) |1st row (ms) |Duration (ms) || * DETAIL|4780 |957.91 |1.00 |1.04 |1.03 |4990.00 || * DETAIL|5146 |1027.96 |1.00 |0.97 |0.96 |5006.00 || * -->DETAIL|11 |2.19 |1.00 |0.90 |0.90 |5018.00 || * TOTALS|3312.33 |662.68 |1.00 |0.97 |0.96 |5004.66 || */ int totalExecLoops = perfTestDuration / perfTestSleepPrint; // Print stats periodically errorFound = false; int loopCounter = 0; while (System.currentTimeMillis() < endTime && !errorFound && loopCounter < totalExecLoops) { Thread.sleep(perfTestSleepPrint * 1000); content = printStats(startTime); if (content != null) buf.append(content); // Reset print stat counters numExecs.set(0); numLatency.set(0); firstRowLatency.set(0); numRows.set(0); startTime = System.currentTimeMillis(); loopCounter++; } // Wait for the workers to finish for (int i = 0; i < workers.length; i++) { workers[i].join(); } // Print stats /* * This is @deprecated as it was determined that the last stat line was inconsistent and throwing off the numbers content = printStats(startTime); if (content != null) buf.append(content); */ // Calculate the Total Average Stats for each run and output as a TOTALS line if (numStatExecs.get() > 0) { // Calculate total average executions BigDecimal execAvg = new BigDecimal(execsTotal); execAvg = execAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR); execAvg = execAvg.setScale(2, BigDecimal.ROUND_DOWN); // Calculate total average execs/sec or tps BigDecimal tpsAvg = tpsTotal; tpsAvg = tpsAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR); tpsAvg = tpsAvg.setScale(2, BigDecimal.ROUND_DOWN); // Calculate total average Rows per Execution BigDecimal rptAvg = rptTotal; rptAvg = rptAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR); rptAvg = rptAvg.setScale(2, BigDecimal.ROUND_DOWN); // Calculate total average Latency BigDecimal latAvg = latTotal; latAvg = latAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR); latAvg = latAvg.setScale(2, BigDecimal.ROUND_DOWN); // Calculate total average First Row Latency BigDecimal frAvg = frTotal; frAvg = frAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR); frAvg = frAvg.setScale(2, BigDecimal.ROUND_DOWN); // Calculate total average Duration BigDecimal durAvg = durTotal; durAvg = durAvg.divide(new BigDecimal(numStatExecs.get()), 5, BigDecimal.ROUND_FLOOR); durAvg = durAvg.setScale(2, BigDecimal.ROUND_DOWN); // Print out the summary Totals line content = CommonUtils.lpad(TOTALS, 8, padChar) + logDelim + CommonUtils.rpad("" + execAvg, 12, padChar) + logDelim + CommonUtils.rpad("" + tpsAvg, 12, padChar) + logDelim + CommonUtils.rpad("" + rptAvg, 12, padChar) + logDelim + CommonUtils.rpad("" + latAvg, 13, padChar) + logDelim + CommonUtils.rpad("" + frAvg, 13, padChar) + logDelim + CommonUtils.rpad("" + durAvg, 20, padChar) + logDelim + logDelim; RegressionManagerUtils.printOutputStr(printOutputType, "summary", content, ""); buf.append(content + "\n"); } return buf.toString(); } catch (Exception e) { throw new ApplicationException(e); } }
From source file:com.osafe.services.OsafePayPalServices.java
public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Delegator delegator = dctx.getDelegator(); HttpServletRequest request = (HttpServletRequest) context.get("request"); HttpServletResponse response = (HttpServletResponse) context.get("response"); Map<String, Object> paramMap = UtilHttp.getParameterMap(request); String token = (String) paramMap.get("TOKEN"); WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token)); ShoppingCart cart = null;/*w w w.j ava 2 s. c o m*/ if (weakCart != null) { cart = weakCart.get(); } if (cart == null) { Debug.logError("Could locate the ShoppingCart for token " + token, module); return ServiceUtil.returnSuccess(); } // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and // then delete once we're done, now is not the time to worry about updating everything String contactMechId = null; Map<String, Object> inMap = FastMap.newInstance(); inMap.put("address1", paramMap.get("SHIPTOSTREET")); inMap.put("address2", paramMap.get("SHIPTOSTREET2")); inMap.put("city", paramMap.get("SHIPTOCITY")); String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY"); String countryGeoId = OsafePayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator); if (countryGeoId == null) { return ServiceUtil.returnSuccess(); } inMap.put("countryGeoId", countryGeoId); inMap.put("stateProvinceGeoId", parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator)); inMap.put("postalCode", paramMap.get("SHIPTOZIP")); try { GenericValue userLogin = delegator.findOne("UserLogin", true, UtilMisc.toMap("userLoginId", "system")); inMap.put("userLogin", userLogin); } catch (GenericEntityException e) { Debug.logError(e, module); } boolean beganTransaction = false; Transaction parentTransaction = null; try { parentTransaction = TransactionUtil.suspend(); beganTransaction = TransactionUtil.begin(); } catch (GenericTransactionException e1) { Debug.logError(e1, module); } try { Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap); contactMechId = (String) outMap.get("contactMechId"); } catch (GenericServiceException e) { Debug.logError(e.getMessage(), module); return ServiceUtil.returnSuccess(); } try { TransactionUtil.commit(beganTransaction); if (parentTransaction != null) TransactionUtil.resume(parentTransaction); } catch (GenericTransactionException e) { Debug.logError(e, module); } // clone the cart so we can modify it temporarily CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart); String oldShipAddress = cart.getShippingContactMechId(); coh.setCheckOutShippingAddress(contactMechId); ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0); int line = 0; NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "CallbackResponse"); for (GenericValue shipMethod : estWrapper.getShippingMethods()) { BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod); //Check that we have a valid estimate (allowing zero value estimates for now) if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) { continue; } cart.setShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId")); cart.setCarrierPartyId(shipMethod.getString("partyId")); try { coh.calcAndAddTax(); } catch (GeneralException e) { Debug.logError(e, module); continue; } String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description"); encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel); encoder.add("L_SHIPPINGOPTIONAMOUNT" + line, estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); // Just make this first one default for now encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false"); encoder.add("L_TAXAMT" + line, cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); line++; } String responseMsg = null; try { responseMsg = encoder.encode(); } catch (PayPalException e) { Debug.logError(e, module); } if (responseMsg != null) { try { response.setContentLength(responseMsg.getBytes("UTF-8").length); } catch (UnsupportedEncodingException e) { Debug.logError(e, module); } try { Writer writer = response.getWriter(); writer.write(responseMsg); writer.close(); } catch (IOException e) { Debug.logError(e, module); } } // Remove the temporary ship address try { GenericValue postalAddress = delegator.findOne("PostalAddress", false, UtilMisc.toMap("contactMechId", contactMechId)); postalAddress.remove(); GenericValue contactMech = delegator.findOne("ContactMech", false, UtilMisc.toMap("contactMechId", contactMechId)); contactMech.remove(); } catch (GenericEntityException e) { Debug.logError(e, module); } coh.setCheckOutShippingAddress(oldShipAddress); return ServiceUtil.returnSuccess(); }
From source file:org.apache.calcite.runtime.SqlFunctions.java
public static BigDecimal floor(BigDecimal b0) { return b0.setScale(0, RoundingMode.FLOOR); }
From source file:org.apache.calcite.runtime.SqlFunctions.java
public static BigDecimal ceil(BigDecimal b0) { return b0.setScale(0, RoundingMode.CEILING); }
From source file:org.gradoop.flink.datagen.transactions.foodbroker.config.FoodBrokerConfig.java
/** * Adds positive or negative influence to the start value, depending on the * quality of the master data objects.// ww w . j a v a 2 s . com * * @param influencingMasterDataQuality list of influencing master data quality * @param higherIsBetter true if positiv influence shall be added, negative * influence otherwise * @param influence influence value to be added to the start value * @param startValue the start value * @return aggregated start value */ protected Float getValue(List<Float> influencingMasterDataQuality, boolean higherIsBetter, Float influence, Float startValue) { Float value = startValue; BigDecimal influenceCount = BigDecimal.ZERO; for (float quality : influencingMasterDataQuality) { // check quality value of the masterdata and adjust the result value influenceCount = influenceCount.add(BigDecimal.valueOf(quality)); } if (influenceCount.compareTo(BigDecimal.ZERO) > 0) { influenceCount = influenceCount.setScale(2, BigDecimal.ROUND_HALF_UP); // normalize the quality value influenceCount = influenceCount.divide(BigDecimal.valueOf(influencingMasterDataQuality.size()), 8, RoundingMode.HALF_UP); // subtract the avg normal, for standard config it is 0.5 influenceCount = influenceCount.subtract(getAvgNormal()); // if the normalized value is greater than the avg if (influenceCount.compareTo(BigDecimal.ZERO) == 1) { // calculate how much times the value is greater than the difference // between the avg normal value and the lowest good value influenceCount = influenceCount.divide( BigDecimal.valueOf(getQualityGood()).subtract(getAvgNormal()).abs(), 0, BigDecimal.ROUND_HALF_UP); // if the normalized value is LOWER than the avg } else if (influenceCount.compareTo(BigDecimal.ZERO) == -1) { // calculate how much times the value is smaller than the difference // between the avg normal value and the lowest normal value influenceCount = influenceCount.divide( BigDecimal.valueOf(getQualityNormal()).subtract(getAvgNormal()).abs(), 0, BigDecimal.ROUND_HALF_UP); } } influence *= influenceCount.intValue(); if (higherIsBetter) { value += influence; } else { value -= influence; } return value; }