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:org.chiba.xml.xforms.ui.Range.java

/**
 * Initializes this range./*from  w w w . java2  s  . com*/
 *
 * @throws XFormsException if the datatype of the bound is not supported.
 */
protected final void initializeRange() throws XFormsException {
    if (!isBound()) {
        return;
    }

    // get model item datatype
    Validator validator = this.model.getValidator();
    String datatype = getDatatype();

    if (validator.isRestricted("decimal", datatype) || validator.isRestricted("float", datatype)
            || validator.isRestricted("double", datatype)) {
        // get bound value
        String value = getInstanceValue();
        BigDecimal valueDecimal;
        if (value != null && value.length() > 0) {
            valueDecimal = new BigDecimal(value);
        } else {
            // set '0.0' as default value
            valueDecimal = new BigDecimal(0d);
        }

        // get step size
        BigDecimal stepDecimal;
        String stepAttribute = getXFormsAttribute(STEP_ATTRIBUTE);
        if (stepAttribute != null) {
            stepDecimal = new BigDecimal(stepAttribute);
        } else {
            // set '1.0' as default step
            stepDecimal = new BigDecimal(1d);
            this.element.setAttributeNS(null, STEP_ATTRIBUTE, stepDecimal.toString());
        }

        // get range start
        BigDecimal startDecimal;
        String startAttribute = getXFormsAttribute(START_ATTRIBUTE);
        if (startAttribute != null) {
            startDecimal = new BigDecimal(startAttribute);
        } else {
            // set 'value - (2 * step)' as default start
            startDecimal = valueDecimal.subtract(stepDecimal.multiply(new BigDecimal(2d)));
            this.element.setAttributeNS(null, START_ATTRIBUTE, startDecimal.toString());
        }

        // get range end
        BigDecimal endDecimal;
        String endAttribute = getXFormsAttribute(END_ATTRIBUTE);
        if (endAttribute != null) {
            endDecimal = new BigDecimal(endAttribute);
        } else {
            // set 'value + (2 * step)' as default end
            endDecimal = valueDecimal.add(stepDecimal.multiply(new BigDecimal(2d)));
            this.element.setAttributeNS(null, END_ATTRIBUTE, endDecimal.toString());
        }

        if (valueDecimal.compareTo(startDecimal) < 0 || valueDecimal.compareTo(endDecimal) > 0) {
            this.model.getContainer().dispatch(this.target, XFormsEventNames.OUT_OF_RANGE, null);
        }

        return;
    }

    throw new XFormsBindingException("datatype not supported by range control", this.target, datatype);
}

From source file:com.qcadoo.mes.productionCounting.ProductionCountingServiceImpl.java

@Override
public BigDecimal getRegisteredProductValueForOperationProductIn(final Entity operationProduct,
        final BigDecimal planed) {
    BigDecimal value = null;
    Entity toc = operationProduct.getBelongsToField(OperationProductInComponentFields.OPERATION_COMPONENT);
    Entity product = operationProduct.getBelongsToField(OperationProductInComponentFields.PRODUCT);

    List<Entity> tracings = getProductionTrackingDD().find()
            .add(SearchRestrictions.belongsTo(ProductionTrackingFields.TECHNOLOGY_OPERATION_COMPONENT, toc))
            .add(SearchRestrictions.eq(ProductionTrackingFields.STATE,
                    ProductionTrackingStateStringValues.ACCEPTED))
            .list().getEntities();//from   w  w w  .j  a v  a 2  s  .  co  m
    for (Entity tracking : tracings) {
        Entity topIN = getTrackingOperationProductInComponentDD().find()
                .add(SearchRestrictions.belongsTo(TrackingOperationProductInComponentFields.PRODUCTION_TRACKING,
                        tracking))
                .add(SearchRestrictions.belongsTo(TrackingOperationProductInComponentFields.PRODUCT, product))
                .setMaxResults(1).uniqueResult();
        if (topIN != null) {
            if (value == null) {
                value = new BigDecimal(0l);
            }
            value = value.add(topIN.getDecimalField(TrackingOperationProductInComponentFields.USED_QUANTITY),
                    numberService.getMathContext());
        }
    }
    if (value != null) {
        value = planed.subtract(value, numberService.getMathContext());
    } else {
        return value;
    }

    if (value.compareTo(new BigDecimal(0l)) == -1) {
        value = new BigDecimal(0l);
    }

    return value;
}

From source file:com.qcadoo.mes.productionCounting.ProductionCountingServiceImpl.java

