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:eionet.cr.util.Util.java

/**
 * Algorithm calculates the estimated number of hashes.
 *
 * @param minHash//ww w  .jav a  2 s  .c om
 * @param maxHash
 * @return
 */
public static int calculateHashesCount(long minHash, long maxHash) {

    BigDecimal minValue = new BigDecimal(Long.MIN_VALUE);
    BigDecimal maxValue = new BigDecimal(Long.MAX_VALUE);
    BigDecimal lowKey = new BigDecimal(minHash);
    BigDecimal highKey = new BigDecimal(maxHash);
    BigDecimal distance = maxValue.subtract(highKey).add(lowKey).subtract(minValue);
    BigDecimal hitCount = new BigDecimal(2).pow(64).divide(distance, 0, BigDecimal.ROUND_HALF_UP);

    return hitCount.intValue();
}

From source file:com.konakart.bl.modules.ordertotal.productdiscount.ProductDiscount.java

/**
 * Create and return an OrderTotal object for the discount amount. *
 * <p>//from  w  ww.j  a v  a 2  s.co m
 * Custom field usage:
 * <p>
 * <ul>
 * <li>custom1 = Minimum Order Value</li>
 * <li>custom2 = Minimum quantity of a single product</li>
 * <li>custom3 = Discount Applied</li>
 * <li>custom4 = Percentage discount if set to true</li>
 * <li>custom5 = Discount applied to pre-tax value if set to true</li>
 * </ul>
 * If the promotion applies to multiple products, we create an array of order total objects and
 * attach the array to the order total that we return (ot.setOrderTotals(otArray)). The reason
 * for doing this is to get a line item of the order for each discounted product. We still need
 * to populate the order total that we return with the total discount amount because this will
 * be used to compare this promotion with other promotions in order to decide which one to use.
 * 
 * @param order
 * @param dispPriceWithTax
 * @param locale
 * @return Returns an OrderTotal object for this module
 * @throws Exception
 */
