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:nl.b3p.kaartenbalie.core.server.accounting.LayerCalculator.java

/**
 * Deze methode bepaalt de prijs van de layer. Indien een van de vereiste
 * gegevens niet is opgegeven dan wordt de layer niet beschikbaar gemeld
 * via LayerNotAvailableException. /*from   ww  w  .j av  a 2  s.com*/
 * <p>
 * De layer naam is verplicht, speciaal bij WMS layers worden layers zonder 
 * naam gebruikt als placeholders voor sublayers. Dergelijke layers kunnen 
 * geen prijsinfo hebben. Er wordt dan een NoPrizingException gegooid.
 * <p>
 * @param spAbbr
 * @param layerName
 * @param validationDate
 * @param projection
 * @param scale
 * @param units
 * @param planType
 * @param service
 * @param operation
 * @return
 * @throws NoPrizingException 
 * @throws LayerNotAvailableException 
 */
public BigDecimal calculateLayer(String spAbbr, String layerName, Date validationDate, String projection,
        BigDecimal scale, BigDecimal units, int planType, String service, String operation)
        throws NoPrizingException, LayerNotAvailableException {
    log.debug("spAbbr: " + spAbbr + ", layerName: " + layerName + ", validationDate: " + validationDate
            + ", projection: " + projection + ", scale: " + scale + ", units: " + units + ", planType: "
            + planType + ", service: " + service + ", operation: " + operation);

    if (spAbbr == null) {
        log.error("spAbbr is required!");
        throw new LayerNotAvailableException("spAbbr is required!");
    }
    if (validationDate == null) {
        log.error("ValidationDate is a required field!");
        throw new LayerNotAvailableException("ValidationDate is a required field!");
    }
    if (units == null) {
        log.error("Units is a required field!");
        throw new LayerNotAvailableException("Units is a required field!");
    }
    if (planType <= 0) {
        log.error("PlanType is a required field!");
        throw new LayerNotAvailableException("PlanType is a required field!");
    }
    if (layerName == null || layerName.trim().length() == 0) {
        throw new NoPrizingException("Layer is a placeholder and therefor cannot hold pricingInformation.");
    }
    BigDecimal layerPrice = null;

    LayerPricing layerPricing = getActiveLayerPricing(spAbbr, layerName, validationDate, projection, scale,
            planType, service, operation);
    if (layerPricing.getUnitPrice() != null
            && (layerPricing.getLayerIsFree() == null || (layerPricing.getLayerIsFree() != null
                    && layerPricing.getLayerIsFree().booleanValue() == false))) {
        layerPrice = layerPricing.getUnitPrice().multiply(units);
    }
    if (layerPrice != null && layerPrice.compareTo(new BigDecimal(0)) < 0) {
        layerPrice = new BigDecimal("0");
    }
    return layerPrice;
}

From source file:edu.usu.sdl.openstorefront.core.sort.AttributeCodeArchComparator.java

@Override
public int compare(T o1, T o2) {
    //Codes should be numbers (Note the description includes the code so they should be sort as well)
    BigDecimal codeKey1;
    BigDecimal codeKey2;//www  .  j av  a2 s.  c  o  m

    if (o1.getSortOrder() != null && o2.getSortOrder() != null) {
        return o1.getSortOrder().compareTo(o2.getSortOrder());
    } else {
        if (StringUtils.isNotBlank(o1.getArchitectureCode())) {
            codeKey1 = StringProcessor.archtecureCodeToDecimal(o1.getArchitectureCode());
        } else {
            codeKey1 = StringProcessor.archtecureCodeToDecimal(o1.getAttributeCodePk().getAttributeCode());
        }

        if (StringUtils.isNotBlank(o2.getArchitectureCode())) {
            codeKey2 = StringProcessor.archtecureCodeToDecimal(o2.getArchitectureCode());
        } else {
            codeKey2 = StringProcessor.archtecureCodeToDecimal(o2.getAttributeCodePk().getAttributeCode());
        }

        int results = codeKey1.compareTo(codeKey2);
        if (results != 0) {
            return results;
        } else {
            return o1.getAttributeCodePk().getAttributeCode()
                    .compareTo(o2.getAttributeCodePk().getAttributeCode());
        }
    }
}

