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.apache.fineract.portfolio.interestratechart.data.InterestRateChartSlabDataValidator.java

public void validateChartSlabsCreate(final JsonElement element, final DataValidatorBuilder baseDataValidator,
        final Locale locale) {

    if (this.fromApiJsonHelper.parameterExists(descriptionParamName, element)) {
        final String description = this.fromApiJsonHelper.extractStringNamed(descriptionParamName, element);
        baseDataValidator.reset().parameter(descriptionParamName).value(description).notNull();
    }/*from  ww w.jav a 2  s  . c  o  m*/

    final Integer periodType = this.fromApiJsonHelper.extractIntegerNamed(periodTypeParamName, element, locale);
    baseDataValidator.reset().parameter(periodTypeParamName).value(periodType).notNull()
            .isOneOfTheseValues(PeriodFrequencyType.integerValues());

    Integer toPeriod = null;

    final Integer fromPeriod = this.fromApiJsonHelper.extractIntegerNamed(fromPeriodParamName, element, locale);
    baseDataValidator.reset().parameter(fromPeriodParamName).value(fromPeriod).notNull().integerZeroOrGreater();

    if (this.fromApiJsonHelper.parameterExists(toPeriodParamName, element)) {
        toPeriod = this.fromApiJsonHelper.extractIntegerNamed(toPeriodParamName, element, locale);
        baseDataValidator.reset().parameter(toPeriodParamName).value(toPeriod).notNull().integerZeroOrGreater();
    }

    if (fromPeriod != null && toPeriod != null) {
        if (fromPeriod > toPeriod) {
            baseDataValidator.parameter(fromPeriodParamName).value(fromPeriod)
                    .failWithCode("fromperiod.greater.than.to.period");
        }
    }
    BigDecimal amountRangeFrom = null;
    BigDecimal amountRangeTo = null;
    if (this.fromApiJsonHelper.parameterExists(amountRangeFromParamName, element)) {
        amountRangeFrom = this.fromApiJsonHelper.extractBigDecimalNamed(amountRangeFromParamName, element,
                locale);
        baseDataValidator.reset().parameter(amountRangeFromParamName).value(amountRangeFrom).notNull()
                .positiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists(amountRangeToParamName, element)) {
        amountRangeTo = this.fromApiJsonHelper.extractBigDecimalNamed(amountRangeToParamName, element, locale);
        baseDataValidator.reset().parameter(amountRangeToParamName).value(amountRangeTo).notNull()
                .positiveAmount();
    }

    if (amountRangeFrom != null && amountRangeTo != null) {
        if (amountRangeFrom.compareTo(amountRangeTo) > 1) {
            baseDataValidator.parameter(fromPeriodParamName).value(fromPeriod)
                    .failWithCode("fromperiod.greater.than.toperiod");
        }
    }

    final BigDecimal annualInterestRate = this.fromApiJsonHelper
            .extractBigDecimalNamed(annualInterestRateParamName, element, locale);
    baseDataValidator.reset().parameter(annualInterestRateParamName).value(annualInterestRate).notNull()
            .zeroOrPositiveAmount();

    validateIncentives(element, baseDataValidator, locale);
}

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

