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.gst.infrastructure.core.data.DataValidatorBuilder.java

public DataValidatorBuilder notGreaterThanMax(final BigDecimal max) {
    if (max != null && this.value != null) {
        final BigDecimal amount = BigDecimal.valueOf(Double.valueOf(this.value.toString()));
        if (amount.compareTo(max) == 1) {
            final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource)
                    .append(".").append(this.parameter).append(".is.greater.than.max");
            final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(this.parameter)
                    .append(" value ").append(amount).append(" must not be more than maximum value ")
                    .append(max);//w  w w. j av a 2  s  .c  o m
            final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
                    defaultEnglishMessage.toString(), this.parameter, amount, max);
            this.dataValidationErrors.add(error);
            return this;
        }
    }
    return this;
}

From source file:org.openvpms.component.business.service.archetype.ArchetypeServiceActTestCase.java

/**
 * Tests OVPMS-211.// www . j a v  a2  s . c  o  m
 */
@Test
public void testOVPMS211() {
    Act estimationItem1 = (Act) create("act.customerEstimationItem");
    ActBean estimationItem1Bean = new ActBean(estimationItem1);
    estimationItem1Bean.setValue("fixedPrice", "1.0");
    estimationItem1Bean.setValue("lowQty", "2.0");
    estimationItem1Bean.setValue("lowUnitPrice", "3.0");
    estimationItem1Bean.setValue("highQty", "4.0");
    estimationItem1Bean.setValue("highUnitPrice", "5.0");
    estimationItem1Bean.save();

    Act estimation = (Act) create("act.customerEstimation");
    ActBean estimationBean = new ActBean(estimation);
    estimationBean.setValue("status", "IN_PROGRESS");
    estimationBean.addRelationship("actRelationship.customerEstimationItem", estimationItem1);

    Act estimationItem2 = (Act) create("act.customerEstimationItem");
    ActBean estimationItem2Bean = new ActBean(estimationItem2);
    estimationItem2Bean.setValue("fixedPrice", "2.0");
    estimationItem2Bean.setValue("lowQty", "3.0");
    estimationItem2Bean.setValue("lowUnitPrice", "4.0");
    estimationItem2Bean.setValue("highQty", "5.0");
    estimationItem2Bean.setValue("highUnitPrice", "6.0");
    estimationItem2Bean.save();

    estimationBean.addRelationship("actRelationship.customerEstimationItem", estimationItem2);
    estimationBean.save();

    // reload the estimation
    estimation = reload(estimation);
    estimationBean = new ActBean(estimation);

    // verify low & high totals have been calculated
    BigDecimal lowTotal = estimationBean.getBigDecimal("lowTotal");
    BigDecimal highTotal = estimationBean.getBigDecimal("highTotal");
    assertTrue(lowTotal.compareTo(BigDecimal.ZERO) > 0);
    assertTrue(highTotal.compareTo(BigDecimal.ZERO) > 0);
}

From source file:com.gst.infrastructure.core.data.DataValidatorBuilder.java

public DataValidatorBuilder inMinAndMaxAmountRange(final BigDecimal minimumAmount,
        final BigDecimal maximumAmount) {
    if (minimumAmount != null && maximumAmount != null && this.value != null) {
        final BigDecimal amount = BigDecimal.valueOf(Double.valueOf(this.value.toString()));
        if (amount.compareTo(minimumAmount) == -1 || amount.compareTo(maximumAmount) == 1) {
            final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource)
                    .append(".").append(this.parameter).append(".amount.is.not.within.min.max.range");
            final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(this.parameter)
                    .append(" amount ").append(amount).append(" must be between ").append(minimumAmount)
                    .append(" and ").append(maximumAmount).append(" .");
            final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
                    defaultEnglishMessage.toString(), this.parameter, amount, minimumAmount, maximumAmount);
            this.dataValidationErrors.add(error);
            return this;
        }//  ww  w  .j av  a2 s . co  m
    }
    return this;
}

From source file:com.gst.infrastructure.core.data.DataValidatorBuilder.java

public DataValidatorBuilder positiveAmount() {
    if (this.value == null && this.ignoreNullValue) {
        return this;
    }/*ww w.  jav  a2  s  .  c om*/

    if (this.value != null) {
        final BigDecimal number = BigDecimal.valueOf(Double.valueOf(this.value.toString()));
        if (number.compareTo(BigDecimal.ZERO) <= 0) {
            final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource)
                    .append(".").append(this.parameter).append(".not.greater.than.zero");
            final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ")
                    .append(this.parameter).append(" must be greater than 0.");
            final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
                    defaultEnglishMessage.toString(), this.parameter, number, 0);
            this.dataValidationErrors.add(error);
        }
    }
    return this;
}

From source file:com.gst.infrastructure.core.data.DataValidatorBuilder.java