@Override
public BigDecimal getRegisteredProductValueForOperationProductOut(final Entity operationProduct,
        final BigDecimal planed) {
    BigDecimal value = null;
    Entity toc = operationProduct.getBelongsToField(OperationProductOutComponentFields.OPERATION_COMPONENT);
    Entity product = operationProduct.getBelongsToField(OperationProductOutComponentFields.PRODUCT);

    List<Entity> tracings = getProductionTrackingDD().find()
            .add(SearchRestrictions.belongsTo(ProductionTrackingFields.TECHNOLOGY_OPERATION_COMPONENT, toc))
            .add(SearchRestrictions.eq(ProductionTrackingFields.STATE,
                    ProductionTrackingStateStringValues.ACCEPTED))
            .list().getEntities();/*from  w ww. ja  v  a2s  .c  o m*/
    for (Entity tracking : tracings) {
        Entity topIN = getTrackingOperationProductOutComponentDD().find()
                .add(SearchRestrictions
                        .belongsTo(TrackingOperationProductOutComponentFields.PRODUCTION_TRACKING, tracking))
                .add(SearchRestrictions.belongsTo(TrackingOperationProductOutComponentFields.PRODUCT, product))
                .setMaxResults(1).uniqueResult();
        if (topIN != null) {
            if (value == null) {
                value = new BigDecimal(0l);
            }
            value = value.add(topIN.getDecimalField(TrackingOperationProductOutComponentFields.USED_QUANTITY),
                    numberService.getMathContext());
        }
    }
    if (value != null) {
        value = planed.subtract(value, numberService.getMathContext());
    } else {
        return value;
    }

    if (value.compareTo(new BigDecimal(0l)) == -1) {
        value = new BigDecimal(0l);
    }

    return value;
}

From source file:com.gst.infrastructure.dataqueries.service.ReadWriteNonCoreDataServiceImpl.java

private boolean notTheSame(final String currValue, final String pValue, final String colType) {
    if (StringUtils.isEmpty(currValue) && StringUtils.isEmpty(pValue)) {
        return false;
    }//from  www.ja v a  2s. c  o  m

    if (StringUtils.isEmpty(currValue)) {
        return true;
    }

    if (StringUtils.isEmpty(pValue)) {
        return true;
    }

    if ("DECIMAL".equalsIgnoreCase(colType)) {
        final BigDecimal currentDecimal = BigDecimal.valueOf(Double.valueOf(currValue));
        final BigDecimal newDecimal = BigDecimal.valueOf(Double.valueOf(pValue));

        return currentDecimal.compareTo(newDecimal) != 0;
    }

    if (currValue.equals(pValue)) {
        return false;
    }

    return true;
}

From source file:com.hyeb.service.SearchServiceImpl.java

