Example usage for java.math BigDecimal add

List of usage examples for java.math BigDecimal add

Introduction

In this page you can find the example usage for java.math BigDecimal add.

Prototype

public BigDecimal add(BigDecimal augend) 

Source Link

Document

Returns a BigDecimal whose value is (this + augend) , and whose scale is max(this.scale(), augend.scale()) .

Usage

From source file:py.una.pol.karaku.dao.entity.interceptors.BigDecimalInterceptor.java

@Override
public void intercept(Operation o, Field field, Object bean) {

    BigDecimal value = (BigDecimal) ReflectionUtils.getField(field, bean);
    if (value == null) {
        return;/*from   www . j a  va2s .  c  om*/
    }
    if (value.longValue() < 1) {
        value = value.add(BigDecimal.ONE);
    }
    BigDecimal trailed = value.stripTrailingZeros();
    int precision = trailed.scale();
    if (precision > MAXIMUM_PRECISION) {
        throw new KarakuRuntimeException(
                String.format("Attribute '%s' of bean '%s' has a precision of {%d}, maximum allowed is {%d}",
                        field.getName(), bean.getClass().getSimpleName(), precision, MAXIMUM_PRECISION));
    }
}

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 ww w  . jav  a2  s  .  co m*/
            }
        } 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:msc.jkuat.mobile.impl.CustomerAccount.java

/**
 * check if this account has enough to carry out a transaction
 * @param debitAmount - the amount to be debited from the account
 * @param commission - what the bank gets for its trouble
 * @return/*from w  w  w  .  ja va  2  s.  com*/
 */
private boolean sufficientFunds(BigDecimal debitAmount, BigDecimal commission) {
    if (balance.subtract(debitAmount.add(commission)).compareTo(minimumBalance) == -1) {
        return false;
    } else {
        return true;
    }
}

From source file:com.willetinc.hadoop.mapreduce.dynamodb.BigDecimalSplitter.java

/**
 * <p>/*from w  w w  .  j ava 2 s .  co m*/
 * Returns a list of BigDecimals one element longer than the list of input
 * splits. This represents the boundaries between input splits. All splits
 * are open on the top end, except the last one.
 * </p>
 * 
 * <p>
 * So the list [0, 5, 8, 12, 18] would represent splits capturing the
 * intervals:
 * </p>
 * 
 * <p>
 * The smallest positive value supported by DynamoDB 'e' is used to separate
 * intervals
 * </p>
 * 
 * <p>
 * e = 0.0000000000000000000000000000000000001
 * </p>
 * 
 * <p>
 * [0, 5] [5+e, 8] [8+e, 12] [12+e, 18]
 * </p>
 */
List<BigDecimal> split(BigDecimal numSplits, BigDecimal minVal, BigDecimal maxVal) {

    List<BigDecimal> splits = new ArrayList<BigDecimal>();

    // Use numSplits as a hint. May need an extra task if the size doesn't
    // divide cleanly.

    BigDecimal splitSize = tryDivide(maxVal.subtract(minVal), (numSplits));
    if (splitSize.compareTo(MIN_INCREMENT) < 0) {
        splitSize = MIN_INCREMENT;
        LOG.warn("Set BigDecimal splitSize to MIN_INCREMENT");
    }

    BigDecimal curVal = minVal;

    while (curVal.compareTo(maxVal) <= 0) {
        splits.add(curVal);
        curVal = curVal.add(splitSize);
    }

    if (splits.get(splits.size() - 1).compareTo(maxVal) != 0 || splits.size() == 1) {
        // We didn't end on the maxVal. Add that to the end of the list.
        splits.add(maxVal);
    }

    return splits;
}

From source file:com.liato.bankdroid.banking.banks.ResursBank.java

