Example usage for java.math BigDecimal ZERO

List of usage examples for java.math BigDecimal ZERO

Introduction

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

Prototype

BigDecimal ZERO

To view the source code for java.math BigDecimal ZERO.

Click Source Link

Document

The value 0, with a scale of 0.

Usage

From source file:org.openvpms.archetype.rules.finance.account.CustomerBalanceGeneratorTestCase.java

/**
 * Verifies that opening and closing balances are updated with correct
 * amounts./* www .j  ava  2 s .com*/
 */
@Test
public void testChangeOpeningAndClosingBalances() {
    Party customer = getCustomer();
    List<FinancialAct> invoice = createChargesInvoice(new Money(10));
    FinancialAct opening1 = createOpeningBalance(customer);
    FinancialAct payment = createPayment(new Money(30));
    FinancialAct closing1 = createClosingBalance(customer);
    FinancialAct opening2 = createOpeningBalance(customer);

    save(invoice);
    save(opening1, payment, closing1, opening2);

    checkEquals(BigDecimal.ZERO, rules.getBalance(customer));

    try {
        rules.getDefinitiveBalance(customer);
        fail("Expected getDefinitiveBalance() to fail");
    } catch (CustomerAccountRuleException expected) {
        assertEquals(CustomerAccountRuleException.ErrorCode.InvalidBalance, expected.getErrorCode());
    }

    checkEquals(new BigDecimal(-20), generate(customer));

    checkEquals(new BigDecimal(-20), rules.getBalance(customer));

    opening1 = get(opening1);
    closing1 = get(closing1);
    opening2 = get(opening2);

    checkEquals(new BigDecimal(10), opening1.getTotal());
    assertFalse(opening1.isCredit());

    checkEquals(new BigDecimal(20), closing1.getTotal());
    assertFalse(closing1.isCredit());

    checkEquals(new BigDecimal(20), opening2.getTotal());
    assertTrue(opening2.isCredit());
}

From source file:com.matel.components.ShoppingCartModel.java

/**
 *
 * @param subCategory//  w w  w  .  j  a  v  a  2  s.co  m
 * @return
 */
private ShoppingCartItemData prepareShoppingCartItem(ProductSubCategory subCategory) {
    ShoppingCartItemData cartItem = new ShoppingCartItemData();
    Product productById = matelProductInterface.getProductById(subCategory.getProductId());
    if (subCategory.getFinishedId() != null) {
        FinishedProduct finishedProduct = matelProductInterface.getFinishedProduct(productById.getProductId(),
                subCategory.getFinishedId());
        cartItem.setFinishedProductId(finishedProduct.getFinishlookup().getId());
        cartItem.setFinishedProductName(finishedProduct.getFinishlookup().getName());
        productById.setPrice(finishedProduct.getRate());
        productById.setProductName(productById.getProductName());
        cartItem.setFinishedProductId(finishedProduct.getFinishlookup().getId());
    }
    cartItem.setName(productById.getProductName());
    cartItem.setProductId(productById.getProductId());
    cartItem.setProduct(productById);
    cartItem.setQuantity(subCategory.getItemQuantity());
    cartItem.setProductPrice(productById.getPrice());
    shoppingCart.setSubTotal(shoppingCart.getSubTotal()
            .add(cartItem.getProductPrice().multiply(new BigDecimal(cartItem.getQuantity()))));
    if (productById.getPrice().compareTo(BigDecimal.ZERO) == 0) {
        return null;
    }
    return cartItem;
}

From source file:de.metas.procurement.webui.sync.SyncRfqImportService.java

