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:com.dp2345.entity.Cart.java

/**
 * ??/*from w w w . ja va  2s.c  o  m*/
 * 
 * @return ?
 */
@Transient
public BigDecimal getEffectivePrice() {
    BigDecimal effectivePrice = getPrice().subtract(getDiscount());
    return effectivePrice.compareTo(new BigDecimal(0)) > 0 ? effectivePrice : new BigDecimal(0);
}

From source file:com.opensky.osis.BraintreeConnector.java

/**
 * Clone a transaction/*from w  w w. j  ava2s .co  m*/
 * 
 * TODO Should amount be optional?
 *
 * {@sample.xml ../../../doc/braintree-connector.xml.sample braintree:clone-transaction}
 *
 * @param originalTxId The original transaction id
 * @param amount The new amount to auth for
 * @param settle to settle or not
 * @return The transaction
 */
@Processor
public Result cloneTransaction(String originalTxId, BigDecimal amount,
        @Optional @Default(value = "false") Boolean settle) {
    log.info("Cloning transaction {} with amount {} settle {}", new Object[] { originalTxId, amount, settle });

    Validate.notNull(originalTxId, "Original transaction id must not be null");
    Validate.notNull(amount, "amount should not be null");
    Validate.isTrue(amount.compareTo(BigDecimal.ZERO) >= 0, "amount must be >= 0");

    TransactionCloneRequest txCloneReq = getRequestFactory().transactionCloneRequest().amount(amount).options()
            .submitForSettlement(settle).done();
    try {
        return getGateway().transaction().cloneTransaction(originalTxId, txCloneReq);
    } catch (BraintreeException e) {
        return new ExceptionResult(e.getClass().getCanonicalName());
    }
}

From source file:org.broadleafcommerce.openadmin.server.service.persistence.validation.MaxGreaterThanMinValidator.java

@Override
public PropertyValidationResult validate(Entity entity, Serializable instance,
        Map<String, FieldMetadata> entityFieldMetadata, Map<String, String> validationConfiguration,
        BasicFieldMetadata propertyMetadata, String propertyName, String value) {
    String otherField = validationConfiguration.get("otherField");
    FieldManager fm = PersistenceManagerFactory.getPersistenceManager().getDynamicEntityDao().getFieldManager();
    boolean valid = true;
    String message = "";
    BigDecimal min = new BigDecimal(0);
    BigDecimal max = min;

    if (StringUtils.isBlank(value) || StringUtils.isBlank(otherField)) {
        return new PropertyValidationResult(true);
    }/*  w  w  w .j a v a 2s. c o  m*/

    try {
        Object minObj = fm.getFieldValue(instance, otherField);
        if (minObj != null) {
            min = new BigDecimal(minObj.toString());
        }
        max = new BigDecimal(fm.getFieldValue(instance, propertyName).toString());
    } catch (IllegalAccessException | FieldNotAvailableException e) {
        valid = false;
        message = e.getMessage();
    }

    if (valid && max != null && min != null && max.compareTo(min) < 0) {
        valid = false;
        message = "minGreaterThanMax";
    }

    return new PropertyValidationResult(valid, message);
}

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

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

From source file:org.egov.egf.web.actions.contra.ContraBTCAction.java

boolean validateInputData() {
    if (null == contraBean.getBankBranchId() || contraBean.getBankBranchId().equalsIgnoreCase("-1")) {
        addActionError(getText("contra.validate.bank"));
        return false;
    }//w w w  . j ava  2  s. c om
    if (null == contraBean.getAccountNumberId() || contraBean.getAccountNumberId().equalsIgnoreCase("-1")) {
        addActionError(getText("contra.validate.accnum"));
        return false;
    }
    if (null == contraBean.getAmount() || contraBean.getAmount().compareTo(BigDecimal.ZERO) == 0) {
        addActionError(getText("contra.validate.amt"));
        return false;
    }
    if (showChequeNumber() && (null == contraBean.getChequeDate() || contraBean.getChequeNumber() == null
            || !validateChequeNumber())) {
        addActionError(getText("contra.invalid.cheque.number"));
        return false;
    }
    if (shouldShowHeaderField("vouchernumber") && StringUtils.isBlank(voucherHeader.getVoucherNumber())) {
        addActionError(getText("contra.invalid.voucher.number"));
        return false;
    }
    if (shouldShowHeaderField("vouchernumber") && voucherHeader.getVoucherDate().compareTo(new Date()) >= 1) {
        addActionError(getText("contra.invalid.voucher.date"));
        return false;
    }
    final BigDecimal cashBalance = getCashBalance();
    if (cashBalance.compareTo(contraBean.getAmount()) == -1 && isBankBalanceMandatory()) {
        addActionError(getText("contra.insufficient.bankbalance", new String[] { "" + cashBalance }));
        return false;
    }
    contraBean.setAccountBalance(cashBalance);
    return true;
}

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

