Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

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

Prototype

int ROUND_HALF_UP

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

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:org.egov.ptis.service.es.PTYearWiseDCBIndexService.java

private List<YearWiseDCBReponse> getResponseForDCB(PTYearWiseDCBRequest serviceRequest) {
    @SuppressWarnings("rawtypes")
    AggregationBuilder aggregationBuilder = getAggregationBuilderForDCB(serviceRequest.getType());
    SearchResponse response;//from w  w  w.jav  a  2 s. c  o  m
    response = elasticsearchTemplate.getClient()
            .prepareSearch(PROPERTY_TAX_INDEX_PREFIX + serviceRequest.getYearIndex())
            .setQuery(getBoolQuery(serviceRequest)).addAggregation(aggregationBuilder).execute().actionGet();

    String aggregationTerms = GROUP_TYPE_WARD.equalsIgnoreCase(serviceRequest.getType()) ? GROUP_TYPE_WARD
            : GROUP_TYPE_BLOCK;
    Sum arrearDemand;
    Sum arrearPenDemand;
    Sum currentDemand;
    Sum currentPenDemand;
    Sum arrearCollected;
    Sum arrearPenCollected;
    Sum currentCollected;
    Sum currentPenCollected;
    Terms aggTerms = response.getAggregations().get(aggregationTerms);
    List<YearWiseDCBReponse> serviceWiseResponses = new ArrayList<>();
    for (Terms.Bucket entry : aggTerms.getBuckets()) {
        YearWiseDCBReponse serviceWiseResponse = new YearWiseDCBReponse();
        arrearDemand = entry.getAggregations().get(ARREARDEMAND);
        arrearPenDemand = entry.getAggregations().get(ARREAR_INTEREST_DMD);
        currentDemand = entry.getAggregations().get(CURRENT_DMD);
        currentPenDemand = entry.getAggregations().get(CURR_INTEREST_DMD);
        arrearCollected = entry.getAggregations().get(ARREAR_COLLECTION);
        arrearPenCollected = entry.getAggregations().get(ARREAR_INTEREST_COLLECTION);
        currentCollected = entry.getAggregations().get(CURRENT_COLLECTION);
        currentPenCollected = entry.getAggregations().get(CURRENT_INTEREST_COLLECTION);
        serviceWiseResponse.setCount(entry.getDocCount());
        serviceWiseResponse.setArrearDemand(
                BigDecimal.valueOf(arrearDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        serviceWiseResponse.setArrearPenDemand(
                BigDecimal.valueOf(arrearPenDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        serviceWiseResponse.setArrearTotalDemand(
                BigDecimal.valueOf(arrearDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP).add(
                        BigDecimal.valueOf(arrearPenDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));
        serviceWiseResponse.setCurrentDemand(
                BigDecimal.valueOf(currentDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        serviceWiseResponse.setCurrentPenDemand(
                BigDecimal.valueOf(currentPenDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        serviceWiseResponse.setCurrentTotalDemand(
                BigDecimal.valueOf(currentDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP).add(
                        BigDecimal.valueOf(currentPenDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));
        serviceWiseResponse.setTotalDemand(BigDecimal.valueOf(arrearDemand.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP)
                .add(BigDecimal.valueOf(arrearPenDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP))
                .add(BigDecimal.valueOf(currentDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP))
                .add(BigDecimal.valueOf(currentPenDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));
        serviceWiseResponse.setArrearCollection(
                BigDecimal.valueOf(arrearCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        serviceWiseResponse.setArrearPenCollection(
                BigDecimal.valueOf(arrearPenCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        serviceWiseResponse.setArrearTotalCollection(BigDecimal.valueOf(arrearCollected.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP)
                .add(BigDecimal.valueOf(arrearPenCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));
        serviceWiseResponse.setCurrentCollection(
                BigDecimal.valueOf(currentCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        serviceWiseResponse.setCurrentPenCollection(
                BigDecimal.valueOf(currentPenCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
        serviceWiseResponse.setCurrentTotalCollection(BigDecimal.valueOf(currentCollected.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP)
                .add(BigDecimal.valueOf(currentPenCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));
        serviceWiseResponse.setTotalCollection(BigDecimal.valueOf(arrearCollected.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP)
                .add(BigDecimal.valueOf(arrearPenCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP))
                .add(BigDecimal.valueOf(currentCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP))
                .add(BigDecimal.valueOf(currentPenCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));

        serviceWiseResponse.setArrearBalance(
                BigDecimal.valueOf(arrearDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP).subtract(
                        BigDecimal.valueOf(arrearCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));

        serviceWiseResponse.setArrearPenBalance(BigDecimal.valueOf(arrearPenDemand.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP).subtract(BigDecimal
                        .valueOf(arrearPenCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));

        serviceWiseResponse.setCurrentBalance(
                BigDecimal.valueOf(currentDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP).subtract(
                        BigDecimal.valueOf(currentCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));

        serviceWiseResponse.setCurrentPenBalance(BigDecimal.valueOf(currentPenDemand.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP).subtract(BigDecimal
                        .valueOf(currentPenCollected.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)));

        serviceWiseResponse.setTotalBalance(BigDecimal.valueOf(arrearDemand.getValue())
                .setScale(0, BigDecimal.ROUND_HALF_UP)
                .add(BigDecimal.valueOf(arrearPenDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)
                        .add(BigDecimal.valueOf(currentDemand.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP))
                        .add(BigDecimal.valueOf(currentPenDemand.getValue())
                                .setScale(0, BigDecimal.ROUND_HALF_UP)
                                .subtract(BigDecimal.valueOf(arrearCollected.getValue())
                                        .setScale(0, BigDecimal.ROUND_HALF_UP)
                                        .add(BigDecimal.valueOf(arrearPenCollected.getValue()).setScale(0,
                                                BigDecimal.ROUND_HALF_UP))
                                        .add(BigDecimal.valueOf(currentCollected.getValue()).setScale(0,
                                                BigDecimal.ROUND_HALF_UP))
                                        .add(BigDecimal.valueOf(currentPenCollected.getValue()).setScale(0,
                                                BigDecimal.ROUND_HALF_UP))))));

        serviceWiseResponse.setDrillDownType(entry.getKeyAsString());
        serviceWiseResponses.add(serviceWiseResponse);
    }

    return serviceWiseResponses;
}

From source file:org.egov.ptis.service.es.PropertyTaxElasticSearchIndexService.java

/**
 * Returns total demand from Property tax index, based on input filters
 *
 * @param collectionDetailsRequest/*ww w  .j  av a  2 s .  c om*/
 * @return
 */
public BigDecimal getTotalDemandBasedOnInputFilters(final CollectionDetailsRequest collectionDetailsRequest) {
    final BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest)
            .filter(QueryBuilders.matchQuery(IS_ACTIVE, true))
            .filter(QueryBuilders.matchQuery(IS_EXEMPTED, false));

    final SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(PROPERTY_TAX_INDEX_NAME)
            .withQuery(boolQuery).addAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND))
            .build();
    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());

    final Sum aggr = collAggr.get(TOTALDEMAND);
    return BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP);
}

From source file:org.apache.ofbiz.accounting.thirdparty.paypal.PayPalServices.java

private static void addCartDetails(NVPEncoder encoder, ShoppingCart cart) throws GenericEntityException {
    encoder.add("CURRENCYCODE", cart.getCurrency());
    int line = 0;
    for (ShoppingCartItem item : cart.items()) {
        encoder.add("L_NUMBER" + line, item.getProductId());
        encoder.add("L_NAME" + line, item.getName());
        encoder.add("L_AMT" + line, item.getBasePrice().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        encoder.add("L_QTY" + line, item.getQuantity().toBigInteger().toString());
        line++;//from  w w  w.  j a v  a  2s.co  m
        BigDecimal otherAdjustments = item.getOtherAdjustments();
        if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
            encoder.add("L_NUMBER" + line, item.getProductId());
            encoder.add("L_NAME" + line, item.getName() + " Adjustments");
            encoder.add("L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            encoder.add("L_QTY" + line, "1");
            line++;
        }
    }
    BigDecimal otherAdjustments = cart.getOrderOtherAdjustmentTotal();
    if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
        encoder.add("L_NUMBER" + line, "N/A");
        encoder.add("L_NAME" + line, "Order Adjustments");
        encoder.add("L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        encoder.add("L_QTY" + line, "1");
        line++;
    }
    encoder.add("ITEMAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    encoder.add("SHIPPINGAMT", "0.00");
    encoder.add("TAXAMT", "0.00");
    encoder.add("AMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    //NOTE: The docs say this is optional but then won't work without it
    encoder.add("MAXAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
}

From source file:com.salesmanager.core.service.tax.TaxService.java

/**
 * Calculates tax on an OrderTotalSummary object (products applicable,
 * shipping...), creates and set the shopping cart lines. Returns the amount
 * with tax//w w w  . java  2s .  c  om
 * 
 * @param summary
 * @param amount
 * @param customer
 * @param merchantId
 * @return
 * @throws Exception
 */
@Transactional
public OrderTotalSummary calculateTax(OrderTotalSummary summary, Collection<OrderProduct> products,
        Customer customer, int merchantId, Locale locale, String currency) throws Exception {

    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore store = mservice.getMerchantStore(merchantId);

    Map productsTax = new HashMap();

    //rounding definition
    BigDecimal totalTaxAmount = new BigDecimal(0);
    //totalTaxAmount.setScale(2, BigDecimal.ROUND_DOWN);

    // check if tax is applicable and build a map
    // of tax class - product
    if (products != null) {
        Iterator prodIt = products.iterator();
        while (prodIt.hasNext()) {
            OrderProduct prod = (OrderProduct) prodIt.next();
            if (prod.getTaxClassId() > -1) {

                BigDecimal groupBeforeTaxAmount = (BigDecimal) productsTax.get(prod.getTaxClassId());

                if (groupBeforeTaxAmount == null) {
                    groupBeforeTaxAmount = new BigDecimal("0");
                }

                BigDecimal finalPrice = prod.getFinalPrice();// unit price +
                // attribute
                // * qty
                // finalPrice = finalPrice.multiply(new
                // BigDecimal(prod.getProductQuantity()));

                groupBeforeTaxAmount = groupBeforeTaxAmount.add(finalPrice);

                // getPrices
                Set prices = prod.getPrices();
                // List prices = prod.getRelatedPrices();
                if (prices != null) {
                    Iterator ppriceIter = prices.iterator();
                    while (ppriceIter.hasNext()) {
                        OrderProductPrice pprice = (OrderProductPrice) ppriceIter.next();
                        if (!pprice.isDefaultPrice()) {// related price
                            // activation...
                            // PriceModule module =
                            // (PriceModule)SpringUtil.getBean(pprice.getProductPriceModuleName());
                            // if(module.isTaxApplicable()) {//related price
                            // becomes taxeable
                            // if(pprice.isProductHasTax()) {
                            // groupBeforeTaxAmount =
                            // groupBeforeTaxAmount.add(ProductUtil.determinePrice(pprice));

                            BigDecimal ppPrice = pprice.getProductPriceAmount();
                            ppPrice = ppPrice.multiply(new BigDecimal(prod.getProductQuantity()));

                            groupBeforeTaxAmount = groupBeforeTaxAmount.add(ppPrice);
                            // }
                        }
                    }
                }

                BigDecimal credits = prod.getApplicableCreditOneTimeCharge();
                groupBeforeTaxAmount = groupBeforeTaxAmount.subtract(credits);

                productsTax.put(prod.getTaxClassId(), groupBeforeTaxAmount);

            }
        }
    }

    if (productsTax.size() == 0) {
        return summary;
    }

    // determine if tax applies on billing or shipping address

    // get shipping & tax informations
    ConfigurationRequest request = new ConfigurationRequest(merchantId);
    ConfigurationResponse response = mservice.getConfiguration(request);

    String taxBasis = TaxConstants.SHIPPING_TAX_BASIS;

    // get tax basis
    MerchantConfiguration taxConf = response.getMerchantConfiguration(TaxConstants.MODULE_TAX_BASIS);
    if (taxConf != null && !StringUtils.isBlank(taxConf.getConfigurationValue())) {// tax
        // basis
        taxBasis = taxConf.getConfigurationValue();
    }

    // tax on shipping
    if (summary.getShippingTotal() != null && summary.getShippingTotal().floatValue() > 0) {
        MerchantConfiguration shippingTaxConf = response
                .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_TAX_CLASS);
        if (shippingTaxConf != null && !StringUtils.isBlank(shippingTaxConf.getConfigurationValue())) {// tax on shipping

            long taxClass = Long.parseLong(shippingTaxConf.getConfigurationValue());
            BigDecimal groupSubTotal = (BigDecimal) productsTax.get(taxClass);
            if (groupSubTotal == null) {
                groupSubTotal = new BigDecimal("0");
                productsTax.put(taxClass, groupSubTotal);
            }
            groupSubTotal = groupSubTotal.add(summary.getShippingTotal());
            productsTax.put(taxClass, groupSubTotal);
        }
    }

    Map taxDescriptionsHolder = new TreeMap();

    Iterator taxMapIter = productsTax.keySet().iterator();
    while (taxMapIter.hasNext()) {// get each tax class

        long key = (Long) taxMapIter.next();
        // List taxClassGroup = (List)productsTax.get(key);

        int countryId = 0;

        Collection taxCollection = null;
        if (taxBasis.equals(TaxConstants.SHIPPING_TAX_BASIS)) {

            if (store.getCountry() != customer.getCustomerCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerCountryId(),
                    customer.getCustomerZoneId(), key, merchantId);
            countryId = customer.getCustomerCountryId();
        } else { // BILLING

            if (store.getCountry() != customer.getCustomerBillingCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerBillingCountryId(),
                    customer.getCustomerBillingZoneId(), key, merchantId);
            countryId = customer.getCustomerBillingCountryId();
        }

        if (taxCollection == null || taxCollection.size() == 0) {// no tax
            continue;
        }

        Map countries = RefCache.getCountriesMap();
        Country c = (Country) countries.get(countryId);

        if (c != null) {// tax adjustment rules
            TaxModule module = (TaxModule) SpringUtil.getBean(c.getCountryIsoCode2());
            if (module != null) {
                taxCollection = module.adjustTaxRate(taxCollection, store);
            }
        }

        //BigDecimal beforeTaxAmount = new BigDecimal("0");
        //beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal groupSubTotal = (BigDecimal) productsTax.get(key);

        //beforeTaxAmount = beforeTaxAmount.add(groupSubTotal);
        BigDecimal beforeTaxAmount = groupSubTotal;
        beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);

        // iterate through tax collection and calculate tax lines
        if (taxCollection != null) {

            Iterator i = taxCollection.iterator();
            while (i.hasNext()) {

                TaxRate trv = (TaxRate) i.next();
                // double value = ((trv.getTaxRate().doubleValue() *
                // beforeTaxAmount.doubleValue())/100)+beforeTaxAmount.doubleValue();
                double trDouble = trv.getTaxRate().doubleValue();

                // if piggy back, add tax to subtotal
                BigDecimal amount = beforeTaxAmount;
                if (trv.isPiggyback()) {
                    // add previous calculated tax on top of subtotal
                    amount = amount.add(totalTaxAmount);
                }

                // commented for piggyback
                // double beforeTaxDouble = beforeTaxAmount.doubleValue();
                double beforeTaxDouble = amount.doubleValue();

                double value = ((trDouble * beforeTaxDouble) / 100);

                BigDecimal nValue = BigDecimal.valueOf(value);

                //BigDecimal nValue = new BigDecimal(value);
                nValue.setScale(2, BigDecimal.ROUND_HALF_UP);

                //nValue = nValue.add(new BigDecimal(value));

                // commented for piggyback
                // beforeTaxAmount = beforeTaxAmount.add(nValue);

                //BigDecimal bdValue = nValue;
                String am = CurrencyUtil.getAmount(nValue, store.getCurrency());

                /** this one **/
                totalTaxAmount = totalTaxAmount.add(new BigDecimal(am));

                String name = LabelUtil.getInstance().getText(locale, "label.generic.tax");

                OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder
                        .get(trv.getZoneToGeoZone().getGeoZoneId());

                if (line == null) {
                    // tax description
                    line = new OrderTotalLine();
                    Set descriptionsSet = trv.getDescriptions();
                    if (descriptionsSet != null) {
                        Iterator li = descriptionsSet.iterator();
                        while (li.hasNext()) {
                            TaxRateDescription description = (TaxRateDescription) li.next();
                            if (description.getId().getLanguageId() == LanguageUtil
                                    .getLanguageNumberCode(locale.getLanguage())) {
                                name = description.getTaxDescription();
                                break;
                            }
                        }
                    }

                    line.setText(name);
                    line.setCost(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(nValue, currency));
                    taxDescriptionsHolder.put(trv.getZoneToGeoZone().getGeoZoneId(), line);
                } else {// needs to re-use the same shopping cart line
                    BigDecimal cost = line.getCost();
                    cost = cost.add(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(cost, currency));
                }

                // now set tax on producs
                Iterator prodIt = products.iterator();
                while (prodIt.hasNext()) {
                    OrderProduct prod = (OrderProduct) prodIt.next();
                    if (prod.getTaxClassId() == key) {
                        // calculate tax for this product
                        BigDecimal price = prod.getProductPrice();
                        BigDecimal productTax = prod.getProductTax();
                        if (productTax == null) {
                            productTax = new BigDecimal("0");
                        }
                        price = price.add(productTax);
                        double pTax = ((trDouble * price.doubleValue()) / 100);

                        prod.setProductTax(new BigDecimal(pTax));

                    }
                }

            } // end while

        }

        Iterator titer = taxDescriptionsHolder.keySet().iterator();
        while (titer.hasNext()) {
            long lineKey = (Long) titer.next();
            OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder.get(lineKey);
            summary.addTaxPrice(line);
        }

    }

    summary.setTaxTotal(totalTaxAmount);

    return summary;

}

From source file:org.efaps.esjp.ui.print.Table_Base.java

/**
 * Execute for table.//www  .  j a va  2s  .  c  om
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @param _object the object
 * @param _mime the mime
 * @return the jasper report builder
 * @throws EFapsException on error
 */
protected JasperReportBuilder execute4Table(final Parameter _parameter, final AbstractUIPageObject _object,
        final String _mime) throws EFapsException {
    final String[] oids = (String[]) Context.getThreadContext().getSessionAttribute("selectedOIDs4print");

    final TargetMode mode = "xls".equalsIgnoreCase(_mime) ? TargetMode.PRINT : TargetMode.VIEW;
    final boolean print = mode.equals(TargetMode.VIEW);
    if (!mode.equals(_object.getMode())) {
        _object.resetModel();
        _object.setMode(mode);
        _object.execute();
    }

    final JasperReportBuilder jrb = getBuilder(_parameter, _object, _mime);
    if (print) {
        jrb.setPageMargin(DynamicReports.margin(20)).setPageFormat(PageType.A4, PageOrientation.LANDSCAPE)
                .setColumnHeaderStyle(getStyle(_parameter, Table_Base.Section.HEADER)).highlightDetailEvenRows()
                .pageFooter(DynamicReports.cmp.pageXofY().setStyle(
                        DynamicReports.stl.style().setHorizontalTextAlignment(HorizontalTextAlignment.CENTER)));
    } else {
        jrb.setIgnorePagination(true).setPageMargin(DynamicReports.margin(0));
    }
    final int widthWeight = ((AbstractUIHeaderObject) _object).getWidthWeight();
    final String[] columns = _parameter.getParameterValues("columns");
    final Set<String> selCols = new HashSet<>();
    for (final String col : columns) {
        selCols.add(col);
    }
    final Map<String, Attribute> selAttr = new HashMap<>();
    final List<Map<String, Object>> values = new ArrayList<>();
    if (_object instanceof UITable) {
        for (final UIRow row : ((UITable) _object).getValues()) {
            if (oids == null || ArrayUtils.contains(oids, row.getInstanceKey())) {
                final Map<String, Object> map = new HashMap<>();
                for (final IFilterable filterable : row.getCells()) {
                    if (filterable instanceof UIField) {
                        final UIField uiField = (UIField) filterable;
                        if (selCols.contains(uiField.getFieldConfiguration().getName())) {
                            Object value = print ? uiField.getPickListValue()
                                    : uiField.getCompareValue() != null ? uiField.getCompareValue()
                                            : uiField.getPickListValue();
                            if (value instanceof DateTime) {
                                value = ((DateTime) value).toDate();
                            } else if (uiField.getFactory() != null
                                    && uiField.getFactoryKey().endsWith("DateUIFactory")
                                    && value instanceof String && StringUtils.isEmpty((String) value)) {
                                value = null;
                            }
                            map.put(uiField.getFieldConfiguration().getName(), value);
                            selAttr.put(uiField.getFieldConfiguration().getName(), null);
                        }
                    }
                }
                values.add(map);
            }
        }
    } else if (_object instanceof UIStructurBrowser) {
        final List<UIStructurBrowser> roots = ((UIStructurBrowser) _object).getChildren();
        add2Values4StrBrws(selCols, selAttr, print, values, roots);
    }

    for (final UITableHeader header : ((AbstractUIHeaderObject) _object).getHeaders()) {
        final boolean add;
        if (print) {
            add = selCols.contains(header.getFieldName());
        } else {
            final Field field = Field.get(header.getFieldId());
            add = field.isNoneDisplay(TargetMode.VIEW) && !field.isNoneDisplay(TargetMode.PRINT)
                    || selCols.contains(header.getFieldName());
            if (add && !selCols.contains(header.getFieldName())) {
                selCols.add(header.getFieldName());
            }
        }
        if (add) {
            final BigDecimal width = new BigDecimal(header.getWidth()).setScale(2)
                    .divide(new BigDecimal(widthWeight), BigDecimal.ROUND_HALF_UP)
                    .multiply(new BigDecimal(555));

            TextColumnBuilder<?> clbdr = null;
            final Attribute attr = selAttr.get(header.getFieldName());
            if (attr != null && !print) {
                if (attr.getAttributeType().getDbAttrType() instanceof LongType) {
                    if (checkValues(values, header.getFieldName(), Long.class)) {
                        clbdr = DynamicReports.col.column(header.getLabel(), header.getFieldName(),
                                DynamicReports.type.longType());
                    }
                } else if (attr.getAttributeType().getDbAttrType() instanceof DecimalType) {
                    if (checkValues(values, header.getFieldName(), BigDecimal.class)) {
                        clbdr = DynamicReports.col.column(header.getLabel(), header.getFieldName(),
                                DynamicReports.type.bigDecimalType());
                    }
                } else if (attr.getAttributeType().getDbAttrType() instanceof IntegerType) {
                    clbdr = DynamicReports.col.column(header.getLabel(), header.getFieldName(),
                            DynamicReports.type.integerType());
                } else if (attr.getAttributeType().getDbAttrType() instanceof BooleanType) {
                    if (checkValues(values, header.getFieldName(), Boolean.class)) {
                        clbdr = DynamicReports.col.column(header.getLabel(), header.getFieldName(),
                                DynamicReports.type.booleanType());
                    }
                } else if (attr.getAttributeType().getDbAttrType() instanceof DateTimeType) {
                    if (checkValues(values, header.getFieldName(), Date.class)) {
                        clbdr = DynamicReports.col.column(header.getLabel(), header.getFieldName(),
                                DynamicReports.type.dateType());
                    }
                } else if (attr.getAttributeType().getDbAttrType() instanceof RateType) {
                    clbdr = DynamicReports.col.column(header.getLabel(), header.getFieldName(),
                            DynamicReports.type.bigDecimalType());
                }
            }

            if (clbdr == null) {
                clbdr = getColumnBuilder4Values(values, header);
            }
            if (print) {
                clbdr.setWidth(header.isFixedWidth() ? header.getWidth() : width.intValue());
            }
            jrb.addColumn(clbdr);
        }
    }
    jrb.setLocale(Context.getThreadContext().getLocale()).setDataSource(getSource(_parameter, values));
    return jrb;
}

From source file:com.panet.imeta.core.row.ValueDataUtil.java

public static Object divide(ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB)
        throws KettleValueException {
    if (dataA == null || dataB == null)
        return null;

    switch (metaA.getType()) {
    case ValueMetaInterface.TYPE_NUMBER:
        return new Double(metaA.getNumber(dataA).doubleValue() / metaB.getNumber(dataB).doubleValue());
    case ValueMetaInterface.TYPE_INTEGER:
        return new Long(metaA.getInteger(dataA).longValue() / metaB.getInteger(dataB).longValue());
    case ValueMetaInterface.TYPE_BIGNUMBER:
        return metaA.getBigNumber(dataA).divide(metaB.getBigNumber(dataB), BigDecimal.ROUND_HALF_UP);

    default:/*www.j  a  v  a 2  s.  c  om*/
        throw new KettleValueException("The 'divide' function only works on numeric data.");
    }
}

From source file:com.osafe.services.OsafePayPalServices.java

private static void addCartDetails(NVPEncoder encoder, ShoppingCart cart) throws GenericEntityException {
    encoder.add("CURRENCYCODE", cart.getCurrency());
    int line = 0;
    for (ShoppingCartItem item : cart.items()) {
        encoder.add("L_NUMBER" + line, item.getProductId());
        encoder.add("L_NAME" + line, item.getName());
        encoder.add("L_AMT" + line, item.getBasePrice().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        encoder.add("L_QTY" + line, item.getQuantity().toBigInteger().toString());
        line++;//  ww w.  j  a v  a 2s  .  c  o  m
        BigDecimal otherAdjustments = item.getOtherAdjustments();
        if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
            encoder.add("L_NUMBER" + line, item.getProductId());
            encoder.add("L_NAME" + line, item.getName() + " Adjustments");
            encoder.add("L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            encoder.add("L_QTY" + line, "1");
            line++;
        }
    }
    BigDecimal otherAdjustments = cart.getOrderOtherAdjustmentTotal();
    if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
        encoder.add("L_NUMBER" + line, "N/A");
        encoder.add("L_NAME" + line, "Order Adjustments");
        encoder.add("L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        encoder.add("L_QTY" + line, "1");
        line++;
    }
    encoder.add("ITEMAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    //encoder.add("SHIPPINGAMT", "0.00");
    //encoder.add("TAXAMT", "0.00");
    encoder.add("SHIPPINGAMT", cart.getTotalShipping().setScale(2).toPlainString());
    encoder.add("TAXAMT", cart.getTotalSalesTax().setScale(2).toPlainString());
    encoder.add("AMT", cart.getGrandTotal().setScale(2).toPlainString());
    //encoder.add("AMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
    //NOTE: The docs say this is optional but then won't work without it
    //encoder.add("MAXAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
}

From source file:org.devgateway.ocds.web.rest.controller.CorruptionRiskDashboardIndicatorsStatsController.java

@ApiOperation(value = "Percent of total projects eligible (denominator is total projects)")
@RequestMapping(value = "/api/percentTotalProjectsEligibleByYear", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> percentTotalProjectsEligibleByYear(final YearFilterPagingRequest filter) {

    //get the total projects eligible by year
    List<DBObject> totalEligibleProjects = totalEligibleProjectsByIndicatorTypeByYear(filter);

    //denominator total projects eligible by year
    List<DBObject> totalProjectsByYear = totalProjectsByYear(filter);

    totalEligibleProjects.forEach(e -> {
        findByYearAndTypeAndMonth(totalProjectsByYear, (Integer) e.get(Keys.YEAR), null,
                (Integer) e.get(Keys.MONTH)).forEach(f -> {
                    e.put(Keys.PROJECT_COUNT, f.get(Keys.PROJECT_COUNT));
                    e.put(Keys.PERCENT,// w  w  w  .  j a  v  a  2  s  .com
                            (BigDecimal.valueOf((Integer) e.get(Keys.ELIGIBLE_PROJECT_COUNT))
                                    .setScale(BIGDECIMAL_SCALE)
                                    .divide(BigDecimal.valueOf((Integer) f.get(Keys.PROJECT_COUNT)),
                                            BigDecimal.ROUND_HALF_UP)
                                    .multiply(ONE_HUNDRED)));
                });
    });

    return totalEligibleProjects;
}

From source file:com.aliyun.fs.oss.nat.BufferReader.java

private void progressPrint() {
    long hasRead = pos + realContentSize - instreamStart;
    double currentProgress = hasRead >= lengthToFetch ? 1.0d : (double) hasRead / lengthToFetch;
    if (currentProgress - lastProgress >= 0.1 || currentProgress == 1.0d) {
        BigDecimal b = new BigDecimal(currentProgress);
        LOG.info("Current progress of reading '" + key + " [" + instreamStart + ":...]' is "
                + b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        lastProgress = currentProgress;/*from  w w w  .j  a  v  a  2s  .com*/
    }
}

From source file:org.jasig.ssp.service.impl.AbstractPlanServiceImpl.java

private BigDecimal calculateTotalPlanDevHours(List<TermCourses<T, TO>> courses) {
    BigDecimal totalDevCreditHours = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);
    for (TermCourses<T, TO> termCourses : courses) {
        totalDevCreditHours = totalDevCreditHours.add(termCourses.getTotalDevCreditHours());
    }/* w  w  w  . jav a  2s  .co  m*/
    return totalDevCreditHours;
}