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.aoindustries.website.signup.SignupCustomizeServerActionHelper.java

public static void setRequestAttributes(ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response, SignupSelectPackageForm signupSelectPackageForm,
        SignupCustomizeServerForm signupCustomizeServerForm) throws IOException, SQLException {
    AOServConnector rootConn = SiteSettings.getInstance(servletContext).getRootAOServConnector();
    PackageDefinition packageDefinition = rootConn.getPackageDefinitions()
            .get(signupSelectPackageForm.getPackageDefinition());
    if (packageDefinition == null)
        throw new SQLException(
                "Unable to find PackageDefinition: " + signupSelectPackageForm.getPackageDefinition());
    List<PackageDefinitionLimit> limits = packageDefinition.getLimits();

    // Find the cheapest resources to scale prices from
    int maxPowers = 0;
    PackageDefinitionLimit cheapestPower = null;
    int maxCPUs = 0;
    PackageDefinitionLimit cheapestCPU = null;
    int maxRAMs = 0;
    PackageDefinitionLimit cheapestRAM = null;
    int maxSataControllers = 0;
    PackageDefinitionLimit cheapestSataController = null;
    int maxScsiControllers = 0;
    PackageDefinitionLimit cheapestScsiController = null;
    int maxDisks = 0;
    PackageDefinitionLimit cheapestDisk = null;
    for (PackageDefinitionLimit limit : limits) {
        String resourceName = limit.getResource().getName();
        if (resourceName.startsWith("hardware_power_")) {
            int limitPower = limit.getHardLimit();
            if (limitPower > 0) {
                if (limitPower > maxPowers)
                    maxPowers = limitPower;
                if (cheapestPower == null)
                    cheapestPower = limit;
                else {
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    BigDecimal cheapestRate = cheapestPower.getAdditionalRate();
                    if (cheapestRate == null)
                        cheapestRate = BigDecimal.valueOf(0, 2);
                    if (additionalRate.compareTo(cheapestRate) < 0)
                        cheapestPower = limit;
                }//from w w  w .j a va2s . c om
            }
        } else if (resourceName.startsWith("hardware_processor_")) {
            int limitCpu = limit.getHardLimit();
            if (limitCpu > 0) {
                if (limitCpu > maxCPUs)
                    maxCPUs = limitCpu;
                if (cheapestCPU == null)
                    cheapestCPU = limit;
                else {
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    BigDecimal cheapestRate = cheapestCPU.getAdditionalRate();
                    if (cheapestRate == null)
                        cheapestRate = BigDecimal.valueOf(0, 2);
                    if (additionalRate.compareTo(cheapestRate) < 0)
                        cheapestCPU = limit;
                }
            }
        } else if (resourceName.startsWith("hardware_ram_")) {
            int limitRAM = limit.getHardLimit();
            if (limitRAM > 0) {
                if (limitRAM > maxRAMs)
                    maxRAMs = limitRAM;
                if (cheapestRAM == null)
                    cheapestRAM = limit;
                else {
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    BigDecimal cheapestRate = cheapestRAM.getAdditionalRate();
                    if (cheapestRate == null)
                        cheapestRate = BigDecimal.valueOf(0, 2);
                    if (additionalRate.compareTo(cheapestRate) < 0)
                        cheapestRAM = limit;
                }
            }
        } else if (resourceName.startsWith("hardware_disk_controller_sata_")) {
            int limitSataController = limit.getHardLimit();
            if (limitSataController > 0) {
                if (limitSataController > maxSataControllers)
                    maxSataControllers = limitSataController;
                if (cheapestSataController == null)
                    cheapestSataController = limit;
                else {
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    BigDecimal cheapestRate = cheapestSataController.getAdditionalRate();
                    if (cheapestRate == null)
                        cheapestRate = BigDecimal.valueOf(0, 2);
                    if (additionalRate.compareTo(cheapestRate) < 0)
                        cheapestSataController = limit;
                }
            }
        } else if (resourceName.startsWith("hardware_disk_controller_scsi_")) {
            int limitScsiController = limit.getHardLimit();
            if (limitScsiController > 0) {
                if (limitScsiController > maxScsiControllers)
                    maxScsiControllers = limitScsiController;
                if (cheapestScsiController == null)
                    cheapestScsiController = limit;
                else {
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    BigDecimal cheapestRate = cheapestScsiController.getAdditionalRate();
                    if (cheapestRate == null)
                        cheapestRate = BigDecimal.valueOf(0, 2);
                    if (additionalRate.compareTo(cheapestRate) < 0)
                        cheapestScsiController = limit;
                }
            }
        } else if (resourceName.startsWith("hardware_disk_")) {
            int hardLimit = limit.getHardLimit();
            if (hardLimit > 0) {
                if (cheapestDisk == null)
                    cheapestDisk = limit;
                else {
                    BigDecimal additionalRate = limit.getAdditionalRate();
                    if (additionalRate == null)
                        additionalRate = BigDecimal.valueOf(0, 2);
                    BigDecimal cheapestRate = cheapestDisk.getAdditionalRate();
                    if (cheapestRate == null)
                        cheapestRate = BigDecimal.valueOf(0, 2);
                    if (additionalRate.compareTo(cheapestRate) < 0)
                        cheapestDisk = limit;
                }
                if (hardLimit > maxDisks)
                    maxDisks = hardLimit;
            }
        }
    }
    if (cheapestCPU == null)
        throw new SQLException("Unable to find cheapestCPU");
    if (cheapestRAM == null)
        throw new SQLException("Unable to find cheapestRAM");
    if (cheapestDisk == null)
        throw new SQLException("Unable to find cheapestDisk");

    // Find all the options
    List<Option> powerOptions = new ArrayList<Option>();
    List<Option> cpuOptions = new ArrayList<Option>();
    List<Option> ramOptions = new ArrayList<Option>();
    List<Option> sataControllerOptions = new ArrayList<Option>();
    List<Option> scsiControllerOptions = new ArrayList<Option>();
    List<List<Option>> diskOptions = new ArrayList<List<Option>>();
    for (int c = 0; c < maxDisks; c++)
        diskOptions.add(new ArrayList<Option>());
    for (PackageDefinitionLimit limit : limits) {
        Resource resource = limit.getResource();
        String resourceName = resource.getName();
        if (resourceName.startsWith("hardware_power_")) {
            int limitPower = limit.getHardLimit();
            if (limitPower > 0) {
                assert cheapestPower != null;
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                BigDecimal cheapestRate = cheapestPower.getAdditionalRate();
                if (cheapestRate == null)
                    cheapestRate = BigDecimal.valueOf(0, 2);
                String description = maxPowers == 1 ? resource.toString()
                        : (maxPowers + "x" + resource.toString());
                powerOptions.add(new Option(limit.getPkey(), description,
                        BigDecimal.valueOf(maxPowers).multiply(additionalRate.subtract(cheapestRate))));
            }
        } else if (resourceName.startsWith("hardware_processor_")) {
            int limitCpu = limit.getHardLimit();
            if (limitCpu > 0) {
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                BigDecimal cheapestRate = cheapestCPU.getAdditionalRate();
                if (cheapestRate == null)
                    cheapestRate = BigDecimal.valueOf(0, 2);
                String description = maxCPUs == 1 ? resource.toString() : (maxCPUs + "x" + resource.toString());
                cpuOptions.add(new Option(limit.getPkey(), description,
                        BigDecimal.valueOf(maxCPUs).multiply(additionalRate.subtract(cheapestRate))));
            }
        } else if (resourceName.startsWith("hardware_ram_")) {
            int limitRAM = limit.getHardLimit();
            if (limitRAM > 0) {
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                BigDecimal cheapestRate = cheapestRAM.getAdditionalRate();
                if (cheapestRate == null)
                    cheapestRate = BigDecimal.valueOf(0, 2);
                String description = maxRAMs == 1 ? resource.toString() : (maxRAMs + "x" + resource.toString());
                ramOptions.add(new Option(limit.getPkey(), description,
                        BigDecimal.valueOf(maxRAMs).multiply(additionalRate.subtract(cheapestRate))));
            }
        } else if (resourceName.startsWith("hardware_disk_controller_sata_")) {
            int limitSataController = limit.getHardLimit();
            if (limitSataController > 0) {
                assert cheapestSataController != null;
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                BigDecimal cheapestRate = cheapestSataController.getAdditionalRate();
                if (cheapestRate == null)
                    cheapestRate = BigDecimal.valueOf(0, 2);
                String description = maxSataControllers == 1 ? resource.toString()
                        : (maxSataControllers + "x" + resource.toString());
                sataControllerOptions.add(new Option(limit.getPkey(), description, BigDecimal
                        .valueOf(maxSataControllers).multiply(additionalRate.subtract(cheapestRate))));
            }
        } else if (resourceName.startsWith("hardware_disk_controller_scsi_")) {
            int limitScsiController = limit.getHardLimit();
            if (limitScsiController > 0) {
                assert cheapestScsiController != null;
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                BigDecimal cheapestRate = cheapestScsiController.getAdditionalRate();
                if (cheapestRate == null)
                    cheapestRate = BigDecimal.valueOf(0, 2);
                String description = maxScsiControllers == 1 ? resource.toString()
                        : (maxScsiControllers + "x" + resource.toString());
                scsiControllerOptions.add(new Option(limit.getPkey(), description, BigDecimal
                        .valueOf(maxScsiControllers).multiply(additionalRate.subtract(cheapestRate))));
            }
        } else if (resourceName.startsWith("hardware_disk_")) {
            int limitDisk = limit.getHardLimit();
            if (limitDisk > 0) {
                BigDecimal additionalRate = limit.getAdditionalRate();
                if (additionalRate == null)
                    additionalRate = BigDecimal.valueOf(0, 2);
                BigDecimal adjustedRate = additionalRate;
                // Discount adjusted rate if the cheapest disk is of this type
                if (cheapestDisk.getResource().getName().startsWith("hardware_disk_")) {
                    BigDecimal cheapestRate = cheapestDisk.getAdditionalRate();
                    if (cheapestRate == null)
                        cheapestRate = BigDecimal.valueOf(0, 2);
                    adjustedRate = adjustedRate.subtract(cheapestRate);
                }
                for (int c = 0; c < maxDisks; c++) {
                    List<Option> options = diskOptions.get(c);
                    // Add none option
                    if (maxDisks > 1 && options.isEmpty())
                        options.add(new Option(-1, "None",
                                c == 0 ? adjustedRate.subtract(additionalRate) : BigDecimal.valueOf(0, 2)));
                    options.add(new Option(limit.getPkey(), resource.toString(),
                            c == 0 ? adjustedRate : additionalRate));
                }
            }
        }
    }

    // Sort by price
    Collections.sort(powerOptions, new Option.PriceComparator());
    Collections.sort(cpuOptions, new Option.PriceComparator());
    Collections.sort(ramOptions, new Option.PriceComparator());
    Collections.sort(sataControllerOptions, new Option.PriceComparator());
    Collections.sort(scsiControllerOptions, new Option.PriceComparator());
    for (List<Option> diskOptionList : diskOptions)
        Collections.sort(diskOptionList, new Option.PriceComparator());

    // Clear any customization settings that are not part of the current package definition (this happens when they
    // select a different package type)
    if (signupCustomizeServerForm.getPowerOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeServerForm.getPowerOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeServerForm.setPowerOption(-1);
    }
    if (signupCustomizeServerForm.getCpuOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeServerForm.getCpuOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeServerForm.setCpuOption(-1);
    }
    if (signupCustomizeServerForm.getRamOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeServerForm.getRamOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeServerForm.setRamOption(-1);
    }
    if (signupCustomizeServerForm.getSataControllerOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeServerForm.getSataControllerOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeServerForm.setSataControllerOption(-1);
    }
    if (signupCustomizeServerForm.getScsiControllerOption() != -1) {
        PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits()
                .get(signupCustomizeServerForm.getScsiControllerOption());
        if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
            signupCustomizeServerForm.setScsiControllerOption(-1);
    }
    List<String> formDiskOptions = signupCustomizeServerForm.getDiskOptions();
    while (formDiskOptions.size() > maxDisks)
        formDiskOptions.remove(formDiskOptions.size() - 1);
    for (int c = 0; c < formDiskOptions.size(); c++) {
        String S = formDiskOptions.get(c);
        if (S != null && S.length() > 0 && !S.equals("-1")) {
            int pkey = Integer.parseInt(S);
            PackageDefinitionLimit pdl = rootConn.getPackageDefinitionLimits().get(pkey);
            if (pdl == null || !packageDefinition.equals(pdl.getPackageDefinition()))
                formDiskOptions.set(c, "-1");
        }
    }

    // Determine if at least one disk is selected
    boolean isAtLeastOneDiskSelected = signupCustomizeServerForm.isAtLeastOneDiskSelected();

    // Default to cheapest if not already selected
    if (cheapestPower != null && signupCustomizeServerForm.getPowerOption() == -1)
        signupCustomizeServerForm.setPowerOption(cheapestPower.getPkey());
    if (signupCustomizeServerForm.getCpuOption() == -1)
        signupCustomizeServerForm.setCpuOption(cheapestCPU.getPkey());
    if (signupCustomizeServerForm.getRamOption() == -1)
        signupCustomizeServerForm.setRamOption(cheapestRAM.getPkey());
    if (cheapestSataController != null && signupCustomizeServerForm.getSataControllerOption() == -1)
        signupCustomizeServerForm.setSataControllerOption(cheapestSataController.getPkey());
    if (cheapestScsiController != null && signupCustomizeServerForm.getScsiControllerOption() == -1)
        signupCustomizeServerForm.setScsiControllerOption(cheapestScsiController.getPkey());
    for (int c = 0; c < maxDisks; c++) {
        List<Option> options = diskOptions.get(c);
        if (!options.isEmpty()) {
            Option firstOption = options.get(0);
            if (!isAtLeastOneDiskSelected && options.size() >= 2
                    && firstOption.getPriceDifference().compareTo(BigDecimal.ZERO) < 0) {
                firstOption = options.get(1);
            }
            String defaultSelected = Integer.toString(firstOption.getPackageDefinitionLimit());
            if (formDiskOptions.size() <= c || formDiskOptions.get(c) == null
                    || formDiskOptions.get(c).length() == 0 || formDiskOptions.get(c).equals("-1"))
                formDiskOptions.set(c, defaultSelected);
        } else {
            formDiskOptions.set(c, "-1");
        }
    }

    // Find the basePrice (base plus minimum number of cheapest of each resource class)
    BigDecimal basePrice = packageDefinition.getMonthlyRate();
    if (basePrice == null)
        basePrice = BigDecimal.valueOf(0, 2);
    if (cheapestPower != null && cheapestPower.getAdditionalRate() != null)
        basePrice = basePrice.add(cheapestPower.getAdditionalRate().multiply(BigDecimal.valueOf(maxPowers)));
    if (cheapestCPU.getAdditionalRate() != null)
        basePrice = basePrice.add(cheapestCPU.getAdditionalRate().multiply(BigDecimal.valueOf(maxCPUs)));
    if (cheapestRAM.getAdditionalRate() != null)
        basePrice = basePrice.add(cheapestRAM.getAdditionalRate());
    if (cheapestSataController != null && cheapestSataController.getAdditionalRate() != null)
        basePrice = basePrice.add(cheapestSataController.getAdditionalRate());
    if (cheapestScsiController != null && cheapestScsiController.getAdditionalRate() != null)
        basePrice = basePrice.add(cheapestScsiController.getAdditionalRate());
    if (cheapestDisk.getAdditionalRate() != null)
        basePrice = basePrice.add(cheapestDisk.getAdditionalRate());

    // Store to request
    request.setAttribute("packageDefinition", packageDefinition);
    request.setAttribute("powerOptions", powerOptions);
    request.setAttribute("cpuOptions", cpuOptions);
    request.setAttribute("ramOptions", ramOptions);
    request.setAttribute("sataControllerOptions", sataControllerOptions);
    request.setAttribute("scsiControllerOptions", scsiControllerOptions);
    request.setAttribute("diskOptions", diskOptions);
    request.setAttribute("basePrice", basePrice);
}

