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:org.kuali.kpme.tklm.leave.accrual.service.AccrualCategoryMaxBalanceServiceImpl.java

@Override
public Map<String, Set<LeaveBlock>> getMaxBalanceViolations(CalendarEntry entry, String principalId) {

    Map<String, Set<LeaveBlock>> maxBalanceViolations = new HashMap<String, Set<LeaveBlock>>();

    Map<String, Set<LeaveBlock>> eligibilities = new HashMap<String, Set<LeaveBlock>>();

    eligibilities.put(HrConstants.MAX_BAL_ACTION_FREQ.LEAVE_APPROVE, new HashSet<LeaveBlock>());
    eligibilities.put(HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END, new HashSet<LeaveBlock>());
    eligibilities.put(HrConstants.MAX_BAL_ACTION_FREQ.ON_DEMAND, new HashSet<LeaveBlock>());

    Interval thisEntryInterval = new Interval(entry.getBeginPeriodFullDateTime(),
            entry.getEndPeriodFullDateTime());

    LocalDate asOfDate = LocalDate.now();

    if (!thisEntryInterval.contains(asOfDate.toDate().getTime())) {
        asOfDate = entry.getEndPeriodFullDateTime().minusDays(1).toLocalDate();
    }/* www.j av a  2 s .co  m*/
    PrincipalHRAttributes pha = HrServiceLocator.getPrincipalHRAttributeService()
            .getPrincipalCalendar(principalId, asOfDate);

    if (pha == null) {
        return eligibilities;
    }
    Calendar cal = pha.getLeaveCalObj();

    if (cal == null) {
        return eligibilities;
    }
    //Consider time sheet intervals that stagger a leave period end date...
    List<CalendarEntry> leaveCalEntries = HrServiceLocator.getCalendarEntryService()
            .getCalendarEntriesEndingBetweenBeginAndEndDate(cal.getHrCalendarId(),
                    entry.getBeginPeriodFullDateTime(), entry.getEndPeriodFullDateTime());
    CalendarEntry yearEndLeaveEntry = null;
    CalendarEntry leaveLeaveEntry = null;
    if (!leaveCalEntries.isEmpty()) {
        for (CalendarEntry leaveEntry : leaveCalEntries) {
            if (StringUtils.equals(cal.getCalendarName(), leaveEntry.getCalendarName())) {
                if (leaveEntry.getEndPeriodFullDateTime().compareTo(entry.getBeginPeriodFullDateTime()) > 0) {
                    leaveLeaveEntry = leaveEntry;
                }
            }
        }
    }

    Interval leavePeriodInterval = null;
    Interval yearEndPeriodInterval = null;
    if (leaveLeaveEntry != null) {
        leavePeriodInterval = new Interval(entry.getBeginPeriodFullDateTime(),
                leaveLeaveEntry.getEndPeriodFullDateTime());
        if (HrServiceLocator.getLeavePlanService().isLastCalendarPeriodOfLeavePlan(leaveLeaveEntry,
                pha.getLeavePlan(), asOfDate)) {
            yearEndPeriodInterval = leavePeriodInterval;
        }
    }

    List<AccrualCategory> accrualCategories = HrServiceLocator.getAccrualCategoryService()
            .getActiveAccrualCategoriesForLeavePlan(pha.getLeavePlan(), asOfDate);

    if (!accrualCategories.isEmpty()) {

        List<LeaveBlock> leaveBlocks = new ArrayList<LeaveBlock>();
        Map<String, BigDecimal> accruedBalance = new HashMap<String, BigDecimal>();

        for (AccrualCategoryContract accrualCategory : accrualCategories) {
            LocalDate leaveBlockEndDate = leaveLeaveEntry == null
                    ? entry.getEndPeriodFullDateTime().toLocalDate().plusDays(1)
                    : leaveLeaveEntry.getEndPeriodFullDateTime().toLocalDate().plusDays(1);
            //if ()
            leaveBlocks.addAll(LmServiceLocator.getLeaveBlockService().getLeaveBlocksWithAccrualCategory(
                    principalId, pha.getServiceLocalDate(), leaveBlockEndDate,
                    accrualCategory.getAccrualCategory()));
            accruedBalance.put(accrualCategory.getLmAccrualCategoryId(), BigDecimal.ZERO);
            /*   Un-comment to consider service interval end-point changes. i.e. when defining a new action frequency - "ON_SERVICE_MILESTONE"
                        List<AccrualCategoryRule> accrualRules = HrServiceLocator.getAccrualCategoryRuleService().getActiveAccrualCategoryRules(accrualCategory.getLmAccrualCategoryId());
                        for(AccrualCategoryRule rule : accrualRules) {
                           String serviceUnits = rule.getServiceUnitOfTime();
                           LocalDate rollOverDate = null;
                           //TODO: Accrual Category Rules' start and end field allow only whole integer values. This should be reflected in storage.
                           if(StringUtils.equals(serviceUnits, "M")) {
                              rollOverDate = pha.getServiceLocalDate().plusMonths(rule.getEnd().intValue());
                           }
                           else if(StringUtils.equals(serviceUnits, "Y")) {
                              rollOverDate = pha.getServiceLocalDate().plusYears(rule.getEnd().intValue());
                           }
                           if(ObjectUtils.isNotNull(rollOverDate)) {
                              if(thisEntryInterval.contains(rollOverDate.minusDays(1).toDate().getTime())) {
             //Add a max balance allocation leave block.
             LeaveBlock allocation = new LeaveBlock();
             allocation.setAccrualCategory(accrualCategory.getAccrualCategory());
             allocation.setLeaveLocalDate(rollOverDate.minusDays(1));
             allocation.setLeaveAmount(BigDecimal.ZERO);
             allocation.setPrincipalId(principalId);
             leaveBlocks.add(allocation);
                              }
                           }
                        }
            */

            //Add a max balance allocation leave block.
            LeaveBlockBo allocation = new LeaveBlockBo();
            allocation.setAccrualCategory(accrualCategory.getAccrualCategory());

            if (thisEntryInterval.contains(LocalDate.now().toDate().getTime())) {
                allocation.setLeaveLocalDate(LocalDate.now());
            } else {
                allocation.setLeaveLocalDate(entry.getEndPeriodFullDateTime().toLocalDate().minusDays(1));
            }

            if (leaveLeaveEntry == null) {
                allocation.setLeaveAmount(BigDecimal.ZERO);
                allocation.setPrincipalId(principalId);
                allocation.setLeaveBlockType("allocation");
                leaveBlocks.add(LeaveBlockBo.to(allocation));
            } else {
                //if(ObjectUtils.isNotNull(leaveLeaveEntry)) {
                //if entry belongs to a time calendar, check the balances at the end date for the calendar year that ends
                //within entry's interval.
                //if entry belongs to a leave calendar, this empty block will simply duplicate and override
                //the block created above.
                allocation = new LeaveBlockBo();
                allocation.setAccrualCategory(accrualCategory.getAccrualCategory());
                allocation.setLeaveLocalDate(
                        leaveLeaveEntry.getEndPeriodFullDateTime().toLocalDate().minusDays(1));
                allocation.setLeaveAmount(BigDecimal.ZERO);
                allocation.setPrincipalId(principalId);
                allocation.setLeaveBlockType("allocation");
                leaveBlocks.add(LeaveBlockBo.to(allocation));
            }

            if (!leaveBlocks.isEmpty()) {
                Collections.sort(leaveBlocks, new Comparator<LeaveBlock>() {

                    @Override
                    public int compare(LeaveBlock o1, LeaveBlock o2) {
                        return o1.getLeaveDateTime().compareTo(o2.getLeaveDateTime());
                    }

                });
            }
        }

        for (LeaveBlock lb : leaveBlocks) {
            if (StringUtils.equals(lb.getRequestStatus(), HrConstants.REQUEST_STATUS.DISAPPROVED)
                    || StringUtils.equals(lb.getRequestStatus(), HrConstants.REQUEST_STATUS.DEFERRED)) {
                continue;
            }
            AccrualCategory accrualCategory = lb.getAccrualCategoryObj();
            BigDecimal tally = accruedBalance.get(accrualCategory.getLmAccrualCategoryId());
            if (tally == null) {
                tally = new BigDecimal(0);
            }
            tally = tally.add(lb.getLeaveAmount());
            AccrualCategoryRule asOfLeaveDateRule = lb.getAccrualCategoryRule();
            //AccrualCategoryRule asOfLeaveDateRule = HrServiceLocator.getAccrualCategoryRuleService().getAccrualCategoryRuleForDate(accrualCategory, lb.getLeaveLocalDate(), pha.getServiceLocalDate());

            //Employee overrides...
            if (ObjectUtils.isNotNull(asOfLeaveDateRule)) {
                if (StringUtils.equals(asOfLeaveDateRule.getMaxBalFlag(), "Y")) {
                    if (StringUtils.isNotBlank(asOfLeaveDateRule.getActionAtMaxBalance())) {
                        if (ObjectUtils.isNotNull(asOfLeaveDateRule.getMaxBalanceActionFrequency())) {

                            if (maxBalanceViolations.get(asOfLeaveDateRule.getLmAccrualCategoryId()) == null) {
                                maxBalanceViolations.put(asOfLeaveDateRule.getLmAccrualCategoryId(),
                                        new HashSet<LeaveBlock>());
                            }
                            BigDecimal maxBalance = asOfLeaveDateRule.getMaxBalance();

                            BigDecimal fte = HrServiceLocator.getJobService()
                                    .getFteSumForAllActiveLeaveEligibleJobs(principalId, LocalDate.now());
                            BigDecimal adjustedMaxBalance = maxBalance.multiply(fte);

                            BigDecimal maxAnnualCarryOver = null;
                            if (ObjectUtils.isNotNull(asOfLeaveDateRule.getMaxCarryOver()))
                                maxAnnualCarryOver = new BigDecimal(asOfLeaveDateRule.getMaxCarryOver());

                            BigDecimal adjustedMaxAnnualCarryOver = null;
                            if (ObjectUtils.isNotNull(maxAnnualCarryOver)) {
                                adjustedMaxAnnualCarryOver = maxAnnualCarryOver.multiply(fte);
                            }

                            List<? extends EmployeeOverrideContract> overrides = LmServiceLocator
                                    .getEmployeeOverrideService()
                                    .getEmployeeOverrides(principalId, lb.getLeaveLocalDate());
                            for (EmployeeOverrideContract override : overrides) {
                                if (StringUtils.equals(override.getAccrualCategory(),
                                        lb.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(), "MAC"))
                                        adjustedMaxAnnualCarryOver = new BigDecimal(
                                                override.getOverrideValue());
                                }
                            }

                            boolean yearEndCandidate = false;
                            if (StringUtils.equals(asOfLeaveDateRule.getMaxBalanceActionFrequency(),
                                    HrConstants.MAX_BAL_ACTION_FREQ.YEAR_END)
                                    && adjustedMaxAnnualCarryOver != null) {
                                yearEndCandidate = true;
                            }
                            //callers must determine if the violation exists on the calendar prior to the leave plan's calendar year end date.
                            if (tally.compareTo(adjustedMaxBalance) > 0
                                    || (yearEndCandidate && tally.compareTo(adjustedMaxAnnualCarryOver) > 0)) {
                                if (maxBalanceViolations.get(asOfLeaveDateRule.getLmAccrualCategoryId())
                                        .isEmpty()) {
                                    maxBalanceViolations.get(asOfLeaveDateRule.getLmAccrualCategoryId())
                                            .add(lb);
                                } else {
                                    Set<LeaveBlock> eligibleLeaveBlocks = maxBalanceViolations
                                            .get(asOfLeaveDateRule.getLmAccrualCategoryId());
                                    LeaveBlock previousInfraction = retreivePreviousInfraction(
                                            eligibleLeaveBlocks, lb, leavePeriodInterval, yearEndPeriodInterval,
                                            thisEntryInterval, asOfLeaveDateRule);

                                    if (previousInfraction != null) {
                                        eligibleLeaveBlocks.remove(previousInfraction);
                                    }
                                    /* Replace the leave block with the most recent infraction that occurred so long as the infraction takes place
                                     * before the end of the [underlying] leave period. This includes accrual categories that undergo a rule change
                                     * as the result of the employee crossing a service milestone.
                                     * Doing so will correctly trigger the action on timesheets that stagger a leave
                                     * period end date, since the block would exist on a leave period whose end date is not contained within
                                     * the time period. For on-demand frequencies, we want to replace the block with the latest no matter what.
                                     * Doing so will ensure that the latest rule is used to initiate the action.
                                     * 
                                     */
                                    eligibleLeaveBlocks.add(lb);
                                    maxBalanceViolations.put(asOfLeaveDateRule.getLmAccrualCategoryId(),
                                            eligibleLeaveBlocks);
                                }
                            } else { // the leave amount (usage), as of lb's leave date, is under the balance limit.
                                if (!maxBalanceViolations.get(asOfLeaveDateRule.getLmAccrualCategoryId())
                                        .isEmpty()) {
                                    //if there was a previous infraction, it must be removed so long as the leave date of lb lies within
                                    //the same period as the previous infraction.
                                    Set<LeaveBlock> eligibleLeaveBlocks = maxBalanceViolations
                                            .get(asOfLeaveDateRule.getLmAccrualCategoryId());
                                    LeaveBlock previousInfraction = retreivePreviousInfraction(
                                            eligibleLeaveBlocks, lb, leavePeriodInterval, yearEndPeriodInterval,
                                            thisEntryInterval, asOfLeaveDateRule);
                                    if (previousInfraction != null) {
                                        eligibleLeaveBlocks.remove(previousInfraction);
                                        maxBalanceViolations.put(asOfLeaveDateRule.getLmAccrualCategoryId(),
                                                eligibleLeaveBlocks);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            accruedBalance.put(accrualCategory.getLmAccrualCategoryId(), tally);
        }
    }

    for (Entry<String, Set<LeaveBlock>> entries : maxBalanceViolations.entrySet()) {
        for (LeaveBlock lb : entries.getValue()) {
            AccrualCategoryRuleContract aRule = lb.getAccrualCategoryRule();
            eligibilities.get(aRule.getMaxBalanceActionFrequency()).add(lb);
        }
    }

    return eligibilities;
}

From source file:org.osgp.adapter.protocol.dlms.domain.commands.DlmsHelperService.java

public DlmsMeterValue getScaledMeterValue(final DataObject value, final DataObject scalerUnitObject,
        final String description) throws ProtocolAdapterException {
    LOGGER.debug(this.getDebugInfo(value));
    LOGGER.debug(this.getDebugInfo(scalerUnitObject));
    final Long rawValue = this.readLong(value, description);
    if (rawValue == null) {
        return null;
    }//from  ww  w . j  av  a2  s . c o m

    if (!scalerUnitObject.isComplex()) {
        throw new ProtocolAdapterException("complex data (structure) expected while retrieving scaler and unit."
                + this.getDebugInfo(scalerUnitObject));
    }
    final List<DataObject> dataObjects = scalerUnitObject.value();
    if (dataObjects.size() != 2) {
        throw new ProtocolAdapterException(
                "expected 2 values while retrieving scaler and unit." + this.getDebugInfo(scalerUnitObject));
    }
    final int scaler = this.readLongNotNull(dataObjects.get(0), description).intValue();
    final DlmsUnit unit = DlmsUnit
            .fromDlmsEnum(this.readLongNotNull(dataObjects.get(1), description).intValue());

    // determine value
    BigDecimal scaledValue = BigDecimal.valueOf(rawValue);
    if (scaler != 0) {
        scaledValue = scaledValue.multiply(BigDecimal.valueOf(Math.pow(10, scaler)));
    }

    return new DlmsMeterValue(scaledValue, unit);
}

From source file:mx.edu.um.mateo.inventario.dao.impl.SalidaDaoHibernate.java

@Override
@Transactional(rollbackFor = { NoEstaAbiertaException.class, ProductoNoSoportaFraccionException.class })
public LoteSalida creaLote(LoteSalida lote) throws ProductoNoSoportaFraccionException, NoEstaAbiertaException {
    if (lote.getSalida().getEstatus().getNombre().equals(Constantes.ABIERTA)) {
        if (!lote.getProducto().getFraccion()) {
            BigDecimal[] resultado = lote.getCantidad().divideAndRemainder(new BigDecimal("1"));
            if (resultado[1].doubleValue() > 0) {
                throw new ProductoNoSoportaFraccionException();
            }/* w w w  .  j  av  a 2s. c om*/
        }

        lote.setPrecioUnitario(lote.getProducto().getPrecioUnitario());

        BigDecimal subtotal = lote.getPrecioUnitario().multiply(lote.getCantidad());
        BigDecimal iva = subtotal.multiply(lote.getProducto().getIva()).setScale(2, RoundingMode.HALF_UP);
        lote.setIva(iva);
        BigDecimal total = subtotal.add(iva).setScale(2, RoundingMode.HALF_UP);
        lote.setFechaCreacion(new Date());
        currentSession().save(lote);

        Salida salida = lote.getSalida();
        salida.setIva(salida.getIva().add(iva));
        salida.setTotal(salida.getTotal().add(total));
        currentSession().save(salida);

        currentSession().flush();

        return lote;
    } else {
        throw new NoEstaAbiertaException("No se puede crear un lote en una salida que no este abierta");
    }
}

From source file:org.kuali.kfs.module.bc.document.service.impl.BudgetConstructionReasonSummaryReportServiceImpl.java

protected void adjustPersonTotal(PersonTotalHolder totalsHolder) {
    Integer restatementCsfAmount = 0;
    if (totalsHolder.salaryPayMonth == 0 || totalsHolder.csfPayMonths == 0
            || BigDecimal.ZERO.compareTo(totalsHolder.csfPercent) == 0 || totalsHolder.csfNormalMonths == 0) {
        restatementCsfAmount = 0;//from  w  w w  . j a va2s  .co  m
    } else {
        BigDecimal salaryMonthPercent = new BigDecimal(
                totalsHolder.salaryNormalMonths * 1.0 / totalsHolder.salaryPayMonth);
        BigDecimal salaryFteQuantity = totalsHolder.salaryPercent.multiply(salaryMonthPercent);

        BigDecimal csfMonthpercent = new BigDecimal(
                totalsHolder.csfNormalMonths * 1.0 / totalsHolder.csfPayMonths);
        BigDecimal csfFteQuantity = totalsHolder.csfPercent.multiply(csfMonthpercent);

        BigDecimal restatementCsfPercent = salaryFteQuantity.divide(csfFteQuantity, 6,
                BigDecimal.ROUND_HALF_UP);
        BigDecimal csfAmount = new BigDecimal(totalsHolder.csfAmount);
        restatementCsfAmount = csfAmount.multiply(restatementCsfPercent).setScale(0, BigDecimal.ROUND_HALF_UP)
                .intValue();
    }

    if (totalsHolder.salaryPayMonth == 0) {
        totalsHolder.salaryFte = BigDecimal.ZERO;
    } else {
        BigDecimal salaryFte = totalsHolder.salaryPercent.multiply(
                new BigDecimal(totalsHolder.salaryNormalMonths * 1.0 / (totalsHolder.salaryPayMonth * 100.0)));
        totalsHolder.salaryFte = BudgetConstructionReportHelper.setDecimalDigit(salaryFte, 5, false);
    }

    if (totalsHolder.salaryPayMonth != totalsHolder.csfPayMonths) {
        if (totalsHolder.csfPayMonths == 0) {
            restatementCsfAmount = 0;
        } else {
            BigDecimal amount = new BigDecimal(
                    restatementCsfAmount * totalsHolder.salaryPayMonth * 1.0 / totalsHolder.csfPayMonths);
            restatementCsfAmount = BudgetConstructionReportHelper.setDecimalDigit(amount, 0, false).intValue();
        }
    }

    totalsHolder.csfAmount = restatementCsfAmount;
    totalsHolder.amountChange = totalsHolder.salaryAmount - totalsHolder.csfAmount;

    if (totalsHolder.csfAmount != 0) {
        totalsHolder.percentChange = BudgetConstructionReportHelper.calculatePercent(totalsHolder.amountChange,
                totalsHolder.csfAmount);
    } else {
        totalsHolder.percentChange = BigDecimal.ZERO;
    }

    if (totalsHolder.curToInt != 0 && totalsHolder.curToInt != -1
            && totalsHolder.curToInt != totalsHolder.salaryAmount.intValue()
            || totalsHolder.curFteInt != 0 && totalsHolder.curFteInt != -1.00
                    && totalsHolder.curFteInt != totalsHolder.salaryFte.doubleValue()) {
        totalsHolder.tiFlag = BCConstants.Report.PLUS;
    } else {
        totalsHolder.tiFlag = BCConstants.Report.BLANK;
    }
}

From source file:org.finra.herd.dao.helper.EmrPricingHelper.java

/**
 * Finds all the clusters that are within the range of lowest core instance price.
 * <p>//w w  w  .jav  a  2  s.co m
 * For example, if the core prices are 0.30, 0.32, 0.34, 0.36, and the threshold value is 0.1(10%), then the lowest core price range should be [0.30, 0.33].
 * The upper bound is derived by calculating 0.30*(1 + 0.1) = 0.33
 *
 * @param emrClusterPrices the list of clusters to select from
 * @param lowestCoreInstancePriceThresholdPercentage the threshold value that defines the range of lowest core instance price
 *
 * @return the list of clusters that fall in lowest core instance price range
 */
List<EmrClusterPriceDto> getEmrClusterPricesWithinLowestCoreInstancePriceThreshold(
        final List<EmrClusterPriceDto> emrClusterPrices,
        final BigDecimal lowestCoreInstancePriceThresholdPercentage) {
    // Builds a tree map that has the core instance price as the key, and the list of pricing with the same core instance price as the value. The tree map
    // is automatically sorted, so it is easy to find the lowest core instance price range.
    TreeMap<BigDecimal, List<EmrClusterPriceDto>> emrClusterPriceMapKeyedByCoreInstancePrice = new TreeMap<>();
    for (final EmrClusterPriceDto emrClusterPriceDto : emrClusterPrices) {
        final BigDecimal coreInstancePrice = getEmrClusterCoreInstancePrice(emrClusterPriceDto);
        if (emrClusterPriceMapKeyedByCoreInstancePrice.containsKey(coreInstancePrice)) {
            emrClusterPriceMapKeyedByCoreInstancePrice.get(coreInstancePrice).add(emrClusterPriceDto);
        } else {
            List<EmrClusterPriceDto> emrClusterPriceList = new ArrayList<>();
            emrClusterPriceList.add(emrClusterPriceDto);
            emrClusterPriceMapKeyedByCoreInstancePrice.put(coreInstancePrice, emrClusterPriceList);
        }
    }

    // Log all the information in the tree map
    LOGGER.info("All available EMR clusters keyed by core instance price: availableEmrClusters={}",
            jsonHelper.objectToJson(emrClusterPriceMapKeyedByCoreInstancePrice));

    // Finds the list of pricing in the range of the lowest core instance price
    List<EmrClusterPriceDto> lowestCoreInstancePriceEmrClusters = new ArrayList<>();
    if (!emrClusterPriceMapKeyedByCoreInstancePrice.isEmpty()) {
        // calculate the lowest core instance price range
        final BigDecimal lowestCoreInstancePriceLowerBound = emrClusterPriceMapKeyedByCoreInstancePrice
                .firstEntry().getKey();
        final BigDecimal lowestCoreInstancePriceUpperBound = lowestCoreInstancePriceLowerBound
                .multiply(BigDecimal.ONE.add(lowestCoreInstancePriceThresholdPercentage));

        LOGGER.info("emrClusterLowestCoreInstancePriceRange={}", jsonHelper.objectToJson(
                Arrays.asList(lowestCoreInstancePriceLowerBound, lowestCoreInstancePriceUpperBound)));

        for (final Map.Entry<BigDecimal, List<EmrClusterPriceDto>> entry : emrClusterPriceMapKeyedByCoreInstancePrice
                .entrySet()) {
            final BigDecimal coreInstancePrice = entry.getKey();
            // Fall into the lowest price range? add it to the list.
            // There is no need to check the lower bound here, since the tree map is sorted, and lower bound is the lowest core price in the tree map.
            if (coreInstancePrice.compareTo(lowestCoreInstancePriceUpperBound) <= 0) {
                lowestCoreInstancePriceEmrClusters.addAll(entry.getValue());
            } else {
                // since the tree map is sorted in ascending order, we do not need to check the rest of entries in the map
                break;
            }
        }
    }
    return lowestCoreInstancePriceEmrClusters;
}

From source file:org.broadleafcommerce.core.search.service.solr.index.SolrIndexServiceImpl.java

/**
 *  We multiply the BigDecimal by 1,000,000 to maintain any possible decimals in use the
 *  displayOrder value.// w w  w  .  j  a  v  a 2s  . co m
 *
 * @param cache
 * @param displayOrderKey
 * @return
 */
protected Long convertDisplayOrderToLong(CatalogStructure cache, String displayOrderKey) {
    BigDecimal displayOrder = cache.getDisplayOrdersByCategoryProduct().get(displayOrderKey);

    if (displayOrder == null) {
        return null;
    }

    return displayOrder.multiply(BigDecimal.valueOf(1000000)).longValue();
}

From source file:com.esd.cs.audit.AuditsController.java

/**
 * ??/*from ww w.  ja v a  2 s  .  co m*/
 * 
 * @param calculateModel
 * @return
 */
@RequestMapping(value = "/calculate", method = RequestMethod.POST)
@ResponseBody
public CalculateModel calculateModel(CalculateModel calculateModel) {
    logger.debug(calculateModel.toString());
    Integer companyId = calculateModel.getCompanyId();
    String year = calculateModel.getYear();
    AuditParameter auditParameter = auditParameterService.getByYear(year);

    // ?
    Integer zaiZhiYuanGongZongShu = calculateModel.getZaiZhiYuanGongZongShu();
    if (zaiZhiYuanGongZongShu == null) {
        zaiZhiYuanGongZongShu = 0;
    }
    // 
    BigDecimal putScale = auditParameter.getPutScale();
    // 
    // =????*
    BigDecimal yingAnPaiCanJiRen = putScale.multiply(new BigDecimal(zaiZhiYuanGongZongShu)).setScale(2,
            BigDecimal.ROUND_HALF_UP);
    calculateModel.setYingAnPaiCanJiRen(yingAnPaiCanJiRen);// 
    // ========================================================================================
    // 
    Integer yiLuRuCanJiRen = calculateModel.getYiLuRuCanJiRen();
    // ???
    List<WorkerCalculator> list = auditParameterService.getSpecialSetting(year);
    for (WorkerCalculator workerCalculator : list) {
        Integer per = workerCalculator.getPer().intValue();
        Integer type = workerCalculator.getType();
        Integer lvl = workerCalculator.getLvl();
        Integer num = auditParameterService.getSpecialCount(companyId, year, type, lvl);
        logger.debug("type:{},lvl:{},per:{}", type, lvl, per);
        yiLuRuCanJiRen = ((yiLuRuCanJiRen - num) + (num * per));
    }
    // 
    Integer yuDingCanJiRen = calculateModel.getYuDingCanJiRen();
    // 
    Integer yiAnPaiCanJiRen = yiLuRuCanJiRen + yuDingCanJiRen;
    calculateModel.setYiAnPaiCanJiRen(yiAnPaiCanJiRen);// ;
    // =========================================================================================
    // ??
    BigDecimal averageSalary = auditParameter.getAverageSalary();
    // ?
    // ??*()
    BigDecimal yingJiaoJinE = averageSalary
            .multiply(yingAnPaiCanJiRen.subtract(new BigDecimal(yiAnPaiCanJiRen)));
    if (yingJiaoJinE.signum() == 1) {//  0
        calculateModel.setYingJiaoJinE(yingJiaoJinE);
    } else {
        yingJiaoJinE = Constants.ZERO;
        calculateModel.setYingJiaoJinE(yingJiaoJinE);
    }
    // ??
    BigDecimal jianJiaoJinE = calculateModel.getJianJiaoJinE();
    // ?=?-??
    BigDecimal shiJiaoJinE = yingJiaoJinE.subtract(jianJiaoJinE);
    // ? --------?

    // ============================================================? 
    List<AccountModel> qianJiaoMingXi = new ArrayList<AccountModel>();
    BigDecimal qianJiao = getSectionPaid(year, companyId, qianJiaoMingXi);
    calculateModel.setQianJiaoMingXi(qianJiaoMingXi);
    // ============================================================
    List<AccountModel> weiShenMingXi = new ArrayList<AccountModel>();
    BigDecimal weiShen = getUnAudits(year, companyId, new BigDecimal(zaiZhiYuanGongZongShu), weiShenMingXi);
    calculateModel.setWeiShenMingXi(weiShenMingXi);
    // =============================================================
    List<AccountModel> weiJiaoMingXi = new ArrayList<AccountModel>();
    BigDecimal weiJiao = getUnpaid(year, companyId, weiJiaoMingXi);
    calculateModel.setWeiJiaoMingXi(weiJiaoMingXi);
    // ==================================================================?
    logger.debug("qianJiao:{} weiShen:{} weiJiao{}", qianJiao, weiShen, weiJiao);
    // ? =++
    BigDecimal shangNianDuWeiJiaoBaoZhangJin = qianJiao.add(weiShen).add(weiJiao);
    calculateModel.setShangNianDuWeiJiaoBaoZhangJin(shangNianDuWeiJiaoBaoZhangJin);
    // =====================================================================================================
    // ?=?-??+?+?
    BigDecimal real_yingJiaoJinE = shiJiaoJinE.add(shangNianDuWeiJiaoBaoZhangJin);
    // BigDecimal real_yingJiaoJinE = shiJiaoJinE;
    calculateModel.setShiJiaoJinE(real_yingJiaoJinE);// ?
    // ============================================================================================
    // 
    Date date = auditParameter.getAuditDelayDate();
    // 
    BigDecimal zhiNaJinBiLi = auditParameter.getAuditDelayRate();
    // 
    int zhiNanJinTianshu = CalendarUtil.getDaySub(date, new Date());
    if (zhiNanJinTianshu < 0) {
        zhiNanJinTianshu = 0;
    }
    calculateModel.setZhiNaJinTianShu(zhiNanJinTianshu);// 
    // 
    BigDecimal zhiNaJin = real_yingJiaoJinE.multiply(zhiNaJinBiLi).multiply(new BigDecimal(zhiNanJinTianshu));
    // ??
    Boolean mian = calculateModel.getMianZhiNaJin();
    if (mian) {
        zhiNaJin = new BigDecimal(0.00);
    }
    calculateModel.setZhiNaJin(zhiNaJin);// 
    // ===============================================================================================
    // ?=?+
    BigDecimal shiJiaoZongJinE = real_yingJiaoJinE.add(zhiNaJin);
    Boolean mianJiao = calculateModel.getMianJiao();// ???
    if (mianJiao) {
        shiJiaoZongJinE = new BigDecimal(0.00);
    }
    calculateModel.setShiJiaoZongJinE(shiJiaoZongJinE);
    return calculateModel;
}

From source file:uk.ac.leeds.ccg.andyt.projects.moses.process.Comparison.java

public void compareCASUV003WithCAS001() throws Exception {
    File infile;/*from  w w  w .  j a  v a2  s .c o  m*/
    infile = new File("C:/Work/Projects/MoSeS/Workspace/UV003.dat");
    CASUV003DataHandler cASUV003DataHandler = new CASUV003DataHandler(infile);
    infile = new File("C:/Work/Projects/MoSeS/Workspace/CAS001.dat");
    CAS001DataHandler tCAS001DataHandler = new CAS001DataHandler(infile);

    CASUV003DataRecord aCASUV003DataRecord;
    CAS001DataRecord aCAS001DataRecord;
    long difference;
    long maxDifference = Long.MIN_VALUE;
    long sumOfSquaredDifference = 0L;
    long totalDifference = 0L;
    long absoluteDifference = 0L;
    long totalAbsoluteDifference = 0L;
    long RecordID;
    long nRecords = cASUV003DataHandler.getNDataRecords();
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        difference = (long) (aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        if (difference < 0) {
            absoluteDifference = difference * -1L;
        }
        sumOfSquaredDifference += (difference * difference);
        maxDifference = Math.max(maxDifference, difference);
        totalDifference += difference;
        totalAbsoluteDifference += absoluteDifference;
    }
    int scale = 100;
    int roundingMode = BigDecimal.ROUND_HALF_EVEN;
    BigDecimal nRecordsBigDecimal = new BigDecimal(nRecords);
    BigDecimal meanDifferenceBigDecimal = new BigDecimal(maxDifference).divide(nRecordsBigDecimal, scale,
            roundingMode);
    System.out.println("nRecords " + nRecords);
    System.out.println("meanDifferenceBigDecimal " + meanDifferenceBigDecimal.toString());
    System.out.println("sumOfSquaredDifference " + sumOfSquaredDifference);
    System.out.println("maxDifference " + maxDifference);
    System.out.println("totalAbsoluteDifference " + totalAbsoluteDifference);
    System.out.println("totalDifference " + totalDifference);
    BigDecimal standardDeviationOfDifferenceBigDecimal = new BigDecimal("0");
    BigDecimal differenceBigDecimal;
    for (RecordID = 0; RecordID < nRecords; RecordID++) {
        aCASUV003DataRecord = cASUV003DataHandler.getCASUV003DataRecord(RecordID);
        aCAS001DataRecord = tCAS001DataHandler.getCAS001DataRecord(RecordID);
        differenceBigDecimal = new BigDecimal(
                aCASUV003DataRecord.getAllPeople() - aCAS001DataRecord.getAllPeople());
        standardDeviationOfDifferenceBigDecimal = differenceBigDecimal.multiply(differenceBigDecimal);
    }
    standardDeviationOfDifferenceBigDecimal = standardDeviationOfDifferenceBigDecimal
            .divide(nRecordsBigDecimal.subtract(BigDecimal.ONE), scale, roundingMode);
    standardDeviationOfDifferenceBigDecimal = Generic_BigDecimal.sqrt(standardDeviationOfDifferenceBigDecimal,
            scale, RoundingMode.HALF_EVEN);
    System.out.println("standardDeviationOfDifferenceBigDecimal " + standardDeviationOfDifferenceBigDecimal);
}

From source file:com.salesmanager.core.module.impl.application.prices.MonthlyPriceModule.java

public OrderTotalSummary calculateOrderPrice(Order order, OrderTotalSummary orderSummary,
        OrderProduct orderProduct, OrderProductPrice productPrice, String currency, Locale locale) {

    /**/*  w  w  w.  j  a v  a2 s  .  c  om*/
     * Monthly price goes in the oneTime fees as well as in the upcoming
     * recursive fees
     */

    BigDecimal finalPrice = null;
    BigDecimal discountPrice = null;

    BigDecimal originalPrice = orderProduct.getOriginalProductPrice();
    if (!productPrice.isDefaultPrice()) {
        originalPrice = productPrice.getProductPriceAmount();
    }

    int quantity = orderProduct.getProductQuantity();

    // the real price is the price submited
    finalPrice = orderProduct.getProductPrice();
    finalPrice = finalPrice.multiply(new BigDecimal(quantity));

    // the final price is the product price * quantity

    if (finalPrice == null) {// pick it from the productPrice
        finalPrice = productPrice.getProductPriceAmount();
        finalPrice = finalPrice.multiply(new BigDecimal(quantity));
    }

    // this type of price needs an upfront payment
    BigDecimal otprice = orderSummary.getOneTimeSubTotal();
    if (otprice == null) {
        otprice = new BigDecimal(0);
    }

    otprice = otprice.add(finalPrice);
    orderSummary.setOneTimeSubTotal(otprice);

    ProductPriceSpecial pps = productPrice.getSpecial();

    // Build text
    StringBuffer notes = new StringBuffer();
    notes.append(quantity).append(" x ");
    notes.append(orderProduct.getProductName());
    notes.append(" ");
    if (!productPrice.isDefaultPrice()) {
        notes.append(
                CurrencyUtil.displayFormatedAmountWithCurrency(productPrice.getProductPriceAmount(), currency));
    } else {
        notes.append(CurrencyUtil.displayFormatedAmountWithCurrency(orderProduct.getProductPrice(), currency));
    }
    notes.append(" ");
    notes.append(this.getPriceSuffixText(currency, locale));

    if (pps != null) {
        if (pps.getProductPriceSpecialStartDate() != null && pps.getProductPriceSpecialEndDate() != null) {
            if (pps.getProductPriceSpecialStartDate().before(order.getDatePurchased())
                    && pps.getProductPriceSpecialEndDate().after(order.getDatePurchased())) {

                BigDecimal dPrice = new BigDecimal(ProductUtil.determinePrice(productPrice).floatValue());

                BigDecimal subTotal = originalPrice.multiply(new BigDecimal(orderProduct.getProductQuantity()));
                BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount()
                        .multiply(new BigDecimal(orderProduct.getProductQuantity()));
                BigDecimal credit = subTotal.subtract(creditSubTotal);

                if (dPrice.floatValue() < productPrice.getProductPriceAmount().floatValue()) {

                    discountPrice = productPrice.getProductPriceAmount().subtract(dPrice);

                    BigDecimal newPrice = orderProduct.getProductPrice();

                    if (!productPrice.isDefaultPrice()) {
                        newPrice = productPrice.getProductPriceAmount();
                    } else {
                        newPrice = newPrice.add(discountPrice);
                    }

                    StringBuffer spacialNote = new StringBuffer();
                    spacialNote.append("<font color=\"red\">[");
                    spacialNote.append(orderProduct.getProductName());
                    spacialNote.append(" ");
                    spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                    spacialNote.append(" ");
                    spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.rebate"));
                    spacialNote.append(" ");
                    spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.until"));

                    spacialNote.append(" ");
                    spacialNote.append(DateUtil.formatDate(pps.getProductPriceSpecialEndDate()));
                    spacialNote.append("]</font>");

                    OrderTotalLine line = new OrderTotalLine();
                    // BigDecimal credit = discountPrice;
                    line.setText(spacialNote.toString());
                    line.setCost(credit);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                    orderSummary.addDueNowCredits(line);
                    orderSummary.addRecursiveCredits(line);

                    BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge();
                    oneTimeCredit = oneTimeCredit.add(credit);
                    orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit);

                }

            } else if (pps.getProductPriceSpecialDurationDays() > -1) {

                Date dt = new Date(new Date().getTime());

                int numDays = pps.getProductPriceSpecialDurationDays();
                Date purchased = order.getDatePurchased();
                Calendar c = Calendar.getInstance();
                c.setTime(dt);
                c.add(Calendar.DATE, numDays);

                BigDecimal dPrice = new BigDecimal(ProductUtil.determinePrice(productPrice).floatValue());

                if (dt.before(c.getTime())
                        && dPrice.floatValue() < productPrice.getProductPriceAmount().floatValue()) {

                    discountPrice = productPrice.getProductPriceAmount().subtract(dPrice);

                    BigDecimal newPrice = orderProduct.getProductPrice();

                    BigDecimal subTotal = originalPrice
                            .multiply(new BigDecimal(orderProduct.getProductQuantity()));
                    BigDecimal creditSubTotal = pps.getProductPriceSpecialAmount()
                            .multiply(new BigDecimal(orderProduct.getProductQuantity()));
                    BigDecimal credit = subTotal.subtract(creditSubTotal);

                    if (!productPrice.isDefaultPrice()) {
                        newPrice = productPrice.getProductPriceAmount();
                    } else {
                        newPrice = newPrice.add(discountPrice);
                    }

                    StringBuffer spacialNote = new StringBuffer();

                    spacialNote.append("<font color=\"red\">[");
                    spacialNote.append(orderProduct.getProductName());
                    spacialNote.append(" ");
                    spacialNote.append(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                    spacialNote.append(" ");
                    spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.rebate"));
                    spacialNote.append(" ");
                    spacialNote.append(LabelUtil.getInstance().getText(locale, "label.generic.until"));

                    spacialNote.append(" ");
                    spacialNote.append(DateUtil.formatDate(c.getTime()));
                    spacialNote.append("]</font>");

                    OrderTotalLine line = new OrderTotalLine();

                    line.setText(spacialNote.toString());
                    line.setCost(credit);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(credit, currency));
                    orderSummary.addDueNowCredits(line);
                    if (numDays > 30) {
                        orderSummary.addRecursiveCredits(line);
                    }

                    BigDecimal oneTimeCredit = orderProduct.getApplicableCreditOneTimeCharge();
                    oneTimeCredit = oneTimeCredit.add(credit);
                    orderProduct.setApplicableCreditOneTimeCharge(oneTimeCredit);

                    // }

                }

            }

        }

    }

    BigDecimal newPrice = orderProduct.getProductPrice();
    if (!productPrice.isDefaultPrice()) {
        newPrice = productPrice.getProductPriceAmount();
    }

    newPrice = newPrice.multiply(new BigDecimal(quantity));

    // Recursive sub total
    BigDecimal rprice = orderSummary.getRecursiveSubTotal();
    if (rprice == null) {
        rprice = new BigDecimal(0);
    }

    // recursive always contain full price
    rprice = rprice.add(newPrice);
    orderSummary.setRecursiveSubTotal(rprice);

    // recursive price
    OrderTotalLine scl = new OrderTotalLine();
    scl.setText(notes.toString());
    scl.setCost(newPrice);
    scl.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(newPrice, currency));
    orderSummary.addRecursivePrice(scl);

    return orderSummary;

}

From source file:com.esd.cs.audit.AuditsController.java

/**
 * // w w  w.  j  a  v a  2s.c o  m
 * 
 * @param companyId
 * @param sb
 * @return
 */
private BigDecimal getUnpaid(String year, Integer companyId, List<AccountModel> sb) {
    BigDecimal amount = new BigDecimal(0.00);
    List<Accounts> accounts = accountsService.getByYearAndCompany(year, companyId,
            Constants.PROCESS_STATIC_WJK);
    Map<String, Accounts> map = new HashMap<>();
    for (Accounts group : accounts) {
        Object obj = map.get(group.getYear());
        if (obj == null) {
            map.put(group.getYear(), group);
        } else {
            Accounts a = (Accounts) obj;
            a.setTotalMoney(a.getTotalMoney().add(group.getTotalMoney()));
        }
    }
    for (Accounts a : map.values()) {
        BigDecimal total = a.getTotalMoney();
        AuditParameter auditParameter = auditParameterService.getByYear(a.getYear());
        Date auditDelayDate = auditParameter.getAuditDelayDate();
        int days = CalendarUtil.getDaySub(auditDelayDate, new Date());
        BigDecimal penalty = total.multiply(auditParameter.getAuditDelayRate()).multiply(new BigDecimal(days));
        AccountModel am = new AccountModel();
        am.setYear(a.getYear());
        am.setDays(String.valueOf(days));
        am.setMoney(df.format(total));
        am.setPenalty(df.format(penalty));
        am.setProp(df4.format(auditParameter.getAuditDelayRate()));
        am.setTotal(df.format(total));
        sb.add(am);
        amount = amount.add(total);
    }
    if (amount.compareTo(new BigDecimal(0.00)) != 0) {
        AccountModel am = new AccountModel();
        am.setTotal(df.format(amount));
        sb.add(am);
    }
    return amount;
}