Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFJNumberEditor.java

public void setMaxValue(BigDecimal value) {
    final String S_ProcName = "setMaxValue";
    if (value == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1, "value");
    }/*from  ww  w . j av  a 2 s  .c om*/
    BigDecimal absoluteMaxValue = getAbsoluteMaxValue();
    if (value.compareTo(absoluteMaxValue) > 0) {
        throw CFLib.getDefaultExceptionFactory().newArgumentOverflowException(getClass(), S_ProcName, 1,
                "value", value, absoluteMaxValue);
    }
    maxValue = value;
}

From source file:och.comp.billing.standalone.BillingSyncService.java

private List<SyncPayError> syncUserAccs(long userId, Set<ChatAccount> userAccs, Map<Long, Tariff> tariffs,
        Date curMonthStart, Date now) throws ConcurrentUpdateSqlException, Exception {

    List<SyncPayError> errors = new ArrayList<>();
    BigDecimal totalPrice = ZERO;
    Date lastMonthStart = addMonths(curMonthStart, -1);
    Date lastMonthEnd = monthEnd(lastMonthStart);

    ArrayList<ChatAccount> accsToUpdate = new ArrayList<>();
    for (ChatAccount acc : userAccs) {
        if (isNeedToPay(acc, curMonthStart)) {
            Tariff tariff = tariffs.get(acc.tariffId);
            if (tariff == null) {
                errors.add(new SyncPayError(userId, singleton(acc),
                        new IllegalStateException("can't find tariff")));
                continue;
            }/*  w ww  .j a  v  a 2s.co m*/

            accsToUpdate.add(acc);

            BigDecimal price = tariff.price;
            if (price.compareTo(ZERO) < 1)
                continue;

            //?  ?? -  ,  ?  
            BigDecimal accAmount;
            Date oldPayDate = acc.tariffLastPay;
            if (oldPayDate.compareTo(lastMonthStart) == 0)
                accAmount = price;
            else
                accAmount = calcForPeriod(price, oldPayDate, lastMonthEnd, ZERO);

            totalPrice = totalPrice.add(accAmount);
        }
    }

    //final amount
    BigDecimal amount = totalPrice;
    boolean hasBill = ZERO.compareTo(amount) != 0;
    BigDecimal[] updatedBalance = { null };
    BigDecimal minActiveBalance = props.getBigDecimalVal(billing_minActiveBalance);
    boolean[] accBlocked = { false };

    //update db
    doInSingleTxMode(() -> {

        boolean isBlocked = findBalance(universal, userId).accsBlocked;

        //bill
        if (!isBlocked && hasBill) {

            long payId = universal.nextSeqFor(payments);
            PaymentExt payment = createSystemBill(payId, userId, amount, now, TARIFF_MONTH_BIll,
                    collectionToStr(accsToUpdate));
            universal.update(new CreatePayment(payment));

            updatedBalance[0] = appendBalance(universal, userId, payment.amount);

            //? ? ?     
            if (updatedBalance[0].compareTo(minActiveBalance) < 0) {
                accBlocked[0] = true;
                universal.update(new UpdateUserAccsBlocked(userId, true));
            }

        }

        //update last pay dates
        if (accsToUpdate.size() > 0) {
            for (ChatAccount acc : accsToUpdate) {
                int result = universal.updateOne(new UpdateChatAccountByUid(acc.uid, acc.tariffLastPay,
                        new TariffLastPay(curMonthStart)));
                //concurrent check
                if (result == 0)
                    throw new ConcurrentUpdateSqlException("UpdateChatAccountByUid: uid=" + acc.uid);
            }
        }

    });

    //update cache
    if (updatedBalance[0] != null) {
        cache.tryPutCache(getBalanceCacheKey(userId), updatedBalance[0].toString());
    }

    //update chat servers
    if (accBlocked[0]) {
        sendAccsBlocked(props, db, cache, userId, true);
    }

    return errors;

}

From source file:org.stockwatcher.data.cassandra.DailySummaryGenerator.java