From source file:com.osafe.services.OsafePayPalServices.java

public static Map<String, Object> payPalCheckoutUpdate(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");

    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);

    String token = (String) paramMap.get("TOKEN");
    WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token));
    ShoppingCart cart = null;/*from   ww w. j a  v a 2 s. co  m*/
    if (weakCart != null) {
        cart = weakCart.get();
    }
    if (cart == null) {
        Debug.logError("Could locate the ShoppingCart for token " + token, module);
        return ServiceUtil.returnSuccess();
    }
    // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll create one and
    // then delete once we're done, now is not the time to worry about updating everything
    String contactMechId = null;
    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("address1", paramMap.get("SHIPTOSTREET"));
    inMap.put("address2", paramMap.get("SHIPTOSTREET2"));
    inMap.put("city", paramMap.get("SHIPTOCITY"));
    String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY");
    String countryGeoId = OsafePayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator);
    if (countryGeoId == null) {
        return ServiceUtil.returnSuccess();
    }
    inMap.put("countryGeoId", countryGeoId);
    inMap.put("stateProvinceGeoId",
            parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator));
    inMap.put("postalCode", paramMap.get("SHIPTOZIP"));

    try {
        GenericValue userLogin = delegator.findOne("UserLogin", true, UtilMisc.toMap("userLoginId", "system"));
        inMap.put("userLogin", userLogin);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    boolean beganTransaction = false;
    Transaction parentTransaction = null;
    try {
        parentTransaction = TransactionUtil.suspend();
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, module);
    }
    try {
        Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap);
        contactMechId = (String) outMap.get("contactMechId");
    } catch (GenericServiceException e) {
        Debug.logError(e.getMessage(), module);
        return ServiceUtil.returnSuccess();
    }
    try {
        TransactionUtil.commit(beganTransaction);
        if (parentTransaction != null)
            TransactionUtil.resume(parentTransaction);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    // clone the cart so we can modify it temporarily
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    String oldShipAddress = cart.getShippingContactMechId();
    coh.setCheckOutShippingAddress(contactMechId);
    ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0);
    int line = 0;
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "CallbackResponse");

    for (GenericValue shipMethod : estWrapper.getShippingMethods()) {
        BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod);
        //Check that we have a valid estimate (allowing zero value estimates for now)
        if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) {
            continue;
        }
        cart.setShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId"));
        cart.setCarrierPartyId(shipMethod.getString("partyId"));
        try {
            coh.calcAndAddTax();
        } catch (GeneralException e) {
            Debug.logError(e, module);
            continue;
        }
        String estimateLabel = shipMethod.getString("partyId") + " - " + shipMethod.getString("description");
        encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel);
        encoder.add("L_SHIPPINGOPTIONAMOUNT" + line,
                estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        // Just make this first one default for now
        encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false");
        encoder.add("L_TAXAMT" + line,
                cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        line++;
    }
    String responseMsg = null;
    try {
        responseMsg = encoder.encode();
    } catch (PayPalException e) {
        Debug.logError(e, module);
    }
    if (responseMsg != null) {
        try {
            response.setContentLength(responseMsg.getBytes("UTF-8").length);
        } catch (UnsupportedEncodingException e) {
            Debug.logError(e, module);
        }

        try {
            Writer writer = response.getWriter();
            writer.write(responseMsg);
            writer.close();
        } catch (IOException e) {
            Debug.logError(e, module);
        }
    }

    // Remove the temporary ship address
    try {
        GenericValue postalAddress = delegator.findOne("PostalAddress", false,
                UtilMisc.toMap("contactMechId", contactMechId));
        postalAddress.remove();
        GenericValue contactMech = delegator.findOne("ContactMech", false,
                UtilMisc.toMap("contactMechId", contactMechId));
        contactMech.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    coh.setCheckOutShippingAddress(oldShipAddress);
    return ServiceUtil.returnSuccess();
}

From source file:com.gst.infrastructure.core.api.JsonQuery.java

private boolean differenceExists(final BigDecimal baseValue, final BigDecimal workingCopyValue) {
    boolean differenceExists = false;

    if (baseValue != null) {
        differenceExists = baseValue.compareTo(workingCopyValue) != 0;
    } else {//from w w  w  . j a v  a2s  . com
        differenceExists = workingCopyValue != null;
    }

    return differenceExists;
}

From source file:egovframework.rte.fdl.idgnr.impl.AbstractIdGnrService.java

/**
 *    ? Long ? ? ID//w w  w.  jav a2 s  .  c  o  m
 * @param maxId
 *        
 * @return long value to be less than the specified
 *         maxId
 * @throws FdlException
 *         ? ID ? MaxId ?
 */
protected final long getNextLongIdChecked(long maxId) throws FdlException {
    long nextId;
    if (useBigDecimals) {
        // Use BigDecimal data type
        BigDecimal bd;
        synchronized (mSemaphore) {
            bd = getNextBigDecimalIdInner();
        }

        if (bd.compareTo(BIG_DECIMAL_MAX_LONG) > 0) {
            getLogger().error(messageSource.getMessage("error.idgnr.greater.maxid", new String[] { "Long" },
                    Locale.getDefault()));
            throw new FdlException(messageSource, "error.idgnr.greater.maxid");
        }
        nextId = bd.longValue();
    } else {
        // Use long data type
        synchronized (mSemaphore) {
            nextId = getNextLongIdInner();
        }
    }

    // Make sure that the id is valid for the
    // requested data type.
    if (nextId > maxId) {
        getLogger().error(messageSource.getMessage("error.idgnr.greater.maxid", new String[] { "Long" },
                Locale.getDefault()));
        throw new FdlException(messageSource, "error.idgnr.greater.maxid");
    }

    return nextId;
}

From source file:es.tid.fiware.rss.expenditureLimit.processing.ProcessingLimitService.java

/**
 * /**//from   w  ww . j av a 2s .c  om
 * Check that a charge do not exceed control limit.
 * 
 * @param tx
 * @param update
 * @throws RSSException
 */
public void proccesLimit(DbeTransaction tx) throws RSSException {
    ProcessingLimitService.logger.debug("Process limit for tx:" + tx.getTxTransactionId());
    // transaction to take into account: charge, capture, refund
    String operationType = tx.getTcTransactionType();
    if (operationType.equalsIgnoreCase(Constants.CAPTURE_TYPE)
            || operationType.equalsIgnoreCase(Constants.CHARGE_TYPE)
            || operationType.equalsIgnoreCase(Constants.REFUND_TYPE)) {
        // Obtain accumulated
        List<DbeExpendControl> controls = getControls(tx);
        DbeExpendControl control;
        BigDecimal levelExceded = new BigDecimal(0);
        List<DbeExpendLimit> limits = getLimits(tx);
        if (null != limits && limits.size() > 0) {
            boolean notification = false;
            for (DbeExpendLimit limit : limits) {
                if (ProcessingLimitService.TRANSACTION_TYPE.equalsIgnoreCase(limit.getId().getTxElType())) {
                    ProcessingLimitUtil utils = new ProcessingLimitUtil();
                    BigDecimal total = utils.getValueToAddFromTx(tx);
                    checkMaxAmountExceed(total, limit, tx);
                } else {
                    // Get control to check against the limit
                    control = getExpendControlToCheck(controls, limit, tx);
                    // check end period do not exceeded
                    // reset control limit if done
                    // Add amount.
                    // Obtain the limits and accumulates of an user.
                    // check if there is notifications
                    BigDecimal controlLevelExceded = checkLimit(control, limit, tx);
                    if (controlLevelExceded.compareTo(levelExceded) > 0) {
                        ProcessingLimitService.logger.debug("level exceeded: " + controlLevelExceded);
                        levelExceded = controlLevelExceded;
                        notification = true;
                    }
                }
            }
            if (notification) {
                ProcessingLimitService.logger.warn(
                        "Notification limit " + levelExceded + " exceed for tx:" + tx.getTxTransactionId());
            }
        }
    }
}

From source file:com.siapa.managedbean.RegistroAlimentacionManagedBean.java

public Boolean UpdateStock() {
    Boolean isOk;/*from   ww w . j  a  v  a 2s  .  co m*/
    BigDecimal existencia = BigDecimal.ZERO;
    BigDecimal existenciaActual = alimento.getExistenciaAlimento();
    Integer id = alimento.getIdAlimento();
    BigDecimal existenciaNueva;
    BigDecimal reduccion = registroAlimentacion.getCantidadRegistroAlimentacion();

    if (existenciaActual.compareTo(reduccion) == -1) {
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage("El inventario no es suficiente"));
        isOk = false;
    } else {
        existenciaNueva = existenciaActual.subtract(reduccion);
        Alimento newAlimento = getAlimento();
        Alimento idAlimento = registroAlimentacion.getIdAlimento();
        Alimento cactual = alimentoService.findById(idAlimento.getIdAlimento());
        existencia = cactual.getExistenciaAlimento().subtract(reduccion);
        newAlimento.setExistenciaAlimento(existencia);
        alimentoService.merge(newAlimento);
        isOk = true;

    }
    /* System.out.println("el id es "+id);
     System.out.println("la existencia es "+existenciaActual);
     System.out.println("la reduccion es "+reduccion);*/
    // System.out.println("la nueva existencia es "+existenciaNueva);
    return isOk;

}