From source file:com.zuora.api.UsageAdjInvoiceRegenerator.java

protected UsageAdjInvoiceRegenerator() throws Exception {

    //MAX_ITEMS_PER_CALL = AppParamManager.MAX_ZOBJECTS_PER_BATCH;

    // Initialize the API Client.
    zApiClient = new ApiClient(AppParamManager.API_URL, AppParamManager.USER_NAME,
            AppParamManager.USER_PASSWORD, AppParamManager.USER_SESSION);

    zApiClient.login();// w w  w . j  av a  2  s  .  c om
    //Logger.print("logged in");

    /*
    threadDataArray = new ThreadData[AppParamManager.MAX_WORKING_THREADS];
            
    for (int i = 0; i < AppParamManager.MAX_WORKING_THREADS; i++) {
       threadDataArray[i] = new ThreadData(i);
    }
    */

    //int indexOfThreadDataArray = 0;
    int itemsCollectionIndex = 0;
    String savedRPId = "";
    String savedAccountId = "";
    String savedInvoiceId = "";
    String savedPRPCId = "";
    Calendar savedServiceEndDt = null;
    Calendar savedInvoiceDt = null;
    Calendar savedTargetDt = null;

    String savedBaseUOM = null;
    String savedOverUOM = null;
    String basePRPCId = null;

    List<Usage> deleteUOMs = null;

    boolean skipDelete = false;
    /*
    String InvoiceNumberDisplay = "";
    BufferedWriter  writer = new BufferedWriter(
    new FileWriter("C:\\Temp\\output"+output+".txt"));
    */

    //Logger.print("thread initiated, max objects: "+AppParamManager.MAX_ZOBJECTS_PER_BATCH+" Total number of Line Items: "+eInvoiceItemAll.size());
    //String rpcQuery1 = "SELECT Price, base_quantity__c from RatePlanCharge where ProductRatePlanChargeId = '";
    String rpcQuery1 = "SELECT Price from RatePlanCharge where ProductRatePlanChargeId = '";
    String rpcQuery2 = "' and RatePlanId = '";
    //String rpcQuery3 = "' and Base_Quantity__c <> '0'";
    String rpcQuery3 = "'";
    String finalquery = "";
    BigDecimal result = BigDecimal.ZERO;
    BigDecimal amountTotal = BigDecimal.ZERO;
    BigDecimal baseAmount = BigDecimal.ZERO;
    BigDecimal savedQuantity = BigDecimal.ZERO;

    InvoiceItemEntity baseEntity = null;
    InvoiceItemEntity overageEntity = null;

    //Logger.print("Before loop.");

    for (InvoiceItemEntity eInvoiceItem : eUsageItemsValid) {
        Logger.print("in loop0" + eInvoiceItem.getRPId());
        if (!eInvoiceItem.getRPId().equals(savedRPId)) {
            if (itemsCollectionIndex != 0) {
                Logger.print("in if 1");
                if (!skipDelete) {
                    /*
                    //add base usage
                    baseEntity = new InvoiceItemEntity();
                    baseEntity.setAccountId(savedAccountId);
                            
                    finalquery = rpcQuery1 + basePRPCId + rpcQuery2 + savedRPId + rpcQuery3;
                    results = zApiClient.getBaseQuantity(finalquery);
                    baseEntity.setQuantity(results[0]);
                    baseAmount = results[1];
                            
                    baseEntity.setUOM(savedBaseUOM);
                    baseEntity.setServiceEnddt(savedServiceEndDt);   
                    //Logger.print("setting invoice id base: "+savedInvoiceId);
                    baseEntity.setInvoiceId(savedInvoiceId);
                    baseEntity.setTargetDate(savedTargetDt);
                    baseEntity.setInvoicedate(savedInvoiceDt);
                    newUsageCollection.add(baseEntity);
                    */

                    //add overage usage
                    BigDecimal overageQnty = amountTotal.subtract(baseAmount);
                    if (overageQnty.compareTo(BigDecimal.ZERO) > 0) {
                        overageEntity = new InvoiceItemEntity();
                        overageEntity.setAccountId(savedAccountId);
                        Logger.print("setting invoice id over: " + savedInvoiceId);
                        overageEntity.setInvoiceId(savedInvoiceId);

                        overageEntity.setQuantity(overageQnty);

                        overageEntity.setUOM(savedOverUOM);
                        overageEntity.setServiceEnddt(savedServiceEndDt);
                        overageEntity.setTargetDate(savedTargetDt);
                        overageEntity.setInvoicedate(savedInvoiceDt);
                        Logger.print("added to collection, overage: " + overageEntity.getQuantity());
                        newUsageCollection.add(overageEntity);
                    }
                }

                skipDelete = false;
                amountTotal = BigDecimal.ZERO;
                baseAmount = BigDecimal.ZERO;
            }

            savedRPId = eInvoiceItem.getRPId();
            savedPRPCId = eInvoiceItem.getPRPCId();
            savedAccountId = eInvoiceItem.getAccountId();

            if (!eInvoiceItem.getInvoiceId().equals(savedInvoiceId)) {
                Logger.print("getting usage for invoice: " + eInvoiceItem.getInvoiceId());
                deleteUOMs = zApiClient.getUsageForDelete(
                        "select id, uom from usage where invoiceid = '" + eInvoiceItem.getInvoiceId() + "'");
                savedInvoiceId = eInvoiceItem.getInvoiceId();
            }
            savedInvoiceDt = eInvoiceItem.getInvoicedate();
            savedTargetDt = eInvoiceItem.getTargetDate();
            savedServiceEndDt = eInvoiceItem.getServiceEnddt();

            if (eInvoiceItem.getFeeFlag().equals("B")) {
                savedBaseUOM = eInvoiceItem.getUOM();
                basePRPCId = eInvoiceItem.getPRPCId();
            }
            if (eInvoiceItem.getFeeFlag().equals("O")) {
                savedOverUOM = eInvoiceItem.getUOM();
            }
            savedBaseUOM = null;
            savedOverUOM = null;
            savedQuantity = BigDecimal.ZERO;
        }

        Logger.print("In loop1");
        savedRPId = eInvoiceItem.getRPId();
        //Logger.print("In loop2");
        savedPRPCId = eInvoiceItem.getPRPCId();
        //Logger.print("In loop3");
        savedAccountId = eInvoiceItem.getAccountId();
        //Logger.print("In loop4");
        savedInvoiceDt = eInvoiceItem.getInvoicedate();
        //Logger.print("In loop6");
        savedTargetDt = eInvoiceItem.getTargetDate();
        //Logger.print("In loop7");
        savedServiceEndDt = eInvoiceItem.getServiceEnddt();
        //Logger.print("In loop8");

        if (eInvoiceItem.getFeeFlag().equals("B")) {
            Logger.print("setting base UOM");
            basePRPCId = eInvoiceItem.getPRPCId();

            //add base usage
            finalquery = rpcQuery1 + basePRPCId + rpcQuery2 + savedRPId + rpcQuery3;
            result = zApiClient.getBaseQuantity(finalquery);
            Logger.print("setting base UOM");
            Logger.print(
                    "curr line quantity: " + eInvoiceItem.getQuantity() + " base quantity: " + savedQuantity);
            if (result.compareTo(BigDecimal.ZERO) > 0
                    && eInvoiceItem.getQuantity().compareTo(savedQuantity) < 0) {
                //Logger.print("setting invoice id base1: ");
                savedBaseUOM = eInvoiceItem.getUOM();
                //Logger.print("setting invoice id base2: ");
                baseEntity = new InvoiceItemEntity();
                baseEntity.setAccountId(savedAccountId);
                //Logger.print("setting invoice id base3: ");
                //result
                baseEntity.setQuantity(savedQuantity);
                baseAmount = savedQuantity.multiply(result);
                baseEntity.setUOM(savedBaseUOM);
                baseEntity.setServiceEnddt(savedServiceEndDt);
                Logger.print("setting invoice id base: " + savedInvoiceId);
                baseEntity.setInvoiceId(savedInvoiceId);
                baseEntity.setTargetDate(savedTargetDt);
                baseEntity.setInvoicedate(savedInvoiceDt);
                newUsageCollection.add(baseEntity);
            }
        }

        if (eInvoiceItem.getLicenseFlag().equals("True")) {
            savedQuantity = eInvoiceItem.getQuantity();
            Logger.print("within license flag, quantity set to :" + savedQuantity);
        }

        if (eInvoiceItem.getFeeFlag().equals("O")) {
            Logger.print("setting over UOM");
            savedOverUOM = eInvoiceItem.getUOM();
        }
        if (eInvoiceItem.getFeeFlag().equals("") && eInvoiceItem.getLicenseFlag().equals("")) {
            Logger.print("setting usage " + savedBaseUOM);
            if (savedBaseUOM == null) {
                skipDelete = true;
            } else {
                Logger.print("setting usage1");
                amountTotal = amountTotal.add(eInvoiceItem.getAmount());
                Logger.print("setting usage2: " + eInvoiceItem.getInvoiceId() + " saved: " + savedInvoiceId);
                if (!eInvoiceItem.getInvoiceId().equals(savedInvoiceId)) {
                    Logger.print("setting usage3");
                    deleteUOMs = zApiClient.getUsageForDelete("select id, uom from usage where invoiceid = '"
                            + eInvoiceItem.getInvoiceId() + "'");
                    Logger.print("deleted list: " + deleteUOMs.size());
                    savedInvoiceId = eInvoiceItem.getInvoiceId();
                }
                Logger.print("before usage loop" + deleteUOMs.size());
                if (deleteUOMs.size() >= 1 && deleteUOMs.get(0).getUOM() != null) {
                    for (Usage usage : deleteUOMs) {
                        Logger.print("in loop, usage UOM: " + usage.getUOM() + " invoice UOM: "
                                + eInvoiceItem.getUOM());
                        if (usage.getUOM().equals(eInvoiceItem.getUOM())) {
                            deleteList.add(usage.getId());
                            Logger.print("added to delete list: " + usage.getUOM());
                            break;
                        }
                    }
                }
            }

        }
        itemsCollectionIndex++;
        Logger.print("done setting usage");
    }

    if (!skipDelete) {
        /*
        //add base usage
        baseEntity = new InvoiceItemEntity();
        baseEntity.setAccountId(savedAccountId);
        Logger.print("after loop1");
        finalquery = rpcQuery1 + basePRPCId + rpcQuery2 + savedRPId + rpcQuery3;
        results = zApiClient.getBaseQuantity(finalquery);
        baseEntity.setQuantity(results[0]);
        baseAmount = results[1];
        Logger.print("after loop2");
        baseEntity.setUOM(savedBaseUOM);
        baseEntity.setServiceEnddt(savedServiceEndDt);   
        Logger.print("setting invoice id base: "+savedInvoiceId);
        baseEntity.setInvoiceId(savedInvoiceId);
        baseEntity.setTargetDate(savedTargetDt);
        baseEntity.setInvoicedate(savedInvoiceDt);
        newUsageCollection.add(baseEntity);
        Logger.print("after loop3");
        //add overage usage
         */
        BigDecimal overageQnty = amountTotal.subtract(baseAmount);
        if (overageQnty.compareTo(BigDecimal.ZERO) > 0) {
            overageEntity = new InvoiceItemEntity();
            overageEntity.setAccountId(savedAccountId);
            Logger.print("after loop3.1");
            //Logger.print("setting invoice id over: "+savedInvoiceId);
            overageEntity.setInvoiceId(savedInvoiceId);
            //Logger.print("after loop3.2");

            //Logger.print("after loop3.3");
            overageEntity.setQuantity(overageQnty);
            //Logger.print("after loop4");
            overageEntity.setUOM(savedOverUOM);
            //Logger.print("after loop4.1");
            overageEntity.setServiceEnddt(savedServiceEndDt);
            //Logger.print("after loop4.2");
            overageEntity.setTargetDate(savedTargetDt);
            //Logger.print("after loop4.3");
            overageEntity.setInvoicedate(savedInvoiceDt);
            //Logger.print("after loop4.4");
            Logger.print("added to collection, overage: " + overageEntity.getQuantity());
            newUsageCollection.add(overageEntity);
            //Logger.print("after loop5");
        }
        skipDelete = false;
    }
    amountTotal = BigDecimal.ZERO;
    baseAmount = BigDecimal.ZERO;
    //writer.close();

}