private void importPlannedProductSupply(final SyncProductSupply syncProductSupply, final BPartner bpartner) {
    final String product_uuid = syncProductSupply.getProduct_uuid();
    final Product product = productRepo.findByUuid(product_uuid);
    ///*from   w  w  w.  j a v a  2  s  .co m*/
    final String contractLine_uuid = syncProductSupply.getContractLine_uuid();
    final ContractLine contractLine = contractLineRepo.findByUuid(contractLine_uuid);
    //
    final Date day = DateUtils.truncToDay(syncProductSupply.getDay());
    final BigDecimal qty = Objects.firstNonNull(syncProductSupply.getQty(), BigDecimal.ZERO);

    ProductSupply productSupply = productSupplyRepo.findByProductAndBpartnerAndDay(product, bpartner, day);
    final boolean isNew;
    if (productSupply == null) {
        isNew = true;
        productSupply = ProductSupply.build(bpartner, product, contractLine, day);
    } else {
        isNew = false;
    }

    //
    // Contract line
    if (!isNew) {
        final ContractLine contractLineOld = productSupply.getContractLine();
        if (!Objects.equal(contractLine, contractLineOld)) {
            logger.warn("Changing contract line {}->{} for {} because of planning supply: {}", contractLineOld,
                    contractLine, productSupply, syncProductSupply);
        }
        productSupply.setContractLine(contractLine);
    }

    //
    // Quantity
    if (!isNew) {
        final BigDecimal qtyOld = productSupply.getQty();
        if (qty.compareTo(qtyOld) != 0) {
            logger.warn("Changing quantity {}->{} for {} because of planning supply: {}", qtyOld, qty,
                    productSupply, syncProductSupply);
        }
    }
    productSupply.setQty(qty);

    //
    // Save the product supply
    productSupplyRepo.save(productSupply);

    applicationEventBus.post(ProductSupplyChangedEvent.of(productSupply));
}

From source file:org.fineract.module.stellar.controller.BridgeController.java

@RequestMapping(value = "/vault/{assetCode}", method = RequestMethod.PUT, consumes = {
        "application/json" }, produces = { "application/json" })
public ResponseEntity<BigDecimal> adjustVaultIssuedAssets(
        @RequestHeader(API_KEY_HEADER_LABEL) final String apiKey,
        @RequestHeader(TENANT_ID_HEADER_LABEL) final String mifosTenantId,
        @PathVariable("assetCode") final String assetCode,
        @RequestBody final AmountConfiguration amountConfiguration) {
    this.securityService.verifyApiKey(apiKey, mifosTenantId);
    //TODO: add security for currency issuing.
    final BigDecimal amount = amountConfiguration.getAmount();
    if (amount.compareTo(BigDecimal.ZERO) < 0) {
        return new ResponseEntity<>(amount, HttpStatus.BAD_REQUEST);
    }/*from w  w  w  .j av a  2  s  .co  m*/

    final BigDecimal amountAdjustedTo = bridgeService.adjustVaultIssuedAssets(mifosTenantId, assetCode, amount);

    if (amountAdjustedTo.compareTo(amount) != 0)
        return new ResponseEntity<>(amountAdjustedTo, HttpStatus.CONFLICT);
    else
        return new ResponseEntity<>(amountAdjustedTo, HttpStatus.OK);
}

From source file:org.openvpms.archetype.rules.stock.ChargeStockUpdaterTestCase.java

/**
 * Verifies that the stock is updated correctly if referred to by two different items in a transaction.
 *//*from   ww w  .  j a v a 2  s  . c o  m*/
@Test
public void testMultipleStockUpdatesInTxn() {
    final List<FinancialAct> acts = new ArrayList<FinancialAct>(createInvoice());
    final FinancialAct item1 = acts.get(1);
    final FinancialAct item2 = FinancialTestHelper.createChargeItem(CustomerAccountArchetypes.INVOICE_ITEM,
            patient, product, BigDecimal.ONE);
    addStockLocation(item2);
    acts.add(item2);

    BigDecimal initialQuantity = BigDecimal.ZERO;
    BigDecimal quantity = BigDecimal.valueOf(5);

    item1.setQuantity(quantity);
    item2.setQuantity(quantity);

    checkEquals(initialQuantity, getStock(stockLocation, product));
    BigDecimal expected = getQuantity(initialQuantity, quantity.add(quantity), false);

    TransactionTemplate template = new TransactionTemplate(txnManager);
    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            save(acts);
        }
    });
    checkEquals(expected, getStock(stockLocation, product));

    template.execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            item1.setQuantity(BigDecimal.ONE);
            save(item1);
            remove(item2);
        }
    });
    expected = getQuantity(initialQuantity, BigDecimal.ONE, false);
    checkEquals(expected, getStock(stockLocation, product));
}