public OrderTotal getOrderTotal(Order order, boolean dispPriceWithTax, Locale locale) throws Exception {
    OrderTotal ot;
    StaticData sd = staticDataHM.get(getStoreId());

    // Get the resource bundle
    ResourceBundle rb = getResourceBundle(mutex, bundleName, resourceBundleMap, locale);
    if (rb == null) {
        throw new KKException("A resource file cannot be found for the country " + locale.getCountry());
    }

    // Get the promotions
    Promotion[] promArray = getPromMgr().getPromotions(code, order);

    // List to contain an order total for each promotion
    List<OrderTotal> orderTotalList = new ArrayList<OrderTotal>();

    if (promArray != null) {

        for (int i = 0; i < promArray.length; i++) {
            Promotion promotion = promArray[i];

            /*
             * Get the configuration parameters from the promotion
             */

            // Minimum value for order
            BigDecimal minTotalOrderVal = getCustomBigDecimal(promotion.getCustom1(), 1);

            // Need to order at least this quantity of a single product for promotion to apply
            int minProdQuantity = getCustomInt(promotion.getCustom2(), 2);

            // Actual discount. Could be a percentage or an amount.
            BigDecimal discountApplied = getCustomBigDecimal(promotion.getCustom3(), 3);

            // If set to true it is a percentage. Otherwise it is an amount.
            boolean percentageDiscount = getCustomBoolean(promotion.getCustom4(), 4);

            // If set to true, discount is applied to pre-tax value. Only relevant for
            // percentage discount.
            boolean applyBeforeTax = getCustomBoolean(promotion.getCustom5(), 5);

            // Don't bother going any further if there is no discount
            if (discountApplied == null || discountApplied.equals(new BigDecimal(0))) {
                continue;
            }

            // Get the order value
            BigDecimal orderValue = null;
            if (applyBeforeTax) {
                orderValue = order.getSubTotalExTax();
                log.debug("Order value before tax: " + orderValue);
            } else {
                orderValue = order.getSubTotalIncTax();
                log.debug("Order value after tax: " + orderValue);
            }

            // If promotion doesn't cover any of the products in the order then go on to the
            // next promotion
            if (promotion.getApplicableProducts() == null || promotion.getApplicableProducts().length == 0) {
                continue;
            }

            ot = new OrderTotal();
            ot.setSortOrder(sd.getSortOrder());
            ot.setClassName(code);
            ot.setPromotions(new Promotion[] { promotion });

            // Does promotion only apply to a min order value ?
            if (minTotalOrderVal != null) {
                if (orderValue.compareTo(minTotalOrderVal) < 0) {
                    // If we haven't reached the minimum amount then continue to the next
                    // promotion
                    continue;
                }
            }

            // Continue if promotion has no applicable products (should never happen)
            if (promotion.getApplicableProducts() == null) {
                continue;
            }

            /*
             * Create a new Order Total module for each discounted product and store in this
             * list
             */
            ArrayList<OrderTotal> otList = new ArrayList<OrderTotal>();

            // Loop through promotion products to determine whether to apply a discount
            boolean firstLoop = true;
            for (int j = 0; j < promotion.getApplicableProducts().length; j++) {
                OrderProductIf op = promotion.getApplicableProducts()[j];
                if (op != null && op.getQuantity() >= minProdQuantity) {
                    // Get the current total price of the product(s)
                    BigDecimal currentPrice = null;
                    if (applyBeforeTax) {
                        currentPrice = op.getFinalPriceExTax();
                    } else {
                        currentPrice = op.getFinalPriceIncTax();
                    }

                    // Apply the discount
                    BigDecimal discount = null;
                    if (percentageDiscount) {
                        // Apply a percentage discount
                        discount = (currentPrice.multiply(discountApplied)).divide(new BigDecimal(100));
                    } else {
                        // Apply an amount based discount
                        discount = discountApplied.multiply(new BigDecimal(op.getQuantity()));
                    }

                    // Determine whether it is the first discounted product or not
                    String formattedDiscount = getCurrMgr().formatPrice(discount, order.getCurrencyCode());
                    if (firstLoop) {
                        // Set the order total attributes
                        ot.setValue(discount);
                        if (percentageDiscount) {
                            try {
                                ot.setText(String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TEXT),
                                        "-", formattedDiscount));
                                ot.setTitle(
                                        String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TITLE),
                                                "-", discountApplied, "%", op.getName()));
                            } catch (MissingResourceException e) {
                                ot.setText("-" + formattedDiscount);
                                // Title looks like "-10% Philips TV"
                                ot.setTitle("-" + discountApplied + "% " + op.getName());
                            }

                        } else {
                            try {
                                ot.setText(String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TEXT),
                                        "-", formattedDiscount));
                                ot.setTitle(
                                        String.format(rb.getString(MODULE_ORDER_TOTAL_PRODUCT_DISCOUNT_TITLE),
                                                "-", formattedDiscount, "", op.getName()));
                            } catch (MissingResourceException e) {
                                ot.setText("-" + formattedDiscount);
                                // Title looks like "-10EUR Philips TV"
                                ot.setTitle("-" + formattedDiscount + " " + op.getName());
                            }
                        }
                    } else {
                        // Set the order total attributes
                        ot.setValue(ot.getValue().add(discount));
                        ot.setText("-" + getCurrMgr().formatPrice(ot.getValue(), order.getCurrencyCode()));
                        ot.setTitle(ot.getTitle() + "," + op.getName());
                    }
                    firstLoop = false;

                    /*
                     * Create a new Order Total module for each product
                     */
                    OrderTotal singleOt = new OrderTotal();
                    singleOt.setSortOrder(sd.getSortOrder());
                    singleOt.setClassName(code);
                    singleOt.setValue(discount);
                    singleOt.setText("-" + formattedDiscount);
                    if (percentageDiscount) {
                        singleOt.setTitle("-" + discountApplied + "% " + op.getName() + ":");
                    } else {
                        singleOt.setTitle("-" + formattedDiscount + " " + op.getName() + ":");
                    }
                    otList.add(singleOt);
                }
            }

            /*
             * If we have more than one discounted product we create an array of order totals
             * (one for each product) and add the array to the order total to be returned.
             */
            if (otList.size() > 1) {
                OrderTotal[] otArray = new OrderTotal[otList.size()];
                int k = 0;
                for (Iterator<OrderTotal> iterator = otList.iterator(); iterator.hasNext();) {
                    OrderTotal lot = iterator.next();
                    otArray[k++] = lot;
                }
                ot.setOrderTotals(otArray);
            }

            if (ot.getValue() != null) {
                int scale = new Integer(order.getCurrency().getDecimalPlaces()).intValue();
                ot.setValue(ot.getValue().setScale(scale, BigDecimal.ROUND_HALF_UP));
                log.debug("Order total is :" + ot.toString());
                orderTotalList.add(ot);
            }
        }
    } else {
        // Return null if there are no promotions
        return null;
    }

    // Call a helper method to decide which OrderTotal we should return
    OrderTotal retOT = getDiscountOrderTotalFromList(order, orderTotalList);
    log.debug("Selected order total is: " + retOT);

    return retOT;

}

From source file:org.egov.wtms.web.controller.application.MeterReadingController.java