From source file:nl.strohalm.cyclos.services.transactions.LoanServiceImpl.java

private Transfer doRepay(final RepayLoanDTO params) {
    BigDecimal amount = params.getAmount();

    // Check if the amount is valid
    if (amount.compareTo(paymentService.getMinimumPayment()) < 0) {
        throw new ValidationException("amount", "loan.amount", new InvalidError());
    }//from   ww  w.  ja v  a2 s .co  m

    // Get the loan payment to repay
    Calendar date = params.getDate();
    if (date == null) {
        date = Calendar.getInstance();
        params.setDate(date);
    }
    final LoanRepaymentAmountsDTO amountsDTO = getLoanPaymentAmount(params);
    final LoanPayment payment = amountsDTO.getLoanPayment();
    if (payment == null) {
        throw new UnexpectedEntityException();
    }

    // Validate the amount
    final BigDecimal remainingAmount = amountsDTO.getRemainingAmountAtDate();
    final BigDecimal diff = remainingAmount.subtract(amount);
    final MutableBoolean totallyRepaid = new MutableBoolean();
    // If the amount is on an acceptable delta, set the transfer value = parcel value
    if (diff.abs().floatValue() < PRECISION_DELTA) {
        amount = remainingAmount;
        totallyRepaid.setValue(true);
    } else if (diff.compareTo(BigDecimal.ZERO) < 0
            || !params.getLoan().getTransfer().getType().getLoan().getType().allowsPartialRepayments()) {
        throw new ValidationException("amount", "loan.amount", new InvalidError());
    }
    final LocalSettings localSettings = settingsService.getLocalSettings();
    Loan loan = fetchService.fetch(params.getLoan(), Loan.Relationships.PAYMENTS, RelationshipHelper
            .nested(Loan.Relationships.TRANSFER, Payment.Relationships.TO, MemberAccount.Relationships.MEMBER),
            Loan.Relationships.TO_MEMBERS);

    // Build the transfers for repayment
    final List<TransferDTO> transfers = handlersByType.get(loan.getParameters().getType())
            .buildTransfersForRepayment(params, amountsDTO);
    Transfer root = null;
    BigDecimal totalAmount = BigDecimal.ZERO;
    for (final TransferDTO dto : transfers) {
        if (dto.getAmount().floatValue() < PRECISION_DELTA) {
            // If the root amount is zero, it means that the parent transfer should be the last transfer for this loan payment
            final TransferQuery tq = new TransferQuery();
            tq.setLoanPayment(payment);
            tq.setReverseOrder(true);
            tq.setUniqueResult();
            final List<Transfer> paymentTransfers = paymentService.search(tq);
            if (paymentTransfers.isEmpty()) {
                throw new IllegalStateException(
                        "The root transfer has amount 0 and there is no other transfers for this payment");
            }
            root = paymentTransfers.iterator().next();
        } else {
            totalAmount = totalAmount.add(dto.getAmount());
            dto.setParent(root);
            dto.setLoanPayment(payment);
            final Transfer transfer = (Transfer) paymentService.insertWithoutNotification(dto);
            if (root == null) {
                // The first will be the root. All others are it's children
                root = transfer;
            }
        }
    }

    // Update the loan payment
    final BigDecimal totalRepaid = localSettings.round(payment.getRepaidAmount().add(totalAmount));
    payment.setRepaidAmount(totalRepaid);
    if (totallyRepaid.booleanValue()) {
        // Mark the payment as repaid, if is the case
        payment.setStatus(LoanPayment.Status.REPAID);
        payment.setRepaymentDate(params.getDate());
    }
    payment.setTransfers(null); // Avoid 2 representations of the transfers collection. It's inverse="true", no problem setting null
    loanPaymentDao.update(payment);

    // Return the generated root transfer
    return root;
}