private List<ResultSetFuture> processTradesForSymbol(List<ResultSetFuture> selectFutures) {
    List<ResultSetFuture> insertFutures = new ArrayList<ResultSetFuture>();
    for (ResultSetFuture future : selectFutures) {
        String symbol = null;//  w  w  w  .  j a  v a 2  s.c  o m
        Date tradeDate = null;
        BigDecimal open = BigDecimal.ZERO;
        BigDecimal high = BigDecimal.ZERO;
        BigDecimal low = BigDecimal.valueOf(Long.MAX_VALUE);
        BigDecimal close = BigDecimal.ZERO;
        BigDecimal sharePrice = null;
        int volume = 0;
        for (Row row : future.getUninterruptibly()) {
            if (symbol == null) {
                symbol = row.getString("stock_symbol");
                tradeDate = row.getDate("trade_date");
                open = row.getDecimal("share_price");
                LOGGER.debug("Processing trades for symbol {} on {}", symbol, tradeDate);
            }
            sharePrice = row.getDecimal("share_price");
            if (sharePrice.compareTo(high) > 0) {
                high = sharePrice;
            }
            if (sharePrice.compareTo(low) < 0) {
                low = sharePrice;
            }
            close = sharePrice;
            volume += row.getInt("share_quantity");
        }
        if (volume > 0) {
            insertFutures.add(insert(symbol, tradeDate, open, high, low, close, volume));
        }
    }
    selectFutures.clear();
    return insertFutures;
}

From source file:hydrograph.ui.propertywindow.widgets.utility.SchemaRowValidation.java

private boolean checkIfSchemaRangeAndLengethIsInvalid(BigDecimal rangeFrom, int fieldLength, BigDecimal rangeTo,
        BigDecimal minRangeValue, BigDecimal maxRangeValue) {
    if (rangeFrom != null && fieldLength > 0 && rangeTo != null) {
        if (rangeFrom.compareTo(minRangeValue) < 0) {
            return true;
        } else if (rangeTo.compareTo(maxRangeValue) > 0) {
            return true;
        }/*  w  w w  . j a  v a2  s . c  o m*/
    } else if (rangeFrom != null && fieldLength > 0 && rangeTo == null) {
        if (rangeFrom.compareTo(maxRangeValue) > 0) {
            return true;
        }
    } else if (rangeFrom == null && fieldLength > 0 && rangeTo != null) {
        if (rangeTo.compareTo(minRangeValue) < 0) {
            return true;
        }
    }
    return false;
}

From source file:es.tid.fiware.rss.expenditureLimit.server.service.ExpenditureLimitDataChecker.java

/**
 * /*from ww w  . j  av a2 s  .c  om*/
 * @param urlEndUserId
 * @param appPorviderId
 * @param currency
 * @throws RSSException
 */
public void checkChargeRequiredParameters(String urlEndUserId, String service, String appPorviderId,
        String currency, String chargeType, BigDecimal amount) throws RSSException {

    if (null == urlEndUserId || urlEndUserId.length() == 0 || null == service || service.length() == 0
            || null == appPorviderId || appPorviderId.length() == 0 || null == currency
            || currency.length() == 0 || null == chargeType || chargeType.length() == 0 || null == amount
            || amount.compareTo(new BigDecimal(0)) < 1) {
        String[] args = {
                "Required parameters not found:enUserId, service, appProvider, currency, chargeType, amount." };
        throw new RSSException(UNICAExceptionType.NON_EXISTENT_RESOURCE_ID, args);
    }

}

From source file:com.osafe.events.CheckOutEvents.java