/**
 * Sets the amount of the transaction.  This amount should not include any tax, shipping charges, or duty.
 * Thus the total amount of the transaction is the amount + taxAmount + shippingAmount + dutyAmount.
 *
 * The amount is normalized to the proper number of decimal places for the selected currency.
 *
 * @throws  IllegalArgumentException  if amount <= 0 or is incorrectly formatted for the currency.
 *//*from w w  w  .j  av  a2  s .co  m*/
public void setAmount(BigDecimal amount) throws IllegalArgumentException {
    if (amount == null) {
        this.amount = null;
    } else {
        if (amount.compareTo(BigDecimal.ZERO) <= 0)
            throw new LocalizedIllegalArgumentException(accessor,
                    "TransactionRequest.setAmount.amount.lessThanEqualZero");
        try {
            this.amount = amount.setScale(currency.getDefaultFractionDigits());
        } catch (ArithmeticException err) {
            throw new LocalizedIllegalArgumentException(err, accessor,
                    "TransactionRequest.setAmount.amount.cannotNormalize");
        }
    }
}

From source file:com.axelor.studio.service.builder.ModelBuilderService.java

/**
 * Method to process decimal type of field for default,min,max attributes
 * and append it to field xml./* ww w . ja  v  a  2  s  .  c o  m*/
 * 
 * @param field
 *            MetaField to process
 */
private void addDecimal(StringBuilder fieldXml, MetaField field) {

    BigDecimal max = field.getDecimalMax();
    if (max != null && max.compareTo(BigDecimal.ZERO) != 0) {
        fieldXml.append("max=\"" + max + "\" ");
    }

    BigDecimal min = field.getDecimalMin();
    if (min != null && min.compareTo(BigDecimal.ZERO) != 0) {
        fieldXml.append("min=\"" + min + "\" ");
    }

    BigDecimal defaultDecimal = field.getDefaultDecimal();
    if (defaultDecimal != null && defaultDecimal.compareTo(BigDecimal.ZERO) != 0) {
        fieldXml.append("default=\"" + defaultDecimal + "\" ");
    }

}

From source file:ch.algotrader.service.algo.SlicingOrderService.java

private void sendNextOrder(SlicingOrder slicingOrder, SlicingOrderStateVO slicingOrderState) {

    Validate.notNull(slicingOrder, "slicingOrder missing");
    if (slicingOrderState == null) {
        return; // already done
    }//from ww w . ja  v  a 2 s  .  c  om

    Security security = slicingOrder.getSecurity();
    SecurityFamily family = security.getSecurityFamily();

    long remainingQuantity;
    OrderStatusVO orderStatus = this.orderExecutionService.getStatusByIntId(slicingOrder.getIntId());
    if (orderStatus != null) {
        remainingQuantity = orderStatus.getRemainingQuantity();
    } else {
        remainingQuantity = slicingOrder.getQuantity();
    }

    TickVO tick = (TickVO) this.marketDataCacheService.getCurrentMarketDataEvent(security.getId());
    if (tick == null) {
        throw new IllegalStateException("no market data subscription for " + security);
    }

    // limit (at least one tick above market but do not exceed the market)
    BigDecimal limit;
    long marketVolume;
    if (Side.BUY.equals(slicingOrder.getSide())) {

        marketVolume = tick.getVolAsk();
        limit = family.adjustPrice(null, tick.getAsk(), -slicingOrderState.getCurrentOffsetTicks());

        if (limit.compareTo(tick.getBid()) <= 0.0) {
            limit = family.adjustPrice(null, tick.getBid(), 1);
            slicingOrderState
                    .setCurrentOffsetTicks(family.getSpreadTicks(null, tick.getBid(), tick.getAsk()) - 1);
        }

        if (limit.compareTo(tick.getAsk()) > 0.0) {
            limit = tick.getAsk();
            slicingOrderState.setCurrentOffsetTicks(0);
        }

    } else {

        marketVolume = tick.getVolBid();
        limit = family.adjustPrice(null, tick.getBid(), slicingOrderState.getCurrentOffsetTicks());

        if (limit.compareTo(tick.getAsk()) >= 0.0) {
            limit = family.adjustPrice(null, tick.getAsk(), -1);
            slicingOrderState
                    .setCurrentOffsetTicks(family.getSpreadTicks(null, tick.getBid(), tick.getAsk()) - 1);
        }

        if (limit.compareTo(tick.getBid()) < 0.0) {
            limit = tick.getBid();
            slicingOrderState.setCurrentOffsetTicks(0);
        }
    }

    // ignore maxVolPct / maxQuantity if they are zero
    double maxVolPct = slicingOrder.getMaxVolPct() == 0.0 ? Double.MAX_VALUE : slicingOrder.getMaxVolPct();
    long maxQuantity = slicingOrder.getMaxQuantity() == 0 ? Long.MAX_VALUE : slicingOrder.getMaxQuantity();

    // evaluate the order minimum and maximum qty
    long orderMinQty = Math.max(Math.round(marketVolume * slicingOrder.getMinVolPct()),
            slicingOrder.getMinQuantity());
    long orderMaxQty = Math.min(Math.round(marketVolume * maxVolPct), maxQuantity);

    // orderMinQty cannot be greater than orderMaxQty
    if (orderMinQty > orderMaxQty) {
        orderMinQty = orderMaxQty;
    }

    // randomize the quantity between orderMinQty and orderMaxQty
    long quantity = Math.round(orderMinQty + Math.random() * (orderMaxQty - orderMinQty));

    // make sure that the remainingQty after the next slice is greater than minQuantity
    long remainingQuantityAfterSlice = remainingQuantity - quantity;
    if (slicingOrder.getMinQuantity() > 0 && slicingOrder.getMaxQuantity() > 0
            && remainingQuantityAfterSlice > 0 && remainingQuantityAfterSlice < slicingOrder.getMinQuantity()) {

        // if quantity is below half between minQuantity and maxQuantity
        if (quantity < (slicingOrder.getMinQuantity() + slicingOrder.getMaxQuantity()) / 2.0) {

            // take full remaining quantity but not more than orderMaxQty
            quantity = Math.min(remainingQuantity, orderMaxQty);
        } else {

            // make sure remaining after slice quantity is greater than minQuantity
            quantity = remainingQuantity - slicingOrder.getMinQuantity();
        }
    }

    // qty should be at least one
    quantity = Math.max(quantity, 1);

    // qty should be maximum remainingQuantity
    quantity = Math.min(quantity, remainingQuantity);

    // create the limit order
    LimitOrder order = LimitOrder.Factory.newInstance();
    order.setSecurity(security);
    order.setStrategy(slicingOrder.getStrategy());
    order.setSide(slicingOrder.getSide());
    order.setQuantity(quantity);
    order.setLimit(limit);
    order.setAccount(slicingOrder.getAccount());

    // associate the childOrder with the parentOrder(this)
    order.setParentOrder(slicingOrder);

    // store the current order and tick
    slicingOrderState.addPair(new Pair<>(order, tick));

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("next slice for {},currentOffsetTicks={},qty={},vol={},limit={},bid={},ask={}",
                slicingOrder.getDescription(), slicingOrderState.getCurrentOffsetTicks(), order.getQuantity(),
                (Side.BUY.equals(order.getSide()) ? tick.getVolAsk() : tick.getVolBid()), limit, tick.getBid(),
                tick.getAsk());
    }

    this.simpleOrderService.sendOrder(order);
}