public DataValidatorBuilder zeroOrPositiveAmount() {
    if (this.value == null && this.ignoreNullValue) {
        return this;
    }//from w w  w  .  j ava 2s  .co  m

    if (this.value != null) {
        final BigDecimal number = BigDecimal.valueOf(Double.valueOf(this.value.toString()));
        if (number.compareTo(BigDecimal.ZERO) < 0) {
            final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource)
                    .append(".").append(this.parameter).append(".not.zero.or.greater");
            final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ")
                    .append(this.parameter).append(" must be greater than or equal to 0.");
            final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
                    defaultEnglishMessage.toString(), this.parameter, number, 0);
            this.dataValidationErrors.add(error);
        }
    }
    return this;
}

From source file:com.gst.infrastructure.core.data.DataValidatorBuilder.java

public DataValidatorBuilder comapareMinimumAndMaximumAmounts(final BigDecimal minimumBalance,
        final BigDecimal maximumBalance) {
    if (minimumBalance != null && maximumBalance != null) {
        if (maximumBalance.compareTo(minimumBalance) == -1) {
            final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource)
                    .append(".").append(this.parameter).append(".is.not.within.expected.range");
            final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ")
                    .append(" minimum amount ").append(minimumBalance)
                    .append(" should less than maximum amount ").append(maximumBalance).append(".");
            final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(),
                    defaultEnglishMessage.toString(), this.parameter, minimumBalance, maximumBalance);
            this.dataValidationErrors.add(error);
            return this;
        }//from w ww . j a  va 2 s.c  o m
    }
    return this;
}

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

