List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:org.kuali.rice.kew.docsearch.xml.StandardGenericXMLSearchableAttributeRangesTest.java
@Test public void testFloatRanges() throws Exception { WorkflowDocument doc = setUpSearchableDoc(); String userId = doc.getInitiatorPrincipalId(); String docType = doc.getDocumentTypeName(); String searchAttributeFloatKey = TestXMLSearchableAttributeFloat.SEARCH_STORAGE_KEY; BigDecimal searchAttributeFloatValue = TestXMLSearchableAttributeFloat.SEARCH_STORAGE_VALUE; BigDecimal floatValueToUse = null; // test lower bound only floatValueToUse = searchAttributeFloatValue; // lower bound == value // NOTE: original test asserted 0 results, mysql actually does match the value assertRangeSearchResults(docType, userId, searchAttributeFloatKey, floatValueToUse.toString(), null, false, 1);/* w w w.j a va 2s .c om*/ floatValueToUse = searchAttributeFloatValue.subtract(BigDecimal.ONE); // lowerbound < value assertRangeSearchResults(docType, userId, searchAttributeFloatKey, floatValueToUse.toString(), null, false, 1); floatValueToUse = searchAttributeFloatValue.add(BigDecimal.ONE); // lowerbound > value assertRangeSearchResults(docType, userId, searchAttributeFloatKey, floatValueToUse.toString(), null, false, 0); // test upper bound only floatValueToUse = searchAttributeFloatValue; // upperbound == value (does not match float) // NOTE: another case where original test had 0 results, but in fact we see a float match assertRangeSearchResults(docType, userId, searchAttributeFloatKey, null, floatValueToUse.toString(), true, 1); floatValueToUse = searchAttributeFloatValue.subtract(BigDecimal.ONE); // upperbound < value assertRangeSearchResults(docType, userId, searchAttributeFloatKey, null, floatValueToUse.toString(), true, 0); floatValueToUse = searchAttributeFloatValue.add(BigDecimal.ONE); // upperbound > value assertRangeSearchResults(docType, userId, searchAttributeFloatKey, null, floatValueToUse.toString(), true, 1); // test both bounds // upper == lower == value // NOTE: original case had 0 results, now seeing 1 result // search generator invokes criteria which calls addNumericRangeCriteria when produces: (EXT1.VAL BETWEEN 123456.3456 AND 123456.3456) assertRangeSearchResults(docType, userId, searchAttributeFloatKey, searchAttributeFloatValue.toString(), searchAttributeFloatValue.toString(), true, 1); // upper and lower > value assertRangeSearchResults(docType, userId, searchAttributeFloatKey, searchAttributeFloatValue.add(new BigDecimal(2)).toString(), searchAttributeFloatValue.add(new BigDecimal(4)).toString(), true, 0); // upper and lower < value assertRangeSearchResults(docType, userId, searchAttributeFloatKey, searchAttributeFloatValue.subtract(new BigDecimal(4)).toString(), searchAttributeFloatValue.subtract(new BigDecimal(2)).toString(), true, 0); // lower < value, upper > value assertRangeSearchResults(docType, userId, searchAttributeFloatKey, searchAttributeFloatValue.subtract(new BigDecimal(2)).toString(), searchAttributeFloatValue.add(new BigDecimal(2)).toString(), true, 1); // upper < lower assertRangeSearchResults(docType, userId, searchAttributeFloatKey, searchAttributeFloatValue.add(new BigDecimal(2)).toString(), searchAttributeFloatValue.subtract(new BigDecimal(2)).toString(), true, EXPECT_EXCEPTION); }
From source file:org.kuali.ole.select.document.web.struts.OlePaymentRequestAction.java
/** * @see org.kuali.ole.sys.web.struts.KualiAccountingDocumentActionBase#insertSourceLine(org.apache.struts.action.ActionMapping, * org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// ww w .ja va2 s . co m @Override public ActionForward insertSourceLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // It would be preferable to find a way to genericize the KualiAccountingDocument methods but this will work for now PurchasingAccountsPayableFormBase purapForm = (PurchasingAccountsPayableFormBase) form; // index of item selected int itemIndex = getSelectedLine(request); PurApItem item = null; // if custom processing of an accounting line is not done then insert a line generically. if (processCustomInsertAccountingLine(purapForm, request) == false) { String errorPrefix = null; PurApAccountingLine line = null; boolean rulePassed = false; if (itemIndex >= 0) { item = ((PurchasingAccountsPayableDocument) purapForm.getDocument()).getItem((itemIndex)); //Calculating the dollar amount for the accounting Line. PurApAccountingLine lineItem = item.getNewSourceLine(); if (lineItem.getAccountLinePercent() != null) { BigDecimal percent = lineItem.getAccountLinePercent().divide(new BigDecimal(100)); lineItem.setAmount((item.getTotalAmount().multiply(new KualiDecimal(percent)))); } else if (lineItem.getAmount() != null && lineItem.getAccountLinePercent() == null) { KualiDecimal dollar = lineItem.getAmount().multiply(new KualiDecimal(100)); BigDecimal dollarToPercent = dollar.bigDecimalValue() .divide((item.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR); lineItem.setAccountLinePercent(dollarToPercent); } line = (PurApAccountingLine) ObjectUtils.deepCopy(lineItem); //end //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line); errorPrefix = OLEPropertyConstants.DOCUMENT + "." + PurapPropertyConstants.ITEM + "[" + Integer.toString(itemIndex) + "]." + OLEConstants.NEW_SOURCE_ACCT_LINE_PROPERTY_NAME; rulePassed = SpringContext.getBean(KualiRuleService.class) .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line)); } else if (itemIndex == -2) { //corrected: itemIndex == -2 is the only case for distribute account //This is the case when we're inserting an accounting line for distribute account. line = ((PurchasingFormBase) purapForm).getAccountDistributionnewSourceLine(); //SpringContext.getBean(AccountService.class).populateAccountingLineChartIfNeeded(line); errorPrefix = PurapPropertyConstants.ACCOUNT_DISTRIBUTION_NEW_SRC_LINE; rulePassed = SpringContext.getBean(KualiRuleService.class) .applyRules(new AddAccountingLineEvent(errorPrefix, purapForm.getDocument(), line)); } AccountingLineBase accountingLineBase = (AccountingLineBase) item.getNewSourceLine(); if (accountingLineBase != null) { String accountNumber = accountingLineBase.getAccountNumber(); String chartOfAccountsCode = accountingLineBase.getChartOfAccountsCode(); Map<String, String> criteria = new HashMap<String, String>(); criteria.put(OleSelectConstant.ACCOUNT_NUMBER, accountNumber); criteria.put(OleSelectConstant.CHART_OF_ACCOUNTS_CODE, chartOfAccountsCode); Account account = SpringContext.getBean(BusinessObjectService.class).findByPrimaryKey(Account.class, criteria); rulePassed = checkForValidAccount(account); } /* if (rulePassed) { // add accountingLine SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line); if (itemIndex >=0) { insertAccountingLine(purapForm, item, line); // clear the temp account item.resetAccount(); } else if (itemIndex == -2) { //this is the case for distribute account ((PurchasingFormBase)purapForm).addAccountDistributionsourceAccountingLine(line); } }*/ if (rulePassed) { // add accountingLine SpringContext.getBean(PersistenceService.class).retrieveNonKeyFields(line); PurApAccountingLine newSourceLine = item.getNewSourceLine(); List<PurApAccountingLine> existingSourceLine = item.getSourceAccountingLines(); BigDecimal initialValue = new BigDecimal(0); for (PurApAccountingLine accountLine : existingSourceLine) { initialValue = initialValue.add(accountLine.getAccountLinePercent()); } if (itemIndex >= 0) { if ((newSourceLine.getAccountLinePercent() .intValue() <= OleSelectConstant.ACCOUNTINGLINE_PERCENT_HUNDRED && newSourceLine.getAccountLinePercent().intValue() <= OleSelectConstant.MAX_PERCENT .subtract(initialValue).intValue()) && newSourceLine.getAccountLinePercent().intValue() > OleSelectConstant.ZERO) { if (OleSelectConstant.MAX_PERCENT.subtract(initialValue) .intValue() != OleSelectConstant.ZERO) { insertAccountingLine(purapForm, item, line); } } else { checkAccountingLinePercent(newSourceLine); } for (PurApAccountingLine oldSourceAccountingLine : item.getSourceAccountingLines()) { if (oldSourceAccountingLine instanceof PaymentRequestAccount) { ((PaymentRequestAccount) oldSourceAccountingLine) .setExistingAmount(oldSourceAccountingLine.getAmount()); } } List<PurApAccountingLine> existingAccountingLine = item.getSourceAccountingLines(); BigDecimal totalPercent = new BigDecimal(100); BigDecimal initialPercent = new BigDecimal(0); for (PurApAccountingLine purApAccountingLine : existingAccountingLine) { initialPercent = initialPercent.add(purApAccountingLine.getAccountLinePercent()); } initialPercent = totalPercent.subtract(initialPercent); BigDecimal maxPercent = initialPercent.max(OleSelectConstant.ZERO_PERCENT); if (maxPercent.intValue() == OleSelectConstant.ZERO) { item.resetAccount(OleSelectConstant.ZERO_PERCENT); } else { item.resetAccount(initialPercent); } } else if (itemIndex == -2) { //this is the case for distribute account ((PurchasingFormBase) purapForm).addAccountDistributionsourceAccountingLine(line); } } } return mapping.findForward(OLEConstants.MAPPING_BASIC); }
From source file:com.xumpy.thuisadmin.services.implementations.BedragenSrvImpl.java
public Map OverviewRekeningData(List<? extends Bedragen> bedragen) { Map overviewRekeningData = new LinkedHashMap(); BigDecimal rekeningStand; if (isRekeningUnique(bedragen)) { rekeningStand = getBedragAtDate(bedragen.get(0).getDatum(), bedragen.get(0).getRekening()); } else {/*from ww w. ja v a 2 s .c o m*/ rekeningStand = getBedragAtDate(bedragen.get(0).getDatum(), null); } overviewRekeningData.put(bedragen.get(0).getDatum(), rekeningStand); for (Integer i = 1; i < bedragen.size(); i++) { if (!bedragen.get(i).getDatum().equals(bedragen.get(0).getDatum())) { if (bedragen.get(i).getGroep().getNegatief().equals(1)) { rekeningStand = rekeningStand.subtract(bedragen.get(i).getBedrag()); } if (bedragen.get(i).getGroep().getNegatief().equals(0)) { rekeningStand = rekeningStand.add(bedragen.get(i).getBedrag()); } overviewRekeningData.put(bedragen.get(i).getDatum(), rekeningStand); } } return overviewRekeningData; }
From source file:org.chiba.xml.xforms.ui.Range.java
/** * Initializes this range.//from w ww.ja v a 2s . c o m * * @throws XFormsException if the datatype of the bound is not supported. */ protected final void initializeRange() throws XFormsException { if (!isBound()) { return; } // get model item datatype Validator validator = this.model.getValidator(); String datatype = getDatatype(); if (validator.isRestricted("decimal", datatype) || validator.isRestricted("float", datatype) || validator.isRestricted("double", datatype)) { // get bound value String value = getInstanceValue(); BigDecimal valueDecimal; if (value != null && value.length() > 0) { valueDecimal = new BigDecimal(value); } else { // set '0.0' as default value valueDecimal = new BigDecimal(0d); } // get step size BigDecimal stepDecimal; String stepAttribute = getXFormsAttribute(STEP_ATTRIBUTE); if (stepAttribute != null) { stepDecimal = new BigDecimal(stepAttribute); } else { // set '1.0' as default step stepDecimal = new BigDecimal(1d); this.element.setAttributeNS(null, STEP_ATTRIBUTE, stepDecimal.toString()); } // get range start BigDecimal startDecimal; String startAttribute = getXFormsAttribute(START_ATTRIBUTE); if (startAttribute != null) { startDecimal = new BigDecimal(startAttribute); } else { // set 'value - (2 * step)' as default start startDecimal = valueDecimal.subtract(stepDecimal.multiply(new BigDecimal(2d))); this.element.setAttributeNS(null, START_ATTRIBUTE, startDecimal.toString()); } // get range end BigDecimal endDecimal; String endAttribute = getXFormsAttribute(END_ATTRIBUTE); if (endAttribute != null) { endDecimal = new BigDecimal(endAttribute); } else { // set 'value + (2 * step)' as default end endDecimal = valueDecimal.add(stepDecimal.multiply(new BigDecimal(2d))); this.element.setAttributeNS(null, END_ATTRIBUTE, endDecimal.toString()); } if (valueDecimal.compareTo(startDecimal) < 0 || valueDecimal.compareTo(endDecimal) > 0) { this.model.getContainer().dispatch(this.target, XFormsEventNames.OUT_OF_RANGE, null); } return; } throw new XFormsBindingException("datatype not supported by range control", this.target, datatype); }
From source file:org.ofbiz.order.shoppingcart.CheckOutHelper.java
public static void adjustFaceToFacePayment(String orderId, BigDecimal cartTotal, List<GenericValue> allPaymentPrefs, GenericValue userLogin, Delegator delegator) throws GeneralException { BigDecimal prefTotal = BigDecimal.ZERO; if (allPaymentPrefs != null) { for (GenericValue pref : allPaymentPrefs) { BigDecimal maxAmount = pref.getBigDecimal("maxAmount"); if (maxAmount == null) maxAmount = BigDecimal.ZERO; prefTotal = prefTotal.add(maxAmount); }//w ww. j a v a2 s . c om } if (prefTotal.compareTo(cartTotal) > 0) { BigDecimal change = prefTotal.subtract(cartTotal).negate(); GenericValue newPref = delegator.makeValue("OrderPaymentPreference"); newPref.set("orderId", orderId); newPref.set("paymentMethodTypeId", "CASH"); newPref.set("statusId", "PAYMENT_RECEIVED"); newPref.set("maxAmount", change); newPref.set("createdDate", UtilDateTime.nowTimestamp()); if (userLogin != null) { newPref.set("createdByUserLogin", userLogin.getString("userLoginId")); } delegator.createSetNextSeqId(newPref); } }
From source file:org.sputnikdev.bluetooth.gattparser.FieldHolder.java
/** * Sets the field value into a new BigInteger value. * @param value a new field value/*from ww w.j a v a 2s . c o m*/ */ public void setBigInteger(BigInteger value) { if (value == null) { this.value = null; } else { BigDecimal vl = new BigDecimal(value); Double maximum = field.getMaximum(); if (maximum != null && vl.compareTo(new BigDecimal(maximum)) > 0) { throw new IllegalArgumentException("Value [" + value + "] is greater than maximum: " + maximum); } Double minimum = field.getMinimum(); if (minimum != null && vl.compareTo(new BigDecimal(minimum)) < 0) { throw new IllegalArgumentException("Value [" + value + "] is less than minimum: " + minimum); } double multiplier = getMultiplier(); double offset = getOffset(); BigInteger adjusted; if (multiplier != 1.0 || offset != 0.0) { adjusted = vl.subtract(BigDecimal.valueOf(offset)).setScale(0, RoundingMode.HALF_UP) .divide(BigDecimal.valueOf(multiplier)).toBigInteger(); } else { adjusted = value; } if (field.getFormat().isStruct()) { this.value = new TwosComplementNumberFormatter().serialize(adjusted, adjusted.bitLength(), false) .toByteArray(); } else { this.value = getConverter().convert(null, adjusted); } } }
From source file:org.egov.wtms.service.es.WaterChargeElasticSearchService.java
/** * Returns Top Ten with ULB wise grouping and total amount aggregation * * @param waterChargedashBoardRequest/* w w w . j av a 2s .com*/ * @param indexName * @param order * @param orderingAggregationName * @return */ public List<WaterTaxPayerDetails> returnUlbWiseAggregationResults( final WaterChargeDashBoardRequest waterChargedashBoardRequest, final String indexName, final Boolean order, final String orderingAggregationName, final int size, final boolean isBillCollectorWise) { final List<WaterTaxPayerDetails> taxPayers = new ArrayList<>(); Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>(); final BoolQueryBuilder boolQuery = waterChargeCollDocService.prepareWhereClause(waterChargedashBoardRequest, null); CFinancialYear currFinYear = cFinancialYearService.getCurrentFinancialYear(); // orderingAggregationName is the aggregation name by which we have to // order the results // IN this case can be one of "totaldemand" or TOTAL_COLLECTION or // "avg_achievement" String groupingField; if (StringUtils.isNotBlank(waterChargedashBoardRequest.getUlbCode()) || StringUtils .isNotBlank(waterChargedashBoardRequest.getType()) && (waterChargedashBoardRequest.getType().equals(DASHBOARD_GROUPING_WARDWISE) || waterChargedashBoardRequest.getType().equals(DASHBOARD_GROUPING_BILLCOLLECTORWISE))) groupingField = WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD; else groupingField = WaterTaxConstants.CITYNAMEAGGREGATIONFIELD; Long startTime = System.currentTimeMillis(); @SuppressWarnings("rawtypes") AggregationBuilder aggregation; SearchQuery searchQueryColl; // Apply the ordering and max results size only if the type is not // billcollector if (!isBillCollectorWise) { aggregation = AggregationBuilders.terms(AGGREGATION_FIELD).field(groupingField).size(size) .order(Terms.Order.aggregation(orderingAggregationName, order)) .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND)) .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field("totalCollection")); searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery) .addAggregation(aggregation).build(); } else { aggregation = AggregationBuilders.terms(AGGREGATION_FIELD).field(groupingField).size(250) .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND)) .subAggregation(AggregationBuilders.sum(TOTAL_COLLECTION).field("totalCollection")); searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName).withQuery(boolQuery) .withPageable(new PageRequest(0, 250)).addAggregation(aggregation).build(); } final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl, response -> response.getAggregations()); // Fetch ward wise Bill Collector details for ward based grouping if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(waterChargedashBoardRequest.getType())) wardWiseBillCollectors = waterChargeCollDocService .getWardWiseBillCollectors(waterChargedashBoardRequest); Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by ulbWiseAggregations is (millisecs) : " + timeTaken); WaterTaxPayerDetails taxDetail; startTime = System.currentTimeMillis(); final Date fromDate = DateUtils.startOfDay(currFinYear.getStartingDate()); 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(AGGREGATION_FIELD); for (final Terms.Bucket entry : totalAmountAggr.getBuckets()) { taxDetail = new WaterTaxPayerDetails(); taxDetail.setRegionName(waterChargedashBoardRequest.getRegionName()); taxDetail.setDistrictName(waterChargedashBoardRequest.getDistrictName()); taxDetail.setUlbGrade(waterChargedashBoardRequest.getUlbGrade()); final String fieldName = String.valueOf(entry.getKey()); if (groupingField.equals(WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD)) { taxDetail.setWardName(fieldName); if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(waterChargedashBoardRequest.getType()) && !wardWiseBillCollectors.isEmpty()) taxDetail.setBillCollector(wardWiseBillCollectors.get(fieldName) == null ? StringUtils.EMPTY : wardWiseBillCollectors.get(fieldName).getBillCollector()); } else taxDetail.setUlbName(fieldName); // Proportional Demand = (totalDemand/12)*noOfmonths final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1; final Sum totalDemandAggregation = entry.getAggregations().get(TOTALDEMAND); final Sum totalCollectionAggregation = entry.getAggregations().get(TOTAL_COLLECTION); final BigDecimal totalDemandValue = BigDecimal.valueOf(totalDemandAggregation.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP); final BigDecimal totalCollections = BigDecimal.valueOf(totalCollectionAggregation.getValue()) .setScale(0, BigDecimal.ROUND_HALF_UP); final BigDecimal proportionalDemand = totalDemandValue .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths)); taxDetail.setTotalDmd(totalDemandValue); taxDetail.setCurrentYearTillDateColl(totalCollections); taxDetail.setCurrentYearTillDateDmd(proportionalDemand); taxDetail.setAchievement(totalCollections.multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP)); taxDetail.setCurrentYearTillDateBalDmd(proportionalDemand.subtract(totalCollections)); final BigDecimal lastYearCollection = waterChargeCollDocService.getCollectionBetweenDates( waterChargedashBoardRequest, lastYearFromDate, lastYearToDate, fieldName); // variance = ((lastYearCollection/currentYearCollection )*100) BigDecimal variation = BigDecimal.ZERO; taxDetail.setLastYearTillDateColl(lastYearCollection); if (lastYearCollection.compareTo(BigDecimal.ZERO) == 0) variation = WaterTaxConstants.BIGDECIMAL_100; else if (totalCollections.compareTo(BigDecimal.ZERO) > 0) variation = taxDetail.getCurrentYearTillDateColl().subtract(taxDetail.getLastYearTillDateColl()) .multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(taxDetail.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP); /* * variation * =taxDetail.getLastYearTillDateColl().multiply(WaterTaxConstants. * BIGDECIMAL_100) .divide(totalCollections, 1, * BigDecimal.ROUND_HALF_UP); */ taxDetail.setLastYearVar(variation); taxPayers.add(taxDetail); } timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken for setting values in returnUlbWiseAggregationResults() is (millisecs) : " + timeTaken); return returnTopResults(taxPayers, size, order); }
From source file:com.mb.ext.web.controller.UserController.java
/** * //from w w w .ja v a2 s . c om * get news * */ @RequestMapping(value = "/getIncome", method = RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) @ResponseBody public ResultDTO getIncome(@RequestBody UserDTO userDTO) { ResultDTO resultDTO = new ResultDTO(); String loginId = userDTO.getLoginId(); IncomeDTO incomeDTO = new IncomeDTO(); try { BigDecimal income = userService.getTotalIncomeByUser(loginId); BigDecimal payment = userService.getTotalTransferAmountByUser(loginId); incomeDTO.setTotalIncome(income); incomeDTO.setTotalPayment(payment); incomeDTO.setTotalOutstanding(income.subtract(payment)); resultDTO.setCode("0"); resultDTO.setMessage("Get product list successfully"); resultDTO.setBody(incomeDTO); } catch (BusinessException e) { resultDTO.setCode("1"); resultDTO.setMessage(e.getMessage()); } return resultDTO; }
From source file:com.foglyn.fogbugz.FogBugzClient.java
/** * Computes remaining time from current estimate and elapsed time. * @param current current estimate in hours, can be null * @param elapsed elapsed time in hours, can be null *///from ww w .j a va2 s . c o m private BigDecimal computeRemainingTime(BigDecimal current, BigDecimal elapsed) { BigDecimal remaining = current; // possibly null if (current != null && elapsed != null) { remaining = current.subtract(elapsed); if (remaining.compareTo(BigDecimal.ZERO) < 0) { remaining = BigDecimal.ZERO; } } return remaining; }
From source file:org.efaps.esjp.accounting.transaction.Create_Base.java
/** * Used form a from to create the transaction for opening a balance. * * @param _parameter Paramter as passed from the eFaps API * @return new Return//w ww. java 2s . com * @throws EFapsException on error */ public Return createTransactionOpeningBalance(final Parameter _parameter) throws EFapsException { final String debitAccOId = _parameter.getParameterValue("accountLink_Debit"); final String[] amounts = _parameter.getParameterValues("amount"); final String[] accounts = _parameter.getParameterValues("accountLink_Credit"); final Instance periodInst = _parameter.getInstance(); final Insert insert = new Insert(CIAccounting.TransactionOpeningBalance); insert.add(CIAccounting.TransactionOpeningBalance.Name, 0); insert.add(CIAccounting.TransactionOpeningBalance.Description, DBProperties.getProperty("org.efaps.esjp.accounting.Transaction.openingBalance.description")); insert.add(CIAccounting.TransactionOpeningBalance.Date, _parameter.getParameterValue("date")); insert.add(CIAccounting.TransactionOpeningBalance.PeriodLink, periodInst.getId()); insert.add(CIAccounting.TransactionOpeningBalance.Status, ((Long) Status.find(CIAccounting.TransactionStatus.uuid, "Open").getId()).toString()); insert.execute(); BigDecimal debitAmount = BigDecimal.ZERO; final CurrencyInst curr = new Period().getCurrency(periodInst); final DecimalFormat formater = NumberFormatter.get().getFormatter(null, 2); for (int i = 0; i < amounts.length; i++) { final Instance accInst = Instance.get(accounts[i]); final PrintQuery print = new PrintQuery(accInst); print.addAttribute(CIAccounting.AccountAbstract.SumReport); print.execute(); final BigDecimal sumreport = print.<BigDecimal>getAttribute(CIAccounting.AccountAbstract.SumReport); try { BigDecimal amount = (BigDecimal) formater.parse(amounts[i]); amount = amount.subtract(sumreport == null ? BigDecimal.ZERO : sumreport); final CIType type = amount.compareTo(BigDecimal.ZERO) > 0 ? CIAccounting.TransactionPositionCredit : CIAccounting.TransactionPositionDebit; final Insert posInsert = new Insert(type); posInsert.add(CIAccounting.TransactionPositionAbstract.AccountLink, accInst.getId()); posInsert.add(CIAccounting.TransactionPositionAbstract.Amount, amount); posInsert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curr.getInstance().getId()); posInsert.add(CIAccounting.TransactionPositionAbstract.Rate, new Object[] { 1, 1 }); posInsert.add(CIAccounting.TransactionPositionAbstract.RateAmount, amount); posInsert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, curr.getInstance().getId()); posInsert.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance().getId()); posInsert.execute(); debitAmount = debitAmount.add(amount); } catch (final ParseException e) { throw new EFapsException(Create_Base.class, "createTransactionOpeningBalance", e); } } final Instance accInst = Instance.get(debitAccOId); final CIType type = debitAmount.compareTo(BigDecimal.ZERO) < 0 ? CIAccounting.TransactionPositionCredit : CIAccounting.TransactionPositionDebit; final Insert posInsert = new Insert(type); posInsert.add(CIAccounting.TransactionPositionAbstract.AccountLink, accInst.getId()); posInsert.add(CIAccounting.TransactionPositionAbstract.Amount, debitAmount.negate()); posInsert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curr.getInstance().getId()); posInsert.add(CIAccounting.TransactionPositionAbstract.Rate, new Object[] { 1, 1 }); posInsert.add(CIAccounting.TransactionPositionAbstract.RateAmount, debitAmount.negate()); posInsert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, curr.getInstance().getId()); posInsert.add(CIAccounting.TransactionPositionAbstract.TransactionLink, insert.getInstance().getId()); posInsert.execute(); return new Return(); }