From source file:nl.strohalm.cyclos.taglibs.FormatTag.java

@Override
public int doEndTag() throws JspException {
    String out = "";
    final LocalSettings localSettings = getLocalSettings();
    if (number != null) {
        if (number instanceof Double || number instanceof BigDecimal || number instanceof Float) {
            final BigDecimal theNumber = CoercionHelper.coerce(BigDecimal.class, number);
            NumberConverter<BigDecimal> numberConverter;
            if (StringUtils.isNotEmpty(unitsPattern)) {
                numberConverter = localSettings.getUnitsConverter(unitsPattern);
            } else if (precision == null) {
                numberConverter = localSettings.getNumberConverter();
            } else {
                numberConverter = localSettings.getNumberConverterForPrecision(precision);
            }//from w  w  w .  j ava 2s. c om
            out = numberConverter.toString(theNumber);
            if (forceSignal && theNumber.compareTo(BigDecimal.ZERO) > 0) {
                out = "+" + out;
            }
        } else if (number instanceof StatisticalNumber) {
            out = convertStatisticalNumber((StatisticalNumber) number);
        } else if (number instanceof BigInteger && cardNumberPattern != null) {
            out = new CardNumberConverter(cardNumberPattern).toString((BigInteger) number);
        } else {
            final NumberConverter<Long> longConverter = localSettings.getLongConverter();
            final Long theNumber = CoercionHelper.coerce(Long.class, number);
            out = longConverter.toString(theNumber);
        }
    } else if (amount != null) {
        Converter<Amount> converter;
        if (StringUtils.isEmpty(unitsPattern)) {
            converter = localSettings.getAmountConverter();
        } else {
            converter = localSettings.getAmountConverter(unitsPattern);
        }
        out = converter.toString(amount);
    } else if (rawDate != null) {
        out = localSettings.getRawDateConverter().toString(rawDate);
    } else if (date != null) {
        out = localSettings.getDateConverter().toString(date);
    } else if (dateTime != null) {
        out = localSettings.getDateTimeConverter().toString(dateTime);
    } else if (time != null) {
        out = localSettings.getTimeConverter().toString(time);
    } else if (bytes != null) {
        out = FileUtils.byteCountToDisplaySize(bytes);
    } else {
        out = defaultValue == null ? null : defaultValue.toString();
    }
    try {
        if (StringUtils.isNotEmpty(out)) {
            pageContext.getOut().print(out);
        }
    } catch (final IOException e) {
        throw new JspException(e);
    } finally {
        release();
    }
    return EVAL_PAGE;
}

