Example usage for java.math BigDecimal divide

List of usage examples for java.math BigDecimal divide

Introduction

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

Prototype

public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , and whose scale is as specified.

Usage

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

@SuppressWarnings("unchecked")
@Override//ww w  .j  a va 2s  . c  o m
public void runAccrual(String principalId, DateTime startDate, DateTime endDate, boolean recordRanData,
        String runAsPrincipalId) {
    List<LeaveBlock> accrualLeaveBlocks = new ArrayList<LeaveBlock>();
    Map<String, BigDecimal> accumulatedAccrualCatToAccrualAmounts = new HashMap<String, BigDecimal>();
    Map<String, BigDecimal> accumulatedAccrualCatToNegativeAccrualAmounts = new HashMap<String, BigDecimal>();

    if (startDate != null && endDate != null) {
        LOG.info("AccrualServiceImpl.runAccrual() STARTED with Principal: " + principalId + " Start: "
                + startDate.toString() + " End: " + endDate.toString());
    }
    if (startDate.isAfter(endDate)) {
        LOG.error("Start Date " + startDate.toString() + " should not be later than End Date "
                + endDate.toString());
        return;
        //         throw new RuntimeException("Start Date " + startDate.toString() + " should not be later than End Date " + endDate.toString());
    }
    //Inactivate all previous accrual-generated entries for this span of time
    deactivateOldAccruals(principalId, startDate, endDate, runAsPrincipalId);

    //Build a rate range aggregate with appropriate information for this period of time detailing Rate Ranges for job
    //entries for this range of time
    RateRangeAggregate rrAggregate = this.buildRateRangeAggregate(principalId, startDate, endDate);
    PrincipalHRAttributes phra = null;
    PrincipalHRAttributes endPhra = null;
    LeavePlanContract lp = null;
    List<? extends AccrualCategoryContract> accrCatList = null;

    //Iterate over every day in span 
    DateTime currentDate = startDate;
    while (!currentDate.isAfter(endDate)) {
        RateRange currentRange = rrAggregate.getRateOnDate(currentDate);
        if (currentRange == null) {
            currentDate = currentDate.plusDays(1);
            continue;
        }

        phra = currentRange.getPrincipalHRAttributes();
        if (phra == null || currentDate.toLocalDate().isBefore(phra.getServiceLocalDate())) {
            currentDate = currentDate.plusDays(1);
            continue;
        }

        // use the effectiveDate of this principalHRAttribute to search for inactive entries for this principalId
        // If there's an inactive entry, it means the job is going to end on the effectiveDate of the inactive entry
        // used for minimumPercentage and proration
        endPhra = currentRange.getEndPrincipalHRAttributes();
        if (endPhra != null && currentDate.toLocalDate().isAfter(endPhra.getEffectiveLocalDate())) {
            currentDate = currentDate.plusDays(1);
            continue;
        }

        // if the date range is before the service date of this employee, do not calculate accrual
        if (endDate.toLocalDate().isBefore(phra.getServiceLocalDate())) {
            return;
        }
        lp = currentRange.getLeavePlan();
        accrCatList = currentRange.getAcList();
        // if the employee status is changed, create an empty leave block on the currentDate
        if (currentRange.isStatusChanged()) {
            this.createEmptyLeaveBlockForStatusChange(principalId, accrualLeaveBlocks,
                    currentDate.toLocalDate());
        }
        // if no job found for the employee on the currentDate, do nothing
        if (CollectionUtils.isEmpty(currentRange.getJobs())) {
            currentDate = currentDate.plusDays(1);
            continue;
        }

        BigDecimal ftePercentage = currentRange.getAccrualRatePercentageModifier();
        BigDecimal totalOfStandardHours = currentRange.getStandardHours();
        boolean fullFteGranted = false;
        for (AccrualCategoryContract anAC : accrCatList) {
            if (anAC == null)
                continue;

            fullFteGranted = false;
            if (!currentDate.toLocalDate().isBefore(phra.getEffectiveLocalDate())
                    && !anAC.getAccrualEarnInterval().equals("N")) { // "N" means no accrual
                boolean prorationFlag = this.isProrationFlag(anAC.getProration());
                // get the accrual rule 
                AccrualCategoryRuleContract currentAcRule = this
                        .getRuleForAccrualCategory(currentRange.getAcRuleList(), anAC);

                // check if accrual category rule changed
                if (currentAcRule != null) {
                    DateTime ruleStartDate = getRuleStartDate(currentAcRule.getServiceUnitOfTime(),
                            phra.getServiceLocalDate(), currentAcRule.getStart());
                    DateTime previousIntervalDay = this.getPrevIntervalDate(ruleStartDate,
                            anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap());
                    DateTime nextIntervalDay = this.getNextIntervalDate(ruleStartDate,
                            anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap());

                    RateRangeContract previousRange = rrAggregate.getRateOnDate(previousIntervalDay);
                    AccrualCategoryRuleContract previousAcRule = null;
                    if (previousRange != null) {
                        previousAcRule = this.getRuleForAccrualCategory(previousRange.getAcRuleList(), anAC);
                    }
                    // rule changed
                    if (previousAcRule != null && !previousAcRule.getLmAccrualCategoryRuleId()
                            .equals(currentAcRule.getLmAccrualCategoryRuleId())) {
                        if (currentDate.toLocalDate().compareTo(previousIntervalDay.toLocalDate()) >= 0
                                && currentDate.toLocalDate().compareTo(nextIntervalDay.toLocalDate()) <= 0) {
                            int workDaysInBetween = TKUtils.getWorkDays(ruleStartDate, nextIntervalDay);
                            boolean minReachedFlag = minimumPercentageReachedForPayPeriod(
                                    anAC.getMinPercentWorked(), anAC.getAccrualEarnInterval(),
                                    workDaysInBetween, nextIntervalDay, phra.getPayCalendar(),
                                    rrAggregate.getCalEntryMap());
                            if (prorationFlag) {
                                if (minReachedFlag) {
                                    // min reached, proration=true, rule changed, then use actual work days of currentRule for calculation
                                    // so nothing special needs to be done here                        
                                } else {
                                    //minimum percentage NOT reached, proration = true, rule changed, then use previousRule for the whole pay period
                                    currentAcRule = previousAcRule;
                                }
                            } else {
                                if (minReachedFlag) {
                                    // min reached, proration = false, rule changed, then accrual the whole fte of the new rule for this pay interval
                                    accumulatedAccrualCatToAccrualAmounts.put(anAC.getLmAccrualCategoryId(),
                                            currentAcRule.getAccrualRate());
                                    fullFteGranted = true;
                                } else {
                                    //min NOT reached, proration = false, rule changed, then accrual the whole fte of the previous rule for this pay interval
                                    accumulatedAccrualCatToAccrualAmounts.put(anAC.getLmAccrualCategoryId(),
                                            previousAcRule.getAccrualRate());
                                    fullFteGranted = true;
                                }
                            }
                        }
                    }
                }

                // check for first pay period of principal attributes considering minimum percentage and proration   
                DateTime firstIntervalDate = this.getNextIntervalDate(
                        phra.getEffectiveLocalDate().toDateTimeAtStartOfDay(), anAC.getAccrualEarnInterval(),
                        phra.getPayCalendar(), rrAggregate.getCalEntryMap());
                if (!currentDate.toLocalDate().isBefore(phra.getEffectiveLocalDate())
                        && !currentDate.toLocalDate().isAfter(firstIntervalDate.toLocalDate())) {
                    int workDaysInBetween = TKUtils.getWorkDays(
                            phra.getEffectiveLocalDate().toDateTimeAtStartOfDay(), firstIntervalDate);
                    boolean minReachedFlag = minimumPercentageReachedForPayPeriod(anAC.getMinPercentWorked(),
                            anAC.getAccrualEarnInterval(), workDaysInBetween, firstIntervalDate,
                            phra.getPayCalendar(), rrAggregate.getCalEntryMap());

                    if (prorationFlag) {
                        if (minReachedFlag) {
                            // minimum reached, proration = true, first pay period, then use actual work days of currentRule for calculation
                            // so nothing special needs to be done here
                        } else {
                            // min NOT reached, proration = true, first pay period, then no accrual for this pay period
                            accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId());
                            accumulatedAccrualCatToNegativeAccrualAmounts.remove(anAC.getLmAccrualCategoryId());
                            continue;
                        }
                    } else {
                        if (minReachedFlag && currentAcRule != null) {
                            //  minimum reached, proration = false, first pay period, then accrual the whole fte of current AC rule for this pay interval
                            accumulatedAccrualCatToAccrualAmounts.put(anAC.getLmAccrualCategoryId(),
                                    currentAcRule.getAccrualRate());
                            fullFteGranted = true;
                        } else {
                            // min NOT reached, proration = false, first pay period, then no accrual for this pay period
                            accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId());
                            accumulatedAccrualCatToNegativeAccrualAmounts.remove(anAC.getLmAccrualCategoryId());
                            continue;
                        }
                    }
                }
                // last accrual interval
                if (endPhra != null) { // the employment is going to end on the effectiveDate of enPhra
                    DateTime previousIntervalDate = this.getPrevIntervalDate(
                            endPhra.getEffectiveLocalDate().toDateTimeAtStartOfDay(),
                            anAC.getAccrualEarnInterval(), phra.getPayCalendar(), rrAggregate.getCalEntryMap());
                    // currentDate is between the end date and the last interval date, so we are in the last interval
                    if (!currentDate.toLocalDate().isAfter(endPhra.getEffectiveLocalDate())
                            && currentDate.toLocalDate().isAfter(previousIntervalDate.toLocalDate())) {
                        DateTime lastIntervalDate = this.getNextIntervalDate(
                                endPhra.getEffectiveLocalDate().toDateTimeAtStartOfDay(),
                                anAC.getAccrualEarnInterval(), phra.getPayCalendar(),
                                rrAggregate.getCalEntryMap());
                        int workDaysInBetween = TKUtils.getWorkDays(previousIntervalDate,
                                endPhra.getEffectiveLocalDate().toDateTimeAtStartOfDay());
                        boolean minReachedFlag = minimumPercentageReachedForPayPeriod(
                                anAC.getMinPercentWorked(), anAC.getAccrualEarnInterval(), workDaysInBetween,
                                lastIntervalDate, phra.getPayCalendar(), rrAggregate.getCalEntryMap());
                        if (prorationFlag) {
                            if (minReachedFlag) {
                                // minimum reached, proration = true, first pay period, then use actual work days of currentRule for calculation
                                // so nothing special needs to be done here
                            } else {
                                // min NOT reached, proration = true, first pay period, then no accrual for this pay period
                                accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId());
                                accumulatedAccrualCatToNegativeAccrualAmounts
                                        .remove(anAC.getLmAccrualCategoryId());
                                continue;
                            }
                        } else {
                            if (minReachedFlag) {
                                //  minimum reached, proration = false, first pay period, then accrual the whole fte of current AC rule for this pay interval
                                accumulatedAccrualCatToAccrualAmounts.put(anAC.getLmAccrualCategoryId(),
                                        currentAcRule.getAccrualRate());
                                fullFteGranted = true;
                            } else {
                                // min NOT reached, proration = false, first pay period, then no accrual for this pay period
                                accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId());
                                accumulatedAccrualCatToNegativeAccrualAmounts
                                        .remove(anAC.getLmAccrualCategoryId());
                                continue;
                            }
                        }
                    }
                }

                if (currentAcRule == null) {
                    accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId());
                    accumulatedAccrualCatToNegativeAccrualAmounts.remove(anAC.getLmAccrualCategoryId());
                    continue;
                }

                //Fetch the accrual rate based on rate range for today(Rate range is the accumulated list of jobs and accrual rate for today)
                BigDecimal accrualRate = currentAcRule.getAccrualRate();
                int numberOfWorkDays = this.getWorkDaysInInterval(currentDate, anAC.getAccrualEarnInterval(),
                        phra.getPayCalendar(), rrAggregate.getCalEntryMap());
                BigDecimal dayRate = numberOfWorkDays > 0
                        ? accrualRate.divide(new BigDecimal(numberOfWorkDays), 6, BigDecimal.ROUND_HALF_UP)
                        : new BigDecimal(0);

                //get not eligible for accrual hours based on leave block on this day
                BigDecimal noAccrualHours = getNotEligibleForAccrualHours(principalId,
                        currentDate.toLocalDate());
                if (noAccrualHours != null && noAccrualHours.compareTo(BigDecimal.ZERO) != 0
                        && totalOfStandardHours.compareTo(BigDecimal.ZERO) != 0) {
                    BigDecimal dayHours = totalOfStandardHours.divide(new BigDecimal(5), 6,
                            BigDecimal.ROUND_HALF_UP);
                    // if leave hours on the day is more than the standard hours, use the standard hour to calculate the adjustment
                    if (noAccrualHours.abs().compareTo(dayHours.abs()) == 1) {
                        noAccrualHours = dayHours.abs().negate();
                    }
                    BigDecimal noAccrualRate = dayRate.multiply(noAccrualHours.divide(dayHours));
                    this.calculateHours(anAC.getLmAccrualCategoryId(), ftePercentage, noAccrualRate,
                            accumulatedAccrualCatToNegativeAccrualAmounts);
                }

                // only accrual on work days
                if (!TKUtils.isWeekend(currentDate) && !fullFteGranted) {
                    //Add to total accumulatedAccrualCatToAccrualAmounts
                    //use rule and ftePercentage to calculate the hours            
                    this.calculateHours(anAC.getLmAccrualCategoryId(), ftePercentage, dayRate,
                            accumulatedAccrualCatToAccrualAmounts);
                }
                //Determine if we are at the accrual earn interval in the span, if so add leave block for accumulated accrual amount to list
                //and reset accumulatedAccrualCatToAccrualAmounts and accumulatedAccrualCatToNegativeAccrualAmounts for this accrual category
                if (this.isDateAnIntervalDate(currentDate.toLocalDate(), anAC.getAccrualEarnInterval(),
                        phra.getPayCalendar(), rrAggregate.getCalEntryMap())) {
                    BigDecimal acHours = accumulatedAccrualCatToAccrualAmounts
                            .get(anAC.getLmAccrualCategoryId());

                    if (acHours != null) {
                        createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(), acHours,
                                anAC, null, true, currentRange.getLeaveCalendarDocumentId(), null);
                        accumulatedAccrualCatToAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); // reset accumulatedAccrualCatToAccrualAmounts
                        fullFteGranted = false;
                    }

                    BigDecimal adjustmentHours = accumulatedAccrualCatToNegativeAccrualAmounts
                            .get(anAC.getLmAccrualCategoryId());
                    if (adjustmentHours != null && adjustmentHours.compareTo(BigDecimal.ZERO) != 0) {
                        // do not create leave block if the ajustment amount is 0
                        createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(),
                                adjustmentHours, anAC, null, false, currentRange.getLeaveCalendarDocumentId(),
                                null);
                        accumulatedAccrualCatToNegativeAccrualAmounts.remove(anAC.getLmAccrualCategoryId()); // reset accumulatedAccrualCatToNegativeAccrualAmounts
                    }
                }
            }
        }
        //Determine if today is a system scheduled time off and accrue holiday if so.
        SystemScheduledTimeOffContract ssto = currentRange.getSysScheTimeOff();
        if (ssto != null) {
            AccrualCategory anAC = HrServiceLocator.getAccrualCategoryService()
                    .getAccrualCategory(ssto.getAccrualCategory(), ssto.getEffectiveLocalDate());
            if (anAC == null) {
                LOG.error("Cannot find Accrual Category for system scheduled time off "
                        + ssto.getLmSystemScheduledTimeOffId());
                return;
                //               throw new RuntimeException("Cannot find Accrual Category for system scheduled time off " + ssto.getLmSystemScheduledTimeOffId());
            }
            BigDecimal hrs = ssto.getAmountofTime().multiply(ftePercentage);
            // system scheduled time off leave block
            createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(), hrs, anAC,
                    ssto.getLmSystemScheduledTimeOffId(), true, currentRange.getLeaveCalendarDocumentId(),
                    null);
            // we only need to create usage leave block for ssto if there is a scheduled time off date
            if (ssto.getScheduledTimeOffDate() != null) {
                // usage leave block with negative amount. Assign primary leave assignment information to ssto usage leave block
                createLeaveBlock(principalId, accrualLeaveBlocks, ssto.getScheduledTimeOffLocalDate(),
                        hrs.negate(), anAC, ssto.getLmSystemScheduledTimeOffId(), true,
                        currentRange.getLeaveCalendarDocumentId(), currentRange.getPrimaryLeaveAssignmentId());
            }
        }
        // if today is the last day of the employment, create leave blocks if there's any hours available
        if (endPhra != null && currentDate.toLocalDate().equals(endPhra.getEffectiveLocalDate())) {
            // accumulated accrual amount
            if (!accumulatedAccrualCatToAccrualAmounts.isEmpty()) {
                for (Map.Entry<String, BigDecimal> entry : accumulatedAccrualCatToAccrualAmounts.entrySet()) {
                    if (entry.getValue() != null && entry.getValue().compareTo(BigDecimal.ZERO) != 0) {
                        AccrualCategory anAC = HrServiceLocator.getAccrualCategoryService()
                                .getAccrualCategory(entry.getKey());
                        createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(),
                                entry.getValue(), anAC, null, true, currentRange.getLeaveCalendarDocumentId(),
                                null);
                    }
                }
                accumulatedAccrualCatToAccrualAmounts = new HashMap<String, BigDecimal>(); // reset accumulatedAccrualCatToAccrualAmounts
            }
            // negative/adjustment accrual amount
            if (!accumulatedAccrualCatToNegativeAccrualAmounts.isEmpty()) {
                for (Map.Entry<String, BigDecimal> entry : accumulatedAccrualCatToNegativeAccrualAmounts
                        .entrySet()) {
                    if (entry.getValue() != null && entry.getValue().compareTo(BigDecimal.ZERO) != 0) {
                        AccrualCategory anAC = HrServiceLocator.getAccrualCategoryService()
                                .getAccrualCategory(entry.getKey());
                        createLeaveBlock(principalId, accrualLeaveBlocks, currentDate.toLocalDate(),
                                entry.getValue(), anAC, null, true, currentRange.getLeaveCalendarDocumentId(),
                                null);
                    }
                }
                accumulatedAccrualCatToNegativeAccrualAmounts = new HashMap<String, BigDecimal>(); // reset accumulatedAccrualCatToNegativeAccrualAmounts
            }
            phra = null; // reset principal attribute so new value will be retrieved
            endPhra = null; // reset end principal attribute so new value will be retrieved
        }

        currentDate = currentDate.plusDays(1);
    }

    //Save accrual leave blocks at the very end
    LmServiceLocator.getLeaveBlockService().saveLeaveBlocks(accrualLeaveBlocks);

    // record timestamp of this accrual run in database
    if (recordRanData) {
        LmServiceLocator.getPrincipalAccrualRanService().updatePrincipalAccrualRanInfo(principalId);
    }

}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * get a download/upload report./*from  w  w w.  j  a v a 2s.co  m*/
 *
 * @param mode speed test mode requested
 * @return speed test report
 */