public static String setShipGroups(HttpServletRequest request, HttpServletResponse response) {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Locale locale = UtilHttp.getLocale(request);
    ShoppingCart shoppingCart = ShoppingCartEvents.getCartObject(request);
    String sItemTotalQty = request.getParameter("itemTotalQuantity");
    String sNumberOfItems = request.getParameter("numberOfItems");
    int iNumberOfItems = Integer.valueOf(sNumberOfItems);
    int iItemTotalQty = 0;
    BigDecimal bcartItemTotalQty = shoppingCart.getTotalQuantity();
    Map shippingContactMechMap = FastMap.newInstance();
    Map cartLineShippingContactMechQtyMap = FastMap.newInstance();
    Map cartLineShippingContactMechGiftMsgMap = FastMap.newInstance();
    Map cartLineQtyMap = FastMap.newInstance();
    Map cartLineProductInfoMap = FastMap.newInstance();
    Map cartItemQtyMap = FastMap.newInstance();
    List<MessageString> error_list = new ArrayList<MessageString>();
    MessageString messageString = null;//from  w w w . j  ava 2 s . co  m
    String message = null;
    if (UtilValidate.isNotEmpty(sItemTotalQty)) {
        iItemTotalQty = Integer.valueOf(sItemTotalQty).intValue();
    }

    /* Build quantity-product maps based on items on page */
    for (int i = 0; i < iItemTotalQty; i++) {
        String shippingContactMechId = request.getParameter("shippingContactMechId_" + i);
        String sCartLineIndex = request.getParameter("cartLineIndex_" + i);
        int iCartLineIndex = Integer.valueOf(sCartLineIndex).intValue();

        String qtyInCart = request.getParameter("qtyInCart_" + i);
        String productName = request.getParameter("productName_" + i);
        String productId = request.getParameter("productId_" + i);
        String productCategoryId = request.getParameter("productCategoryId_" + i);
        String prodCatalogId = request.getParameter("prodCatelogId_" + i);
        String unitPrice = request.getParameter("unitPrice_" + i);
        Map productInfoMap = FastMap.newInstance();
        productInfoMap.put("productName", productName);
        productInfoMap.put("productId", productId);
        productInfoMap.put("productCategoryId", productCategoryId);
        productInfoMap.put("prodCatalogId", prodCatalogId);
        productInfoMap.put("unitPrice", unitPrice);
        String giftMsgFrom = request.getParameter("lineItemGiftFrom_" + i);
        String giftMsgTo = request.getParameter("lineItemGiftTo_" + i);
        String giftMsg = request.getParameter("lineItemGiftMsg_" + i);
        Map giftMessageInfoMap = FastMap.newInstance();
        if (UtilValidate.isNotEmpty(giftMsgFrom)) {
            giftMessageInfoMap.put("from", giftMsgFrom);
        }
        if (UtilValidate.isNotEmpty(giftMsgTo)) {
            giftMessageInfoMap.put("to", giftMsgTo);
        }
        if (UtilValidate.isNotEmpty(giftMsg)) {
            giftMessageInfoMap.put("msg", giftMsg);
        }
        BigDecimal bLineQty = BigDecimal.ZERO;
        BigDecimal bShipQty = BigDecimal.ZERO;
        BigDecimal bCartQty = BigDecimal.ZERO;
        try {
            if (UtilValidate.isNotEmpty(qtyInCart)) {
                Double dQty = Double.valueOf(qtyInCart);
                if (UtilValidate.isInteger(qtyInCart) && dQty >= 0) {
                    bLineQty = BigDecimal.valueOf(dQty.doubleValue());
                } else {
                    bLineQty = BigDecimal.ZERO;
                    message = OSAFE_UI_LABELS.getString("PDPQtyDecimalNumberError");
                    message = StringUtil.replaceString(message, "_PRODUCT_NAME_", productName);
                    messageString = new MessageString(message, "qtyInCart_" + i, true);
                    error_list.add(messageString);

                }
            }
        } catch (Exception e) {
            bLineQty = BigDecimal.ZERO;
            message = OSAFE_UI_LABELS.getString("PDPQtyDecimalNumberError");
            message = StringUtil.replaceString(message, "_PRODUCT_NAME_", productName);
            messageString = new MessageString(message, "qtyInCart_" + i, true);
            error_list.add(messageString);

        }
        shippingContactMechMap.put(shippingContactMechId, shippingContactMechId);

        if (cartLineShippingContactMechQtyMap.containsKey(sCartLineIndex + "_" + shippingContactMechId)) {
            BigDecimal bTempQty = (BigDecimal) cartLineShippingContactMechQtyMap
                    .get(sCartLineIndex + "_" + shippingContactMechId);
            bShipQty = bShipQty.add(bTempQty);
        }
        bShipQty = bShipQty.add(bLineQty);
        cartLineShippingContactMechQtyMap.put(sCartLineIndex + "_" + shippingContactMechId, bShipQty);

        if (UtilValidate.isNotEmpty(giftMessageInfoMap)) {
            List lGiftMsg = null;
            if (cartLineShippingContactMechGiftMsgMap
                    .containsKey(sCartLineIndex + "_" + shippingContactMechId)) {
                lGiftMsg = (List) cartLineShippingContactMechGiftMsgMap
                        .get(sCartLineIndex + "_" + shippingContactMechId);
            } else {
                lGiftMsg = FastList.newInstance();
            }
            lGiftMsg.add(giftMessageInfoMap);
            cartLineShippingContactMechGiftMsgMap.put(sCartLineIndex + "_" + shippingContactMechId, lGiftMsg);
        }

        if (cartLineQtyMap.containsKey(sCartLineIndex)) {
            BigDecimal bTempQty = (BigDecimal) cartLineQtyMap.get(sCartLineIndex);
            bCartQty = bCartQty.add(bTempQty);
        }
        bCartQty = bCartQty.add(bLineQty);
        cartLineQtyMap.put(sCartLineIndex, bCartQty);
        cartLineProductInfoMap.put(sCartLineIndex, productInfoMap);
    }

    /* Validate Quantities entered */
    if (UtilValidate.isNotEmpty(cartLineQtyMap)) {
        try {

            String pdpQtyMin = Util.getProductStoreParm(request, "PDP_QTY_MIN");
            if (UtilValidate.isEmpty(pdpQtyMin)) {
                pdpQtyMin = "1";
            }
            String pdpQtyMax = Util.getProductStoreParm(request, "PDP_QTY_MAX");
            if (UtilValidate.isEmpty(pdpQtyMax)) {
                pdpQtyMax = "99";
            }
            BigDecimal bPdpQtyMin = BigDecimal.valueOf(Double.valueOf(pdpQtyMin).doubleValue());
            BigDecimal bPdpQtyMax = BigDecimal.valueOf(Double.valueOf(pdpQtyMax).doubleValue());

            Iterator<String> cartItemIter = cartLineQtyMap.keySet().iterator();
            while (cartItemIter.hasNext()) {
                String sCartLineIndex = cartItemIter.next();
                BigDecimal bChangeQty = (BigDecimal) cartLineQtyMap.get(sCartLineIndex);
                if (bChangeQty.compareTo(BigDecimal.ZERO) == 0) {
                    continue;
                }
                int iCartLineIndex = Integer.valueOf(sCartLineIndex).intValue();
                Map productInfoMap = (Map) cartLineProductInfoMap.get(sCartLineIndex);
                GenericValue prodPdpQtyMin = delegator.findOne("ProductAttribute",
                        UtilMisc.toMap("productId", productInfoMap.get("productId"), "attrName", "PDP_QTY_MIN"),
                        true);
                GenericValue prodPdpQtyMax = delegator.findOne("ProductAttribute",
                        UtilMisc.toMap("productId", productInfoMap.get("productId"), "attrName", "PDP_QTY_MAX"),
                        true);
                if (UtilValidate.isNotEmpty(prodPdpQtyMin) && UtilValidate.isNotEmpty(prodPdpQtyMax)) {
                    bPdpQtyMin = BigDecimal
                            .valueOf(Double.valueOf(prodPdpQtyMin.getString("attrValue")).doubleValue());
                    bPdpQtyMax = BigDecimal
                            .valueOf(Double.valueOf(prodPdpQtyMax.getString("attrValue")).doubleValue());
                }
                if (bChangeQty.compareTo(bPdpQtyMin) < 0) {
                    message = OSAFE_UI_LABELS.getString("PDPMinQtyError");
                    message = StringUtil.replaceString(message, "_PRODUCT_NAME_",
                            "" + productInfoMap.get("productName"));
                    message = StringUtil.replaceString(message, "_PDP_QTY_MIN_", "" + bPdpQtyMin.intValue());
                    messageString = new MessageString(message, "qtyInCart_" + sCartLineIndex, true);
                    error_list.add(messageString);

                }
                if (bChangeQty.compareTo(bPdpQtyMax) > 0) {
                    message = OSAFE_UI_LABELS.getString("PDPMaxQtyError");
                    message = StringUtil.replaceString(message, "_PRODUCT_NAME_",
                            "" + productInfoMap.get("productName"));
                    message = StringUtil.replaceString(message, "_PDP_QTY_MAX_", "" + bPdpQtyMax.intValue());
                    messageString = new MessageString(message, "qtyInCart_" + sCartLineIndex, true);
                    error_list.add(messageString);

                }

            }
        } catch (Exception e) {
            Debug.logError(e, "Error: updating cart quantity", module);
        }

    }
    if (error_list.size() != 0) {
        request.setAttribute("_ERROR_MESSAGE_LIST_", error_list);
        return "error";
    }
    /* Check the number of items passed from the screen matches the number of items in the cart.
     * If the number of items has changed remove all products from the cart and add back.
     * If the number of items have not changed remove zero quantities and set changed item quantities
     * The number of item check is essentially protecting against the usage of the back button.
     */
    if (UtilValidate.isNotEmpty(cartLineQtyMap)) {
        if (shoppingCart.items().size() != iNumberOfItems) {
            ShoppingCartItem shoppingCartItem = null;
            try {
                Iterator<ShoppingCartItem> cartItemIter = shoppingCart.items().iterator();
                while (cartItemIter.hasNext()) {
                    shoppingCartItem = (ShoppingCartItem) cartItemIter.next();
                    shoppingCart.removeCartItem(shoppingCartItem, dispatcher);
                }

                Iterator<String> cartLineItemIter = cartLineQtyMap.keySet().iterator();
                while (cartLineItemIter.hasNext()) {
                    String sCartLineIndex = cartLineItemIter.next();
                    BigDecimal bChangeQty = (BigDecimal) cartLineQtyMap.get(sCartLineIndex);
                    if (bChangeQty.compareTo(BigDecimal.ZERO) == 0) {
                        continue;
                    }
                    Map productInfoMap = (Map) cartLineProductInfoMap.get(sCartLineIndex);
                    String unitPrice = (String) productInfoMap.get("unitPrice");
                    BigDecimal bUnitPrice = null;
                    if (UtilValidate.isNotEmpty(unitPrice)) {
                        bUnitPrice = BigDecimal.valueOf(Double.valueOf(unitPrice).doubleValue());
                    }
                    if (UtilValidate.isEmpty(bUnitPrice)) {
                        message = OSAFE_UI_LABELS.getString("PDPMaxQtyError");
                        error_list.add(messageString);
                        request.setAttribute("_ERROR_MESSAGE_LIST_", error_list);
                        return "error";

                    }

                    ShoppingCartItem item = ShoppingCartItem.makeItem(null,
                            "" + productInfoMap.get("productId"), null, bChangeQty, bUnitPrice, null, null,
                            null, null, null, null, null, null, null, "" + productInfoMap.get("prodCatelogId"),
                            null, null, null, dispatcher, shoppingCart, Boolean.TRUE, Boolean.FALSE,
                            "" + productInfoMap.get("parentProductId"), Boolean.TRUE, Boolean.TRUE);
                    shoppingCart.addItemToEnd(item);
                    com.osafe.events.ShoppingCartEvents.setProductFeaturesOnCart(shoppingCart,
                            "" + productInfoMap.get("productId"));

                }

            } catch (Exception e) {
                Debug.logError("Error: removing cart item" + shoppingCartItem, module);
            }

        } else {
            try {

                Iterator<String> cartItemIter = cartLineQtyMap.keySet().iterator();
                while (cartItemIter.hasNext()) {
                    String sCartLineIndex = cartItemIter.next();
                    BigDecimal bChangeQty = (BigDecimal) cartLineQtyMap.get(sCartLineIndex);
                    int iCartLineIndex = Integer.valueOf(sCartLineIndex).intValue();
                    ShoppingCartItem shoppingCartItem = shoppingCart.findCartItem(iCartLineIndex);
                    if (bChangeQty.compareTo(BigDecimal.ZERO) == 0) {
                        shoppingCart.removeCartItem(shoppingCartItem, dispatcher);
                        continue;
                    }
                    if (bChangeQty.compareTo(shoppingCartItem.getQuantity()) != 0) {
                        shoppingCartItem.setQuantity(bChangeQty, dispatcher, shoppingCart);
                    }

                }
            } catch (Exception e) {
                Debug.logError("Error: updating cart quantity", module);
            }

        }

    }

    if (UtilValidate.isNotEmpty(shoppingCart.items())) {
        Iterator<ShoppingCartItem> cartItemIter = shoppingCart.items().iterator();
        int iItemIndex = 0;
        while (cartItemIter.hasNext()) {
            ShoppingCartItem shoppingCartItem = (ShoppingCartItem) cartItemIter.next();
            BigDecimal itemQuantity = shoppingCartItem.getQuantity();
            cartItemQtyMap.put("" + iItemIndex, itemQuantity);
            iItemIndex++;

            /* Clear Gift Messages per item.  Will be Reset
             * 
             */
            Map<String, String> orderItemAttributesMap = shoppingCartItem.getOrderItemAttributes();
            if (UtilValidate.isNotEmpty(orderItemAttributesMap)) {
                for (Entry<String, String> itemAttr : orderItemAttributesMap.entrySet()) {
                    String sAttrName = (String) itemAttr.getKey();
                    if (sAttrName.startsWith("GIFT_MSG_FROM_")) {
                        shoppingCartItem.removeOrderItemAttribute(sAttrName);

                    }
                    if (sAttrName.startsWith("GIFT_MSG_TO_")) {
                        shoppingCartItem.removeOrderItemAttribute(sAttrName);

                    }
                    if (sAttrName.startsWith("GIFT_MSG_TEXT_")) {
                        shoppingCartItem.removeOrderItemAttribute(sAttrName);

                    }

                }
            }
        }
    } else {
        return "emptyCart";

    }
    /* Clear item Ship Groups and create new ones */
    if (UtilValidate.isNotEmpty(shippingContactMechMap)) {
        Iterator<ShoppingCartItem> cartItemIter = shoppingCart.items().iterator();
        while (cartItemIter.hasNext()) {
            shoppingCart.clearItemShipInfo(cartItemIter.next());

        }
        shoppingCart.cleanUpShipGroups();

        Iterator<String> shipGroupIter = shippingContactMechMap.keySet().iterator();
        while (shipGroupIter.hasNext()) {
            int shipGroupIndex = shoppingCart.addShipInfo();
            String shippingContactMechId = shipGroupIter.next();
            shoppingCart.setShippingContactMechId(shipGroupIndex, shippingContactMechId);
            shippingContactMechMap.put(shippingContactMechId, Integer.valueOf(shipGroupIndex));

        }

    }

    if (UtilValidate.isNotEmpty(cartLineShippingContactMechQtyMap)) {
        Map<ShoppingCartItem, String> cartItemMessageCount = FastMap.newInstance();
        Iterator<String> cartLineShippingQtyIter = cartLineShippingContactMechQtyMap.keySet().iterator();
        while (cartLineShippingQtyIter.hasNext()) {
            String cartLineShippingContactMechKey = cartLineShippingQtyIter.next();
            int iKeySeparator = cartLineShippingContactMechKey.indexOf('_');

            String sCartLineIndex = cartLineShippingContactMechKey.substring(0, iKeySeparator);
            int iCartLineIndex = Integer.valueOf(sCartLineIndex);
            int iItemGiftMsgCount = 0;

            String shippingContactMechId = cartLineShippingContactMechKey.substring(iKeySeparator + 1);

            BigDecimal bShipQty = (BigDecimal) cartLineShippingContactMechQtyMap
                    .get(cartLineShippingContactMechKey);
            BigDecimal bCartItemQty = (BigDecimal) cartItemQtyMap.get(sCartLineIndex);
            BigDecimal bCartQty = BigDecimal.ZERO;
            if (UtilValidate.isNotEmpty(bCartItemQty)) {
                bCartQty = bCartItemQty;
            }
            BigDecimal bTotalShipGroupQty = BigDecimal.ZERO;
            BigDecimal bAddShipQty = BigDecimal.ZERO;

            if (bShipQty.compareTo(BigDecimal.ZERO) > 0) {
                Map shipGroupQtyMap = shoppingCart.getShipGroups(iCartLineIndex);
                Iterator shipGroupQtyIter = shipGroupQtyMap.keySet().iterator();
                while (shipGroupQtyIter.hasNext()) {
                    BigDecimal bShipGroupQty = (BigDecimal) shipGroupQtyMap.get(shipGroupQtyIter.next());
                    bTotalShipGroupQty = bTotalShipGroupQty.add(bShipGroupQty);
                }
                /* Total quantity designated to Ship has already been met */
                if (bTotalShipGroupQty.compareTo(bCartQty) == 0) {
                    continue;
                }
                /* If the ship quantity is greater than the quantity in the cart, set the ship quantity equal to cart quantity. */
                if (bShipQty.compareTo(bCartQty) > 0) {
                    bShipQty = bCartQty;
                }
                /* Add the Ship quantity to total ship quantity, If greater set the ship quantity to the quantity left that can be shipped
                 * (cart quantity minus total ship quantity) */
                bAddShipQty = bShipQty.add(bTotalShipGroupQty);
                if (bAddShipQty.compareTo(bCartQty) > 0) {
                    bShipQty = bCartQty.subtract(bTotalShipGroupQty);
                }
                if (bShipQty.compareTo(BigDecimal.ZERO) > 0) {
                    int shipGroupIndex = ((Integer) shippingContactMechMap.get(shippingContactMechId))
                            .intValue();
                    shoppingCart.setItemShipGroupQty(iCartLineIndex, bShipQty, shipGroupIndex);
                    /* Check Cart item Gift Messages going to this Ship Group (Address)
                     * 
                     */
                    List lGiftMsg = (List) cartLineShippingContactMechGiftMsgMap
                            .get(cartLineShippingContactMechKey);
                    if (UtilValidate.isNotEmpty(lGiftMsg)) {
                        ShoppingCartItem cartItem = shoppingCart.findCartItem(iCartLineIndex);
                        for (int i = 0; i < lGiftMsg.size(); i++) {
                            if (i > bShipQty.intValue()) {
                                break;
                            }
                            String sItemGiftMsgCount = (String) cartItemMessageCount.get(cartItem);
                            if (UtilValidate.isEmpty(sItemGiftMsgCount)) {
                                iItemGiftMsgCount = 1;
                            } else {
                                iItemGiftMsgCount = Integer.valueOf(sItemGiftMsgCount);
                                iItemGiftMsgCount++;

                            }

                            sItemGiftMsgCount = "" + iItemGiftMsgCount;
                            cartItemMessageCount.put(cartItem, sItemGiftMsgCount);

                            Map giftMsgMap = (Map) lGiftMsg.get(i);
                            String msgFrom = (String) giftMsgMap.get("from");
                            if (UtilValidate.isNotEmpty(msgFrom)) {
                                cartItem.setOrderItemAttribute(
                                        "GIFT_MSG_FROM_" + sItemGiftMsgCount + "_" + (shipGroupIndex + 1),
                                        msgFrom);

                            }
                            String msgTo = (String) giftMsgMap.get("to");
                            if (UtilValidate.isNotEmpty(msgTo)) {
                                cartItem.setOrderItemAttribute(
                                        "GIFT_MSG_TO_" + sItemGiftMsgCount + "_" + (shipGroupIndex + 1), msgTo);

                            }
                            String msg = (String) giftMsgMap.get("msg");
                            if (UtilValidate.isNotEmpty(msg)) {
                                cartItem.setOrderItemAttribute(
                                        "GIFT_MSG_TEXT_" + sItemGiftMsgCount + "_" + (shipGroupIndex + 1), msg);

                            }

                        }
                    }
                }

            }

        }

        /* Now check all quantities of each cart items have been assigned to a ship group
         * If not calculate and add the missing quantity to the last ship group defined for the item
         * */
        Iterator<ShoppingCartItem> cartItemIter = shoppingCart.items().iterator();
        while (cartItemIter.hasNext()) {
            ShoppingCartItem shoppingCartItem = (ShoppingCartItem) cartItemIter.next();

            BigDecimal bTotalShipGroupQty = BigDecimal.ZERO;
            BigDecimal bCartQty = shoppingCartItem.getQuantity();
            BigDecimal bShipGroupQty = BigDecimal.ZERO;
            int iShipGroupIndex = 0;

            Map shipGroupQtyMap = shoppingCart.getShipGroups(shoppingCartItem);
            Iterator shipGroupQtyIter = shipGroupQtyMap.keySet().iterator();
            while (shipGroupQtyIter.hasNext()) {
                iShipGroupIndex = Integer.valueOf(shipGroupQtyIter.next().toString());
                bShipGroupQty = (BigDecimal) shipGroupQtyMap.get(iShipGroupIndex);
                bTotalShipGroupQty = bTotalShipGroupQty.add(bShipGroupQty);

            }

            if (bTotalShipGroupQty.compareTo(bCartQty) < 0) {
                BigDecimal bAddShipQty = bCartQty.subtract(bTotalShipGroupQty);
                bAddShipQty = bAddShipQty.add(bShipGroupQty);

                shoppingCart.setItemShipGroupQty(shoppingCartItem, bAddShipQty, iShipGroupIndex);
            }
        }

        /* Clean up ship groups, if no quantities in group the group is removed.
         * If not calculate and add the missing quantity to the last ship group defined for the item
         * */
        shoppingCart.cleanUpShipGroups();

        /* Check ship group with multiple items, if more than one item in the group check
         * the shipping options available for each item,; if different count the group is split. 
         * */

        splitShipGroupByShipOptions(request, response);

    }

    return "success";
}