@SuppressWarnings("unchecked")
@Transactional(readOnly = true)//from  ww  w  .  ja v  a 2 s.  co  m
public Page<Product> search(String keyword, BigDecimal startPrice, BigDecimal endPrice, OrderType orderType,
        Pageable pageable) {
    if (StringUtils.isEmpty(keyword)) {
        return new Page<Product>();
    }
    if (pageable == null) {
        pageable = new Pageable();
    }
    try {
        String text = QueryParser.escape(keyword);
        TermQuery snQuery = new TermQuery(new Term("sn", text));
        Query keywordQuery = new QueryParser("keyword", new IKAnalyzer()).parse(text);
        QueryParser nameParser = new QueryParser("name", new IKAnalyzer());
        nameParser.setDefaultOperator(QueryParser.AND_OPERATOR);
        Query nameQuery = nameParser.parse(text);
        FuzzyQuery nameFuzzyQuery = new FuzzyQuery(new Term("name", text), FUZZY_QUERY_MINIMUM_SIMILARITY);
        TermQuery introductionQuery = new TermQuery(new Term("introduction", text));
        TermQuery isMarketableQuery = new TermQuery(new Term("isMarketable", "true"));
        TermQuery isListQuery = new TermQuery(new Term("isList", "true"));
        TermQuery isGiftQuery = new TermQuery(new Term("isGift", "false"));
        BooleanQuery textQuery = new BooleanQuery();
        BooleanQuery query = new BooleanQuery();
        textQuery.add(snQuery, Occur.SHOULD);
        textQuery.add(keywordQuery, Occur.SHOULD);
        textQuery.add(nameQuery, Occur.SHOULD);
        textQuery.add(nameFuzzyQuery, Occur.SHOULD);
        textQuery.add(introductionQuery, Occur.SHOULD);
        query.add(isMarketableQuery, Occur.MUST);
        query.add(isListQuery, Occur.MUST);
        query.add(isGiftQuery, Occur.MUST);
        query.add(textQuery, Occur.MUST);
        if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
            BigDecimal temp = startPrice;
            startPrice = endPrice;
            endPrice = temp;
        }
        if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0 && endPrice != null
                && endPrice.compareTo(new BigDecimal(0)) >= 0) {
            NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price",
                    startPrice.doubleValue(), endPrice.doubleValue(), true, true);
            query.add(numericRangeQuery, Occur.MUST);
        } else if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
            NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price",
                    startPrice.doubleValue(), null, true, false);
            query.add(numericRangeQuery, Occur.MUST);
        } else if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
            NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", null,
                    endPrice.doubleValue(), false, true);
            query.add(numericRangeQuery, Occur.MUST);
        }
        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
        FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Product.class);
        SortField[] sortFields = null;
        if (orderType == OrderType.priceAsc) {
            sortFields = new SortField[] { new SortField("price", SortField.Type.DOUBLE, false),
                    new SortField("createDate", SortField.Type.LONG, true) };
        } else if (orderType == OrderType.priceDesc) {
            sortFields = new SortField[] { new SortField("price", SortField.Type.DOUBLE, true),
                    new SortField("createDate", SortField.Type.LONG, true) };
        } else if (orderType == OrderType.salesDesc) {
            sortFields = new SortField[] { new SortField("sales", SortField.Type.INT, true),
                    new SortField("createDate", SortField.Type.LONG, true) };
        } else if (orderType == OrderType.scoreDesc) {
            sortFields = new SortField[] { new SortField("score", SortField.Type.INT, true),
                    new SortField("createDate", SortField.Type.LONG, true) };
        } else if (orderType == OrderType.dateDesc) {
            sortFields = new SortField[] { new SortField("createDate", SortField.Type.LONG, true) };
        } else {
            sortFields = new SortField[] { new SortField("isTop", SortField.Type.STRING, true),
                    new SortField(null, SortField.Type.SCORE),
                    new SortField("modifyDate", SortField.Type.LONG, true) };
        }
        fullTextQuery.setSort(new Sort(sortFields));
        fullTextQuery.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize());
        fullTextQuery.setMaxResults(pageable.getPageSize());
        return new Page<Product>(fullTextQuery.getResultList(), fullTextQuery.getResultSize(), pageable);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new Page<Product>();
}

From source file:com.esd.cs.audit.AuditsController.java

/**
 * //from  www . java2s  . c  o  m
 * 
 * @param companyId
 * @param sb
 * @return
 */
private BigDecimal getUnpaid(String year, Integer companyId, List<AccountModel> sb) {
    BigDecimal amount = new BigDecimal(0.00);
    List<Accounts> accounts = accountsService.getByYearAndCompany(year, companyId,
            Constants.PROCESS_STATIC_WJK);
    Map<String, Accounts> map = new HashMap<>();
    for (Accounts group : accounts) {
        Object obj = map.get(group.getYear());
        if (obj == null) {
            map.put(group.getYear(), group);
        } else {
            Accounts a = (Accounts) obj;
            a.setTotalMoney(a.getTotalMoney().add(group.getTotalMoney()));
        }
    }
    for (Accounts a : map.values()) {
        BigDecimal total = a.getTotalMoney();
        AuditParameter auditParameter = auditParameterService.getByYear(a.getYear());
        Date auditDelayDate = auditParameter.getAuditDelayDate();
        int days = CalendarUtil.getDaySub(auditDelayDate, new Date());
        BigDecimal penalty = total.multiply(auditParameter.getAuditDelayRate()).multiply(new BigDecimal(days));
        AccountModel am = new AccountModel();
        am.setYear(a.getYear());
        am.setDays(String.valueOf(days));
        am.setMoney(df.format(total));
        am.setPenalty(df.format(penalty));
        am.setProp(df4.format(auditParameter.getAuditDelayRate()));
        am.setTotal(df.format(total));
        sb.add(am);
        amount = amount.add(total);
    }
    if (amount.compareTo(new BigDecimal(0.00)) != 0) {
        AccountModel am = new AccountModel();
        am.setTotal(df.format(amount));
        sb.add(am);
    }
    return amount;
}

From source file:net.groupbuy.service.impl.SearchServiceImpl.java