public SpeedTestReport getReport(final SpeedTestMode mode) {

    BigDecimal temporaryPacketSize = BigDecimal.ZERO;
    BigDecimal totalPacketSize = BigDecimal.ZERO;

    switch (mode) {
    case DOWNLOAD:
        temporaryPacketSize = new BigDecimal(mDownloadTemporaryPacketSize);
        totalPacketSize = mDownloadPckSize;
        break;
    case UPLOAD:
        temporaryPacketSize = new BigDecimal(mUploadTempFileSize);
        totalPacketSize = mUploadFileSize;
        break;
    default:
        break;
    }

    long currentTime;
    if (mTimeEnd == 0) {
        currentTime = System.currentTimeMillis();
    } else {
        currentTime = mTimeEnd;
    }

    BigDecimal transferRateOps = BigDecimal.ZERO;

    final int scale = mSocketInterface.getDefaultScale();
    final RoundingMode roundingMode = mSocketInterface.getDefaultRoundingMode();

    if (shallCalculateTransferRate(currentTime, mode)) {
        transferRateOps = temporaryPacketSize.divide(new BigDecimal(currentTime - mTimeStart)
                .divide(SpeedTestConst.MILLIS_DIVIDER, scale, roundingMode), scale, roundingMode);
    }

    final BigDecimal transferRateBitps = transferRateOps.multiply(SpeedTestConst.BIT_MULTIPLIER);

    BigDecimal percent = BigDecimal.ZERO;

    SpeedTestReport report;

    if (mRepeatWrapper.isRepeat()) {

        report = mRepeatWrapper.getRepeatReport(scale, roundingMode, mode, currentTime, transferRateOps);

    } else {

        if (totalPacketSize != BigDecimal.ZERO) {

            percent = temporaryPacketSize.multiply(SpeedTestConst.PERCENT_MAX).divide(totalPacketSize, scale,
                    roundingMode);
        }

        report = new SpeedTestReport(mode, percent.floatValue(), mTimeStart, currentTime,
                temporaryPacketSize.longValueExact(), totalPacketSize.longValueExact(), transferRateOps,
                transferRateBitps, 1);
    }
    return report;
}