From source file:com.impetus.kundera.validation.rules.AttributeConstraintRule.java

/**
 * Checks whether a given value is a valid maximum decimal digit when compared to given value 
 * or not/*from   w w w  .  jav  a  2s .  co m*/
 * 
 * @param validationObject
 * @param annotate
 * @return
 */
private boolean validateMaxDecimal(Object validationObject, Annotation annotate) {
    if (validationObject != null) {
        try {
            if (checkvalidDeciDigitTypes(validationObject.getClass())) {
                BigDecimal maxValue = NumberUtils.createBigDecimal(((DecimalMax) annotate).value());
                BigDecimal actualValue = NumberUtils.createBigDecimal(toString(validationObject));
                int res = actualValue.compareTo(maxValue);
                if (res > 0) {
                    throwValidationException(((DecimalMax) annotate).message());
                }

            }
        } catch (NumberFormatException nfe) {
            throw new RuleValidationException(nfe.getMessage());
        }

    }
    return true;
}

From source file:com.impetus.kundera.validation.rules.AttributeConstraintRule.java

/**
 * Checks whether a given value is a valid minimum decimal digit when compared to given value 
 * or not/*from w  ww . j  av a  2 s .c  o  m*/
 * 
 * @param validationObject
 * @param annotate
 * @return
 */