From source file:es.upm.fiware.rss.expenditureLimit.processing.ProcessingLimitService.java

/**
 *
 * Check that a charge do not exceed control limit.
 * /*from w w  w  . j av a 2s . c  om*/
 * @param tx
 * @param update
 * @throws RSSException
 */
public void proccesLimit(DbeTransaction tx) throws RSSException {
    ProcessingLimitService.logger.debug("=========== Process limit for tx:" + tx.getTxTransactionId());

    // transaction to take into account: charge, capture, refund
    String operationType = tx.getTcTransactionType();

    if (operationType.equalsIgnoreCase(Constants.CAPTURE_TYPE)
            || operationType.equalsIgnoreCase(Constants.CHARGE_TYPE)
            || operationType.equalsIgnoreCase(Constants.REFUND_TYPE)) {

        ProcessingLimitService.logger.debug("===== IF");

        // Obtain accumulated
        List<DbeExpendControl> controls = getControls(tx);
        DbeExpendControl control;
        BigDecimal levelExceded = new BigDecimal(0);

        List<DbeExpendLimit> limits = getLimits(tx);

        if (null != limits && !limits.isEmpty()) {
            boolean notification = false;

            for (DbeExpendLimit limit : limits) {
                if (ProcessingLimitService.TRANSACTION_TYPE.equalsIgnoreCase(limit.getId().getTxElType())) {
                    ProcessingLimitUtil utils = new ProcessingLimitUtil();
                    BigDecimal total = utils.getValueToAddFromTx(tx);
                    checkMaxAmountExceed(total, limit, tx);
                } else {
                    // Get control to check against the limit
                    control = getExpendControlToCheck(controls, limit, tx);
                    // check end period do not exceeded
                    // reset control limit if done
                    // Add amount.
                    // Obtain the limits and accumulates of an user.
                    // check if there is notifications
                    BigDecimal controlLevelExceded = checkLimit(control, limit, tx);

                    if (controlLevelExceded.compareTo(levelExceded) > 0) {
                        ProcessingLimitService.logger.debug("level exceeded: " + controlLevelExceded);
                        levelExceded = controlLevelExceded;
                        notification = true;
                    }
                }
            }
            if (notification) {
                ProcessingLimitService.logger.warn(
                        "Notification limit " + levelExceded + " exceed for tx:" + tx.getTxTransactionId());
            }
        }
    }
}