From source file:org.efaps.esjp.accounting.transaction.Create_Base.java

/**
 * Create a position. The type is given with the properties of the calling
 * command.//from   w  ww.j  a v  a 2  s .  co  m
 *
 * @param _parameter Parameter as passed from the eFaps API
 * @return new Return
 * @throws EFapsException on error
 */
public Return createPosition(final Parameter _parameter) throws EFapsException {
    final Instance parent = _parameter.getCallInstance();
    final String amountStr = _parameter.getParameterValue("rateAmount");
    final String account = _parameter.getParameterValue("accountLink");
    final String rateCurrencyLink = _parameter.getParameterValue("rateCurrencyLink");

    final Map<?, ?> properties = (Map<?, ?>) _parameter.get(ParameterValues.PROPERTIES);
    final String typeName = (String) properties.get("Type");
    final Instance curInstance;
    if (parent.getType().isKindOf(CIAccounting.TransactionAbstract.getType())) {
        final PrintQuery print = new PrintQuery(parent);
        final SelectBuilder sel = new SelectBuilder().linkto(CIAccounting.TransactionAbstract.PeriodLink).oid();
        print.addSelect(sel);
        print.execute();
        final Instance periodInst = Instance.get(print.<String>getSelect(sel));
        curInstance = new Period().getCurrency(periodInst).getInstance();
    } else {
        curInstance = new Period().getCurrency(_parameter.getCallInstance()).getInstance();
    }
    BigDecimal amount = DecimalType.parseLocalized(amountStr);
    final Type type = Type.get(typeName);
    if (!type.getUUID().equals(CIAccounting.TransactionPositionCredit.uuid)) {
        amount = amount.negate();
    }
    final Object[] rateObj = new Transaction().getRateObject(_parameter, "", 0);
    final BigDecimal rate = ((BigDecimal) rateObj[0]).divide((BigDecimal) rateObj[1], 12,
            BigDecimal.ROUND_HALF_UP);
    final Insert insert = new Insert(type);
    insert.add(CIAccounting.TransactionPositionAbstract.TransactionLink, parent.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.AccountLink, Instance.get(account).getId());
    insert.add(CIAccounting.TransactionPositionAbstract.CurrencyLink, curInstance.getId());
    insert.add(CIAccounting.TransactionPositionAbstract.RateCurrencyLink, rateCurrencyLink);
    insert.add(CIAccounting.TransactionPositionAbstract.Rate, rateObj);
    insert.add(CIAccounting.TransactionPositionAbstract.Amount,
            amount.divide(rate, 12, BigDecimal.ROUND_HALF_UP));
    insert.add(CIAccounting.TransactionPositionAbstract.RateAmount, amount);
    insert.execute();
    return new Return();
}