private boolean validateSchemaRangeForBigDecimal(GenerateRecordSchemaGridRow generateRecordSchemaGridRow) {

    BigDecimal rangeFrom = null, rangeTo = null;

    if (StringUtils.isNotBlank(generateRecordSchemaGridRow.getRangeFrom())
            && generateRecordSchemaGridRow.getRangeFrom().matches(REGULAR_EXPRESSION_FOR_NUMBER)) {
        rangeFrom = new BigDecimal(generateRecordSchemaGridRow.getRangeFrom());
    }/*from  ww w.j a v  a 2 s  .  c om*/

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

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

    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 true;
        } else if (scaleLength < 0) {
            return true;
        } else if (scaleLength >= fieldLength) {
            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 (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);

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

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsInternationalRateInquire(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    Locale locale = (Locale) context.get("locale");

    // check for 0 weight
    BigDecimal shippableWeight = (BigDecimal) context.get("shippableWeight");
    if (shippableWeight.compareTo(BigDecimal.ZERO) == 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsShippableWeightMustGreaterThanZero", locale));
    }//from  w ww  . j a  v  a2 s  . c  o m

    // get the destination country
    String destinationCountry = null;
    String shippingContactMechId = (String) context.get("shippingContactMechId");
    if (UtilValidate.isNotEmpty(shippingContactMechId)) {
        try {
            GenericValue shipToAddress = EntityQuery.use(delegator).from("PostalAddress")
                    .where("contactMechId", shippingContactMechId).queryOne();
            if (domesticCountries.contains(shipToAddress.get("countryGeoId"))) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateInternationCannotBeUsedForUsDestinations", locale));
            }
            if (shipToAddress != null && UtilValidate.isNotEmpty(shipToAddress.getString("countryGeoId"))) {
                GenericValue countryGeo = shipToAddress.getRelatedOne("CountryGeo", false);
                // TODO: Test against all country geoNames against what USPS expects
                destinationCountry = countryGeo.getString("geoName");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (UtilValidate.isEmpty(destinationCountry)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineDestinationCountry", locale));
    }

    // get the service code
    String serviceCode = null;
    try {
        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("shipmentMethodTypeId", (String) context.get("shipmentMethodTypeId"), "partyId",
                        (String) context.get("carrierPartyId"), "roleTypeId",
                        (String) context.get("carrierRoleTypeId"))
                .queryOne();
        if (carrierShipmentMethod != null) {
            serviceCode = carrierShipmentMethod.getString("carrierServiceCode");
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (UtilValidate.isEmpty(serviceCode)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineServiceCode", locale));
    }

    BigDecimal maxWeight = new BigDecimal("70");
    String maxWeightStr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "maxEstimateWeight",
            resource, "shipment.usps.max.estimate.weight", "70");
    try {
        maxWeight = new BigDecimal(maxWeightStr);
    } catch (NumberFormatException e) {
        Debug.logWarning(
                "Error parsing max estimate weight string [" + maxWeightStr + "], using default instead",
                module);
        maxWeight = new BigDecimal("70");
    }

    List<Map<String, Object>> shippableItemInfo = UtilGenerics.checkList(context.get("shippableItemInfo"));
    List<Map<String, BigDecimal>> packages = ShipmentWorker.getPackageSplit(dctx, shippableItemInfo, maxWeight);
    boolean isOnePackage = packages.size() == 1; // use shippableWeight if there's only one package

    // create the request document
    Document requestDocument = createUspsRequestDocument("IntlRateRequest", false, delegator,
            shipmentGatewayConfigId, resource);

    // TODO: Up to 25 packages can be included per request - handle more than 25
    for (ListIterator<Map<String, BigDecimal>> li = packages.listIterator(); li.hasNext();) {
        Map<String, BigDecimal> packageMap = li.next();

        Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                requestDocument);
        packageElement.setAttribute("ID", String.valueOf(li.nextIndex() - 1)); // use zero-based index (see examples)

        BigDecimal packageWeight = isOnePackage ? shippableWeight
                : ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, BigDecimal.ZERO);
        if (packageWeight.compareTo(BigDecimal.ZERO) == 0) {
            continue;
        }
        Integer[] weightPoundsOunces = convertPoundsToPoundsOunces(packageWeight);
        // for Parcel post, the weight must be at least 1 lb
        if ("PARCEL".equals(serviceCode.toUpperCase()) && (weightPoundsOunces[0] < 1)) {
            weightPoundsOunces[0] = 1;
            weightPoundsOunces[1] = 0;
        }
        UtilXml.addChildElementValue(packageElement, "Pounds", weightPoundsOunces[0].toString(),
                requestDocument);
        UtilXml.addChildElementValue(packageElement, "Ounces", weightPoundsOunces[1].toString(),
                requestDocument);

        UtilXml.addChildElementValue(packageElement, "Machinable", "False", requestDocument);
        UtilXml.addChildElementValue(packageElement, "MailType", "Package", requestDocument);

        // TODO: Add package value so that an insurance fee can be returned

        UtilXml.addChildElementValue(packageElement, "Country", destinationCountry, requestDocument);
    }

    // send the request
    Document responseDocument = null;
    try {
        responseDocument = sendUspsRequest("IntlRate", requestDocument, delegator, shipmentGatewayConfigId,
                resource, locale);
    } catch (UspsRequestException e) {
        Debug.logInfo(e, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateInternationalSendingError",
                        UtilMisc.toMap("errorString", e.getMessage()), locale));
    }

    if (responseDocument == null) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    List<? extends Element> packageElements = UtilXml.childElementList(responseDocument.getDocumentElement(),
            "Package");
    if (UtilValidate.isEmpty(packageElements)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
    }

    BigDecimal estimateAmount = BigDecimal.ZERO;
    for (Element packageElement : packageElements) {
        Element errorElement = UtilXml.firstChildElement(packageElement, "Error");
        if (errorElement != null) {
            String errorDescription = UtilXml.childElementValue(errorElement, "Description");
            Debug.logInfo("USPS International Rate Calculation returned a package error: " + errorDescription,
                    module);
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
        }
        List<? extends Element> serviceElements = UtilXml.childElementList(packageElement, "Service");
        for (Element serviceElement : serviceElements) {
            String respServiceCode = serviceElement.getAttribute("ID");
            if (!serviceCode.equalsIgnoreCase(respServiceCode)) {
                continue;
            }
            try {
                BigDecimal packageAmount = new BigDecimal(UtilXml.childElementValue(serviceElement, "Postage"));
                estimateAmount = estimateAmount.add(packageAmount);
            } catch (NumberFormatException e) {
                Debug.logInfo("USPS International Rate Calculation returned an unparsable postage amount: "
                        + UtilXml.childElementValue(serviceElement, "Postage"), module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resourceError, "FacilityShipmentRateNotAvailable", locale));
            }
        }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shippingEstimateAmount", estimateAmount);
    return result;
}

From source file:jp.aegif.nemaki.cmis.aspect.impl.ExceptionServiceImpl.java

private void constraintDecimalPropertyValue(PropertyDefinition<?> definition, PropertyData<?> propertyData,
        String objectId) {// w  w  w . j a va 2s. c  om
    final String msg = "An DECIMAL property violates the range constraints";

    if (!(propertyData instanceof PropertyDecimal))
        return;
    BigDecimal val = ((PropertyDecimal) propertyData).getFirstValue();

    BigDecimal min = ((PropertyDecimalDefinition) definition).getMinValue();
    if (min != null && min.compareTo(val) > 0) {
        constraint(objectId, msg);
    }

    BigDecimal max = ((PropertyDecimalDefinition) definition).getMaxValue();
    if (max != null && max.compareTo(val) > 0) {
        constraint(objectId, msg);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.scholarship.utl.report.StudentLine.java

public Boolean getStudentHadPerformanceLastYear() {
    BigDecimal numberOfApprovedEctsOneYearAgo = getNumberOfApprovedEctsOneYearAgo();
    BigDecimal numberOfEnrolledEctsOneYearAgo = getNumberOfEnrolledEctsOneYearAgo();

    if (numberOfEnrolledEctsOneYearAgo.compareTo(BigDecimal.ZERO) == 0) {
        return false;
    }/*from  w ww  . ja  v a2 s.  c o  m*/

    BigDecimal average = numberOfApprovedEctsOneYearAgo.divide(numberOfEnrolledEctsOneYearAgo,
            RoundingMode.HALF_EVEN);
    average.setScale(2);

    return average.compareTo(new BigDecimal(0.5f)) >= 0;
}