From source file:ch.algotrader.entity.security.SecurityFamilyImpl.java

@Override
public int getSpreadTicks(String broker, BigDecimal bid, BigDecimal ask) {

    Validate.notNull(bid, "Bid cannot be null");
    Validate.notNull(ask, "Ask cannot be null");

    int ticks = 0;
    BigDecimal price = bid;/*from w ww . j av a2s  . com*/
    if (bid.compareTo(ask) <= 0) {
        while (price.compareTo(ask) < 0) {
            ticks++;
            price = adjustPrice(broker, price, 1);
        }
    } else {
        while (price.compareTo(ask) > 0) {
            ticks--;
            price = adjustPrice(broker, price, -1);
        }
    }
    return ticks;
}

From source file:com.firstdata.globalgatewaye4.CheckRequest.java

/**
 * @param amount {@link #} dollar amount of transaction.  Max value of 999999.99
 * @return {@link #CheckRequest}//  w w  w  . j  a va2  s .  c om
 */
@NotNull
public CheckRequest amount(BigDecimal amount) {
    Validate.isTrue(amount.compareTo(new BigDecimal("1000000.00")) == -1,
            "Dollar amount is too large.  Maximum value is 999999.99.");
    this.amount = amount;
    return this;
}

From source file:nl.strohalm.cyclos.entities.accounts.loans.LoanParameters.java