From source file:org.kuali.ole.module.purap.document.service.impl.PaymentRequestServiceImpl.java

/**
 * Generates a PurAP accounting line and adds to the specified tax item.
 *
 * @param taxItem       The specified tax item the accounting line will be associated with.
 * @param taxableAmount The amount to which tax is computed against.
 * @return A fully populated PurApAccountingLine instance for the specified tax item.
 *///from   w ww .  j  a va2s .  co m
protected PurApAccountingLine addTaxAccountingLine(PurApItem taxItem, BigDecimal taxableAmount) {
    PaymentRequestDocument preq = taxItem.getPurapDocument();
    PurApAccountingLine taxLine = null;

    try {
        taxLine = (PurApAccountingLine) taxItem.getAccountingLineClass().newInstance();
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("Unable to access sourceAccountingLineClass", e);
    } catch (InstantiationException e) {
        throw new IllegalArgumentException("Unable to instantiate sourceAccountingLineClass", e);
    }

    // tax item type indicators
    boolean isFederalTax = ItemTypeCodes.ITEM_TYPE_FEDERAL_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederalGross = ItemTypeCodes.ITEM_TYPE_FEDERAL_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateTax = ItemTypeCodes.ITEM_TYPE_STATE_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateGross = ItemTypeCodes.ITEM_TYPE_STATE_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederal = isFederalTax || isFederalGross; // true for federal tax/gross; false for state tax/gross
    boolean isGross = isFederalGross || isStateGross; // true for federal/state gross, false for federal/state tax

    // obtain accounting line info according to tax item type code
    String taxChart = null;
    String taxAccount = null;
    String taxObjectCode = null;

    if (isGross) {
        // for gross up tax items, use preq's first item's first accounting line, which shall exist at this point
        AccountingLine line1 = preq.getFirstAccount();
        taxChart = line1.getChartOfAccountsCode();
        taxAccount = line1.getAccountNumber();
        taxObjectCode = line1.getFinancialObjectCode();
    } else if (isFederalTax) {
        // for federal tax item, get chart, account, object code info from parameters
        taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                preq.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve federal tax parameters.");
            throw new RuntimeException("Unable to retrieve federal tax parameters.");
        }
    } else if (isStateTax) {
        // for state tax item, get chart, account, object code info from parameters
        taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                preq.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve state tax parameters.");
            throw new RuntimeException("Unable to retrieve state tax parameters.");
        }
    }

    // calculate tax amount according to gross up indicator and federal/state tax type
    /*
     * The formula of tax and gross up amount are as follows: if (not gross up) gross not existing taxFederal/State = - amount *
     * rateFederal/State otherwise gross up grossFederal/State = amount * rateFederal/State / (1 - rateFederal - rateState) tax
     * = - gross
     */

    // pick federal/state tax rate
    BigDecimal taxPercentFederal = preq.getTaxFederalPercent();
    BigDecimal taxPercentState = preq.getTaxStatePercent();
    BigDecimal taxPercent = isFederal ? taxPercentFederal : taxPercentState;

    // divider value according to gross up or not
    BigDecimal taxDivider = new BigDecimal(100);
    if (preq.getTaxGrossUpIndicator()) {
        taxDivider = taxDivider.subtract(taxPercentFederal.add(taxPercentState));
    }

    // tax = amount * rate / divider
    BigDecimal taxAmount = taxableAmount.multiply(taxPercent);
    taxAmount = taxAmount.divide(taxDivider, 5, BigDecimal.ROUND_HALF_UP);

    // tax is always negative, since it reduces the total amount; while gross up is always the positive of tax
    if (!isGross) {
        taxAmount = taxAmount.negate();
    }

    // populate necessary accounting line fields
    taxLine.setDocumentNumber(preq.getDocumentNumber());
    taxLine.setSequenceNumber(preq.getNextSourceLineNumber());
    taxLine.setChartOfAccountsCode(taxChart);
    taxLine.setAccountNumber(taxAccount);
    taxLine.setFinancialObjectCode(taxObjectCode);
    taxLine.setAmount(new KualiDecimal(taxAmount));

    // add the accounting line to the item
    taxLine.setItemIdentifier(taxItem.getItemIdentifier());
    taxLine.setPurapItem(taxItem);
    taxItem.getSourceAccountingLines().add(taxLine);

    return taxLine;
}