private WaterConnectionDetails billCalculationAndDemandUpdate(
        final WaterConnectionDetails waterConnectionDetails, final HttpServletRequest request,
        final MeterReadingConnectionDetails meterReadingConnectionDetailObj, final Long previousReading,
        final Date currentDate, final Date previousDate, final Boolean currentMonthIncluded) {
    int noOfMonths;
    Date previousReadingDate = null;
    if (previousDate != null)
        previousReadingDate = previousDate;
    BigDecimal noOfUnitsPerMonth = BigDecimal.ZERO;
    if (isNotBlank(request.getParameter(METERCURRENTREADING)))
        meterReadingConnectionDetailObj//from  w ww.j a  va 2s.c om
                .setCurrentReading(Long.valueOf(request.getParameter(METERCURRENTREADING)));
    meterReadingConnectionDetailObj.setCurrentReadingDate(currentDate);
    DateTime previousMidDate = null;
    if (previousReadingDate != null) {
        final DateTime previousDateTime = new DateTime(previousReadingDate);
        final int previousMidday = previousDateTime.dayOfMonth().getMaximumValue() / 2;
        previousMidDate = new DateTime(previousDateTime).withDayOfMonth(previousMidday);
    }
    final DateTime currentDateTime = new DateTime(currentDate);
    final int currentMidday = currentDateTime.dayOfMonth().getMaximumValue() / 2;
    final DateTime currentMidDate = new DateTime(currentDate).withDayOfMonth(currentMidday);

    populateMeterReadingDetails(meterReadingConnectionDetailObj, waterConnectionDetails);
    if (previousReadingDate == null) {
        noOfMonths = noOfMonthsBetween(waterConnectionDetails.getExecutionDate(), currentDate);
        previousReadingDate = waterConnectionDetails.getExecutionDate();
    } else
        noOfMonths = noOfMonthsBetween(previousReadingDate, currentDate);

    if (previousReadingDate != null && previousMidDate != null
            && previousReadingDate.before(previousMidDate.toDate())
            && !currentDate.before(currentMidDate.toDate()))
        noOfMonths++;

    if (!meterReadingConnectionDetailObj.isMeterDamaged()) {
        final Long currentToPreviousDiffOfUnits = Long.valueOf(request.getParameter(METERCURRENTREADING))
                - previousReading;
        if (noOfMonths > 0)
            noOfUnitsPerMonth = BigDecimal.valueOf(currentToPreviousDiffOfUnits)
                    .divide(BigDecimal.valueOf(noOfMonths), 0, BigDecimal.ROUND_HALF_UP);
        else
            noOfUnitsPerMonth = BigDecimal.valueOf(currentToPreviousDiffOfUnits);
    }
    WaterConnectionDetails waterconnectionDetails = null;
    if (meterReadingConnectionDetailObj.isMeterDamaged())
        waterconnectionDetails = calculateDemandForDamagedMeter(waterConnectionDetails, previousReadingDate,
                noOfMonths, currentMonthIncluded);
    else {
        final BigDecimal finalAmountToBePaid = calculateAmountTobePaid(waterConnectionDetails,
                noOfUnitsPerMonth).setScale(0, BigDecimal.ROUND_HALF_UP);

        if (finalAmountToBePaid.compareTo(BigDecimal.ZERO) > 0)
            waterconnectionDetails = connectionDemandService.updateDemandForMeteredConnection(
                    waterConnectionDetails, finalAmountToBePaid, currentDate, previousReadingDate, noOfMonths,
                    currentMonthIncluded);
        else
            throw new ApplicationRuntimeException("err.no.amount.due");
    }
    return waterconnectionDetails;
}

From source file:org.kalypso.ui.wizards.results.editor.EditStyleDialog.java