/**
 * Calculates the monthly interests for the given parameters
 * @return 0 if no monthly interests, or the applied interests otherwise (ie: if monthly interests = 1%, paymentCount = 1 and delay = 0, returns
 * 10 for amount = 1000)/*from w  ww .  j  a va 2s  .  c  o  m*/
 */
public BigDecimal calculateMonthlyInterests(final BigDecimal amount, final int paymentCount, Calendar grantDate,
        Calendar firstExpirationDate, final MathContext mathContext) {
    if (monthlyInterest == null || amount.compareTo(BigDecimal.ZERO) != 1 || paymentCount < 1) {
        return BigDecimal.ZERO;
    }
    // Calculate the delay
    final Calendar now = Calendar.getInstance();
    grantDate = grantDate == null ? now : grantDate;
    firstExpirationDate = firstExpirationDate == null ? (Calendar) now.clone() : firstExpirationDate;
    final Calendar shouldBeFirstExpiration = (Calendar) grantDate.clone();
    shouldBeFirstExpiration.add(Calendar.MONTH, 1);
    int delay = DateHelper.daysBetween(shouldBeFirstExpiration, firstExpirationDate);
    if (delay < 0) {
        delay = 0;
    }

    final BigDecimal grantFee = calculateGrantFee(amount);
    final BigDecimal baseAmount = amount.add(grantFee);
    final BigDecimal interests = monthlyInterest.divide(new BigDecimal(100), mathContext);
    final BigDecimal numerator = new BigDecimal(
            Math.pow(1 + interests.doubleValue(), paymentCount + delay / 30F)).multiply(interests);
    final BigDecimal denominator = new BigDecimal(Math.pow(1 + interests.doubleValue(), paymentCount) - 1);
    final BigDecimal paymentAmount = baseAmount.multiply(numerator).divide(denominator, mathContext);
    final BigDecimal totalAmount = paymentAmount.multiply(new BigDecimal(paymentCount));
    return totalAmount.subtract(baseAmount);
}