From source file:UserInterface.FinanceRole.DonateToPoorPeopleJPanel.java

private void autoDonateJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoDonateJButtonActionPerformed

    objWorldEnterprise.getObjTransactionDirectory().updateTransactionAccount();

    BigDecimal worldDonation = AutoDonate.donationCheck(objWorldEnterprise, objUserAccount);
    BigDecimal worldBalance = objWorldEnterprise.getObjTransactionDirectory().getAvailableVirtualBalance();
    System.out.println(worldDonation);

    System.out.println(objWorldEnterprise.getObjTransactionDirectory().getAvailableRealBalance());
    System.out.println(objWorldEnterprise.getObjTransactionDirectory().getAvailableVirtualBalance());

    int positiveWorldBalance = worldBalance.compareTo(worldDonation);

    if (positiveWorldBalance >= 1) {
        //JDialog.setDefaultLookAndFeelDecorated(true);

        int response = JOptionPane.showConfirmDialog(null,
                "Total donation of $ " + worldDonation + "/- Do you want to Donate?", "Confirm",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (response == JOptionPane.YES_OPTION) {
            System.out.println("Yes button clicked");
            worldDonation = AutoDonate.donationConfirm(objWorldEnterprise, objUserAccount);

            JOptionPane.showMessageDialog(null, "$ " + worldDonation + "/- donated successfully");
        }//from   w w  w  .j  ava  2  s  . c o  m
    } else {
        JOptionPane.showMessageDialog(null, "World Balance is low");
    }
}