public static Map<String, Object> uspsRateInquire(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) {
        // TODO: should we return an error, or $0.00 ?
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsShippableWeightMustGreaterThanZero", locale));
    }//from   ww w  .j a  va2  s  .co m

    // get the origination ZIP
    String originationZip = null;
    GenericValue productStore = ProductStoreWorker.getProductStore(((String) context.get("productStoreId")),
            delegator);
    if (productStore != null && productStore.get("inventoryFacilityId") != null) {
        GenericValue facilityContactMech = ContactMechWorker.getFacilityContactMechByPurpose(delegator,
                productStore.getString("inventoryFacilityId"),
                UtilMisc.toList("SHIP_ORIG_LOCATION", "PRIMARY_LOCATION"));
        if (facilityContactMech != null) {
            try {
                GenericValue shipFromAddress = EntityQuery.use(delegator).from("PostalAddress")
                        .where("contactMechId", facilityContactMech.getString("contactMechId")).queryOne();
                if (shipFromAddress != null) {
                    originationZip = shipFromAddress.getString("postalCode");
                }
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
        }
    }
    if (UtilValidate.isEmpty(originationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineOriginationZip", locale));
    }

    // get the destination ZIP
    String destinationZip = null;
    String shippingContactMechId = (String) context.get("shippingContactMechId");
    if (UtilValidate.isNotEmpty(shippingContactMechId)) {
        try {
            GenericValue shipToAddress = EntityQuery.use(delegator).from("PostalAddress")
                    .where("contactMechId", shippingContactMechId).queryOne();
            if (shipToAddress != null) {
                if (!domesticCountries.contains(shipToAddress.getString("countryGeoId"))) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsRateInquiryOnlyInUsDestinations", locale));
                }
                destinationZip = shipToAddress.getString("postalCode");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    if (UtilValidate.isEmpty(destinationZip)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineDestinationZip", 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").toUpperCase();
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (UtilValidate.isEmpty(serviceCode)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsUnableDetermineServiceCode", locale));
    }

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

    // TODO: 70 lb max is valid for Express, Priority and Parcel only - handle other methods
    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
    // 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();

        BigDecimal packageWeight = isOnePackage ? shippableWeight
                : ShipmentWorker.calcPackageWeight(dctx, packageMap, shippableItemInfo, BigDecimal.ZERO);
        if (packageWeight.compareTo(BigDecimal.ZERO) == 0) {
            continue;
        }

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

        UtilXml.addChildElementValue(packageElement, "Service", serviceCode, requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipOrigination",
                StringUtils.substring(originationZip, 0, 5), requestDocument);
        UtilXml.addChildElementValue(packageElement, "ZipDestination",
                StringUtils.substring(destinationZip, 0, 5), requestDocument);

        BigDecimal weightPounds = packageWeight.setScale(0, BigDecimal.ROUND_FLOOR);
        // for Parcel post, the weight must be at least 1 lb
        if ("PARCEL".equals(serviceCode.toUpperCase()) && (weightPounds.compareTo(BigDecimal.ONE) < 0)) {
            weightPounds = BigDecimal.ONE;
            packageWeight = BigDecimal.ZERO;
        }
        // (packageWeight % 1) * 16 (Rounded up to 0 dp)
        BigDecimal weightOunces = packageWeight.remainder(BigDecimal.ONE).multiply(new BigDecimal("16"))
                .setScale(0, BigDecimal.ROUND_CEILING);

        UtilXml.addChildElementValue(packageElement, "Pounds", weightPounds.toPlainString(), requestDocument);
        UtilXml.addChildElementValue(packageElement, "Ounces", weightOunces.toPlainString(), requestDocument);

        // TODO: handle other container types, package sizes, and machinable packages
        // IMPORTANT: Express or Priority Mail will fail if you supply a Container tag: you will get a message like
        // Invalid container type. Valid container types for Priority Mail are Flat Rate Envelope and Flat Rate Box.
        /* This is an official response from the United States Postal Service:
        The <Container> tag is used to specify the flat rate mailing options, or the type of large or oversized package being mailed.
        If you are wanting to get regular Express Mail rates, leave the <Container> tag empty, or do not include it in the request at all.
         */
        if ("Parcel".equalsIgnoreCase(serviceCode)) {
            UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
        }
        UtilXml.addChildElementValue(packageElement, "Size", "REGULAR", requestDocument);
        UtilXml.addChildElementValue(packageElement, "Machinable", "false", requestDocument);
    }

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

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

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

    BigDecimal estimateAmount = BigDecimal.ZERO;
    for (Element packageElement : rates) {
        try {
            Element postageElement = UtilXml.firstChildElement(packageElement, "Postage");
            BigDecimal packageAmount = new BigDecimal(UtilXml.childElementValue(postageElement, "Rate"));
            estimateAmount = estimateAmount.add(packageAmount);
        } catch (NumberFormatException e) {
            Debug.logInfo(e, module);
        }
    }

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

From source file:org.apache.fineract.portfolio.interestratechart.data.InterestRateChartSlabDataValidator.java

public void validateChartSlabsUpdate(final JsonElement element, final DataValidatorBuilder baseDataValidator,
        final Locale locale) {

    if (this.fromApiJsonHelper.parameterExists(descriptionParamName, element)) {
        final String description = this.fromApiJsonHelper.extractStringNamed(descriptionParamName, element);
        baseDataValidator.reset().parameter(descriptionParamName).value(description).ignoreIfNull();
    }//from  w  ww.  ja va2 s  . co  m

    if (this.fromApiJsonHelper.parameterExists(periodTypeParamName, element)) {
        final Integer periodType = this.fromApiJsonHelper.extractIntegerNamed(periodTypeParamName, element,
                locale);
        baseDataValidator.reset().parameter(periodTypeParamName).value(periodType).notNull()
                .isOneOfTheseValues(PeriodFrequencyType.integerValues());
    }

    Integer fromPeriod = null;
    Integer toPeriod = null;

    if (this.fromApiJsonHelper.parameterExists(fromPeriodParamName, element)) {
        fromPeriod = this.fromApiJsonHelper.extractIntegerNamed(fromPeriodParamName, element, locale);
        baseDataValidator.reset().parameter(fromPeriodParamName).value(fromPeriod).notNull()
                .integerGreaterThanNumber(-1);
    }

    if (this.fromApiJsonHelper.parameterExists(toPeriodParamName, element)) {
        toPeriod = this.fromApiJsonHelper.extractIntegerNamed(toPeriodParamName, element, locale);
        baseDataValidator.reset().parameter(toPeriodParamName).value(toPeriod).notNull()
                .integerGreaterThanNumber(-1);
    }

    if (fromPeriod != null && toPeriod != null) {
        if (fromPeriod > toPeriod) {
            baseDataValidator.parameter(fromPeriodParamName).value(fromPeriod)
                    .failWithCode("fromperiod.greater.than.toperiod");
        }
    }
    BigDecimal amountRangeFrom = null;
    BigDecimal amountRangeTo = null;
    if (this.fromApiJsonHelper.parameterExists(amountRangeFromParamName, element)) {
        amountRangeFrom = this.fromApiJsonHelper.extractBigDecimalNamed(amountRangeFromParamName, element,
                locale);
        baseDataValidator.reset().parameter(amountRangeFromParamName).value(amountRangeFrom).notNull()
                .positiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists(amountRangeToParamName, element)) {
        amountRangeTo = this.fromApiJsonHelper.extractBigDecimalNamed(amountRangeToParamName, element, locale);
        baseDataValidator.reset().parameter(amountRangeToParamName).value(amountRangeTo).notNull()
                .positiveAmount();
    }

    if (amountRangeFrom != null && amountRangeTo != null) {
        if (amountRangeFrom.compareTo(amountRangeTo) > 1) {
            baseDataValidator.parameter(fromPeriodParamName).value(fromPeriod)
                    .failWithCode("fromperiod.greater.than.toperiod");
        }
    }

    if (this.fromApiJsonHelper.parameterExists(annualInterestRateParamName, element)) {
        final BigDecimal annualInterestRate = this.fromApiJsonHelper
                .extractBigDecimalNamed(annualInterestRateParamName, element, locale);
        baseDataValidator.reset().parameter(annualInterestRateParamName).value(annualInterestRate).notNull()
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) {
        final String currencyCode = this.fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element);
        baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank()
                .notExceedingLengthOf(3);
    }
    validateIncentives(element, baseDataValidator, locale);
}

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

@RequestMapping(value = "/calculate", params = "type=exchange", method = RequestMethod.GET)
public @ResponseBody Map<String, Object> calculate(Long productId, Integer quantity, Long receiverId,
        Long paymentMethodId, Long shippingMethodId, BigDecimal balance, String memo) {
    Map<String, Object> data = new HashMap<String, Object>();
    if (quantity == null || quantity < 1) {
        data.put("message", ERROR_MESSAGE);
        return data;
    }/* w w w  .j a v a2 s  .c  om*/
    Product product = productService.find(productId);
    if (product == null) {
        data.put("message", ERROR_MESSAGE);
        return data;
    }
    Member member = memberService.getCurrent();
    Receiver receiver = receiverService.find(receiverId);
    if (receiver != null && !member.equals(receiver.getMember())) {
        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;
    }
    PaymentMethod paymentMethod = paymentMethodService.find(paymentMethodId);
    ShippingMethod shippingMethod = shippingMethodService.find(shippingMethodId);
    Set<CartItem> cartItems = new HashSet<CartItem>();
    CartItem cartItem = new CartItem();
    cartItem.setProduct(product);
    cartItem.setQuantity(quantity);
    cartItems.add(cartItem);
    Cart cart = new Cart();
    cart.setMember(member);
    cart.setCartItems(cartItems);
    Order order = orderService.generate(Order.Type.general, cart, receiver, paymentMethod, shippingMethod, null,
            null, balance, null);

    data.put("message", SUCCESS_MESSAGE);
    data.put("price", order.getPrice());
    data.put("fee", order.getFee());
    data.put("freight", order.getFreight());
    data.put("tax", order.getTax());
    data.put("promotionDiscount", order.getPromotionDiscount());
    data.put("couponDiscount", order.getCouponDiscount());
    data.put("amount", order.getAmount());
    data.put("amountPayable", order.getAmountPayable());
    return data;
}

From source file:au.org.ala.delta.editor.slotfile.directive.DirOutDefault.java

private void writeKeyStates(MutableDeltaDataSet dataSet, DirectiveArguments directiveArgs) {
    int prevNo;/*  w w  w  .ja  v  a  2 s .c  o  m*/
    int curNo;
    List<DirectiveArgument<?>> args;
    List<Integer> data;
    // The comparison function will sort all the key states, grouping
    // all those belonging to a single character, sorted in order by
    // there pseudo-value.
    args = directiveArgs.getDirectiveArguments();
    Collections.sort(args);
    prevNo = 0;
    for (DirectiveArgument<?> vectIter : directiveArgs.getDirectiveArguments()) {
        au.org.ala.delta.model.Character charBase = dataSet.getCharacter((Integer) vectIter.getId());
        CharacterType charType = charBase.getCharacterType();
        curNo = charBase.getCharacterId();
        if (curNo != prevNo) {
            _textBuffer.append(" ").append(curNo).append(",");
            prevNo = curNo;
        } else
            _textBuffer.append('/');

        switch (charType) {
        case UnorderedMultiState:
            data = vectIter.getDataList();
            Collections.sort(data);
            for (int j = 0; j < data.size(); j++) {
                if (j != 0)
                    _textBuffer.append('&');
                _textBuffer.append(data.get(j));
            }
            break;

        case OrderedMultiState:

        {
            data = vectIter.getDataList();
            int loState, hiState, aState;

            if (data.size() < 2)
                throw new RuntimeException("ED_INTERNAL_ERROR");
            aState = data.get(0);
            hiState = data.get(1);
            loState = Math.min(aState, hiState);
            hiState = Math.max(aState, hiState);
            _textBuffer.append(loState);
            if (hiState > loState) {
                _textBuffer.append('-');
                _textBuffer.append(hiState);
            }
        }
            break;

        case IntegerNumeric:
        case RealNumeric: {
            List<BigDecimal> bigDecimals = vectIter.getData();
            BigDecimal loNumb, hiNumb;
            if (bigDecimals.size() < 2)
                throw new RuntimeException("ED_INTERNAL_ERROR");
            loNumb = bigDecimals.get(0);
            hiNumb = bigDecimals.get(1);
            if (loNumb.floatValue() == -Float.MAX_VALUE)
                _textBuffer.append('~');
            else {
                _textBuffer.append(loNumb.toPlainString());
            }
            if (hiNumb.floatValue() == Float.MAX_VALUE)
                _textBuffer.append('~');
            else if (loNumb.compareTo(hiNumb) < 0) {
                if (!(loNumb.floatValue() == -Float.MAX_VALUE))
                    _textBuffer.append('-');

                _textBuffer.append(hiNumb.toPlainString());
            }
        }
            break;

        default:
            throw new RuntimeException("ED_INAPPROPRIATE_TYPE");
            // break;
        }
    }
}

From source file:org.openvpms.archetype.rules.finance.till.TillRulesTestCase.java

private BigDecimal checkBalance(BigDecimal initialCashFloat, BigDecimal newCashFloat, FinancialAct balance,
        String status) {//w ww . j  a  va2 s .  c  o m
    // make sure the balance is updated
    assertEquals(status, balance.getStatus());
    // end time should be > startTime < now
    Date startTime = balance.getActivityStartTime();
    Date endTime = balance.getActivityEndTime();
    if (TillBalanceStatus.CLEARED.equals(status)) {
        // CLEARED balances have an end time
        assertEquals(1, endTime.compareTo(startTime));
        assertEquals(-1, endTime.compareTo(new Date()));
    } else {
        // IN_PROGRESS balances do not
        assertNull(endTime);
    }

    BigDecimal total = newCashFloat.subtract(initialCashFloat);

    if (initialCashFloat.compareTo(newCashFloat) != 0) {
        // expect a till balance adjustment to have been made
        Set<ActRelationship> rels = balance.getSourceActRelationships();
        assertEquals(1, rels.size());
        ActRelationship r = rels.toArray(new ActRelationship[rels.size()])[0];
        Act target = (Act) get(r.getTarget());
        assertTrue(TypeHelper.isA(target, "act.tillBalanceAdjustment"));
        ActBean adjBean = new ActBean(target);
        BigDecimal amount = adjBean.getBigDecimal("amount");

        boolean credit = (newCashFloat.compareTo(initialCashFloat) < 0);
        BigDecimal adjustmentTotal = total.abs();
        assertTrue(adjustmentTotal.compareTo(amount) == 0);
        assertEquals(credit, adjBean.getBoolean("credit"));
    } else {
        // no till balance adjustment should have been generated
        assertTrue(balance.getSourceActRelationships().isEmpty());
    }

    // check the till balance.
    BigDecimal expectedBalance = total.negate();
    assertTrue(expectedBalance.compareTo(balance.getTotal()) == 0);

    // make sure the till is updated
    Party till = (Party) get(this.till.getObjectReference());
    IMObjectBean bean = new IMObjectBean(till);
    BigDecimal currentFloat = bean.getBigDecimal("tillFloat");
    Date lastCleared = bean.getDate("lastCleared");
    Date now = new Date();

    assertTrue(currentFloat.compareTo(newCashFloat) == 0);
    assertTrue(now.compareTo(lastCleared) == 1); // expect now > lastCleared
    return expectedBalance;
}

From source file:de.metas.procurement.webui.sync.SyncRfqImportService.java

private void importPlannedProductSupply(final SyncProductSupply syncProductSupply, final BPartner bpartner) {
    final String product_uuid = syncProductSupply.getProduct_uuid();
    final Product product = productRepo.findByUuid(product_uuid);
    ////from  w  w w.j a va 2  s .  c o m
    final String contractLine_uuid = syncProductSupply.getContractLine_uuid();
    final ContractLine contractLine = contractLineRepo.findByUuid(contractLine_uuid);
    //
    final Date day = DateUtils.truncToDay(syncProductSupply.getDay());
    final BigDecimal qty = Objects.firstNonNull(syncProductSupply.getQty(), BigDecimal.ZERO);

    ProductSupply productSupply = productSupplyRepo.findByProductAndBpartnerAndDay(product, bpartner, day);
    final boolean isNew;
    if (productSupply == null) {
        isNew = true;
        productSupply = ProductSupply.build(bpartner, product, contractLine, day);
    } else {
        isNew = false;
    }

    //
    // Contract line
    if (!isNew) {
        final ContractLine contractLineOld = productSupply.getContractLine();
        if (!Objects.equal(contractLine, contractLineOld)) {
            logger.warn("Changing contract line {}->{} for {} because of planning supply: {}", contractLineOld,
                    contractLine, productSupply, syncProductSupply);
        }
        productSupply.setContractLine(contractLine);
    }

    //
    // Quantity
    if (!isNew) {
        final BigDecimal qtyOld = productSupply.getQty();
        if (qty.compareTo(qtyOld) != 0) {
            logger.warn("Changing quantity {}->{} for {} because of planning supply: {}", qtyOld, qty,
                    productSupply, syncProductSupply);
        }
    }
    productSupply.setQty(qty);

    //
    // Save the product supply
    productSupplyRepo.save(productSupply);

    applicationEventBus.post(ProductSupplyChangedEvent.of(productSupply));
}

From source file:com.jeans.iservlet.action.asset.AssetAction.java

/**
 * ?/*from  w  ww.j a v  a 2 s  .c o  m*/
 * 
 * @return
 * @throws Exception
 */
@Action(value = "load-assets", results = { @Result(type = "json", params = { "root", "data" }) })
public String loadAssets() throws Exception {
    long[] total = new long[1];
    List<Asset> assets = assetService.loadAssets(getCurrentCompany(), type, page, rows, total);
    List<AssetItem> assetItemsList = new ArrayList<AssetItem>();
    for (Asset asset : assets) {
        if (asset instanceof Hardware) {
            assetItemsList.add(HardwareItem.createInstance((Hardware) asset));
        } else if (asset instanceof Software) {
            assetItemsList.add(SoftwareItem.createInstance((Software) asset));
        }
    }
    data = new DataGrid<AssetItem>(total[0], assetItemsList);
    if (null != sort && data.getRows().size() > 0) {
        Collections.sort(data.getRows(), new Comparator<AssetItem>() {

            @Override
            public int compare(AssetItem o1, AssetItem o2) {
                int ret = 0;
                boolean asc = "asc".equals(order);
                boolean isHardware = o1 instanceof HardwareItem;
                switch (sort) {
                case "code":
                    ret = compString(((HardwareItem) o1).getCode(), ((HardwareItem) o2).getCode(), asc);
                    break;
                case "financialCode":
                    ret = compString(((HardwareItem) o1).getFinancialCode(),
                            ((HardwareItem) o2).getFinancialCode(), asc);
                    break;
                case "name":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getName(), ((HardwareItem) o2).getName(), asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getName(), ((SoftwareItem) o2).getName(), asc);
                    }
                    break;
                case "vendor":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getVendor(), ((HardwareItem) o2).getVendor(), asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getVendor(), ((SoftwareItem) o2).getVendor(), asc);
                    }
                    break;
                case "modelOrVersion":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getModelOrVersion(), ((HardwareItem) o2).getName(),
                                asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getModelOrVersion(),
                                ((SoftwareItem) o2).getModelOrVersion(), asc);
                    }
                    break;
                case "sn":
                    ret = compString(((HardwareItem) o1).getSn(), ((HardwareItem) o2).getSn(), asc);
                    break;
                case "purchaseTime":
                    Date t1 = isHardware ? ((HardwareItem) o1).getPurchaseTime()
                            : ((SoftwareItem) o1).getPurchaseTime();
                    Date t2 = isHardware ? ((HardwareItem) o2).getPurchaseTime()
                            : ((SoftwareItem) o2).getPurchaseTime();
                    if (null == t1) {
                        if (null == t2) {
                            ret = 0;
                        } else {
                            ret = asc ? -1 : 1;
                        }
                    } else {
                        if (null == t2) {
                            ret = asc ? 1 : -1;
                        } else {
                            ret = asc ? t1.compareTo(t2) : t2.compareTo(t1);
                        }
                    }
                    break;
                case "quantity":
                    if (isHardware) {
                        ret = asc
                                ? Integer.compare(((HardwareItem) o1).getQuantity(),
                                        ((HardwareItem) o2).getQuantity())
                                : Integer.compare(((HardwareItem) o2).getQuantity(),
                                        ((HardwareItem) o1).getQuantity());
                    } else {
                        ret = asc
                                ? Integer.compare(((SoftwareItem) o1).getQuantity(),
                                        ((SoftwareItem) o2).getQuantity())
                                : Integer.compare(((SoftwareItem) o2).getQuantity(),
                                        ((SoftwareItem) o1).getQuantity());
                    }
                    break;
                case "cost":
                    BigDecimal d1 = isHardware ? ((HardwareItem) o1).getCost() : ((SoftwareItem) o1).getCost();
                    BigDecimal d2 = isHardware ? ((HardwareItem) o2).getCost() : ((SoftwareItem) o2).getCost();
                    if (null == d1) {
                        d1 = new BigDecimal(0.0);
                    }
                    if (null == d2) {
                        d2 = new BigDecimal(0.0);
                    }
                    ret = asc ? d1.compareTo(d2) : d2.compareTo(d1);
                    break;
                case "state":
                    if (isHardware) {
                        ret = compString(((HardwareItem) o1).getState(), ((HardwareItem) o2).getState(), asc);
                    } else {
                        ret = compString(((SoftwareItem) o1).getState(), ((SoftwareItem) o2).getState(), asc);
                    }
                    break;
                case "warranty":
                    ret = compString(((HardwareItem) o1).getWarranty(), ((HardwareItem) o2).getWarranty(), asc);
                    break;
                case "location":
                    ret = compString(((HardwareItem) o1).getLocation(), ((HardwareItem) o2).getLocation(), asc);
                    break;
                case "ip":
                    ret = compString(((HardwareItem) o1).getIp(), ((HardwareItem) o2).getIp(), asc);
                    break;
                case "importance":
                    ret = compString(((HardwareItem) o1).getImportance(), ((HardwareItem) o2).getImportance(),
                            asc);
                    break;
                case "owner":
                    ret = compString(((HardwareItem) o1).getOwner(), ((HardwareItem) o2).getOwner(), asc);
                    break;
                case "softwareType":
                    ret = compString(((SoftwareItem) o1).getSoftwareType(),
                            ((SoftwareItem) o2).getSoftwareType(), asc);
                    break;
                case "license":
                    ret = compString(((SoftwareItem) o1).getLicense(), ((SoftwareItem) o2).getLicense(), asc);
                    break;
                case "expiredTime":
                    Date e1 = ((SoftwareItem) o1).getPurchaseTime();
                    Date e2 = ((SoftwareItem) o2).getPurchaseTime();
                    if (null == e1) {
                        if (null == e2) {
                            ret = 0;
                        } else {
                            ret = asc ? -1 : 1;
                        }
                    } else {
                        if (null == e2) {
                            ret = asc ? 1 : -1;
                        } else {
                            ret = asc ? e1.compareTo(e2) : e2.compareTo(e1);
                        }
                    }
                }
                return ret;
            }

            private int compString(String s1, String s2, boolean asc) {
                if (null == s1) {
                    if (null == s2) {
                        return 0;
                    } else {
                        return asc ? -1 : 1;
                    }
                } else {
                    if (null == s2) {
                        return asc ? 1 : -1;
                    } else {
                        return asc ? Collator.getInstance(java.util.Locale.CHINA).compare(s1, s2)
                                : Collator.getInstance(java.util.Locale.CHINA).compare(s2, s1);
                    }
                }
            }

        });
    }
    return SUCCESS;
}