@Override
public void update() throws BankException, LoginException, BankChoiceException {
    super.update();
    if (username == null || password == null || username.length() == 0 || password.length() == 0) {
        throw new LoginException(res.getText(R.string.invalid_username_password).toString());
    }/*w  ww .  j  a  v  a 2  s .  c o  m*/

    urlopen = login();
    Matcher matcher = reAccounts.matcher(response);
    while (matcher.find()) {
        /*
         * Capture groups:
         * GROUP                    EXAMPLE DATA
         * 1: Account number        0000000000000000
         * 2: Beviljad kredit       0,00 kr
         * 3: Utnyttjad kredit      0,00 kr
         * 4: Reserverat  belopp    0,00 kr
         * 5: Kvar att utnyttja     0,00 kr
         * 
         */
        String accountId = Html.fromHtml(matcher.group(1)).toString().trim().replaceAll("[^0-9]*", "");
        accounts.add(new Account("Beviljad kredit", Helpers.parseBalance(matcher.group(2)), "b_" + accountId));

        BigDecimal utnyttjad = Helpers.parseBalance(matcher.group(3));
        utnyttjad = utnyttjad.add(Helpers.parseBalance(matcher.group(4)));
        utnyttjad = utnyttjad.negate();
        accounts.add(new Account("Utnyttjad kredit", utnyttjad, "u_" + accountId));

        balance = balance.add(Helpers.parseBalance(matcher.group(3)));
        balance = balance.add(utnyttjad);
        accounts.add(
                new Account("Reserverat belopp", Helpers.parseBalance(matcher.group(4)), "r_" + accountId));
        accounts.add(new Account("Disponibelt", Helpers.parseBalance(matcher.group(5)), "k_" + accountId));
    }

    if (accounts.isEmpty()) {
        throw new BankException(res.getText(R.string.no_accounts_found).toString());
    }
    super.updateComplete();
}

From source file:co.nubetech.apache.hadoop.BigDecimalSplitter.java

/**
 * Returns a list of BigDecimals one element longer than the list of input
 * splits. This represents the boundaries between input splits. All splits
 * are open on the top end, except the last one.
 * /*from   w ww.  ja  v  a2  s .c o  m*/
 * So the list [0, 5, 8, 12, 18] would represent splits capturing the
 * intervals:
 * 
 * [0, 5) [5, 8) [8, 12) [12, 18] note the closed interval for the last
 * split.
 */
List<BigDecimal> split(BigDecimal numSplits, BigDecimal minVal, BigDecimal maxVal) throws SQLException {

    List<BigDecimal> splits = new ArrayList<BigDecimal>();

    // Use numSplits as a hint. May need an extra task if the size doesn't
    // divide cleanly.

    BigDecimal splitSize = tryDivide(maxVal.subtract(minVal), (numSplits));
    if (splitSize.compareTo(MIN_INCREMENT) < 0) {
        splitSize = MIN_INCREMENT;
        LOG.warn("Set BigDecimal splitSize to MIN_INCREMENT");
    }

    BigDecimal curVal = minVal;

    while (curVal.compareTo(maxVal) <= 0) {
        splits.add(curVal);
        curVal = curVal.add(splitSize);
    }

    if (splits.get(splits.size() - 1).compareTo(maxVal) != 0 || splits.size() == 1) {
        // We didn't end on the maxVal. Add that to the end of the list.
        splits.add(maxVal);
    }

    return splits;
}

From source file:ca.travelagency.salesstats.InvoicePaymentDistribution.java

public BigDecimal getReconciledAmount() {
    BigDecimal amount = MoneyUtils.ZERO_VALUE;
    for (InvoicePayment invoicePayment : getInvoicePayments()) {
        if (invoicePayment.isReconciled()) {
            amount = amount.add(invoicePayment.getAmount());
        }/*from   ww w  .j av  a 2 s .co m*/
    }
    return MoneyUtils.round(amount);
}

From source file:es.upm.fiware.rss.settlement.ProductSettlementTask.java

@Override
public void run() {
    this.logger.info("Processing class " + this.model.getProductClass());

    // Aggregate value
    String curr = this.transactions.get(0).getBmCurrency().getTxIso4217Code();
    BigDecimal value = new BigDecimal("0");

    for (DbeTransaction tx : this.transactions) {
        if (tx.getTcTransactionType().equalsIgnoreCase("c")) {
            value = value.add(tx.getFtChargedAmount());
        } else {//w  w w.  ja  v a 2s  .com
            value = value.subtract(tx.getFtChargedAmount());
        }
    }

    // Calculate RS
    RSSModel sharingRes;
    try {
        AlgorithmFactory factory = new AlgorithmFactory();
        AlgorithmProcessor processor = factory.getAlgorithmProcessor(this.model.getAlgorithmType());

        sharingRes = processor.calculateRevenue(model, value);
        this.settlementManager.generateReport(sharingRes, curr);

    } catch (Exception e) {
        this.logger.info("Error processing transactions of: " + this.model.getAggregatorId() + " "
                + this.model.getOwnerProviderId() + " " + this.model.getProductClass() + " " + e.getMessage());

        // Set transactions as pending
        this.settlementManager.setTxState(transactions, "pending", true);
        return;
    }

    // Set transactions as processed
    this.settlementManager.setTxState(transactions, "processed", true);
}

