List of usage examples for java.math BigDecimal ROUND_HALF_UP
int ROUND_HALF_UP
To view the source code for java.math BigDecimal ROUND_HALF_UP.
Click Source Link
From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java
/** * Prepares Collection Table Data/*www. j av a2 s.c o m*/ * * @param collectionDetailsRequest * @return List */ public List<WaterChargeDashBoardResponse> getResponseTableData( final WaterChargeDashBoardRequest collectionDetailsRequest) { final List<WaterChargeDashBoardResponse> collIndDataList = new ArrayList<>(); Date fromDate; Date toDate; String name; WaterChargeDashBoardResponse collIndData; BigDecimal cytdDmd; BigDecimal performance; BigDecimal balance; BigDecimal variance; String aggregationField = WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD; Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>(); final CFinancialYear financialYear = cFinancialYearService.getCurrentFinancialYear(); /** * Select the grouping based on the type parameter, by default the * grouping is done based on Regions. If type is region, group by * Region, if type is district, group by District, if type is ulb, group * by ULB */ if (StringUtils.isNotBlank(collectionDetailsRequest.getType())) if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_REGIONWISE)) aggregationField = WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD; else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_DISTRICTWISE)) aggregationField = WaterTaxConstants.DISTRICTNAMEAGGREGATIONFIELD; else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_ULBWISE)) aggregationField = WaterTaxConstants.CITYNAMEAGGREGATIONFIELD; else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_GRADEWISE)) aggregationField = WaterTaxConstants.CITYGRADEAGGREGATIONFIELD; else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_WARDWISE) || collectionDetailsRequest.getType() .equalsIgnoreCase(PropertyTaxConstants.DASHBOARD_GROUPING_BILLCOLLECTORWISE)) aggregationField = WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD; /** * As per Elastic Search functionality, to get the total collections * between 2 dates, add a day to the endDate and fetch the results For * Current day's collection if dates are sent in the request, consider * the toDate, else take date range between current date +1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1); } else { fromDate = new Date(); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } Long startTime = System.currentTimeMillis(); // For today collection final Map<String, BigDecimal> todayCollMap = getCollectionAndDemandValues(collectionDetailsRequest, fromDate, toDate, WaterTaxConstants.COLLECTION_INDEX_NAME, TOTAL_AMOUNT, aggregationField); /** * For collection and demand between the date ranges if dates are sent * in the request, consider fromDate and toDate+1 , else calculate from * current year start date till current date+1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1); } else { fromDate = DateUtils.startOfDay(financialYear.getStartingDate()); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1; final Map<String, BigDecimal> cytdCollMap = getCollectionAndDemandValues(collectionDetailsRequest, fromDate, toDate, COLLECTION_INDEX_NAME, TOTAL_AMOUNT, aggregationField); // For total demand final Map<String, BigDecimal> totalDemandMap = getCollectionAndDemandValues(collectionDetailsRequest, fromDate, toDate, WaterTaxConstants.WATER_TAX_INDEX_NAME, WaterTaxConstants.WATERCHARGETOTALDEMAND, aggregationField); // For current year demand final Map<String, BigDecimal> currYrTotalDemandMap = getCollectionAndDemandValues(collectionDetailsRequest, fromDate, toDate, WaterTaxConstants.WATER_TAX_INDEX_NAME, WaterTaxConstants.WATERCHARGETOTALDEMAND, aggregationField); // For last year's till today's date collections final Map<String, BigDecimal> lytdCollMap = getCollectionAndDemandValues(collectionDetailsRequest, org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1), org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1), WaterTaxConstants.COLLECTION_INDEX_NAME, TOTAL_AMOUNT, aggregationField); if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType())) wardWiseBillCollectors = getWardWiseBillCollectors(collectionDetailsRequest); Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by getCollectionAndDemandValues() is (millisecs) : " + timeTaken); startTime = System.currentTimeMillis(); for (final Map.Entry<String, BigDecimal> entry : cytdCollMap.entrySet()) { collIndData = new WaterChargeDashBoardResponse(); name = entry.getKey(); if (aggregationField.equals(WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD)) collIndData.setRegionName(name); else if (aggregationField.equals(WaterTaxConstants.DISTRICTNAMEAGGREGATIONFIELD)) { collIndData.setRegionName(collectionDetailsRequest.getRegionName()); collIndData.setDistrictName(name); } else if (WaterTaxConstants.CITYNAMEAGGREGATIONFIELD.equals(aggregationField)) { collIndData.setUlbName(name); collIndData.setDistrictName(collectionDetailsRequest.getDistrictName()); collIndData.setUlbGrade(collectionDetailsRequest.getUlbGrade()); } else if (aggregationField.equals(WaterTaxConstants.CITYGRADEAGGREGATIONFIELD)) collIndData.setUlbGrade(name); else if (WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD.equals(aggregationField)) collIndData.setWardName(name); if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType()) && !wardWiseBillCollectors.isEmpty()) collIndData.setBillCollector(wardWiseBillCollectors.get(name) == null ? StringUtils.EMPTY : wardWiseBillCollectors.get(name).getBillCollector()); collIndData.setTodayColl(todayCollMap.get(name) == null ? BigDecimal.ZERO : todayCollMap.get(name)); collIndData.setCurrentYearTillDateColl(entry.getValue()); // Proportional Demand = (totalDemand/12)*noOfmonths final BigDecimal currentYearTotalDemand = currYrTotalDemandMap.get(name) == null ? BigDecimal.valueOf(0) : currYrTotalDemandMap.get(name); cytdDmd = currentYearTotalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths)); collIndData.setCurrentYearTillDateDmd(cytdDmd); if (cytdDmd != BigDecimal.valueOf(0)) { balance = cytdDmd.subtract(collIndData.getCurrentYearTillDateColl()); performance = collIndData.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(cytdDmd, 1, BigDecimal.ROUND_HALF_UP); collIndData.setPerformance(performance); collIndData.setCurrentYearTillDateBalDmd(balance); } collIndData.setTotalDmd(totalDemandMap.get(name) == null ? BigDecimal.ZERO : totalDemandMap.get(name)); collIndData.setLastYearTillDateColl( lytdCollMap.get(name) == null ? BigDecimal.ZERO : lytdCollMap.get(name)); // variance = ((currentYearCollection - // lastYearCollection)*100)/lastYearCollection if (collIndData.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0) variance = WaterTaxConstants.BIGDECIMAL_100; else variance = collIndData.getCurrentYearTillDateColl().subtract(collIndData.getLastYearTillDateColl()) .multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(collIndData.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP); collIndData.setLastYearVar(variance); collIndDataList.add(collIndData); } timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken for setting values in getResponseTableData() is (millisecs): " + timeTaken); return collIndDataList; }
From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.java
public static Map<String, Object> doAuthorization(DispatchContext dctx, Map<String, Object> context) { Delegator delegator = dctx.getDelegator(); String orderId = (String) context.get("orderId"); BigDecimal processAmount = (BigDecimal) context.get("processAmount"); GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod"); OrderReadHelper orh = new OrderReadHelper(delegator, orderId); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE); Locale locale = (Locale) context.get("locale"); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoAuthorization"); encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId")); encoder.add("AMT", processAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("TRANSACTIONENTITY", "Order"); String currency = (String) context.get("currency"); if (currency == null) { currency = orh.getCurrency();/*www . j a v a 2s . c o m*/ } encoder.add("CURRENCYCODE", currency); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil .returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("authResult", false); result.put("authRefNum", "N/A"); result.put("processAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("authCode", error.getKey()); result.put("authMessage", error.getValue()); } else { result.put("authMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("authResult", true); result.put("processAmount", new BigDecimal(decoder.get("AMT"))); result.put("authRefNum", decoder.get("TRANSACTIONID")); } //TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction return result; }
From source file:org.codecover.eclipse.views.RedundancyGraphView.java
private final void calculatePairRedundancy(String Criterion) { Set<CoverableItem> coverableItemSet = createCoverableItemSet(Criterion); Set<CoverableItem> mainSet = new HashSet<CoverableItem>(coverableItemSet); if (Criterion.compareTo("Condition") != 0) { for (int i = 0; i < this.wholeTestCases.size(); i++) { TestCase currentTestCase = this.wholeTestCases.get(i); Set<CoverableItem> currentCoveredSet = new HashSet<CoverableItem>( currentTestCase.getCoverageData().keySet()); currentCoveredSet.retainAll(mainSet); double ts = currentCoveredSet.size(); double rts; Double PairR = 0.0D;// w ww . java 2s.c o m for (int a = 0; a < this.wholeTestCases.size(); a++) { if (a != i) { TestCase secondTestCase = this.wholeTestCases.get(a); Set<CoverableItem> secondSet = new HashSet<CoverableItem>( secondTestCase.getCoverageData().keySet()); secondSet.retainAll(mainSet); secondSet.retainAll(currentCoveredSet); rts = secondSet.size(); PairR = 0.0D; if (ts != 0.0D) { PairR = rts / ts; } else { PairR = (0.0D / 0.0D); } TestCasePair tcp = new TestCasePair(); tcp.CurrentTest = currentTestCase.getName(); tcp.WithRespectTo = secondTestCase.getName(); if (this.selectedTestCases.contains(currentTestCase)) { tcp.selected = true; } else { tcp.selected = false; } if (!PairR.isNaN()) { BigDecimal bd = new BigDecimal(PairR); bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); PairR = bd.doubleValue(); } this.PairRedundancy.put(tcp, PairR); } } } } else { Map<TestCase, Integer> totalCoverableItemCount = new HashMap<TestCase, Integer>(); for (int i = 0; i < this.wholeTestCases.size(); i++) { TestCase currentTestCase = this.wholeTestCases.get(i); Set<CoverableItem> currentCoveredSet = new HashSet<CoverableItem>( currentTestCase.getAssignmentsMap().keySet()); currentCoveredSet.retainAll(mainSet); int amountFirstTestCase = 0; for (CoverableItem item : currentCoveredSet) { BooleanAssignmentMap map = currentTestCase.getAssignmentsMap().get(item); amountFirstTestCase += map.getEvaluatedAssignments().size(); } double ts = amountFirstTestCase; totalCoverableItemCount.put(currentTestCase, Integer.valueOf(amountFirstTestCase)); for (int a = 0; a < this.wholeTestCases.size(); a++) { if (a != i) { TestCase secondTestCase = this.wholeTestCases.get(a); Set<CoverableItem> secondSet = new HashSet<CoverableItem>( secondTestCase.getAssignmentsMap().keySet()); secondSet.retainAll(mainSet); secondSet.retainAll(currentCoveredSet); int amountIntersection = 0; for (CoverableItem item : secondSet) { BooleanAssignmentMap map1 = currentTestCase.getAssignmentsMap().get(item); BooleanAssignmentMap map2 = secondTestCase.getAssignmentsMap().get(item); Set<BooleanAssignment> sharedAssignments = new HashSet<BooleanAssignment>( map1.getEvaluatedAssignments()); sharedAssignments.retainAll(map2.getEvaluatedAssignments()); amountIntersection += sharedAssignments.size(); } double rts = amountIntersection; Double PairR = 0.0D; if (ts != 0.0D) { PairR = rts / ts; } else { PairR = (0.0D / 0.0D); } TestCasePair tcp = new TestCasePair(); tcp.CurrentTest = currentTestCase.getName(); tcp.WithRespectTo = secondTestCase.getName(); if (!PairR.isNaN()) { BigDecimal bd = new BigDecimal(PairR); bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); PairR = bd.doubleValue(); } this.PairRedundancy.put(tcp, PairR); } } } } }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractConnectorController.java
private List<HashMap<String, Object>> getQuickProductList(String quickProducts, ServiceInstance instance) throws JSONException { List<HashMap<String, Object>> quickProductList = new ArrayList<HashMap<String, Object>>(); if (instance.getService().getType().equals(CssdkConstants.CLOUD) && StringUtils.isNotEmpty(quickProducts)) { JSONArray productJsonArray = new JSONArray(quickProducts); List<Revision> allRPBRevisions = productService.getAllRevisions(null); // Size of the list should never be 0, as there always is a revision with // null start date, if not any other Revision productRevision = allRPBRevisions.get(allRPBRevisions.size() - 1); for (int index = 0; index < productJsonArray.length(); index++) { JSONObject jsonObj = productJsonArray.getJSONObject(index); HashMap<String, Object> productMap = new HashMap<String, Object>(); String productName = jsonObj.get("name").toString(); String code = jsonObj.get("code").toString(); String scale = jsonObj.get("scale").toString(); String uom = jsonObj.get("uom").toString(); String usageTypeId = jsonObj.get("usageTypeId").toString(); JSONArray priceList = new JSONArray(jsonObj.getString("price")); ServiceUsageType serviceUsageType = connectorConfigurationManager .getServiceUsageTypeById(Long.parseLong(usageTypeId)); Category category = productService.getCategory(jsonObj.getLong("category")); Product product = new Product(); product.setName(productName); product.setCode(code);//from ww w. j av a 2 s . c om product.setUom(uom); product.setCategory(category); productMap.put("product", product); MediationRule mediationRule = createMediationRule(product, serviceUsageType, instance, null, BigDecimal.valueOf(Double.parseDouble(scale)), "", productRevision); productMap.put("mediationRule", mediationRule); List<ProductCharge> productCharges = new ArrayList<ProductCharge>(); for (int priceIndex = 0; priceIndex < priceList.length(); priceIndex++) { JSONObject price = priceList.getJSONObject(priceIndex); ProductCharge productCharge = new ProductCharge(); productCharge.setPrice( new BigDecimal(price.getString("currencyVal")).setScale(4, BigDecimal.ROUND_HALF_UP)); CurrencyValue cv = currencyValueService.locateBYCurrencyCode(price.getString("currencyCode")); productCharge.setCurrencyValue(cv); productCharge.setRevision(productRevision); productCharges.add(productCharge); } productMap.put("productCharges", productCharges); quickProductList.add(productMap); } } return quickProductList; }
From source file:org.efaps.esjp.accounting.transaction.evaluation.DocumentInfo_Base.java
/** * Apply exchange gain loss.//from w ww. j a v a 2s .com * * @param _parameter Parameter as passed by the eFaps API * @throws EFapsException on error */ public void applyExchangeGainLoss(final Parameter _parameter) throws EFapsException { final AccountInfo gainAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGEGAIN); final AccountInfo lossAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGELOSS); if (gainAcc != null && lossAcc != null) { final QueryBuilder queryBldr = new QueryBuilder(CISales.Payment); queryBldr.addWhereAttrEqValue(CISales.Payment.TargetDocument, getInstance()); final MultiPrintQuery multi = queryBldr.getPrint(); final SelectBuilder selDocInst = new SelectBuilder().linkto(CISales.Payment.FromAbstractLink) .instance(); final SelectBuilder selCurInst = new SelectBuilder().linkto(CISales.Payment.CurrencyLink).instance(); multi.addSelect(selDocInst, selCurInst); multi.addAttribute(CISales.Payment.Amount, CISales.Payment.Date); multi.execute(); while (multi.next()) { final Instance docInst = multi.getSelect(selDocInst); final PrintQuery print = new PrintQuery(docInst); final SelectBuilder selDocCurInst = new SelectBuilder() .linkto(CISales.DocumentSumAbstract.RateCurrencyId).instance(); print.addSelect(selDocCurInst); print.addAttribute(CIERP.DocumentAbstract.Date); print.execute(); final Instance curInst = multi.getSelect(selCurInst); final Instance docCurInst = print.getSelect(selDocCurInst); final DateTime docDate = print.getAttribute(CIERP.DocumentAbstract.Date); final DateTime dateTmp = multi.getAttribute(CISales.Payment.Date); final BigDecimal amountTmp = multi.getAttribute(CISales.Payment.Amount); if (!curInst.equals(Currency.getBaseCurrency()) || !docCurInst.equals(Currency.getBaseCurrency())) { final Currency currency = new Currency(); final RateInfo[] rateInfos1 = currency.evaluateRateInfos(_parameter, dateTmp, curInst, docCurInst); final RateInfo[] rateInfos2 = currency.evaluateRateInfos(_parameter, docDate, curInst, docCurInst); final int idx; // payment in BaseCurreny ==> Document was not BaseCurrency therefore current against target if (curInst.equals(Currency.getBaseCurrency())) { idx = 2; // Document in BaseCurrency ==> payment was not BaseCurrency therefore current against base } else if (docCurInst.equals(Currency.getBaseCurrency())) { idx = 0; // neither Document nor payment are BaseCurrency but are the same } else if (curInst.equals(docCurInst)) { idx = 0; } else { idx = 0; } final BigDecimal rate1 = RateInfo.getRate(_parameter, rateInfos1[idx], docInst.getType().getName()); final BigDecimal rate2 = RateInfo.getRate(_parameter, rateInfos2[idx], docInst.getType().getName()); if (rate1.compareTo(rate2) != 0) { final BigDecimal amount1 = amountTmp.divide(rate1, BigDecimal.ROUND_HALF_UP); final BigDecimal amount2 = amountTmp.divide(rate2, BigDecimal.ROUND_HALF_UP); BigDecimal gainLoss = amount1.subtract(amount2); if (idx == 2) { gainLoss = gainLoss.multiply(rate1); } if (gainLoss.compareTo(BigDecimal.ZERO) != 0) { final boolean out = getInstance().getType() .isKindOf(CISales.PaymentDocumentOutAbstract); if (out) { final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) > 0; for (final AccountInfo accinfo : getCreditAccounts()) { if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) { final BigDecimal accAmount; if (accinfo.getRateInfo().getCurrencyInstance() .equals(Currency.getBaseCurrency())) { accAmount = gainLoss; } else { accAmount = gainLoss.multiply(accinfo.getRate(_parameter)); } accinfo.addAmount(accAmount.negate()); } } if (gain) { gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(), getInstance().getType().getName()); addCredit(gainAcc); } else { lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(), getInstance().getType().getName()); addDebit(lossAcc); } } else { final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) < 0; for (final AccountInfo accinfo : getDebitAccounts()) { if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) { final BigDecimal accAmount; if (!accinfo.getRateInfo().getCurrencyInstance() .equals(Currency.getBaseCurrency())) { accAmount = gainLoss; } else { accAmount = gainLoss.multiply(accinfo.getRate(_parameter)); } accinfo.addAmount(accAmount); } } if (gain) { gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(), getInstance().getType().getName()); addDebit(gainAcc); } else { lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(), getInstance().getType().getName()); addCredit(lossAcc); } } } } } } } }
From source file:com.icebreak.p2p.trade.impl.TradeServiceImpl.java
private double getDaysRuleRate(double rule, Trade trade) { String timeLimitUnit = trade.getTimeLimitUnit(); double timeLimit = trade.getTimeLimit(); double days = 0; if (LoanLimitUnitEnum.LOAN_BY_DAY.code().equals(timeLimitUnit)) { days = timeLimit;/*from ww w . j a v a2 s .c o m*/ } else if (LoanLimitUnitEnum.LOAN_BY_YEAR.code().equals(timeLimitUnit)) { days = timeLimit * YrdConstants.TimeRelativeConstants.DAYSOFAYEAR; } else { days = Math.round(timeLimit * YrdConstants.TimeRelativeConstants.DAYSOFAYEAR / 12); } BigDecimal bg = new BigDecimal(rule / YrdConstants.TimeRelativeConstants.DAYSOFAYEAR * days); double daysRate = bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue(); return daysRate; }
From source file:com.selfsoft.business.service.impl.TbBusinessBalanceServiceImpl.java
public Map<String, BigDecimal> sumGroupList(List<TbBusinessBalance> list) { Map<String, BigDecimal> map = new HashMap<String, BigDecimal>(); // ?/* www . j a v a 2 s . c o m*/ BigDecimal total = new BigDecimal(String.valueOf("0.00")); // ? BigDecimal payed = new BigDecimal(String.valueOf("0.00")); // ? BigDecimal fixHour = new BigDecimal(String.valueOf("0.00")); // ??? BigDecimal fixPart = new BigDecimal(String.valueOf("0.00")); // ?? BigDecimal solePart = new BigDecimal(String.valueOf("0.00")); // BigDecimal other = new BigDecimal(String.valueOf("0.00")); // BigDecimal owe = new BigDecimal(String.valueOf("0.00")); // ??? BigDecimal djcb = new BigDecimal(String.valueOf("0.00")); if (null != list && list.size() > 0) { for (TbBusinessBalance t : list) { List<TbReceiveFree> tbReceiveFreeList = tbReceiveFreeService.findByBalanceId(t.getId()); TbFixEntrust tbFixEntrust = t.getTbFixEntrust(); TbFixEntrustCost tbFixEntrustCost = null; if (null != tbFixEntrust) { tbFixEntrustCost = new TbFixEntrustCost(); tbFixEntrustCost.setTbFixEntrust(tbFixEntrust); } List<TbFixEntrustCost> tbFixEntrustCostList = tbFixEntrustCostService .findByTbFixEntrustCost(tbFixEntrustCost); if (null != tbFixEntrustCostList && tbFixEntrustCostList.size() > 0) { for (TbFixEntrustCost _tbFixEntrustCost : tbFixEntrustCostList) { djcb = djcb.add(new BigDecimal( _tbFixEntrustCost.getCostPrice() == null ? 0d : _tbFixEntrustCost.getCostPrice())); } } total = total.add(new BigDecimal(String.valueOf(t.getBalanceTotalAll()))).setScale(2, BigDecimal.ROUND_HALF_UP); payed = payed.add(new BigDecimal(String.valueOf(t.getShouldPayAmount()))).setScale(2, BigDecimal.ROUND_HALF_UP); fixHour = fixHour.add(new BigDecimal(String.valueOf(t.getWorkingHourTotalAll()))).setScale(2, BigDecimal.ROUND_HALF_UP); fixPart = fixPart.add(new BigDecimal(String.valueOf(t.getFixPartTotalAll()))).setScale(2, BigDecimal.ROUND_HALF_UP); solePart = solePart.add(new BigDecimal(String.valueOf(t.getSolePartTotalAll()))).setScale(2, BigDecimal.ROUND_HALF_UP); other = other .add(new BigDecimal(String.valueOf(t.getBalanceTotalAll())) .subtract(new BigDecimal(String.valueOf(t.getWorkingHourTotalAll()))) .subtract(new BigDecimal(String.valueOf(t.getFixPartTotalAll()))) .subtract(new BigDecimal(String.valueOf(t.getSolePartTotalAll())))) .setScale(2, BigDecimal.ROUND_HALF_UP); BigDecimal d = new BigDecimal("0.00"); if (null != tbReceiveFreeList && tbReceiveFreeList.size() > 0) { for (TbReceiveFree tf : tbReceiveFreeList) { if (Constants.AMOUNTS.equals(tf.getAmountType())) { d = d.add(new BigDecimal(tf.getFeeAmount())); } } } owe = owe.add(new BigDecimal(String.valueOf(t.getOweAmount()))); //.subtract(d); } } map.put("total", total); map.put("payed", payed); map.put("fixHour", fixHour); map.put("fixPart", fixPart); map.put("solePart", solePart); map.put("other", other); map.put("owe", owe); map.put("djcb", djcb); return map; }
From source file:com.osafe.services.OsafePayPalServices.java
public static Map<String, Object> doAuthorization(DispatchContext dctx, Map<String, Object> context) { Delegator delegator = dctx.getDelegator(); String orderId = (String) context.get("orderId"); BigDecimal processAmount = (BigDecimal) context.get("processAmount"); GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod"); OrderReadHelper orh = new OrderReadHelper(delegator, orderId); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE); Locale locale = (Locale) context.get("locale"); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoAuthorization"); encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId")); encoder.add("AMT", processAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("TRANSACTIONENTITY", "Order"); String currency = (String) context.get("currency"); if (currency == null) { currency = orh.getCurrency();/*from w w w.ja va 2 s .co m*/ } encoder.add("CURRENCYCODE", currency); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { /* return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));*/ return ServiceUtil.returnError("An unknown error occurred while contacting PayPal"); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("authResult", false); result.put("authRefNum", "N/A"); result.put("processAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("authCode", error.getKey()); result.put("authMessage", error.getValue()); } else { result.put("authMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("authResult", true); result.put("processAmount", new BigDecimal(decoder.get("AMT"))); result.put("authRefNum", decoder.get("TRANSACTIONID")); } //TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction return result; }
From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.java
public static Map<String, Object> doCapture(DispatchContext dctx, Map<String, Object> context) { GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference"); BigDecimal captureAmount = (BigDecimal) context.get("captureAmount"); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE); GenericValue authTrans = (GenericValue) context.get("authTrans"); Locale locale = (Locale) context.get("locale"); if (authTrans == null) { authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref); }/*from ww w. j a va 2 s .com*/ NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoCapture"); encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum")); encoder.add("AMT", captureAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("CURRENCYCODE", authTrans.getString("currencyUomId")); encoder.add("COMPLETETYPE", "NotComplete"); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil .returnError(UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("captureResult", false); result.put("captureRefNum", "N/A"); result.put("captureAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("captureCode", error.getKey()); result.put("captureMessage", error.getValue()); } else { result.put("captureMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("captureResult", true); result.put("captureAmount", new BigDecimal(decoder.get("AMT"))); result.put("captureRefNum", decoder.get("TRANSACTIONID")); } //TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what should be checked for this type of transaction return result; }
From source file:org.egov.collection.service.elasticsearch.CollectionDocumentElasticSearchService.java
public List<TaxPayerDashBoardDetails> returnUlbWiseAggregationResults( final CollectionDashBoardRequest collectionDashBoardRequest, final String indexName, final Boolean order, final String orderingAggregationName, final int size, final List<String> serviceDetails) { final List<TaxPayerDashBoardDetails> taxPayers = new ArrayList<>(); BoolQueryBuilder boolQuery = prepareWhereClause(collectionDashBoardRequest); if (!serviceDetails.isEmpty()) boolQuery = boolQuery.filter(QueryBuilders.termsQuery(BILLING_SERVICE, serviceDetails)); String groupingField;//w w w . jav a 2 s . c o m if (StringUtils.isNotBlank(collectionDashBoardRequest.getUlbCode()) || StringUtils.isNotBlank(collectionDashBoardRequest.getType()) && collectionDashBoardRequest.getType().equals(DASHBOARD_GROUPING_WARDWISE)) groupingField = REVENUE_WARD; else groupingField = CITY_NAME; Long startTime = System.currentTimeMillis(); AggregationBuilder aggregation; SearchQuery searchQueryColl; aggregation = AggregationBuilders.terms(BY_AGGREGATION_FIELD).field(groupingField).size(size) .order(Terms.Order.aggregation(orderingAggregationName, order)) .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field(TOTAL_AMOUNT)); searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery) .addAggregation(aggregation).build(); final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl, response -> response.getAggregations()); Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by ulbWiseAggregations is : " + timeTaken + MILLISECS); TaxPayerDashBoardDetails taxDetail; boolean isWard = false; startTime = System.currentTimeMillis(); final Date fromDate = new DateTime().withMonthOfYear(4).dayOfMonth().withMinimumValue().toDate(); final Date toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); final Date lastYearFromDate = org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1); final Date lastYearToDate = org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1); final StringTerms totalAmountAggr = collAggr.get(BY_AGGREGATION_FIELD); for (final Terms.Bucket entry : totalAmountAggr.getBuckets()) { taxDetail = new TaxPayerDashBoardDetails(); taxDetail.setRegionName(collectionDashBoardRequest.getRegionName()); taxDetail.setDistrictName(collectionDashBoardRequest.getDistrictName()); taxDetail.setUlbGrade(collectionDashBoardRequest.getUlbGrade()); final String fieldName = String.valueOf(entry.getKey()); if (groupingField.equals(REVENUE_WARD)) { taxDetail.setWardName(fieldName); isWard = true; } else taxDetail.setUlbName(fieldName); final Sum totalCollectionAggregation = entry.getAggregations().get(TOTAL_COLLECTION); final BigDecimal totalCollections = BigDecimal.valueOf(totalCollectionAggregation.getValue()) .setScale(0, BigDecimal.ROUND_HALF_UP); taxDetail.setCytdColl(totalCollections); final BigDecimal lastYearCollection = getCollectionBetweenDates(collectionDashBoardRequest, lastYearFromDate, lastYearToDate, fieldName, serviceDetails, isWard); taxDetail.setLytdColl(lastYearCollection); BigDecimal variation; if (lastYearCollection.compareTo(BigDecimal.ZERO) == 0) variation = CollectionConstants.BIGDECIMAL_100; else variation = totalCollections.subtract(lastYearCollection) .multiply(CollectionConstants.BIGDECIMAL_100) .divide(lastYearCollection, 1, BigDecimal.ROUND_HALF_UP); taxDetail.setLyVar(variation); taxPayers.add(taxDetail); } timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken for setting values in returnUlbWiseAggregationResults() is : " + timeTaken + MILLISECS); return returnTopResults(taxPayers, size, order); }