Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

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

Prototype

public BigDecimal multiply(BigDecimal multiplicand) 

Source Link

Document

Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()) .

Usage

From source file:net.sourceforge.fenixedu.domain.credits.util.DepartmentCreditsPoolBean.java

private void addToSet(SortedSet<DepartmentExecutionCourse> set, ExecutionCourse executionCourse) {
    DepartmentExecutionCourse departmentExecutionCourse = new DepartmentExecutionCourse(executionCourse);
    set.add(departmentExecutionCourse);/* w ww. j a  va  2  s  .  c o m*/
    final BigDecimal departmentEffectiveLoad = departmentExecutionCourse.getDepartmentEffectiveLoad();
    final BigDecimal unitCreditValue = executionCourse.getUnitCreditValue();
    if (departmentEffectiveLoad != null && unitCreditValue != null) {
        assignedCredits = assignedCredits.add(departmentEffectiveLoad.multiply(unitCreditValue));
    }
}

From source file:org.kuali.coeus.common.budget.impl.nonpersonnel.BudgetExpenseRule.java

protected boolean processBudgetFormulatedCostValidations(BudgetFormulatedCostDetail budgetFormulatedCost,
        String errorKey) {/* w  w w .j a v a 2 s  .  co m*/
    boolean valid = true;
    MessageMap errorMap = getGlobalVariableService().getMessageMap();

    BigDecimal unitCost = budgetFormulatedCost.getUnitCost().bigDecimalValue();
    BigDecimal count = new ScaleTwoDecimal(budgetFormulatedCost.getCount()).bigDecimalValue();
    BigDecimal frequency = new ScaleTwoDecimal(budgetFormulatedCost.getFrequency()).bigDecimalValue();
    BigDecimal calculatedExpense = unitCost.multiply(count).multiply(frequency);
    if (new ScaleTwoDecimal(unitCost).isGreaterThan(new ScaleTwoDecimal(MAX_BUDGET_DECIMAL_VALUE))) {
        valid = false;
        errorMap.putError(errorKey + UNIT_COST, KeyConstants.ERROR_FORMULATED_UNIT_COST);

    }
    if (new ScaleTwoDecimal(calculatedExpense).isGreaterThan(new ScaleTwoDecimal(MAX_BUDGET_DECIMAL_VALUE))) {
        valid = false;
        errorMap.putError(errorKey + CALCULATED_EXPENSES, KeyConstants.ERROR_FORMULATED_CALCULATED_EXPENSES);

    }
    return valid;
}

From source file:burstcoin.jminer.JMinerCommandLine.java