From source file:hydrograph.ui.propertywindow.widgets.listeners.grid.MouseHoverOnSchemaGridListener.java

private String setToolTipForBigDecimalSchemaRange(GenerateRecordSchemaGridRow generateRecordSchemaGridRow) {
    BigDecimal rangeFrom = null, rangeTo = null;

    if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeFrom())) {
        rangeFrom = new BigDecimal(generateRecordSchemaGridRow.getRangeFrom());
    }/*ww  w .j  av  a 2 s .  com*/

    if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeTo())) {
        rangeTo = new BigDecimal(generateRecordSchemaGridRow.getRangeTo());
    }

    if (rangeFrom != null && rangeTo != null) {
        if (rangeFrom.compareTo(rangeTo) > 0) {
            return Messages.RANGE_FROM_GREATER_THAN_RANGE_TO;
        }
    }

    if (!generateRecordSchemaGridRow.getLength().isEmpty()) {
        int fieldLength = 0, scaleLength = 0;
        fieldLength = Integer.parseInt(generateRecordSchemaGridRow.getLength());

        if (!generateRecordSchemaGridRow.getScale().isEmpty()) {
            scaleLength = Integer.parseInt(generateRecordSchemaGridRow.getScale());
        }

        if (fieldLength < 0) {
            return Messages.FIELD_LENGTH_LESS_THAN_ZERO;
        } else if (scaleLength < 0) {
            return Messages.FIELD_SCALE_LESS_THAN_ZERO;
        } else if (scaleLength >= fieldLength) {
            return Messages.FIELD_SCALE_NOT_LESS_THAN_FIELD_LENGTH;
        } else {

            String minPermissibleRangeValue = "", maxPermissibleRangeValue = "";

            for (int i = 1; i <= fieldLength; i++) {
                maxPermissibleRangeValue = maxPermissibleRangeValue.concat("9");

                if (minPermissibleRangeValue.trim().length() == 0) {
                    minPermissibleRangeValue = minPermissibleRangeValue.concat("-");
                } else {
                    minPermissibleRangeValue = minPermissibleRangeValue.concat("9");
                }
            }

            if (minPermissibleRangeValue.equals("-")) {
                minPermissibleRangeValue = "0";
            }

            if (scaleLength != 0) {
                int decimalPosition = fieldLength - scaleLength;

                if (decimalPosition == 1) {
                    minPermissibleRangeValue = "0";
                    maxPermissibleRangeValue = maxPermissibleRangeValue.replaceFirst("9", ".");
                } else {
                    minPermissibleRangeValue = minPermissibleRangeValue.substring(0, decimalPosition - 1) + "."
                            + minPermissibleRangeValue.substring(decimalPosition);
                }

                maxPermissibleRangeValue = maxPermissibleRangeValue.substring(0, decimalPosition - 1) + "."
                        + maxPermissibleRangeValue.substring(decimalPosition);
            }

            if (fieldLength == 0) {
                minPermissibleRangeValue = "0";
                maxPermissibleRangeValue = "0";
            }

            BigDecimal minRangeValue = new BigDecimal(minPermissibleRangeValue);
            BigDecimal maxRangeValue = new BigDecimal(maxPermissibleRangeValue);

            return setToolTipIfSchemaRangeAndLengthIsInvalid(rangeFrom, fieldLength, rangeTo, minRangeValue,
                    maxRangeValue);
        }
    }
    return "";
}

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