From source file:com.roncoo.pay.app.reconciliation.parser.ALIPAYParser.java

/**
 * ????/* www.  j a  v  a2s .  com*/
 * 
 * @param file
 *            ??
 * @param billDate
 *            ?
 * @param batch
 *            
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<ReconciliationEntityVo> parser(File file, Date billDate, RpAccountCheckBatch batch)
        throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_STYLE);

    // xml?file
    SAXReader reader = new SAXReader();
    Document document;
    try {
        document = reader.read(file);
        // dom4jXpathAccountQueryAccountLogVO
        List projects = document.selectNodes(
                "alipay/response/account_page_query_result/account_log_list/AccountQueryAccountLogVO");

        Iterator it = projects.iterator();
        // ?
        List<AlipayAccountLogVO> tradeList = new ArrayList<AlipayAccountLogVO>();
        // ?
        List<AlipayAccountLogVO> otherAll = new ArrayList<AlipayAccountLogVO>();
        while (it.hasNext()) {
            AlipayAccountLogVO vo = new AlipayAccountLogVO();
            Element elm = (Element) it.next();
            List<Element> childElements = elm.elements();
            for (Element child : childElements) {
                String name = child.getName();
                // 
                switch (name) {
                case "balance":
                    vo.setBalance(new BigDecimal(child.getText()));
                    break;
                case "rate":
                    vo.setBankRate(new BigDecimal(("").equals(child.getText()) ? "0" : child.getText()));
                    break;
                case "buyer_account":
                    vo.setBuyerAccount(child.getText());
                    break;
                case "goods_title":
                    vo.setGoodsTitle(child.getText());
                    break;
                case "income":
                    vo.setIncome(new BigDecimal(("").equals(child.getText()) ? "0" : child.getText()));
                    break;
                case "outcome":
                    vo.setOutcome(new BigDecimal(("").equals(child.getText()) ? "0" : child.getText()));
                    break;
                case "merchant_out_order_no":
                    vo.setMerchantOrderNo(child.getText());
                    break;
                case "total_fee":
                    vo.setTotalFee(new BigDecimal(("").equals(child.getText()) ? "0" : child.getText()));
                    break;
                case "trade_no":// ?
                    vo.setTradeNo(child.getText());
                    break;
                case "trans_code_msg":// 
                    vo.setTransType(child.getText());
                    break;
                case "trans_date":
                    String dateStr = child.getText();
                    Date date;
                    try {
                        date = sdf.parse(dateStr);
                    } catch (ParseException e) {
                        date = billDate;
                    }
                    vo.setTransDate(date);
                    break;

                default:
                    break;
                }
            }

            // ??
            if ("".equals(vo.getTransType())) {
                tradeList.add(vo);
            } else {
                otherAll.add(vo);
            }
        }
        // ?????????
        // ?????????
        for (AlipayAccountLogVO trade : tradeList) {
            String tradeNo = trade.getTradeNo();
            for (AlipayAccountLogVO other : otherAll) {
                String otherTradeNo = other.getTradeNo();
                if (tradeNo.equals(otherTradeNo)) {
                    trade.setBankFee(other.getOutcome());
                }
            }
        }
        // AlipayAccountLogVOvoReconciliationEntityVo?list
        List<ReconciliationEntityVo> list = new ArrayList<ReconciliationEntityVo>();

        // ???
        int totalCount = 0;
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalFee = BigDecimal.ZERO;

        for (AlipayAccountLogVO trade : tradeList) {
            // 
            totalCount++;
            totalAmount = totalAmount.add(trade.getTotalFee());
            totalFee = totalFee.add(trade.getBankFee());

            // AlipayAccountLogVOReconciliationEntityVo
            ReconciliationEntityVo vo = new ReconciliationEntityVo();
            vo.setAccountCheckBatchNo(batch.getBatchNo());
            vo.setBankAmount(trade.getTotalFee());
            vo.setBankFee(trade.getBankFee());
            vo.setBankOrderNo(trade.getMerchantOrderNo());
            vo.setBankRefundAmount(BigDecimal.ZERO);
            vo.setBankTradeStatus("SUCCESS");
            vo.setBankTradeTime(trade.getTransDate());
            vo.setBankTrxNo(trade.getTradeNo());
            vo.setBankType(PayWayEnum.ALIPAY.name());
            vo.setOrderTime(trade.getTransDate());
            list.add(vo);
        }
        batch.setBankTradeCount(totalCount);
        batch.setBankTradeAmount(totalAmount);
        batch.setBankRefundAmount(BigDecimal.ZERO);
        batch.setBankFee(totalFee);

        return list;

    } catch (DocumentException e) {
        LOG.warn("?", e);
        batch.setStatus(BatchStatusEnum.FAIL.name());
        batch.setCheckFailMsg("?, payway[" + PayWayEnum.ALIPAY.name() + "], billdata["
                + sdf.format(billDate) + "]");
        return null;
    }

}