private void initApplicationListeners() {
    context.addApplicationListener(new ApplicationListener<RoundFinishedEvent>() {
        @Override/*  w  w  w .  ja  v  a2  s . c om*/
        public void onApplicationEvent(RoundFinishedEvent event) {
            previousRemainingCapacity = 0;
            previousElapsedTime = 0;

            long s = event.getRoundTime() / 1000;
            long ms = event.getRoundTime() % 1000;

            String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A"
                    : String.valueOf(event.getBestCommittedDeadline());
            LOG.info("FINISH block '" + event.getBlockNumber() + "', " + "best deadline '" + bestDeadline
                    + "', " + "round time '" + s + "s " + ms + "ms'");
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundStoppedEvent>() {
        @Override
        public void onApplicationEvent(RoundStoppedEvent event) {
            previousRemainingCapacity = 0;
            previousElapsedTime = 0;

            long s = event.getElapsedTime() / 1000;
            long ms = event.getElapsedTime() % 1000;

            BigDecimal totalCapacity = new BigDecimal(event.getCapacity());
            BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32);
            BigDecimal progress = factor
                    .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity()));
            int percentage = (int) Math.ceil(progress.doubleValue() * 100);
            percentage = percentage > 100 ? 100 : percentage;

            String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A"
                    : String.valueOf(event.getBestCommittedDeadline());
            LOG.info("STOP block '" + event.getBlockNumber() + "', " + String.valueOf(percentage) + "% done, "
                    + "best deadline '" + bestDeadline + "', " + "elapsed time '" + s + "s " + ms + "ms'");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkLastWinnerEvent>() {
        @Override
        public void onApplicationEvent(NetworkLastWinnerEvent event) {
            if (blockNumber - 1 == event.getLastBlockNumber()) {
                LOG.info(
                        "      winner block '" + event.getLastBlockNumber() + "', '" + event.getWinner() + "'");
            } else {
                LOG.error("Error: NetworkLastWinnerEvent for block: " + event.getLastBlockNumber()
                        + " is outdated!");
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkStateChangeEvent>() {
        @Override
        public void onApplicationEvent(NetworkStateChangeEvent event) {
            blockNumber = event.getBlockNumber();
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundStartedEvent>() {
        @Override
        public void onApplicationEvent(RoundStartedEvent event) {
            progressLogStep = NUMBER_OF_PROGRESS_LOGS_PER_ROUND;

            LOG.info("-------------------------------------------------------");
            LOG.info("START block '" + event.getBlockNumber() + "', " + "scoopNumber '" + event.getScoopNumber()
                    + "', " + "capacity '" + event.getCapacity() / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR
                    + " " + G_UNIT + "'");
            String target = event.getTargetDeadline() == Long.MAX_VALUE ? "N/A"
                    : String.valueOf(event.getTargetDeadline());
            LOG.info("      targetDeadline '" + target + "', " + "baseTarget '"
                    + String.valueOf(event.getBaseTarget()) + "'");
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderProgressChangedEvent>() {
        @Override
        public void onApplicationEvent(ReaderProgressChangedEvent event) {
            long logStepCapacity = event.getCapacity() / NUMBER_OF_PROGRESS_LOGS_PER_ROUND;

            if (event.getRemainingCapacity() < logStepCapacity * progressLogStep
                    || event.getRemainingCapacity() == 0) {
                progressLogStep--;

                // trigger garbage collection on every progress step
                System.gc();

                BigDecimal totalCapacity = new BigDecimal(event.getCapacity());
                BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32);
                BigDecimal progress = factor
                        .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity()));
                int percentage = (int) Math.ceil(progress.doubleValue() * 100);
                percentage = percentage > 100 ? 100 : percentage;

                // calculate capacity
                long effMBPerSec = 0;
                if (previousRemainingCapacity > 0) {
                    long effDoneBytes = previousRemainingCapacity - event.getRemainingCapacity();

                    // calculate current reading speed (since last info)
                    long effBytesPerMs = (effDoneBytes / 4096) / (event.getElapsedTime() - previousElapsedTime);
                    effMBPerSec = (effBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR;
                }

                // calculate capacity
                long doneBytes = event.getCapacity() - event.getRemainingCapacity();
                long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR;
                long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR;

                // calculate reading speed (average)
                long averageBytesPerMs = (doneBytes / 4096) / event.getElapsedTime();
                long averageMBPerSec = (averageBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR;

                previousRemainingCapacity = event.getRemainingCapacity();
                previousElapsedTime = event.getElapsedTime();

                LOG.info(String.valueOf(percentage) + "% done (" + doneTB + T_UNIT + " " + doneGB + G_UNIT
                        + "), avg.'" + averageMBPerSec + " " + M_UNIT + "/s'"
                        + (effMBPerSec > 0 ? ", eff.'" + effMBPerSec + " " + M_UNIT + "/s'" : ""));
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundSingleResultEvent>() {
        @Override
        public void onApplicationEvent(RoundSingleResultEvent event) {
            LOG.info("dl '" + event.getCalculatedDeadline() + "' send ("
                    + (event.isPoolMining() ? "pool" : "solo") + ")");
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundSingleResultSkippedEvent>() {
        @Override
        public void onApplicationEvent(RoundSingleResultSkippedEvent event) {
            LOG.info(
                    "dl '" + event.getCalculatedDeadline() + "' > '" + event.getTargetDeadline() + "' skipped");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkResultConfirmedEvent>() {
        @Override
        public void onApplicationEvent(NetworkResultConfirmedEvent event) {
            LOG.info("dl '" + event.getDeadline() + "' confirmed!  [ " + getDeadlineTime(event.getDeadline())
                    + " ]");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkDevResultConfirmedEvent>() {
        @Override
        public void onApplicationEvent(NetworkDevResultConfirmedEvent event) {
            LOG.info("devPool response '" + event.getResponse() + "', block '" + event.getBlockNumber() + "'");
            for (DevPoolResult devPoolResult : event.getDevPoolResults()) {
                LOG.info("dl '" + devPoolResult.getCalculatedDeadline() + "' successful committed!  [ "
                        + getDeadlineTime(devPoolResult.getCalculatedDeadline()) + " ]");
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkResultErrorEvent>() {
        @Override
        public void onApplicationEvent(NetworkResultErrorEvent event) {
            LOG.info("strange dl result '" + event.getStrangeDeadline() + "', calculated '"
                    + event.getCalculatedDeadline() + "' " + "block '" + event.getBlockNumber() + "' nonce '"
                    + event.getNonce() + "'");
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderCorruptFileEvent>() {
        @Override
        public void onApplicationEvent(ReaderCorruptFileEvent event) {
            LOG.info("strange dl source '" + event.getFilePath() + "' (try replotting!?)");
            LOG.info("strange dl file chunks '" + event.getNumberOfChunks() + "', " + "parts per chunk '"
                    + event.getNumberOfParts() + "', " + "block '" + event.getBlockNumber() + "'");
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderDriveFinishEvent>() {
        @Override
        public void onApplicationEvent(ReaderDriveFinishEvent event) {
            if (blockNumber == event.getBlockNumber()) {
                // calculate capacity
                long doneBytes = event.getSize();
                long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR;
                long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR;

                long s = event.getTime() / 1000;
                long ms = event.getTime() % 1000;

                LOG.info("read '" + event.getDirectory() + "' (" + doneTB + T_UNIT + " " + doneGB + G_UNIT
                        + ") in '" + s + "s " + ms + "ms'");
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderDriveInterruptedEvent>() {
        @Override
        public void onApplicationEvent(ReaderDriveInterruptedEvent event) {
            LOG.info("stopped '" + event.getDirectory() + "' for block '" + event.getBlockNumber() + "'.");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkPoolInfoEvent>() {
        @Override
        public void onApplicationEvent(NetworkPoolInfoEvent event) {
            String value = event.getPoolBalanceNQT();
            String amount = value.length() > 8 ? value.substring(0, value.length() - 8) : value;
            value = event.getPoolForgedBalanceNQT();
            String totalForget = value.length() > 8 ? value.substring(0, value.length() - 8) : value;
            LOG.info("-------------------------------------------------------");
            LOG.info("POOL account '" + event.getPoolAccountRS() + "', assigned miners '"
                    + event.getPoolNumberOfMiningAccounts() + "'");
            LOG.info("     balance '" + amount + " BURST', total mined '" + totalForget + " BURST'");
        }
    });
}

From source file:org.codice.ddf.spatial.ogc.wfs.catalog.converter.impl.AbstractFeatureConverter.java

private String convertToBytes(HierarchicalStreamReader reader, String unit) {

    BigDecimal resourceSize = new BigDecimal(reader.getValue());
    resourceSize = resourceSize.setScale(1, BigDecimal.ROUND_HALF_UP);

    switch (unit) {
    case B://from ww w .j  a v  a2 s  .  c o m
        break;
    case KB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_KB));
        break;
    case MB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_MB));
        break;
    case GB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_GB));
        break;
    case TB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_TB));
        break;
    case PB:
        resourceSize = resourceSize.multiply(new BigDecimal(BYTES_PER_PB));
        break;
    default:
        break;
    }

    String resourceSizeAsString = resourceSize.toPlainString();
    LOGGER.debug("resource size in bytes: {}", resourceSizeAsString);
    return resourceSizeAsString;
}

From source file:co.nubetech.hiho.mapreduce.lib.db.apache.TextSplitter.java

/**
 * Return a BigDecimal representation of string 'str' suitable for use
 * in a numerically-sorting order./*from  w  w w  . j a  va 2s  .c o m*/
 */
BigDecimal stringToBigDecimal(String str) {
    BigDecimal result = BigDecimal.ZERO;
    BigDecimal curPlace = ONE_PLACE; // start with 1/65536 to compute the first digit.

    int len = Math.min(str.length(), MAX_CHARS);

    for (int i = 0; i < len; i++) {
        int codePoint = str.codePointAt(i);
        result = result.add(tryDivide(new BigDecimal(codePoint), curPlace));
        // advance to the next less significant place. e.g., 1/(65536^2) for the second char.
        curPlace = curPlace.multiply(ONE_PLACE);
    }

    return result;
}

From source file:org.kuali.kpme.tklm.leave.accrual.service.AccrualCategoryMaxCarryOverServiceImpl.java

private BigDecimal getAccrualCategoryCarryOverAdjustment(String accrualCategory, String principalId,
        CalendarEntry calendarEntry, LocalDate asOfDate) {
    BigDecimal accrualCategoryCarryOverAdjustment = BigDecimal.ZERO;

    PrincipalHRAttributes principalCalendar = getPrincipalHRAttributesService()
            .getPrincipalCalendar(principalId, asOfDate);

    if (principalCalendar != null) {
        LeavePlan leavePlan = getLeavePlanService().getLeavePlan(principalCalendar.getLeavePlan(),
                principalCalendar.getEffectiveLocalDate());

        if (leavePlan != null) {
            AccrualCategory accrualCategoryObj = getAccrualCategoryService().getAccrualCategory(accrualCategory,
                    asOfDate);//from  ww w  .ja  va2 s. c  om

            if (accrualCategoryObj != null) {
                AccrualCategoryRule accrualCategoryRule = getMaxCarryOverAccrualCategoryRule(accrualCategoryObj,
                        principalCalendar.getServiceLocalDate(), asOfDate);

                if (accrualCategoryRule != null) {
                    Long maxCarryOverLimitValue = getMaxCarryOverLimitValue(principalId, leavePlan,
                            accrualCategoryObj, accrualCategoryRule, asOfDate);

                    if (maxCarryOverLimitValue != null) {
                        BigDecimal accrualCategoryBalance = getAccrualCategoryBalance(principalId,
                                accrualCategoryObj, asOfDate);

                        BigDecimal maxCarryOverLimit = new BigDecimal(maxCarryOverLimitValue);
                        BigDecimal fteSum = getJobService().getFteSumForAllActiveLeaveEligibleJobs(principalId,
                                asOfDate);
                        BigDecimal maxCarryOver = maxCarryOverLimit.multiply(fteSum);

                        accrualCategoryCarryOverAdjustment = accrualCategoryBalance.subtract(maxCarryOver);
                    }
                }
            }
        }
    }

    return accrualCategoryCarryOverAdjustment;
}

From source file:com.cloudera.sqoop.mapreduce.db.TextSplitter.java

/**
 * Return a BigDecimal representation of string 'str' suitable for use in a
 * numerically-sorting order.//from  w  w w .ja  v  a 2 s  .  c  om
 */
BigDecimal stringToBigDecimal(String str) {
    // Start with 1/65536 to compute the first digit.
    BigDecimal curPlace = ONE_PLACE;
    BigDecimal result = BigDecimal.ZERO;

    int len = Math.min(str.length(), MAX_CHARS);

    for (int i = 0; i < len; i++) {
        int codePoint = str.codePointAt(i);
        result = result.add(tryDivide(new BigDecimal(codePoint), curPlace));
        // advance to the next less significant place. e.g., 1/(65536^2) for the
        // second char.
        curPlace = curPlace.multiply(ONE_PLACE);
    }

    return result;
}

From source file:org.apache.sqoop.mapreduce.db.TextSplitter.java

/**
 * Return a BigDecimal representation of string 'str' suitable for use in a
 * numerically-sorting order./*from w w  w  .  j a  va  2  s.c  o  m*/
 */
public BigDecimal stringToBigDecimal(String str) {
    // Start with 1/65536 to compute the first digit.
    BigDecimal curPlace = ONE_PLACE;
    BigDecimal result = BigDecimal.ZERO;

    int len = Math.min(str.length(), MAX_CHARS);

    for (int i = 0; i < len; i++) {
        int codePoint = str.codePointAt(i);
        result = result.add(tryDivide(new BigDecimal(codePoint), curPlace));
        // advance to the next less significant place. e.g., 1/(65536^2) for the
        // second char.
        curPlace = curPlace.multiply(ONE_PLACE);
    }

    return result;
}

From source file:org.kuali.kpme.tklm.leave.transfer.service.BalanceTransferServiceImpl.java

@Override
public BalanceTransfer initializeTransfer(String principalId, String accrualCategoryRule,
        BigDecimal accruedBalance, LocalDate effectiveDate) {
    //Initially, principals may be allowed to edit the transfer amount when prompted to submit this balance transfer, however,
    //a base transfer amount together with a forfeited amount is calculated to bring the balance back to its limit in accordance
    //with transfer limits. This "default" transfer object is used to adjust forfeiture when the user changes the transfer amount.
    BalanceTransfer bt = null;/*from w  ww.j a v  a2 s.c  o  m*/
    AccrualCategoryRule accrualRule = HrServiceLocator.getAccrualCategoryRuleService()
            .getAccrualCategoryRule(accrualCategoryRule);

    if (ObjectUtils.isNotNull(accrualRule) && ObjectUtils.isNotNull(accruedBalance)) {
        bt = new BalanceTransfer();
        //These two objects are essential to balance transfers triggered when the employee submits their leave calendar for approval.
        //Neither of these objects should be null, otherwise this method could not have been called.
        AccrualCategory fromAccrualCategory = HrServiceLocator.getAccrualCategoryService()
                .getAccrualCategory(accrualRule.getLmAccrualCategoryId());
        AccrualCategory toAccrualCategory = HrServiceLocator.getAccrualCategoryService()
                .getAccrualCategory(accrualRule.getMaxBalanceTransferToAccrualCategory(), effectiveDate);
        BigDecimal fullTimeEngagement = HrServiceLocator.getJobService()
                .getFteSumForAllActiveLeaveEligibleJobs(principalId, effectiveDate);

        BigDecimal transferConversionFactor = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxBalanceTransferConversionFactor()))
            transferConversionFactor = accrualRule.getMaxBalanceTransferConversionFactor();

        // AccrualRule.maxBalance == null -> no balance limit. No balance limit -> no accrual triggered transfer / payout / lose.
        // execution point should not be here if max balance on accrualRule is null, unless there exists an employee override.
        BigDecimal maxBalance = accrualRule.getMaxBalance();
        BigDecimal adjustedMaxBalance = maxBalance.multiply(fullTimeEngagement).setScale(2);

        BigDecimal maxTransferAmount = null;
        BigDecimal adjustedMaxTransferAmount = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxTransferAmount())) {
            maxTransferAmount = new BigDecimal(accrualRule.getMaxTransferAmount());
            adjustedMaxTransferAmount = maxTransferAmount.multiply(fullTimeEngagement).setScale(2);
        } else {
            // no limit on transfer amount
            maxTransferAmount = new BigDecimal(Long.MAX_VALUE);
            adjustedMaxTransferAmount = maxTransferAmount;
        }

        BigDecimal maxCarryOver = null;
        BigDecimal adjustedMaxCarryOver = null;
        if (ObjectUtils.isNotNull(accrualRule.getMaxCarryOver())) {
            maxCarryOver = new BigDecimal(accrualRule.getMaxCarryOver());
            adjustedMaxCarryOver = maxCarryOver.multiply(fullTimeEngagement).setScale(2);
        } else {
            //no limit to carry over.
            maxCarryOver = new BigDecimal(Long.MAX_VALUE);
            adjustedMaxCarryOver = maxCarryOver;
        }

        List<? extends EmployeeOverrideContract> overrides = LmServiceLocator.getEmployeeOverrideService()
                .getEmployeeOverrides(principalId, effectiveDate);
        for (EmployeeOverrideContract override : overrides) {
            if (StringUtils.equals(override.getAccrualCategory(), fromAccrualCategory.getAccrualCategory())) {
                //Do not pro-rate override values for FTE.
                if (StringUtils.equals(override.getOverrideType(), "MB"))
                    adjustedMaxBalance = new BigDecimal(override.getOverrideValue());
                if (StringUtils.equals(override.getOverrideType(), "MTA"))
                    adjustedMaxTransferAmount = new BigDecimal(override.getOverrideValue());
                if (StringUtils.equals(override.getOverrideType(), "MAC"))
                    adjustedMaxCarryOver = new BigDecimal(override.getOverrideValue());
            }
        }

        BigDecimal transferAmount = accruedBalance.subtract(adjustedMaxBalance);
        if (StringUtils.equals(accrualRule.getActionAtMaxBalance(), HrConstants.ACTION_AT_MAX_BALANCE.LOSE)) {
            //Move all time in excess of employee's fte adjusted max balance to forfeiture.
            bt.setForfeitedAmount(transferAmount);
            //There is no transfer to another accrual category.
            bt.setTransferAmount(BigDecimal.ZERO);
            bt.setAmountTransferred(BigDecimal.ZERO);
            // to accrual category is a required field on maintenance document. Set as from accrual category
            // to remove validation errors when routing, approving, etc.
            bt.setToAccrualCategory(fromAccrualCategory.getAccrualCategory());
        } else {
            // ACTION_AT_MAX_BALANCE = TRANSFER
            bt.setToAccrualCategory(toAccrualCategory.getAccrualCategory());
            if (transferAmount.compareTo(adjustedMaxTransferAmount) > 0) {
                //there's forfeiture.
                //bring transfer amount down to the adjusted maximum transfer amount, and place excess in forfeiture.
                //accruedBalance - adjustedMaxTransferAmount - adjustedMaxBalance = forfeiture.
                //transferAmount = accruedBalance - adjustedMaxBalance; forfeiture = transferAmount - adjustedMaxTransferAmount.
                BigDecimal forfeiture = transferAmount.subtract(adjustedMaxTransferAmount).setScale(2);
                forfeiture = forfeiture.stripTrailingZeros();
                bt.setForfeitedAmount(forfeiture);
                bt.setTransferAmount(adjustedMaxTransferAmount);
            } else {
                bt.setTransferAmount(transferAmount);
                bt.setForfeitedAmount(BigDecimal.ZERO);
            }
        }

        //assert(adjustedMaxBalance.compareTo(accruedBalance.subtract(bt.getTransferAmount().add(bt.getForfeitedAmount()))) == 0);

        // Max Carry Over logic for Year End transfers.
        if (StringUtils.equals(accrualRule.getMaxBalanceActionFrequency(),
                HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)) {

            //At this point, transfer amount and forfeiture have been set so that the new accrued balance will be the
            //adjusted max balance, so this amount is used to check against carry over.
            if (adjustedMaxBalance.compareTo(adjustedMaxCarryOver) > 0) {
                BigDecimal carryOverDiff = adjustedMaxBalance.subtract(adjustedMaxCarryOver);

                if (StringUtils.equals(accrualRule.getActionAtMaxBalance(),
                        HrConstants.ACTION_AT_MAX_BALANCE.LOSE)) {
                    //add carry over excess to forfeiture.
                    bt.setForfeitedAmount(bt.getForfeitedAmount().add(carryOverDiff));
                } else {
                    //maximize the transfer amount.
                    BigDecimal potentialTransferAmount = bt.getTransferAmount().add(carryOverDiff);

                    //Can this amount be added to the transfer amount without exceeding adjusted max transfer amount??
                    if (potentialTransferAmount.compareTo(adjustedMaxTransferAmount) <= 0) {
                        //yes
                        bt.setTransferAmount(bt.getTransferAmount().add(carryOverDiff));
                    } else {
                        //no
                        BigDecimal carryOverExcess = potentialTransferAmount
                                .subtract(adjustedMaxTransferAmount);
                        //move excess to forfeiture
                        bt.setForfeitedAmount(bt.getForfeitedAmount().add(carryOverExcess));
                        //the remainder (if any) can be added to the transfer amount.
                        bt.setTransferAmount(
                                bt.getTransferAmount().add(carryOverDiff.subtract(carryOverExcess)));

                        assert (bt.getTransferAmount().compareTo(adjustedMaxTransferAmount) == 0);
                        // assert that the new balance will be equal to the adjusted max carry over < adjusted max balance.
                    }
                }
                assert (adjustedMaxCarryOver.compareTo(
                        accruedBalance.subtract(bt.getTransferAmount().add(bt.getForfeitedAmount()))) == 0);
            }
            //otherwise, given balance will be at or under the max annual carry over.
        }

        bt.setEffectiveLocalDate(effectiveDate);
        bt.setAccrualCategoryRule(accrualCategoryRule);
        bt.setFromAccrualCategory(fromAccrualCategory.getAccrualCategory());
        bt.setPrincipalId(principalId);
        bt.setUserPrincipalId(HrContext.getPrincipalId());
        if (ObjectUtils.isNotNull(transferConversionFactor)) {
            bt.setAmountTransferred(bt.getTransferAmount().multiply(transferConversionFactor).setScale(2,
                    RoundingMode.HALF_UP));
        } else {
            bt.setAmountTransferred(bt.getTransferAmount());
        }
    }
    return bt;
}

From source file:jgnash.ui.report.compiled.IncomeExpensePieChart.java

private JFreeChart createPieChart(final Account a) {
    final Engine engine = EngineFactory.getEngine(EngineFactory.DEFAULT);
    Objects.requireNonNull(engine);
    Objects.requireNonNull(a);//  ww  w. j a v a 2  s. c om

    PieDataset data = createPieDataSet(a);
    PiePlot plot = new PiePlot(data);

    // rebuilt each time because they're based on the account's commodity
    CurrencyNode defaultCurrency = engine.getDefaultCurrency();
    NumberFormat valueFormat = CommodityFormat.getFullNumberFormat(a.getCurrencyNode());
    NumberFormat percentFormat = new DecimalFormat("0.0#%");
    defaultLabels = new StandardPieSectionLabelGenerator("{0} = {1}", valueFormat, percentFormat);
    percentLabels = new StandardPieSectionLabelGenerator("{0} = {1}\n{2}", valueFormat, percentFormat);

    plot.setLabelGenerator(showPercentCheck.isSelected() ? percentLabels : defaultLabels);

    plot.setLabelGap(.02);
    plot.setInteriorGap(.1);

    // if we had to add a section for the account (because it has it's
    // own transactions, not just child accounts), separate it from children.
    if (data.getIndex(a) != -1) {
        plot.setExplodePercent(a, .10);
    }

    String title;

    // pick an appropriate title
    if (a.getAccountType() == AccountType.EXPENSE) {
        title = rb.getString("Title.PercentExpense");
    } else if (a.getAccountType() == AccountType.INCOME) {
        title = rb.getString("Title.PercentIncome");
    } else {
        title = rb.getString("Title.PercentDist");
    }

    title = title + " - " + a.getPathName();

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, false);

    BigDecimal total = a.getTreeBalance(startField.getLocalDate(), endField.getLocalDate()).abs();

    String subtitle = valueFormat.format(total);
    if (!defaultCurrency.equals(a.getCurrencyNode())) {
        BigDecimal totalDefaultCurrency = total.multiply(a.getCurrencyNode().getExchangeRate(defaultCurrency));
        NumberFormat defaultValueFormat = CommodityFormat.getFullNumberFormat(defaultCurrency);
        subtitle += "  -  " + defaultValueFormat.format(totalDefaultCurrency);
    }
    chart.addSubtitle(new TextTitle(subtitle));
    chart.setBackgroundPaint(null);

    return chart;
}