From source file:net.sourceforge.fenixedu.domain.Shift.java

public boolean isTotalShiftLoadExceeded() {
    final BigDecimal totalHours = getTotalHours();
    for (final CourseLoad courseLoad : getCourseLoadsSet()) {
        if (totalHours.compareTo(courseLoad.getTotalQuantity()) == 1) {
            return true;
        }/*w ww.j a  v a2  s.c  o m*/
    }
    return false;
}

From source file:org.yes.cart.payment.impl.PayPalExpressCheckoutPaymentGatewayImpl.java

/**
 * Get the express checkout details via GetExpressCheckoutDetails method of
 * pay pal payment gateway/*from   w  ww . j  ava 2  s . c o  m*/
 *
 * @param token   the token obtained via   SetExpressCheckout method
 * @param payerId the token obtained via   GetExpressCheckoutDetails method
 * @param amount  the amount
 * @return map of parsed key - values with detail information
 * @throws java.io.IOException in case of errors
 */
public Map<String, String> doDoExpressCheckoutPayment(final String token, final String payerId,
        final BigDecimal amount, final String currencyCode) throws IOException {

    Assert.notNull(token, "The pay pal tonek must  be not null");
    Assert.notNull(payerId, "Payer must be provided");
    Assert.notNull(amount, "Amount must be provided");
    Assert.isTrue(amount.compareTo(BigDecimal.ZERO) > 0, "Amount must be positive");
    Assert.notNull(currencyCode, "Currency code must be provided");

    final StringBuilder stringBuilder = new StringBuilder();

    stringBuilder.append(PP_EC_TOKEN);
    stringBuilder.append(EQ);
    stringBuilder.append(URLEncoder.encode(token));
    stringBuilder.append(AND);

    stringBuilder.append(PP_EC_PAYERID);
    stringBuilder.append(EQ);
    stringBuilder.append(URLEncoder.encode(payerId));
    stringBuilder.append(AND);

    stringBuilder.append(PP_EC_PAYMENTREQUEST_0_AMT);
    stringBuilder.append(EQ);
    stringBuilder.append(URLEncoder.encode("" + amount));
    stringBuilder.append(AND);

    stringBuilder.append(PP_EC_PAYMENTREQUEST_0_CURRENCYCODE);
    stringBuilder.append(EQ);
    stringBuilder.append(currencyCode);
    stringBuilder.append(AND);

    stringBuilder.append(PP_EC_PAYMENTREQUEST_0_PAYMENTACTION);
    stringBuilder.append(EQ);
    stringBuilder.append(URLEncoder.encode("Sale"));

    return performHttpCall("DoExpressCheckoutPayment", stringBuilder.toString());

}