@SuppressWarnings("unchecked")
@Transactional(readOnly = true)/* ww  w . j a v a 2s .  co  m*/
public Page<Product> search(String keyword, BigDecimal startPrice, BigDecimal endPrice, OrderType orderType,
        Pageable pageable) {
    if (StringUtils.isEmpty(keyword)) {
        return new Page<Product>();
    }
    if (pageable == null) {
        pageable = new Pageable();
    }
    try {
        String text = QueryParser.escape(keyword);
        TermQuery snQuery = new TermQuery(new Term("sn", text));
        Query keywordQuery = new QueryParser(Version.LUCENE_35, "keyword", new IKAnalyzer()).parse(text);
        QueryParser nameParser = new QueryParser(Version.LUCENE_35, "name", new IKAnalyzer());
        nameParser.setDefaultOperator(QueryParser.AND_OPERATOR);
        Query nameQuery = nameParser.parse(text);
        FuzzyQuery nameFuzzyQuery = new FuzzyQuery(new Term("name", text), FUZZY_QUERY_MINIMUM_SIMILARITY);
        TermQuery introductionQuery = new TermQuery(new Term("introduction", text));
        TermQuery isMarketableQuery = new TermQuery(new Term("isMarketable", "true"));
        TermQuery isListQuery = new TermQuery(new Term("isList", "true"));
        TermQuery isGiftQuery = new TermQuery(new Term("isGift", "false"));
        BooleanQuery textQuery = new BooleanQuery();
        BooleanQuery query = new BooleanQuery();
        textQuery.add(snQuery, Occur.SHOULD);
        textQuery.add(keywordQuery, Occur.SHOULD);
        textQuery.add(nameQuery, Occur.SHOULD);
        textQuery.add(nameFuzzyQuery, Occur.SHOULD);
        textQuery.add(introductionQuery, Occur.SHOULD);
        query.add(isMarketableQuery, Occur.MUST);
        query.add(isListQuery, Occur.MUST);
        query.add(isGiftQuery, Occur.MUST);
        query.add(textQuery, Occur.MUST);
        if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
            BigDecimal temp = startPrice;
            startPrice = endPrice;
            endPrice = temp;
        }
        if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0 && endPrice != null
                && endPrice.compareTo(new BigDecimal(0)) >= 0) {
            NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price",
                    startPrice.doubleValue(), endPrice.doubleValue(), true, true);
            query.add(numericRangeQuery, Occur.MUST);
        } else if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
            NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price",
                    startPrice.doubleValue(), null, true, false);
            query.add(numericRangeQuery, Occur.MUST);
        } else if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
            NumericRangeQuery<Double> numericRangeQuery = NumericRangeQuery.newDoubleRange("price", null,
                    endPrice.doubleValue(), false, true);
            query.add(numericRangeQuery, Occur.MUST);
        }
        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
        FullTextQuery fullTextQuery = fullTextEntityManager.createFullTextQuery(query, Product.class);
        SortField[] sortFields = null;
        if (orderType == OrderType.priceAsc) {
            sortFields = new SortField[] { new SortField("price", SortField.DOUBLE, false),
                    new SortField("createDate", SortField.LONG, true) };
        } else if (orderType == OrderType.priceDesc) {
            sortFields = new SortField[] { new SortField("price", SortField.DOUBLE, true),
                    new SortField("createDate", SortField.LONG, true) };
        } else if (orderType == OrderType.salesDesc) {
            sortFields = new SortField[] { new SortField("sales", SortField.INT, true),
                    new SortField("createDate", SortField.LONG, true) };
        } else if (orderType == OrderType.scoreDesc) {
            sortFields = new SortField[] { new SortField("score", SortField.INT, true),
                    new SortField("createDate", SortField.LONG, true) };
        } else if (orderType == OrderType.dateDesc) {
            sortFields = new SortField[] { new SortField("createDate", SortField.LONG, true) };
        } else {
            sortFields = new SortField[] { new SortField("isTop", SortField.STRING, true),
                    new SortField(null, SortField.SCORE), new SortField("modifyDate", SortField.LONG, true) };
        }
        fullTextQuery.setSort(new Sort(sortFields));
        fullTextQuery.setFirstResult((pageable.getPageNumber() - 1) * pageable.getPageSize());
        fullTextQuery.setMaxResults(pageable.getPageSize());
        return new Page<Product>(fullTextQuery.getResultList(), fullTextQuery.getResultSize(), pageable);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new Page<Product>();
}

From source file:nl.strohalm.cyclos.services.accounts.guarantees.GuaranteeServiceImpl.java