From source file:com.dp2345.entity.Cart.java

/**
 * ?/* w  ww  . j  ava  2 s  .co  m*/
 * 
 * @return 
 */
@Transient
public BigDecimal getDiscount() {
    BigDecimal originalPrice = new BigDecimal(0);
    BigDecimal currentPrice = new BigDecimal(0);
    for (Promotion promotion : getPromotions()) {
        if (promotion != null) {
            int promotionQuantity = getQuantity(promotion);
            BigDecimal originalPromotionPrice = getTempPrice(promotion);
            BigDecimal currentPromotionPrice = promotion.calculatePrice(promotionQuantity,
                    originalPromotionPrice);
            originalPrice = originalPrice.add(originalPromotionPrice);
            currentPrice = currentPrice.add(currentPromotionPrice);
            Set<CartItem> cartItems = getCartItems(promotion);
            for (CartItem cartItem : cartItems) {
                if (cartItem != null && cartItem.getTempPrice() != null) {
                    BigDecimal tempPrice;
                    if (originalPromotionPrice.compareTo(new BigDecimal(0)) > 0) {
                        tempPrice = currentPromotionPrice.divide(originalPromotionPrice, 50, RoundingMode.DOWN)
                                .multiply(cartItem.getTempPrice());
                    } else {
                        tempPrice = new BigDecimal(0);
                    }
                    cartItem.setTempPrice(
                            tempPrice.compareTo(new BigDecimal(0)) > 0 ? tempPrice : new BigDecimal(0));
                }
            }
        }
    }
    if (getCartItems() != null) {
        for (CartItem cartItem : getCartItems()) {
            if (cartItem != null) {
                cartItem.setTempPrice(null);
            }
        }
    }
    Setting setting = SettingUtils.get();
    BigDecimal discount = setting.setScale(originalPrice.subtract(currentPrice));
    return discount.compareTo(new BigDecimal(0)) > 0 ? discount : new BigDecimal(0);
}

From source file:op.care.nursingprocess.PnlSchedule.java

private void txtMinutesFocusLost(FocusEvent e) {
    BigDecimal bd = SYSTools.parseDecimal(txtMinutes.getText());
    if (bd == null || bd.compareTo(BigDecimal.ZERO) <= 0) {
        txtMinutes.setText(is.getDauer().toPlainString());
    }/*from  ww  w . j ava2 s .com*/
}