From source file:org.openmrs.module.billing.web.controller.main.BillableServiceBillEditController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(Model model, Object command, BindingResult bindingResult, HttpServletRequest request,
        @RequestParam("cons") Integer[] cons, @RequestParam("patientId") Integer patientId,
        @RequestParam("billId") Integer billId, @RequestParam("action") String action,
        @RequestParam(value = "description", required = false) String description) {

    validate(cons, bindingResult, request);
    if (bindingResult.hasErrors()) {
        model.addAttribute("errors", bindingResult.getAllErrors());
        return "module/billing/main/patientServiceBillEdit";
    }/* w w w. j  a  va  2  s  .  co m*/
    BillingService billingService = Context.getService(BillingService.class);

    PatientServiceBill bill = billingService.getPatientServiceBillById(billId);

    // Get the BillCalculator to calculate the rate of bill item the patient
    // has to pay
    Patient patient = Context.getPatientService().getPatient(patientId);
    Map<String, String> attributes = PatientUtils.getAttributes(patient);
    BillCalculatorService calculator = new BillCalculatorService();

    if (!"".equals(description))
        bill.setDescription(description);

    if ("void".equalsIgnoreCase(action)) {
        bill.setVoided(true);
        bill.setVoidedDate(new Date());
        for (PatientServiceBillItem item : bill.getBillItems()) {
            item.setVoided(true);
            item.setVoidedDate(new Date());
            /*ghanshyam 7-sept-2012 these 5 lines of code written only due to voided item is being updated in "billing_patient_service_bill_item" table
              but not being updated in "orders" table */
            Order ord = item.getOrder();
            if (ord != null) {
                ord.setVoided(true);
                ord.setDateVoided(new Date());
            }
            item.setOrder(ord);
        }
        billingService.savePatientServiceBill(bill);
        //ghanshyam 7-sept-2012 Support #343 [Billing][3.2.7-SNAPSHOT]No Queue to be generated from Old bill
        return "redirect:/module/billing/patientServiceBillEdit.list?patientId=" + patientId;
    }

    // void old items and reset amount
    Map<Integer, PatientServiceBillItem> mapOldItems = new HashMap<Integer, PatientServiceBillItem>();
    for (PatientServiceBillItem item : bill.getBillItems()) {
        item.setVoided(true);
        item.setVoidedDate(new Date());
        //ghanshyam-kesav 16-08-2012 Bug #323 [BILLING] When a bill with a lab\radiology order is edited the order is re-sent
        Order ord = item.getOrder();
        /*ghanshyam 18-08-2012 [Billing - Bug #337] [3.2.7 snap shot][billing(DDU,DDU SDMX,Tanda,mohali)]error in edit bill.
          the problem was while we are editing the bill of other than lab and radiology.
        */
        if (ord != null) {
            ord.setVoided(true);
            ord.setDateVoided(new Date());
        }
        item.setOrder(ord);
        mapOldItems.put(item.getPatientServiceBillItemId(), item);
    }
    bill.setAmount(BigDecimal.ZERO);
    bill.setPrinted(false);

    PatientServiceBillItem item;
    int quantity = 0;
    Money itemAmount;
    Money mUnitPrice;
    Money totalAmount = new Money(BigDecimal.ZERO);
    BigDecimal totalActualAmount = new BigDecimal(0);
    BigDecimal unitPrice;
    String name;
    BillableService service;

    for (int conceptId : cons) {

        unitPrice = NumberUtils.createBigDecimal(request.getParameter(conceptId + "_unitPrice"));
        quantity = NumberUtils.createInteger(request.getParameter(conceptId + "_qty"));
        name = request.getParameter(conceptId + "_name");
        service = billingService.getServiceByConceptId(conceptId);

        mUnitPrice = new Money(unitPrice);
        itemAmount = mUnitPrice.times(quantity);
        totalAmount = totalAmount.plus(itemAmount);

        String sItemId = request.getParameter(conceptId + "_itemId");

        if (sItemId == null) {
            item = new PatientServiceBillItem();

            // Get the ratio for each bill item
            Map<String, Object> parameters = HospitalCoreUtils.buildParameters("patient", patient, "attributes",
                    attributes, "billItem", item);
            BigDecimal rate = calculator.getRate(parameters);

            item.setAmount(itemAmount.getAmount());
            item.setActualAmount(item.getAmount().multiply(rate));
            totalActualAmount = totalActualAmount.add(item.getActualAmount());
            item.setCreatedDate(new Date());
            item.setName(name);
            item.setPatientServiceBill(bill);
            item.setQuantity(quantity);
            item.setService(service);
            item.setUnitPrice(unitPrice);
            bill.addBillItem(item);
        } else {

            item = mapOldItems.get(Integer.parseInt(sItemId));

            // Get the ratio for each bill item
            Map<String, Object> parameters = HospitalCoreUtils.buildParameters("patient", patient, "attributes",
                    attributes, "billItem", item);
            BigDecimal rate = calculator.getRate(parameters);

            //ghanshyam 5-oct-2012 [Billing - Support #344] [Billing] Edited Quantity and Amount information is lost in database
            if (quantity != item.getQuantity()) {
                item.setVoided(true);
                item.setVoidedDate(new Date());
            } else {
                item.setVoided(false);
                item.setVoidedDate(null);
            }
            // ghanshyam-kesav 16-08-2012 Bug #323 [BILLING] When a bill with a lab\radiology order is edited the order is re-sent
            Order ord = item.getOrder();
            if (ord != null) {
                ord.setVoided(false);
                ord.setDateVoided(null);
            }
            item.setOrder(ord);
            //ghanshyam 5-oct-2012 [Billing - Support #344] [Billing] Edited Quantity and Amount information is lost in database
            if (quantity != item.getQuantity()) {
                item = new PatientServiceBillItem();
                item.setService(service);
                item.setUnitPrice(unitPrice);
                item.setQuantity(quantity);
                item.setName(name);
                item.setCreatedDate(new Date());
                item.setOrder(ord);
                bill.addBillItem(item);
            }
            item.setAmount(itemAmount.getAmount());
            item.setActualAmount(item.getAmount().multiply(rate));
            totalActualAmount = totalActualAmount.add(item.getActualAmount());
        }
    }
    bill.setAmount(totalAmount.getAmount());
    bill.setActualAmount(totalActualAmount);

    // Determine whether the bill is free or not

    bill.setFreeBill(calculator.isFreeBill(HospitalCoreUtils.buildParameters("attributes", attributes)));
    logger.info("Is free bill: " + bill.getFreeBill());

    bill = billingService.savePatientServiceBill(bill);
    //ghanshyam 7-sept-2012 Support #343 [Billing][3.2.7-SNAPSHOT]No Queue to be generated from Old bill
    return "redirect:/module/billing/patientServiceBillEdit.list?patientId=" + patientId + "&billId=" + billId;
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.PHS398ChecklistV1_3Generator.java

private static IncomeBudgetPeriod[] getIncomeBudgetPeriod(
        final List<? extends BudgetProjectIncomeContract> projectIncomes) {
    //TreeMap Used to maintain the order of the Budget periods.
    Map<Integer, IncomeBudgetPeriod> incomeBudgetPeriodMap = new TreeMap<>();
    BigDecimal anticipatedAmount;
    for (BudgetProjectIncomeContract projectIncome : projectIncomes) {

        Integer budgetPeriodNumber = projectIncome.getBudgetPeriodNumber();
        IncomeBudgetPeriod incomeBudgPeriod = incomeBudgetPeriodMap.get(budgetPeriodNumber);
        if (incomeBudgPeriod == null) {
            incomeBudgPeriod = IncomeBudgetPeriod.Factory.newInstance();
            incomeBudgPeriod.setBudgetPeriod(budgetPeriodNumber);
            anticipatedAmount = BigDecimal.ZERO;
        } else {//from  w  w w  .ja v  a  2s . c o  m
            anticipatedAmount = incomeBudgPeriod.getAnticipatedAmount();
        }
        anticipatedAmount = anticipatedAmount.add(projectIncome.getProjectIncome().bigDecimalValue());
        incomeBudgPeriod.setAnticipatedAmount(anticipatedAmount);
        String description = getProjectIncomeDescription(projectIncome);
        if (description != null) {
            if (incomeBudgPeriod.getSource() != null) {
                incomeBudgPeriod.setSource(incomeBudgPeriod.getSource() + ";" + description);
            } else {
                incomeBudgPeriod.setSource(description);
            }
        }
        incomeBudgetPeriodMap.put(budgetPeriodNumber, incomeBudgPeriod);
    }
    Collection<IncomeBudgetPeriod> incomeBudgetPeriodCollection = incomeBudgetPeriodMap.values();
    return incomeBudgetPeriodCollection.toArray(new IncomeBudgetPeriod[0]);
}

From source file:com.liato.bankdroid.banking.banks.MinPension.java

private Account updateAccount(String URL, String selector, String name) throws IOException {
    String response = urlopen.open(URL);
    Document dResponse = Jsoup.parse(response);
    List<Transaction> transactions = new ArrayList<>();
    String institute = "";
    String subInstitute = "";
    for (Element e : dResponse.select(selector)) {
        if (e.hasClass("GroupRow")) {
            institute = e.children().first().text();
        } else if (e.hasClass("GroupMemberRow") || e.hasClass("SubRow")) {
            Elements elements = e.children();
            if (elements.size() == 6) { //Special case for "Allmn pension"
                if (elements.get(2).text().isEmpty()) {
                    //   subInstitute =  "  " + elements.get(1).text(); /* Doesn't fit atm. */
                } else {
                    transactions.add(new Transaction(elements.get(5).text(),
                            institute + subInstitute + "\n  " + elements.get(1).text(),
                            Helpers.parseBalance(elements.get(2).text())));
                    subInstitute = "";
                }/*from   ww  w  . ja v a 2  s  .c  o  m*/
            } else if (elements.size() >= 7) {
                transactions.add(
                        new Transaction(elements.get(6).text(), institute + "\n  " + elements.get(1).text(),
                                Helpers.parseBalance(elements.get(4).text())));
            }
        }
    }

    balance = BigDecimal.ZERO;
    for (Transaction t : transactions) {
        balance = balance.add(t.getAmount());
    }
    Account account = new Account(name, balance, name, Account.REGULAR, "");
    account.setTransactions(transactions);
    return account;
}

From source file:Main.java

public static BigDecimal getSeconds(XMLGregorianCalendar x) {
    BigDecimal fractional = x.getFractionalSecond();
    if (fractional == null)
        fractional = BigDecimal.ZERO;

    BigDecimal whole = BigDecimal.valueOf(x.getSecond());

    return whole.add(fractional);
}