@Override
public Guarantee requestGuarantee(final PaymentObligationPackDTO pack) {
    final Long[] poIds = pack.getPaymentObligations();
    // verifies the pack validity
    if (pack.getIssuer() == null) {
        throw new IllegalArgumentException("Invalid guarantee request: Issuer is null");
    } else if (poIds == null || poIds.length == 0) {
        throw new IllegalArgumentException("Invalid guarantee request: payment obligations pack is empty");
    }//from   ww w. ja v a  2s .c om

    // take the first payment obligation to get the currency and buyer (all belong to the same buyer and have the same currency)
    final PaymentObligation firstPaymentObligation = paymentObligationService.load(poIds[0]);
    final Member buyer = firstPaymentObligation.getBuyer();
    final Member seller = firstPaymentObligation.getSeller();
    final Member issuer = pack.getIssuer();
    final AccountOwner accOwner = LoggedUser.accountOwner();

    if (!accOwner.equals(seller)) {
        throw new PermissionDeniedException();
    }

    final Certification certification = certificationService
            .getActiveCertification(firstPaymentObligation.getCurrency(), buyer, issuer);

    // verifies if there is an active certification
    if (certification == null) {
        throw new ActiveCertificationNotFoundException(buyer, issuer, firstPaymentObligation.getCurrency());
    }

    // calculates the guarantee's amount and expirationDate
    BigDecimal amount = firstPaymentObligation.getAmount();
    final ArrayList<PaymentObligation> paymentObligations = new ArrayList<PaymentObligation>();
    paymentObligations.add(firstPaymentObligation);
    Calendar lastExpirationdate = firstPaymentObligation.getExpirationDate();
    for (int i = 1; i < poIds.length; i++) {
        final PaymentObligation po = paymentObligationService.load(poIds[i]);
        if (!accOwner.equals(po.getSeller())) {
            throw new PermissionDeniedException();
        }
        amount = amount.add(po.getAmount());
        if (po.getExpirationDate().after(lastExpirationdate)) {
            lastExpirationdate = po.getExpirationDate();
        }

        paymentObligations.add(po);
    }

    // verify that the certificatin's amount is not exceeded
    final BigDecimal usedCertificationAmount = certificationService.getUsedAmount(certification, true);
    final BigDecimal remainingAmount = certification.getAmount().subtract(usedCertificationAmount);
    if (amount.compareTo(remainingAmount) > 0) {
        throw new CertificationAmountExceededException(certification, remainingAmount, amount);
    }

    // verify that the certificatin's validity is not exceeded
    if (lastExpirationdate.after(certification.getValidity().getEnd())) {
        throw new CertificationValidityExceededException(certification);
    }

    final GuaranteeType guaranteeType = certification.getGuaranteeType();
    Guarantee guarantee = new Guarantee();

    guarantee.setBuyer(buyer);
    guarantee.setSeller(seller);
    guarantee.setIssuer(pack.getIssuer());
    guarantee.setCertification(certification);
    guarantee.setGuaranteeType(guaranteeType);
    guarantee.setAmount(amount);
    guarantee.setValidity(new Period(null, lastExpirationdate));
    guarantee.setPaymentObligations(paymentObligations);
    guarantee.setCreditFeeSpec((GuaranteeFeeVO) guaranteeType.getCreditFee().clone());
    guarantee.setIssueFeeSpec((GuaranteeFeeVO) guaranteeType.getIssueFee().clone());

    guarantee = save(guarantee, false);

    for (int i = 0; i < poIds.length; i++) {
        final PaymentObligation po = paymentObligations.get(i);
        po.setGuarantee(guarantee);
        paymentObligationService.changeStatus(po.getId(), PaymentObligation.Status.ACCEPTED);
    }

    memberNotificationHandler.guaranteePendingIssuerNotification(guarantee);

    return guarantee;
}

From source file:mx.edu.um.mateo.inventario.dao.impl.EntradaDaoHibernate.java