private boolean validateMinDecimal(Object validationObject, Annotation annotate) {

    if (validationObject != null) {
        try {
            if (checkvalidDeciDigitTypes(validationObject.getClass())) {
                BigDecimal minValue = NumberUtils.createBigDecimal(((DecimalMin) annotate).value());
                BigDecimal actualValue = NumberUtils.createBigDecimal(toString(validationObject));
                int res = actualValue.compareTo(minValue);
                if (res < 0) {
                    throwValidationException(((DecimalMin) annotate).message());
                }

            }
        } catch (NumberFormatException nfe) {
            throw new RuleValidationException(nfe.getMessage());
        }

    }

    return true;
}

From source file:com.aoindustries.creditcards.TransactionRequest.java

/**
 * Sets the tax amount of the transaction.
 *
 * The amount is normalized to the proper number of decimal places for the selected currency.
 *
 * @throws  IllegalArgumentException  if taxAmount < 0 or is incorrectly formatted for the currency.
 *///from  ww  w.  java 2 s.co m
public void setTaxAmount(BigDecimal taxAmount) {
    if (taxAmount == null) {
        this.taxAmount = null;
    } else {
        if (taxAmount.compareTo(BigDecimal.ZERO) < 0)
            throw new LocalizedIllegalArgumentException(accessor,
                    "TransactionRequest.setTaxAmount.taxAmount.lessThanZero");
        try {
            this.taxAmount = taxAmount.setScale(currency.getDefaultFractionDigits());
        } catch (ArithmeticException err) {
            throw new LocalizedIllegalArgumentException(err, accessor,
                    "TransactionRequest.setTaxAmount.taxAmount.cannotNormalize");
        }
    }
}

From source file:com.aoindustries.creditcards.TransactionRequest.java

/**
 * Sets the duty charges of the transaction.
 *
 * The amount is normalized to the proper number of decimal places for the selected currency.
 *
 * @throws  IllegalArgumentException  if dutyAmount < 0 or is incorrectly formatted for the currency.
 *///from   w ww . j a va  2 s  .c  om
public void setDutyAmount(BigDecimal dutyAmount) {
    if (dutyAmount == null) {
        this.dutyAmount = null;
    } else {
        if (dutyAmount.compareTo(BigDecimal.ZERO) < 0)
            throw new LocalizedIllegalArgumentException(accessor,
                    "TransactionRequest.setDutyAmount.dutyAmount.lessThanZero");
        try {
            this.dutyAmount = dutyAmount.setScale(currency.getDefaultFractionDigits());
        } catch (ArithmeticException err) {
            throw new LocalizedIllegalArgumentException(err, accessor,
                    "TransactionRequest.setDutyAmount.dutyAmount.cannotNormalize");
        }
    }
}