private void createStyleComponent(final Composite commonComposite) {
    m_symbolizer = parseStyle();//from  w w  w .  j a  v a 2 s .  c o m
    /* choose the composite, depending on the style */
    if (m_symbolizer[0] instanceof SurfaceLineSymbolizer) {
        final SurfaceLineSymbolizer symb = (SurfaceLineSymbolizer) m_symbolizer[0];
        final LineColorMap colorMap = symb.getColorMap();
        if (colorMap.getColorMap().length > 0) {
            final LineColorMapEditorComposite comp = new LineColorMapEditorComposite(commonComposite, SWT.NONE,
                    colorMap, m_minValue, m_maxValue);
            final GridData gridDataComp = new GridData(SWT.FILL, SWT.FILL, true, true);
            gridDataComp.horizontalSpan = 2;
            comp.setLayoutData(gridDataComp);
        } else {
            final Text errorText = new Text(commonComposite, SWT.NONE);
            errorText.setText(Messages.getString("org.kalypso.ui.wizards.results.editor.EditStyleDialog.5")); //$NON-NLS-1$
            errorText.setBackground(commonComposite.getBackground());
        }
    } else if (m_symbolizer[0] instanceof SurfacePolygonSymbolizer) {
        final SurfacePolygonSymbolizer symb = (SurfacePolygonSymbolizer) m_symbolizer[0];
        final PolygonColorMap colorMap = symb.getColorMap();
        final PolygonColorMapEntry[] colorMapEntries = colorMap.getColorMap();
        if (colorMapEntries.length > 0) {
            final PolygonColorMapEntry fromEntry = colorMapEntries[0];
            final PolygonColorMapEntry toEntry = colorMapEntries[colorMapEntries.length - 1];

            final PolygonColorMapEditorComposite comp = new PolygonColorMapEditorComposite(commonComposite,
                    SWT.NONE, fromEntry, toEntry, m_minValue, m_maxValue) {
                @Override
                protected void colorMapChanged() {
                    final List<PolygonColorMapEntry> colorMapList = getColorMap();
                    if (colorMapList.size() > 0)
                        colorMap.replaceColorMap(colorMapList);
                }
            };
            final GridData gridDataComp = new GridData(SWT.FILL, SWT.FILL, true, true);
            gridDataComp.horizontalSpan = 2;
            comp.setLayoutData(gridDataComp);
        } else {
            final Text errorText = new Text(commonComposite, SWT.NONE);
            errorText.setText(Messages.getString("org.kalypso.ui.wizards.results.editor.EditStyleDialog.6")); //$NON-NLS-1$
            errorText.setBackground(commonComposite.getBackground());
        }
    } else if (m_symbolizer[0] instanceof PointSymbolizer) {
        final PointSymbolizer symb = (PointSymbolizer) m_symbolizer[0];
        final Object[] mag = symb.getGraphic().getMarksAndExtGraphics();
        final Object object = mag[0];
        /*
         * getting the static map for actual step with settings for using in property function
         */
        final String sourceFile = m_resultAddLayerCommandData.getSource();
        final int beginIndex = sourceFile.indexOf(ResultMeta1d2dHelper.TIME_STEP_PREFIX)
                + ResultMeta1d2dHelper.TIME_STEP_PREFIX.length();
        final String stepName = sourceFile.substring(beginIndex, beginIndex + 16);
        final String nodeStyleType = ResultMeta1d2dHelper
                .resolveResultTypeFromSldFileName(m_fileName, NodeResultHelper.NODE_TYPE).toLowerCase();
        // m_mapSldSettingsIntern = NodeResultHelper.getSldSettingsMapForStyleStep( nodeStyleType, stepName );
        m_mapSldSettingsIntern = NodeResultHelper.getSldSettingsMapForStep(stepName);
        if (object instanceof Mark) {
            m_mark = (Mark) object;
            try {
                m_fill = m_mark.getFill();
                if (m_fill.getGraphicFill() == null
                        && !nodeStyleType.equals(NodeResultHelper.VELO_TYPE.toLowerCase())
                        && !nodeStyleType.equals(NodeResultHelper.WAVE_DIRECTION_TYPE.toLowerCase())) {
                    /*
                     * getting the according values from sld file, needen to save the last selected configuration for next calls
                     */
                    final CssParameter cssFillMin = m_fill.getParameter("minColor"); //$NON-NLS-1$
                    final CssParameter cssFillMax = m_fill.getParameter("maxColor"); //$NON-NLS-1$
                    final CssParameter cssValueAmountClasses = m_fill.getParameter("amountClasses"); //$NON-NLS-1$
                    Color fromColor = resolveColor(
                            m_mapSldSettingsIntern.get(NodeResultHelper.COLOR_MIN_PREFIX + nodeStyleType));
                    Color toColor = resolveColor(
                            m_mapSldSettingsIntern.get(NodeResultHelper.COLOR_MAX_PREFIX + nodeStyleType));
                    Double amountOfClasses = (Double) m_mapSldSettingsIntern
                            .get(NodeResultHelper.AMOUNT_OF_CLASSES_PREFIX + nodeStyleType);
                    try {
                        /*
                         * replacing the information needed for color settings from the loaded sld. initially set from the static
                         * map in the helper. if this data was provided in sld, set it also in to the map
                         */
                        fromColor = (Color) extractCssValue(cssFillMin);
                        toColor = (Color) extractCssValue(cssFillMax);
                        final Double extValueMin = (Double) m_mapSldSettingsIntern
                                .get(NodeResultHelper.VALUE_MIN_PREFIX + nodeStyleType);
                        final Double extValueMax = (Double) m_mapSldSettingsIntern
                                .get(NodeResultHelper.VALUE_MAX_PREFIX + nodeStyleType);
                        amountOfClasses = (Double) extractCssValue(cssValueAmountClasses);
                        m_mapSldSettingsIntern.put(NodeResultHelper.AMOUNT_OF_CLASSES_PREFIX + nodeStyleType,
                                amountOfClasses);
                        m_maxValue = new BigDecimal(extValueMax);
                        m_minValue = new BigDecimal(extValueMin);
                    } catch (final Exception e) {
                        e.printStackTrace();
                    }
                    final BigDecimal width = m_maxValue.subtract(m_minValue)
                            .divide(new BigDecimal(4), BigDecimal.ROUND_HALF_UP)
                            .setScale(3, BigDecimal.ROUND_HALF_UP);

                    final PolygonColorMapEntry fromEntry = StyleFactory.createPolygonColorMapEntry(fromColor,
                            fromColor, m_minValue, m_minValue.add(width));
                    final PolygonColorMapEntry toEntry = StyleFactory.createPolygonColorMapEntry(toColor,
                            toColor, m_maxValue.subtract(width), m_maxValue);
                    final NodeStyleEditorComposite comp = new NodeStyleEditorComposite(commonComposite,
                            SWT.NONE, fromEntry, toEntry, m_minValue, m_maxValue, amountOfClasses.intValue()) {
                        private Map<Integer, Color> m_mapActualColorsCache;

                        @Override
                        protected void contentChanged() {
                            m_boolNodeStyleChanged = true;
                            /*
                             * changing the name is needed to be placed in sld file.
                             */
                            final CssParameter newMinColor = getFromEntry().getFill().getParameter("fill"); //$NON-NLS-1$
                            newMinColor.setName("minColor"); //$NON-NLS-1$
                            m_fill.addCssParameter("minColor", newMinColor); //$NON-NLS-1$
                            final CssParameter newMaxColor = getToEntry().getFill().getParameter("fill"); //$NON-NLS-1$
                            newMaxColor.setName("maxColor"); //$NON-NLS-1$
                            m_fill.addCssParameter("maxColor", newMaxColor); //$NON-NLS-1$

                            final Double newAmountClasses = ((Integer) getAmountOfClassesForInterpolation())
                                    .doubleValue();
                            final CssParameter cssNewValueAmountClasses = m_fill.getParameter("amountClasses"); //$NON-NLS-1$
                            cssNewValueAmountClasses.setValue("" + newAmountClasses); //$NON-NLS-1$
                            m_fill.addCssParameter("amountClasses", cssNewValueAmountClasses); //$NON-NLS-1$

                            final Color extractedCssValueMinColor = (Color) extractCssValue(newMinColor);
                            m_mapSldSettingsIntern.put(NodeResultHelper.COLOR_MIN_PREFIX + nodeStyleType,
                                    extractedCssValueMinColor);
                            final Color extractedCssValueMaxColor = (Color) extractCssValue(newMaxColor);
                            m_mapSldSettingsIntern.put(NodeResultHelper.COLOR_MAX_PREFIX + nodeStyleType,
                                    extractedCssValueMaxColor);
                            m_mapSldSettingsIntern.put(
                                    NodeResultHelper.AMOUNT_OF_CLASSES_PREFIX + nodeStyleType,
                                    newAmountClasses);
                            /*
                             * this map placed also in the settings of actual result step, works as a cache of interpolated color,
                             * by changing of color settings should be reseted
                             */
                            m_mapActualColorsCache = (Map<Integer, Color>) m_mapSldSettingsIntern
                                    .get(NodeResultHelper.COLOR_MAP_PREFIX + nodeStyleType);
                            if (m_mapActualColorsCache != null)
                                m_mapActualColorsCache.clear();
                        }
                    };
                    final GridData gridDataComp = new GridData(SWT.FILL, SWT.FILL, true, true);
                    gridDataComp.horizontalSpan = 2;
                    comp.setLayoutData(gridDataComp);

                    return;
                }
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }

        final Double extValueMin = (Double) m_mapSldSettingsIntern
                .get(NodeResultHelper.VALUE_MIN_PREFIX + nodeStyleType);
        final Double extValueMax = (Double) m_mapSldSettingsIntern
                .get(NodeResultHelper.VALUE_MAX_PREFIX + nodeStyleType);
        m_maxValue = new BigDecimal(extValueMax).setScale(2, BigDecimal.ROUND_HALF_UP);
        m_minValue = new BigDecimal(extValueMin).setScale(2, BigDecimal.ROUND_HALF_UP);
        final VectorEditorComposite comp = new VectorEditorComposite(commonComposite, SWT.NONE, symb,
                m_minValue, m_maxValue);
        final GridData gridDataComp = new GridData(SWT.FILL, SWT.FILL, true, true);
        gridDataComp.horizontalSpan = 2;
        comp.setLayoutData(gridDataComp);
    } else {
        final Text errorText1 = new Text(commonComposite, SWT.NONE);
        final GridData gridDataText1 = new GridData(SWT.BEGINNING, SWT.CENTER, true, true);
        gridDataText1.horizontalSpan = 2;
        gridDataText1.widthHint = 400;

        errorText1.setLayoutData(gridDataText1);
        errorText1.setText(Messages.getString("org.kalypso.ui.wizards.results.editor.EditStyleDialog.7")); //$NON-NLS-1$
        errorText1.setBackground(commonComposite.getBackground());

        final Text errorText2 = new Text(commonComposite, SWT.NONE);
        errorText2.setLayoutData(gridDataText1);
        errorText2.setText(Messages.getString("org.kalypso.ui.wizards.results.editor.EditStyleDialog.8")); //$NON-NLS-1$
        errorText2.setBackground(commonComposite.getBackground());
    }
}

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

protected BigDecimal calculateTotalPlanHours(List<TermCourses<T, TO>> courses) {
    BigDecimal totalPlanCreditHours = new BigDecimal(0).setScale(2, BigDecimal.ROUND_HALF_UP);
    for (TermCourses<T, TO> termCourses : courses) {
        totalPlanCreditHours = totalPlanCreditHours.add(termCourses.getTotalCreditHours());
    }/*w w w.  j a  va2s. c  om*/
    return totalPlanCreditHours;
}

From source file:org.egov.collection.service.elasticsearch.CollectionDocumentElasticSearchService.java

/**
 * API sets the consolidated collections for single day and between the 2
 * dates/*from  w ww .jav  a  2s  .  c o m*/
 *
 * @param collectionDashBoardRequest
 * @param collectionIndexDetails
 */
public CollectionDocumentDetails getCompleteCollectionIndexDetails(
        final CollectionDashBoardRequest collectionDashBoardRequest, final List<String> serviceDetail,
        final CFinancialYear financialYear) {
    Date fromDate;
    Date toDate;
    BigDecimal todayColl;
    BigDecimal tillDateColl;
    BigDecimal variance;
    final Long startTime = System.currentTimeMillis();
    final CollectionDocumentDetails collectionDocumentDetails = new CollectionDocumentDetails();
    /**
     * 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(collectionDashBoardRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDashBoardRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDashBoardRequest.getToDate(), DATE_FORMAT_YYYYMMDD);
        toDate = org.apache.commons.lang3.time.DateUtils
                .addDays(DateUtils.getDate(collectionDashBoardRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1);
    } else {
        fromDate = new Date();
        toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);
    }
    // Todays collection
    todayColl = getCollectionBetweenDates(collectionDashBoardRequest, fromDate, toDate, null, serviceDetail,
            false);
    collectionDocumentDetails.setTodayColl(todayColl);

    // Last year Todays day collection
    todayColl = getCollectionBetweenDates(collectionDashBoardRequest,
            org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1),
            org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1), null, serviceDetail, false);
    collectionDocumentDetails.setLyTodayColl(todayColl);

    /**
     * For collections between the date ranges if dates are sent in the
     * request, consider the same, else calculate from current year start
     * date till current date+1 day
     */
    if (StringUtils.isNotBlank(collectionDashBoardRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDashBoardRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDashBoardRequest.getFromDate(), DATE_FORMAT_YYYYMMDD);
        toDate = org.apache.commons.lang3.time.DateUtils
                .addDays(DateUtils.getDate(collectionDashBoardRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1);
    } else {
        fromDate = DateUtils.startOfDay(financialYear.getStartingDate());
        toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1);
    }
    // Current Year till today collection
    tillDateColl = getCollectionBetweenDates(collectionDashBoardRequest, fromDate, toDate, null, serviceDetail,
            false);
    collectionDocumentDetails.setCytdColl(tillDateColl);

    // Last year till same date of todays date collection
    tillDateColl = getCollectionBetweenDates(collectionDashBoardRequest,
            org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1),
            org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1), null, serviceDetail, false);
    collectionDocumentDetails.setLytdColl(tillDateColl);
    if (collectionDocumentDetails.getLytdColl().compareTo(BigDecimal.ZERO) == 0)
        variance = CollectionConstants.BIGDECIMAL_100;
    else
        variance = collectionDocumentDetails.getCytdColl().subtract(collectionDocumentDetails.getLytdColl())
                .multiply(CollectionConstants.BIGDECIMAL_100)
                .divide(collectionDocumentDetails.getLytdColl(), 1, BigDecimal.ROUND_HALF_UP);
    collectionDocumentDetails.setLyVar(variance);
    final Long timeTaken = System.currentTimeMillis() - startTime;
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Time taken by getCompleteCollectionIndexDetails() is : " + timeTaken + MILLISECS);
    return collectionDocumentDetails;
}