From source file:com.haulmont.timesheets.service.StatisticServiceBean.java

public Map<Task, BigDecimal> getStatisticsByTasks(Date start, Date end, @Nullable Project project) {
    LoadContext.Query query = LoadContext
            .createQuery("select t from ts$TimeEntry t where t.date >= :start and t.date <= :end")
            .setParameter("start", start).setParameter("end", end);
    if (project != null) {
        query.setQueryString(query.getQueryString() + " and t.task.project.id = :project");
        query.setParameter("project", project);
    }/*from   w  ww . j av a2  s.  c  o  m*/
    LoadContext<TimeEntry> loadContext = LoadContext.create(TimeEntry.class).setQuery(query)
            .setView(new View(TimeEntry.class)
                    .addProperty("task",
                            new View(Task.class).addProperty("name").addProperty("project",
                                    viewRepository.getView(Project.class, View.MINIMAL)))
                    .addProperty("timeInMinutes"));
    List<TimeEntry> timeEntries = dataManager.loadList(loadContext);
    Map<Task, BigDecimal> result = new HashMap<>();
    for (TimeEntry timeEntry : timeEntries) {
        BigDecimal sum = result.get(timeEntry.getTask());
        if (sum == null) {
            sum = BigDecimal.ZERO;
        }

        sum = sum.add(HoursAndMinutes.fromTimeEntry(timeEntry).toBigDecimal());
        result.put(timeEntry.getTask(), sum);
    }

    return result;
}

From source file:com.haulmont.timesheets.service.StatisticServiceBean.java

@Override
public Map<Integer, Map<String, Object>> getStatisticsByProjects(Date start, Date end) {
    LoadContext<TimeEntry> loadContext = new LoadContext<>(TimeEntry.class)
            .setQuery(new LoadContext.Query(
                    "select t from ts$TimeEntry t where t.date >= :start and t.date <= :end order by t.date")
                            .setParameter("start", start).setParameter("end", end))
            .setView(new View(TimeEntry.class)
                    .addProperty("task",
                            new View(Task.class).addProperty("name").addProperty("project",
                                    viewRepository.getView(Project.class, View.MINIMAL)))
                    .addProperty("timeInMinutes").addProperty("date"));
    List<TimeEntry> timeEntries = dataManager.loadList(loadContext);

    Map<WeekAndProject, BigDecimal> statistic = new LinkedHashMap<>();
    Calendar calendar = Calendar.getInstance();
    for (TimeEntry timeEntry : timeEntries) {
        calendar.setTime(timeEntry.getDate());
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
        WeekAndProject key = new WeekAndProject(weekOfYear, timeEntry.getTask().getProject());

        BigDecimal sum = statistic.get(key);
        if (sum == null) {
            sum = BigDecimal.ZERO;
        }//from w ww .j a  v a 2  s  .c  o m

        sum = sum.add(HoursAndMinutes.fromTimeEntry(timeEntry).toBigDecimal());
        statistic.put(key, sum);
    }

    Map<Integer, Map<String, Object>> result = new LinkedHashMap<>();
    for (Map.Entry<WeekAndProject, BigDecimal> entry : statistic.entrySet()) {
        Integer week = entry.getKey().week;
        Map<String, Object> projectsByWeek = result.get(week);
        if (projectsByWeek == null) {
            projectsByWeek = new HashMap<>();
            calendar.set(Calendar.WEEK_OF_YEAR, week);
            calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            projectsByWeek.put("week", DateTimeUtils.getDateFormat().format(calendar.getTime()));

        }
        projectsByWeek.put(entry.getKey().project.getName(), entry.getValue());
        result.put(week, projectsByWeek);
    }

    return result;
}