From source file:org.kuali.ole.module.purap.document.service.impl.InvoiceServiceImpl.java

/**
 * Generates a PurAP accounting line and adds to the specified tax item.
 *
 * @param taxItem       The specified tax item the accounting line will be associated with.
 * @param taxableAmount The amount to which tax is computed against.
 * @return A fully populated PurApAccountingLine instance for the specified tax item.
 *//*ww w. ja v  a 2s . c  o m*/
protected PurApAccountingLine addTaxAccountingLine(PurApItem taxItem, BigDecimal taxableAmount) {
    InvoiceDocument prqs = taxItem.getPurapDocument();
    PurApAccountingLine taxLine = null;

    try {
        taxLine = (PurApAccountingLine) taxItem.getAccountingLineClass().newInstance();
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("Unable to access sourceAccountingLineClass", e);
    } catch (InstantiationException e) {
        throw new IllegalArgumentException("Unable to instantiate sourceAccountingLineClass", e);
    }

    // tax item type indicators
    boolean isFederalTax = ItemTypeCodes.ITEM_TYPE_FEDERAL_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederalGross = ItemTypeCodes.ITEM_TYPE_FEDERAL_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateTax = ItemTypeCodes.ITEM_TYPE_STATE_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateGross = ItemTypeCodes.ITEM_TYPE_STATE_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederal = isFederalTax || isFederalGross; // true for federal tax/gross; false for state tax/gross
    boolean isGross = isFederalGross || isStateGross; // true for federal/state gross, false for federal/state tax

    // obtain accounting line info according to tax item type code
    String taxChart = null;
    String taxAccount = null;
    String taxObjectCode = null;

    if (isGross) {
        // for gross up tax items, use prqs's first item's first accounting line, which shall exist at this point
        AccountingLine line1 = prqs.getFirstAccount();
        taxChart = line1.getChartOfAccountsCode();
        taxAccount = line1.getAccountNumber();
        taxObjectCode = line1.getFinancialObjectCode();
    } else if (isFederalTax) {
        // for federal tax item, get chart, account, object code info from parameters
        taxChart = getParameter(OLEConstants.OptionalModuleNamespaces.PURCHASING_ACCOUNTS_PAYABLE,
                OLEConstants.InvoiceDocument.CMPNT_CD,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = getParameter(OLEConstants.OptionalModuleNamespaces.PURCHASING_ACCOUNTS_PAYABLE,
                OLEConstants.InvoiceDocument.CMPNT_CD,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(InvoiceDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                prqs.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve federal tax parameters.");
            throw new RuntimeException("Unable to retrieve federal tax parameters.");
        }
    } else if (isStateTax) {
        // for state tax item, get chart, account, object code info from parameters
        taxChart = getParameter(OLEConstants.OptionalModuleNamespaces.PURCHASING_ACCOUNTS_PAYABLE,
                OLEConstants.InvoiceDocument.CMPNT_CD,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = getParameter(OLEConstants.OptionalModuleNamespaces.PURCHASING_ACCOUNTS_PAYABLE,
                OLEConstants.InvoiceDocument.CMPNT_CD,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(InvoiceDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                prqs.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve state tax parameters.");
            throw new RuntimeException("Unable to retrieve state tax parameters.");
        }
    }

    // calculate tax amount according to gross up indicator and federal/state tax type
    /*
     * The formula of tax and gross up amount are as follows: if (not gross up) gross not existing taxFederal/State = - amount *
     * rateFederal/State otherwise gross up grossFederal/State = amount * rateFederal/State / (1 - rateFederal - rateState) tax
     * = - gross
     */

    // pick federal/state tax rate
    BigDecimal taxPercentFederal = prqs.getTaxFederalPercent();
    BigDecimal taxPercentState = prqs.getTaxStatePercent();
    BigDecimal taxPercent = isFederal ? taxPercentFederal : taxPercentState;

    // divider value according to gross up or not
    BigDecimal taxDivider = new BigDecimal(100);
    if (prqs.getTaxGrossUpIndicator()) {
        taxDivider = taxDivider.subtract(taxPercentFederal.add(taxPercentState));
    }

    // tax = amount * rate / divider
    BigDecimal taxAmount = taxableAmount.multiply(taxPercent);
    taxAmount = taxAmount.divide(taxDivider, 5, BigDecimal.ROUND_HALF_UP);

    // tax is always negative, since it reduces the total amount; while gross up is always the positive of tax
    if (!isGross) {
        taxAmount = taxAmount.negate();
    }

    // populate necessary accounting line fields
    taxLine.setDocumentNumber(prqs.getDocumentNumber());
    taxLine.setSequenceNumber(prqs.getNextSourceLineNumber());
    taxLine.setChartOfAccountsCode(taxChart);
    taxLine.setAccountNumber(taxAccount);
    taxLine.setFinancialObjectCode(taxObjectCode);
    taxLine.setAmount(new KualiDecimal(taxAmount));

    // add the accounting line to the item
    taxLine.setItemIdentifier(taxItem.getItemIdentifier());
    taxLine.setPurapItem(taxItem);
    taxItem.getSourceAccountingLines().add(taxLine);

    return taxLine;
}

From source file:org.totschnig.myexpenses.activity.ExpenseEdit.java

private void updateExchangeRates() {
    BigDecimal amount = validateAmountInput(mAmountText, false);
    BigDecimal transferAmount = validateAmountInput(mTransferAmountText, false);
    BigDecimal exchangeRate = (amount != null && transferAmount != null && amount.compareTo(nullValue) != 0)
            ? transferAmount.divide(amount, EXCHANGE_RATE_FRACTION_DIGITS, RoundingMode.DOWN)
            : nullValue;//w  w w .  java 2s  .c o m
    BigDecimal inverseExchangeRate = exchangeRate.compareTo(nullValue) != 0
            ? new BigDecimal(1).divide(exchangeRate, EXCHANGE_RATE_FRACTION_DIGITS, RoundingMode.DOWN)
            : nullValue;
    mExchangeRate1Text.setAmount(exchangeRate);
    mExchangeRate2Text.setAmount(inverseExchangeRate);
}

From source file:org.kuali.kfs.module.purap.document.service.impl.PaymentRequestServiceImpl.java

/**
 * Generates a PurAP accounting line and adds to the specified tax item.
 *
 * @param taxItem The specified tax item the accounting line will be associated with.
 * @param taxableAmount The amount to which tax is computed against.
 * @return A fully populated PurApAccountingLine instance for the specified tax item.
 *///ww w .  j  ava2s . co m
protected PurApAccountingLine addTaxAccountingLine(PurApItem taxItem, BigDecimal taxableAmount) {
    PaymentRequestDocument preq = taxItem.getPurapDocument();
    PurApAccountingLine taxLine = null;

    try {
        taxLine = (PurApAccountingLine) taxItem.getAccountingLineClass().newInstance();
    } catch (IllegalAccessException e) {
        throw new InfrastructureException("Unable to access sourceAccountingLineClass", e);
    } catch (InstantiationException e) {
        throw new InfrastructureException("Unable to instantiate sourceAccountingLineClass", e);
    }

    // tax item type indicators
    boolean isFederalTax = ItemTypeCodes.ITEM_TYPE_FEDERAL_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederalGross = ItemTypeCodes.ITEM_TYPE_FEDERAL_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateTax = ItemTypeCodes.ITEM_TYPE_STATE_TAX_CODE.equals(taxItem.getItemTypeCode());
    boolean isStateGross = ItemTypeCodes.ITEM_TYPE_STATE_GROSS_CODE.equals(taxItem.getItemTypeCode());
    boolean isFederal = isFederalTax || isFederalGross; // true for federal tax/gross; false for state tax/gross
    boolean isGross = isFederalGross || isStateGross; // true for federal/state gross, false for federal/state tax

    // obtain accounting line info according to tax item type code
    String taxChart = null;
    String taxAccount = null;
    String taxObjectCode = null;

    if (isGross) {
        // for gross up tax items, use preq's first item's first accounting line, which shall exist at this point
        AccountingLine line1 = preq.getFirstAccount();
        taxChart = line1.getChartOfAccountsCode();
        taxAccount = line1.getAccountNumber();
        taxObjectCode = line1.getFinancialObjectCode();
    } else if (isFederalTax) {
        // for federal tax item, get chart, account, object code info from parameters
        taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.FEDERAL_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                preq.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve federal tax parameters.");
            throw new RuntimeException("Unable to retrieve federal tax parameters.");
        }
    } else if (isStateTax) {
        // for state tax item, get chart, account, object code info from parameters
        taxChart = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_CHART_SUFFIX);
        taxAccount = parameterService.getParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX + NRATaxParameters.TAX_PARM_ACCOUNT_SUFFIX);
        taxObjectCode = parameterService.getSubParameterValueAsString(PaymentRequestDocument.class,
                NRATaxParameters.STATE_TAX_PARM_PREFIX
                        + NRATaxParameters.TAX_PARM_OBJECT_BY_INCOME_CLASS_SUFFIX,
                preq.getTaxClassificationCode());
        if (StringUtils.isBlank(taxChart) || StringUtils.isBlank(taxAccount)
                || StringUtils.isBlank(taxObjectCode)) {
            LOG.error("Unable to retrieve state tax parameters.");
            throw new RuntimeException("Unable to retrieve state tax parameters.");
        }
    }

    // calculate tax amount according to gross up indicator and federal/state tax type
    /*
     * The formula of tax and gross up amount are as follows: if (not gross up) gross not existing taxFederal/State = - amount *
     * rateFederal/State otherwise gross up grossFederal/State = amount * rateFederal/State / (1 - rateFederal - rateState) tax
     * = - gross
     */

    // pick federal/state tax rate
    BigDecimal taxPercentFederal = preq.getTaxFederalPercent();
    BigDecimal taxPercentState = preq.getTaxStatePercent();
    BigDecimal taxPercent = isFederal ? taxPercentFederal : taxPercentState;

    // divider value according to gross up or not
    BigDecimal taxDivider = new BigDecimal(100);
    if (preq.getTaxGrossUpIndicator()) {
        taxDivider = taxDivider.subtract(taxPercentFederal.add(taxPercentState));
    }

    // tax = amount * rate / divider
    BigDecimal taxAmount = taxableAmount.multiply(taxPercent);
    taxAmount = taxAmount.divide(taxDivider, 5, BigDecimal.ROUND_HALF_UP);

    // tax is always negative, since it reduces the total amount; while gross up is always the positive of tax
    if (!isGross) {
        taxAmount = taxAmount.negate();
    }

    // populate necessary accounting line fields
    taxLine.setDocumentNumber(preq.getDocumentNumber());
    taxLine.setSequenceNumber(preq.getNextSourceLineNumber());
    taxLine.setChartOfAccountsCode(taxChart);
    taxLine.setAccountNumber(taxAccount);
    taxLine.setFinancialObjectCode(taxObjectCode);
    taxLine.setAmount(new KualiDecimal(taxAmount));

    // add the accounting line to the item
    taxLine.setItemIdentifier(taxItem.getItemIdentifier());
    taxLine.setPurapItem(taxItem);
    taxItem.getSourceAccountingLines().add(taxLine);

    return taxLine;
}

From source file:org.totschnig.myexpenses.activity.ExpenseEdit.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data == null) {
        return;/*from w  w  w .ja  v  a 2 s  . co m*/
    }
    int id = loader.getId();
    switch (id) {
    case METHODS_CURSOR:
        mMethodsCursor = data;
        View methodContainer = findViewById(R.id.MethodRow);
        if (mMethodsAdapter == null || !data.moveToFirst()) {
            methodContainer.setVisibility(View.GONE);
        } else {
            methodContainer.setVisibility(View.VISIBLE);
            MatrixCursor extras = new MatrixCursor(new String[] { KEY_ROWID, KEY_LABEL, KEY_IS_NUMBERED });
            extras.addRow(new String[] { "0", "- - - -", "0" });
            mMethodsAdapter.swapCursor(new MergeCursor(new Cursor[] { extras, data }));
            if (mSavedInstance) {
                mTransaction.methodId = mMethodId;
            }
            if (mTransaction.methodId != null) {
                while (data.isAfterLast() == false) {
                    if (data.getLong(data.getColumnIndex(KEY_ROWID)) == mTransaction.methodId) {
                        mMethodSpinner.setSelection(data.getPosition() + 1);
                        break;
                    }
                    data.moveToNext();
                }
            } else {
                mMethodSpinner.setSelection(0);
            }
        }
        break;
    case ACCOUNTS_CURSOR:
        mAccountsAdapter.swapCursor(data);
        mAccounts = new Account[data.getCount()];
        if (mSavedInstance) {
            mTransaction.accountId = mAccountId;
            mTransaction.transfer_account = mTransferAccountId;
        }
        data.moveToFirst();
        boolean selectionSet = false;
        String currencyExtra = getIntent().getStringExtra(KEY_CURRENCY);
        while (data.isAfterLast() == false) {
            int position = data.getPosition();
            Account a = Account.fromCacheOrFromCursor(data);
            mAccounts[position] = a;
            if (!selectionSet && (a.currency.getCurrencyCode().equals(currencyExtra)
                    || (currencyExtra == null && a.getId().equals(mTransaction.accountId)))) {
                mAccountSpinner.setSelection(position);
                setAccountLabel(a);
                selectionSet = true;
            }
            data.moveToNext();
        }
        //if the accountId we have been passed does not exist, we select the first entry
        if (mAccountSpinner.getSelectedItemPosition() == android.widget.AdapterView.INVALID_POSITION) {
            mAccountSpinner.setSelection(0);
            mTransaction.accountId = mAccounts[0].getId();
            setAccountLabel(mAccounts[0]);
        }
        if (mOperationType == MyExpenses.TYPE_TRANSFER) {
            mTransferAccountCursor = new FilterCursorWrapper(data);
            int selectedPosition = setTransferAccountFilterMap();
            mTransferAccountsAdapter.swapCursor(mTransferAccountCursor);
            mTransferAccountSpinner.setSelection(selectedPosition);
            mTransaction.transfer_account = mTransferAccountSpinner.getSelectedItemId();
            configureTransferInput();
            if (!mNewInstance && !(mTransaction instanceof Template)) {
                isProcessingLinkedAmountInputs = true;
                mTransferAmountText.setAmount(mTransaction.getTransferAmount().getAmountMajor().abs());
                updateExchangeRates();
                isProcessingLinkedAmountInputs = false;
            }
        } else {
            //the methods cursor is based on the current account,
            //hence it is loaded only after the accounts cursor is loaded
            if (!(mTransaction instanceof SplitPartCategory)) {
                mManager.initLoader(METHODS_CURSOR, null, this);
            }
        }
        mTypeButton.setEnabled(true);
        configureType();
        configureStatusSpinner();
        if (mIsResumed)
            setupListeners();
        break;
    case LAST_EXCHANGE_CURSOR:
        if (data.moveToFirst()) {
            final Currency currency1 = getCurrentAccount().currency;
            final Currency currency2 = Account
                    .getInstanceFromDb(mTransferAccountSpinner.getSelectedItemId()).currency;
            if (currency1.getCurrencyCode().equals(data.getString(0))
                    && currency2.getCurrencyCode().equals(data.getString(1))) {
                BigDecimal amount = new Money(currency1, data.getLong(2)).getAmountMajor();
                BigDecimal transferAmount = new Money(currency2, data.getLong(3)).getAmountMajor();
                BigDecimal exchangeRate = amount.compareTo(nullValue) != 0
                        ? transferAmount.divide(amount, EXCHANGE_RATE_FRACTION_DIGITS, RoundingMode.DOWN)
                        : nullValue;
                if (exchangeRate.compareTo(nullValue) != 0) {
                    mExchangeRate1Text.setAmount(exchangeRate);
                }
            }
        }
    }
}

From source file:com.autentia.intra.bean.billing.FinancialRatioBean.java

public BigDecimal getBatVar1() {
    try {/* ww  w  .  j  a v a  2  s .  co  m*/
        BigDecimal res = new BigDecimal(financialRatio.getBat().doubleValue());
        res = res.divide(financialRatioCompOne.getBat(), 4, RoundingMode.HALF_UP);
        res = res.subtract(new BigDecimal(1));
        return res;

    } catch (Exception e) {
        return new BigDecimal(0);
    }
}

From source file:com.autentia.intra.bean.billing.FinancialRatioBean.java

public BigDecimal getBatVar2() {
    try {//from  w w w . j  av a 2 s.  c o  m
        BigDecimal res = new BigDecimal(financialRatio.getBat().doubleValue());
        res = res.divide(financialRatioCompTwo.getBat(), 4, RoundingMode.HALF_UP);
        res = res.subtract(new BigDecimal(1));
        return res;

    } catch (Exception e) {
        return new BigDecimal(0);
    }
}