From source file:org.kuali.kfs.fp.document.service.impl.BudgetAdjustmentLaborBenefitsServiceImpl.java

/**
 * Formats the stored percentage to be used in multiplication. For example if the percentage is 18.66 it will return 0.1866. The
 * returned number will always have 4 digits.
 *
 * @param percent the stored percent//from www.j  a v  a 2s .co m
 * @return percentage formatted for multiplication
 */
protected BigDecimal formatPercentageForMultiplication(KualiDecimal percent) {

    BigDecimal result = BigDecimal.ZERO;

    if (percent != null) {
        result = percent.bigDecimalValue().divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_UP);
    }

    return result;
}

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

@ApiOperation(value = "Aggregated version of /api/costEffectivenessTenderAmount and "
        + "/api/costEffectivenessAwardAmount."
        + "This endpoint aggregates the responses from the specified endpoints, per year. "
        + "Responds to the same filters.")
@RequestMapping(value = "/api/costEffectivenessTenderAwardAmount", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> costEffectivenessTenderAwardAmount(
        @ModelAttribute @Valid final GroupingFilterPagingRequest filter) {

    Future<List<DBObject>> costEffectivenessAwardAmountFuture = controllerLookupService.asyncInvoke(
            new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() {
                @Override//from  w w  w.j ava 2  s.c  o  m
                public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) {
                    return costEffectivenessAwardAmount(filter);
                }
            }, filter);

    Future<List<DBObject>> costEffectivenessTenderAmountFuture = controllerLookupService.asyncInvoke(
            new AsyncBeanParamControllerMethodCallable<List<DBObject>, GroupingFilterPagingRequest>() {
                @Override
                public List<DBObject> invokeControllerMethod(GroupingFilterPagingRequest filter) {
                    return costEffectivenessTenderAmount(filter);
                }
            }, filter);

    //this is completely unnecessary since the #get methods are blocking
    //controllerLookupService.waitTillDone(costEffectivenessAwardAmountFuture, costEffectivenessTenderAmountFuture);

    LinkedHashMap<Object, DBObject> response = new LinkedHashMap<>();

    try {

        costEffectivenessAwardAmountFuture.get()
                .forEach(dbobj -> response.put(getYearMonthlyKey(filter, dbobj), dbobj));
        costEffectivenessTenderAmountFuture.get().forEach(dbobj -> {
            if (response.containsKey(getYearMonthlyKey(filter, dbobj))) {
                Map<?, ?> map = dbobj.toMap();
                map.remove(Keys.YEAR);
                if (filter.getMonthly()) {
                    map.remove(Keys.MONTH);
                }
                response.get(getYearMonthlyKey(filter, dbobj)).putAll(map);
            } else {
                response.put(getYearMonthlyKey(filter, dbobj), dbobj);
            }
        });

    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    }

    Collection<DBObject> respCollection = response.values();

    respCollection.forEach(dbobj -> {

        BigDecimal totalTenderAmount = BigDecimal.valueOf(dbobj.get(Keys.TOTAL_TENDER_AMOUNT) == null ? 0d
                : ((Number) dbobj.get(Keys.TOTAL_TENDER_AMOUNT)).doubleValue());

        BigDecimal totalAwardAmount = BigDecimal.valueOf(dbobj.get(Keys.TOTAL_AWARD_AMOUNT) == null ? 0d
                : ((Number) dbobj.get(Keys.TOTAL_AWARD_AMOUNT)).doubleValue());

        dbobj.put(Keys.DIFF_TENDER_AWARD_AMOUNT, totalTenderAmount.subtract(totalAwardAmount));

        dbobj.put(Keys.PERCENTAGE_AWARD_AMOUNT,
                totalTenderAmount.compareTo(BigDecimal.ZERO) != 0
                        ? (totalAwardAmount.setScale(15).divide(totalTenderAmount, BigDecimal.ROUND_HALF_UP)
                                .multiply(ONE_HUNDRED))
                        : BigDecimal.ZERO);

        dbobj.put(Keys.PERCENTAGE_DIFF_AMOUNT,
                totalTenderAmount.compareTo(BigDecimal.ZERO) != 0
                        ? (((BigDecimal) dbobj.get(Keys.DIFF_TENDER_AWARD_AMOUNT)).setScale(15)
                                .divide(totalTenderAmount, BigDecimal.ROUND_HALF_UP).multiply(ONE_HUNDRED))
                        : BigDecimal.ZERO);

    });

    return new ArrayList<>(respCollection);
}