@Override
public SortedSet<Stock> findStocks(StatementOptions options, StockCriteria criteria) {
    validateCriteria(criteria);/*from w  w  w  .  j  a  v a  2  s. c o  m*/
    Integer[] industries = criteria.getIndustryIds();
    Set<String> exchanges = new HashSet<String>(Arrays.asList(criteria.getExchangeIds()));
    BigDecimal minPrice = criteria.getMinimumPrice();
    BigDecimal maxPrice = criteria.getMaximumPrice();
    SortedSet<Stock> stocks = new TreeSet<Stock>();
    try {
        Set<String> symbols = getMatchingSymbols(options, industries, exchanges);
        Clause where = in("stock_symbol", symbols.toArray());
        for (Row row : getStockResultSet(options, where)) {
            BigDecimal curPrice = row.getDecimal("current_price");
            if (row.getBool("active") && (minPrice.compareTo(curPrice) <= 0)
                    && (maxPrice.compareTo(curPrice) >= 0)) {
                stocks.add(createStock(row));
            }
        }
    } catch (DriverException e) {
        throw new DAOException(e);
    }
    return stocks;
}

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

private boolean validateSchemaRangeForDoubleFloatIntegerLongShort(
        GenerateRecordSchemaGridRow generateRecordSchemaGridRow) {
    BigDecimal rangeFrom = null, rangeTo = null;

    if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeFrom())) {
        rangeFrom = new BigDecimal(generateRecordSchemaGridRow.getRangeFrom());
    }/*from ww  w  .  ja  v a2  s  . c  o  m*/

    if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeTo())) {
        rangeTo = new BigDecimal(generateRecordSchemaGridRow.getRangeTo());
    }

    if (rangeFrom != null && rangeTo != null) {
        if (rangeFrom.compareTo(rangeTo) > 0) {
            return true;
        }
    }

    if (!generateRecordSchemaGridRow.getLength().isEmpty()) {
        int fieldLength = Integer.parseInt(generateRecordSchemaGridRow.getLength());

        if (fieldLength < 0) {
            return true;
        } else {

            String minPermissibleRangeValue = "", maxPermissibleRangeValue = "";

            for (int i = 1; i <= fieldLength; i++) {
                maxPermissibleRangeValue = maxPermissibleRangeValue.concat("9");
                if (minPermissibleRangeValue.trim().length() == 0) {
                    minPermissibleRangeValue = minPermissibleRangeValue.concat("-");
                } else {
                    minPermissibleRangeValue = minPermissibleRangeValue.concat("9");
                }
            }

            if (fieldLength == 0) {
                minPermissibleRangeValue = "0";
                maxPermissibleRangeValue = "0";
            }

            if (minPermissibleRangeValue.equals("-")) {
                minPermissibleRangeValue = "0";
            }

            BigDecimal minRangeValue = new BigDecimal(minPermissibleRangeValue);
            BigDecimal maxRangeValue = new BigDecimal(maxPermissibleRangeValue);

            if (checkIfSchemaRangeAndLengethIsInvalid(rangeFrom, fieldLength, rangeTo, minRangeValue,
                    maxRangeValue)) {
                return true;
            }
        }
    }
    return false;
}

From source file:com.gst.portfolio.savings.domain.SavingsAccountCharge.java

public boolean isChargeIsOverPaid(final LocalDate nextDueDate) {
    final BigDecimal amountPaid = this.amountPaid == null ? BigDecimal.ZERO : amountPaid();
    return this.getDueLocalDate().isAfter(nextDueDate) && amountPaid.compareTo(BigDecimal.ZERO) == 1;
}