private Entrada preparaParaCerrar(Entrada entrada, Usuario usuario, Date fecha)
        throws NoCuadraException, NoSePuedeCerrarEnCeroException {
    BigDecimal iva = entrada.getIva();
    BigDecimal total = entrada.getTotal();
    entrada.setIva(BigDecimal.ZERO);
    entrada.setTotal(BigDecimal.ZERO);
    for (LoteEntrada lote : entrada.getLotes()) {
        Producto producto = lote.getProducto();
        producto.setPrecioUnitario(costoPromedio(lote));
        if (!entrada.getDevolucion()) {
            producto.setUltimoPrecio(lote.getPrecioUnitario());
        }//w  w  w  .  ja  v  a 2 s . com
        producto.setExistencia(producto.getExistencia().add(lote.getCantidad()));
        producto.setFechaModificacion(fecha);
        currentSession().update(producto);
        auditaProducto(producto, usuario, Constantes.ACTUALIZAR, entrada.getId(), null, fecha);

        BigDecimal subtotal = lote.getPrecioUnitario().multiply(lote.getCantidad());
        entrada.setIva(entrada.getIva().add(lote.getIva()));
        entrada.setTotal(entrada.getTotal().add(subtotal.add(lote.getIva())));
    }
    if (total.equals(BigDecimal.ZERO)) {
        throw new NoSePuedeCerrarEnCeroException("No se puede cerrar la entrada en cero");
    }
    // Si tanto el iva o el total difieren mas de un 5% del valor que
    // viene en la factura lanzar excepcion
    if (iva.compareTo(entrada.getIva()) != 0 || total.compareTo(entrada.getTotal()) != 0) {
        BigDecimal variacion = new BigDecimal("0.05");
        BigDecimal topeIva = entrada.getIva().multiply(variacion);
        BigDecimal topeTotal = entrada.getTotal().multiply(variacion);
        if (iva.compareTo(entrada.getIva()) < 0 || total.compareTo(entrada.getTotal()) < 0) {
            if (iva.compareTo(entrada.getIva().subtract(topeIva)) >= 0
                    && total.compareTo(entrada.getTotal().subtract(topeTotal)) >= 0) {
                // todavia puede pasar
            } else {
                throw new NoCuadraException("No se puede cerrar porque no cuadran los totales");
            }
        } else {
            if (iva.compareTo(entrada.getIva().add(topeIva)) <= 0
                    && total.compareTo(entrada.getTotal().add(topeTotal)) <= 0) {
                // todavia puede pasar
            } else {
                throw new NoCuadraException("No se puede cerrar porque no cuadran los totales");
            }
        }
    }

    return entrada;
}

From source file:net.shopxx.controller.shop.OrderController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> create(String cartToken, Long receiverId, Long paymentMethodId,
        Long shippingMethodId, String code, String invoiceTitle, BigDecimal balance, String memo) {
    Map<String, Object> data = new HashMap<String, Object>();
    Cart cart = cartService.getCurrent();
    if (cart == null || cart.isEmpty()) {
        data.put("message", ERROR_MESSAGE);
        return data;
    }//w  w w . j  a v  a  2 s.  co m
    if (!StringUtils.equals(cart.getToken(), cartToken)) {
        data.put("message", Message.warn("shop.order.cartHasChanged"));
        return data;
    }
    if (cart.hasNotMarketable()) {
        data.put("message", Message.warn("shop.order.hasNotMarketable"));
        return data;
    }
    if (cart.getIsLowStock()) {
        data.put("message", Message.warn("shop.order.cartLowStock"));
        return data;
    }
    Member member = memberService.getCurrent();
    Receiver receiver = null;
    ShippingMethod shippingMethod = null;
    PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
    if (cart.getIsDelivery()) {
        receiver = receiverService.find(receiverId);
        if (receiver == null || !member.equals(receiver.getMember())) {
            data.put("message", ERROR_MESSAGE);
            return data;
        }
        shippingMethod = shippingMethodService.find(shippingMethodId);
        if (shippingMethod == null) {
            data.put("message", ERROR_MESSAGE);
            return data;
        }
    }
    CouponCode couponCode = couponCodeService.findByCode(code);
    if (couponCode != null && !cart.isValid(couponCode)) {
        data.put("message", ERROR_MESSAGE);
        return data;
    }
    if (balance != null && balance.compareTo(BigDecimal.ZERO) < 0) {
        data.put("message", ERROR_MESSAGE);
        return data;
    }
    if (balance != null && balance.compareTo(member.getBalance()) > 0) {
        data.put("message", Message.warn("shop.order.insufficientBalance"));
        return data;
    }
    Invoice invoice = StringUtils.isNotEmpty(invoiceTitle) ? new Invoice(invoiceTitle, null) : null;
    Order order = orderService.create(Order.Type.general, cart, receiver, paymentMethod, shippingMethod,
            couponCode, invoice, balance, memo);

    data.put("message", SUCCESS_MESSAGE);
    data.put("sn", order.getSn());
    return data;
}