From source file:org.kuali.kfs.fp.document.service.impl.DisbursementVoucherTaxServiceImpl.java

/**
 * Generates an accounting line for the chart, account, object code & tax percentage values given.
 * //  w w w.  j a  v  a2  s. co m
 * @param document The disbursement voucher the tax will be applied to.
 * @param chart The chart code to be assigned to the accounting line generated.
 * @param account The account code to be assigned to the accounting line generated.
 * @param objectCode The object code used on the accounting line generated.
 * @param taxPercent The tax rate to be used to calculate the tax amount.
 * @param taxableAmount The total amount that is taxable.  This amount is used in conjunction with the tax percent
 *                      to calculate the amount for the accounting lined being generated.
 * @return A fully populated AccountingLine instance representing the amount of tax that will be applied to the 
 *         disbursement voucher provided.
 */
protected AccountingLine generateTaxAccountingLine(DisbursementVoucherDocument document, String chart,
        String account, String objectCode, KualiDecimal taxPercent, KualiDecimal taxableAmount) {
    AccountingLine taxLine = null;
    try {
        taxLine = (SourceAccountingLine) document.getSourceAccountingLineClass().newInstance();
    } catch (IllegalAccessException e) {
        throw new InfrastructureException("unable to access sourceAccountingLineClass", e);
    } catch (InstantiationException e) {
        throw new InfrastructureException("unable to instantiate sourceAccountingLineClass", e);
    }

    taxLine.setDocumentNumber(document.getDocumentNumber());
    taxLine.setSequenceNumber(document.getNextSourceLineNumber());
    taxLine.setChartOfAccountsCode(chart);
    taxLine.setAccountNumber(account);
    taxLine.setFinancialObjectCode(objectCode);

    // calculate tax amount and set as line amount
    BigDecimal amount = taxableAmount.bigDecimalValue();
    BigDecimal tax = taxPercent.bigDecimalValue();
    BigDecimal taxDecimal = tax.divide(new BigDecimal(100), 5, BigDecimal.ROUND_HALF_UP);
    KualiDecimal taxAmount = new KualiDecimal(
            amount.multiply(taxDecimal).setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR));
    taxLine.setAmount(taxAmount.negated());

    return taxLine;
}

From source file:com.exilant.eGov.src.common.EGovernCommon.java

public BigDecimal getAccountBalance(final Date VoucherDate, final String bankAccountId)
        throws TaskFailedException {
    BigDecimal totalAvailable = BigDecimal.ZERO;
    BigDecimal opeAvailable = BigDecimal.ZERO;
    Query pst = null;//from w ww.j a  v  a 2s  .  com
    List<Object[]> resultset = null;
    List<Object[]> resultset1 = null;
    try {
        final SimpleDateFormat formatter = dtFormat;
        final String vcDate = formatter.format(VoucherDate);

        final String str = "SELECT case when sum(openingDebitBalance) = null then 0 else sum(openingDebitBalance) end-  case when sum(openingCreditBalance) = null  then 0 else sum(openingCreditBalance) end AS \"openingBalance\" "
                + "FROM transactionSummary WHERE financialYearId=( SELECT id FROM financialYear WHERE startingDate <=?"
                + "AND endingDate >= ?)  AND glCodeId =(select glcodeid from bankaccount where id=?)";
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("getAccountBalance(EGovernCommon.java): " + str);
        pst = persistenceService.getSession().createSQLQuery(str);
        pst.setString(0, vcDate);
        pst.setString(1, vcDate);
        pst.setString(2, bankAccountId);
        resultset = pst.list();
        for (final Object[] element : resultset)
            opeAvailable = new BigDecimal(element[0].toString());
        if (resultset == null || resultset.size() == 0)
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Else resultset in getbalance");

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("opening balance  " + opeAvailable);
        // resultset.close();

        final String str1 = "SELECT (case when sum(gl.debitAmount) = null then 0 else sum(gl.debitAmount) end) - (case when sum(gl.creditAmount) = null then 0 else sum(gl.creditAmount) end) + "
                + opeAvailable
                + " as \"totalAmount\" FROM   generalLedger gl, voucherHeader vh WHERE vh.id = gl.voucherHeaderId AND gl.glCodeid = (select glcodeid from bankaccount where id=?) AND  "
                + " vh.voucherDate >=( SELECT TO_CHAR(startingDate, 'dd-Mon-yyyy') FROM financialYear WHERE startingDate <= ? AND endingDate >= ?) AND vh.voucherDate <= ? and vh.status!=4";

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Curr Yr Bal: " + str1);
        pst = persistenceService.getSession().createSQLQuery(str1);
        pst.setString(0, bankAccountId);
        pst.setString(1, vcDate);
        pst.setString(2, vcDate);
        pst.setString(3, vcDate);
        resultset1 = pst.list();
        for (final Object[] element : resultset1) {
            totalAvailable = new BigDecimal(element[0].toString());
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("total balance  " + totalAvailable);
        }
        if (resultset1 == null || resultset1.size() == 0)
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Else resultset in getbalance...");

        totalAvailable = totalAvailable.setScale(2, BigDecimal.ROUND_HALF_UP);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("total balance before return " + totalAvailable);

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw taskExc;
    }
    return totalAvailable;
}