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, MathContext mc) 

Source Link

Document

Returns a BigDecimal whose value is (this / divisor) , with rounding according to the context settings.

Usage

From source file:wm.xmwei.ui.view.indicator.PagerSlidingTabIndicator.java

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (isInEditMode() || tabCount == 0) {
        return;/*  ww w.  jav  a  2s. com*/
    }

    final int height = getHeight();
    final int width = getWidth();

    // draw indicator line

    //rectPaint.setColor(indicatorColor);

    // default: line below current tab
    View currentTab = tabsContainer.getChildAt(currentPosition);
    float lineLeft = currentTab.getLeft();
    float lineRight = currentTab.getRight();

    // if there is an offset, start interpolating left and right coordinates between current and next tab
    if (currentPositionOffset > 0f && currentPosition < tabCount - 1) {

        View nextTab = tabsContainer.getChildAt(currentPosition + 1);
        nextTab.setBackgroundResource(Color.TRANSPARENT);
        final float nextTabLeft = nextTab.getLeft();
        final float nextTabRight = nextTab.getRight();

        lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
        lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
    }

    /*   canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);*/

    float center = (lineLeft + lineRight) / 2;

    // ,??  
    // Path path = new Path();
    //path.moveTo(center,height - indicatorHeight);//   

    BigDecimal a = BigDecimal.valueOf(1.736);
    BigDecimal b = BigDecimal.valueOf(3);
    BigDecimal bigDecimal = a.divide(b, BigDecimal.ROUND_HALF_UP);
    float result = bigDecimal.floatValue() * indicatorHeight;

    //path.lineTo(center-result-2, height);  
    // path.lineTo(center+result+2, height);
    //path.close(); // ??  
    // canvas.drawPath(path, rectPaint);

    Path path2 = new Path();
    path2.moveTo(0, 0);//   
    path2.lineTo(0, height);
    path2.lineTo(center - result - 5, height);
    path2.lineTo(center, height - indicatorHeight);
    path2.lineTo(center + result + 5, height);
    path2.lineTo(tabsContainer.getWidth(), height);
    path2.lineTo(tabsContainer.getWidth(), 0);

    path2.close(); // ??  
    canvas.drawPath(path2, bgPaint);
    // draw underline

    /*rectPaint.setColor(underlineColor);
    canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);*/

    // draw divider

    /*   dividerPaint.setColor(dividerColor);
       for (int i = 0; i < tabCount - 1; i++) {
          View tab = tabsContainer.getChildAt(i);
          canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint);
       }*/
}

From source file:it.newfammulfin.api.EntryResource.java

private <K> boolean checkAndBalanceZeroShares(final Map<K, BigDecimal> shares, BigDecimal expectedSum) {
    if (shares.isEmpty()) {
        return false;
    }/*from  www .  jav a2s .  c o m*/
    boolean equalShares = false;
    if (!Util.containsNotZero(shares.values())) {
        equalShares = true;
        expectedSum = expectedSum.setScale(Math.max(DEFAULT_SHARE_SCALE, expectedSum.scale()));
        for (Map.Entry<K, BigDecimal> shareEntry : shares.entrySet()) {
            shareEntry.setValue(expectedSum.divide(BigDecimal.valueOf(shares.size()), RoundingMode.DOWN));
        }
    }
    K largestKey = shares.keySet().iterator().next();
    for (Map.Entry<K, BigDecimal> share : shares.entrySet()) {
        if (share.getValue().abs().compareTo(shares.get(largestKey).abs()) > 0) {
            largestKey = share.getKey();
        }
    }
    BigDecimal remainder = Util.remainder(shares.values(), expectedSum);
    if (remainder.compareTo(BigDecimal.ZERO) != 0) {
        shares.put(largestKey, shares.get(largestKey).add(remainder));
    }
    return equalShares;
}

From source file:org.pentaho.di.core.row.ValueDataUtil.java

public static BigDecimal divideBigDecimals(BigDecimal a, BigDecimal b, MathContext mc) {
    if (mc == null) {
        mc = MathContext.DECIMAL64;
    }//  w  w  w  . j  a va2  s  .c o  m
    return a.divide(b, mc);
}

From source file:org.kuali.coeus.common.budget.impl.calculator.BudgetPeriodCalculator.java

public boolean syncToPeriodDirectCostLimit(Budget budget, BudgetPeriod budgetPeriodBean,
        BudgetLineItem budgetDetailBean) {
    // If total_cost equals total_cost_limit, disp msg "Cost limit and total cost for this period is already in sync."
    ScaleTwoDecimal directCostLimit = budgetPeriodBean.getDirectCostLimit();
    ScaleTwoDecimal periodDirectTotal = budgetPeriodBean.getTotalDirectCost();
    directCostLimit = budgetPeriodBean.getDirectCostLimit();

    // Set the Difference as TotalCostLimit minus TotalCost.
    BigDecimal difference = directCostLimit.subtract(periodDirectTotal).bigDecimalValue();
    ScaleTwoDecimal lineItemCost = budgetDetailBean.getLineItemCost();
    BigDecimal multifactor;//from  ww  w. j a  v  a 2 s  .c om

    // If line_item_cost is 0 then set the value of line_item_cost in line_items to 10000.
    if (lineItemCost.equals(ScaleTwoDecimal.ZERO)) {
        budgetDetailBean.setLineItemCost(new ScaleTwoDecimal(10000));
    }

    calculate(budget, budgetPeriodBean);

    QueryList<BudgetLineItemCalculatedAmount> vecCalAmts = new QueryList<BudgetLineItemCalculatedAmount>(
            budgetDetailBean.getBudgetLineItemCalculatedAmounts());

    resetRateClassTypeIfNeeded(vecCalAmts);

    ScaleTwoDecimal totalNOHCalcAmount = vecCalAmts.sumObjects("calculatedCost",
            new NotEquals("rateClassType", RateClassType.OVERHEAD.getRateClassType()));
    BigDecimal totalCost = budgetDetailBean.getLineItemCost().add(totalNOHCalcAmount).bigDecimalValue();
    // If the lineItemCost <> 0, set multifactor to TotalCost divided by lineItemCost otherwise multifactor is TotalCost divided
    // by 10000
    if (!lineItemCost.equals(ScaleTwoDecimal.ZERO)) {
        multifactor = totalCost.divide(lineItemCost.bigDecimalValue(), RoundingMode.HALF_UP);
    } else {
        multifactor = totalCost.divide(new ScaleTwoDecimal(10000).bigDecimalValue(), RoundingMode.HALF_UP);
        budgetDetailBean.setLineItemCost(ScaleTwoDecimal.ZERO);
        calculate(budget, budgetPeriodBean);
        totalCost = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
    }

    if (isProposalBudget(budget)
            && new ScaleTwoDecimal(totalCost.add(difference)).isLessEqual(ScaleTwoDecimal.ZERO)) {
        return false;
    }

    // Set New Cost
    ScaleTwoDecimal newCost = lineItemCost
            .add(new ScaleTwoDecimal(difference.divide(multifactor, RoundingMode.HALF_UP)));
    budgetDetailBean.setLineItemCost(newCost);
    calculate(budget, budgetPeriodBean);
    return true;

}

From source file:com.qcadoo.mes.operationTimeCalculations.OrderRealizationTimeServiceImpl.java

@Override
public int evaluateOperationDurationOutOfCycles(final BigDecimal cycles, final Entity operationComponent,
        final Entity productionLine, final boolean maxForWorkstation, final boolean includeTpz,
        final boolean includeAdditionalTime) {
    boolean isTjDivisable = operationComponent.getBooleanField("isTjDivisible");

    Integer workstationsCount = retrieveWorkstationTypesCount(operationComponent, productionLine);
    BigDecimal cyclesPerOperation = cycles;

    if (maxForWorkstation) {
        cyclesPerOperation = cycles.divide(BigDecimal.valueOf(workstationsCount),
                numberService.getMathContext());

        if (!isTjDivisable) {
            cyclesPerOperation = cyclesPerOperation.setScale(0, RoundingMode.CEILING);
        }/* w w  w . j a va  2 s .  c  o m*/
    }

    int tj = getIntegerValue(operationComponent.getField("tj"));
    int operationTime = cyclesPerOperation.multiply(BigDecimal.valueOf(tj), numberService.getMathContext())
            .intValue();

    if (includeTpz) {
        int tpz = getIntegerValue(operationComponent.getField("tpz"));
        operationTime += (maxForWorkstation ? tpz : (tpz * workstationsCount));
    }

    if (includeAdditionalTime) {
        int additionalTime = getIntegerValue(operationComponent.getField("timeNextOperation"));
        operationTime += (maxForWorkstation ? additionalTime : (additionalTime * workstationsCount));
    }

    return operationTime;
}

From source file:com.marcosanta.service.impl.KalturaServiceImpl.java

@Override
public ReporteGeneralGranulado reporteEntrysGranulado(Date fechaInicio, Date fechaFin, String valorUnitarioTam,
        String valorUnitarioMIN, String tipoReporte, String cuenta, String unidad, String fabrica,
        String programa, int novistos) {
    System.out.println(programa + " " + fabrica + " " + unidad + " " + cuenta + " ");
    ChartSeries chartStorage = new ChartSeries();
    ChartSeries chartTiempoVisto = new ChartSeries();
    ChartSeries chartProductividad = new ChartSeries();
    CartesianChartModel graficaStorage = new CartesianChartModel();
    CartesianChartModel graficaTiempoVisto = new CartesianChartModel();
    CartesianChartModel graficaProductividad = new CartesianChartModel();
    Map<Object, Number> mapaSerieTamanio = new HashMap<>();
    Map<Object, Number> mapaSerieTiempoVisto = new HashMap<>();
    Map<Object, Number> mapaSerieProductividad = new HashMap<>();
    List<SistemaReporte> listaTemporalReporte = new ArrayList<>();
    if (fechaInicio != null && fechaFin != null) {
        if (novistos == 0) {
            listaTemporalReporte = this.consultasBDService.findReportByFechaCorteNivelPrograma(fechaInicio,
                    fechaFin, unidad, fabrica, programa);
        } else {//from ww w.  j  a  v  a 2s .com
            listaTemporalReporte = this.consultasBDService.findReportByFechaCorteNivelPrograma2(fechaInicio,
                    fechaFin, unidad, fabrica, programa);
        }
    } else {
        if (novistos == 0) {
            listaTemporalReporte = this.consultasBDService.findReportByNivelPrograma(unidad, fabrica, programa);
        } else {
            listaTemporalReporte = this.consultasBDService.findReportByNivelPrograma2(unidad, fabrica,
                    programa);
        }
    }
    List<CatReporteXls> reporteTemporal = new ArrayList<>();
    List<CatReporteXlsEntry> reporteTemporalGrafica = new ArrayList<>();
    for (SistemaReporte sr : listaTemporalReporte) {
        if (reporteTemporal.contains(new CatReporteXls(sr.getEntryId()))) {
            CatReporteXls caRepTmp2 = reporteTemporal
                    .get(reporteTemporal.indexOf(new CatReporteXls(sr.getEntryId())));
            caRepTmp2.setMinVistos(caRepTmp2.getMinVistos().add(new BigDecimal(sr.getTiempoVisto())));
            caRepTmp2.setTamanio((caRepTmp2.getTamanio()
                    .add(new BigDecimal((sr.getTamanio().doubleValue() / 1028) / 1028))));
            caRepTmp2.setTamUni(caRepTmp2.getTamUni().add(new BigDecimal(
                    ((sr.getTamanio().doubleValue() / 1028) / 1028) * Double.parseDouble(valorUnitarioTam))));
            caRepTmp2.setMinVisUni(caRepTmp2.getMinVisUni()
                    .add(new BigDecimal((sr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN)))));
            //                 caRepTmp2.setTotalEntrys(1L+caRepTmp2.getTotalEntrys());
            //                 System.out.println(caRepTmp2.getTotalEntrys());
            //                 System.out.println(caRepTmp2.getTamanio()+" "+caRepTmp2.getNombre());

        } else {
            reporteTemporal.add(new CatReporteXls(sr.getNombre(), sr.getEntryId(), sr.getNombreFabrica(),
                    sr.getNombrePrograma(), cuenta, sr.getNombre(), sr.getNombreUnidad(),
                    new BigDecimal(((sr.getTamanio().doubleValue() / 1028) / 1028)),
                    new BigDecimal(sr.getDuracion()), new BigDecimal(sr.getTiempoVisto()), sr.getFechaCorte(),
                    sr.getFechaCreacion(),
                    new BigDecimal(sr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN)),
                    new BigDecimal(((sr.getTamanio().doubleValue() / 1028) / 1028)
                            * Double.parseDouble(valorUnitarioTam)),
                    new BigDecimal(1L)));
        }
        if (reporteTemporalGrafica.contains(new CatReporteXlsEntry(sr.getFechaCorte()))) {
            CatReporteXlsEntry caRepTmp = reporteTemporalGrafica
                    .get(reporteTemporalGrafica.indexOf(new CatReporteXlsEntry(sr.getFechaCorte())));
            caRepTmp.setTotalEntrys(caRepTmp.getTotalEntrys() + 1L);
            caRepTmp.setTamanio(((sr.getTamanio().doubleValue() / 1028) / 1028) + caRepTmp.getTamanio());
            caRepTmp.setMinVistos(sr.getTiempoVisto() + caRepTmp.getMinVistos());
            caRepTmp.setMinVisUni(
                    (sr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN)) + caRepTmp.getMinVisUni());
            caRepTmp.setTamUni((sr.getTamanio() * Double.parseDouble(valorUnitarioTam)) + caRepTmp.getTamUni());
            mapaSerieTamanio.put(sr.getFechaCorte(), caRepTmp.getTamanio());
            mapaSerieTiempoVisto.put(sr.getFechaCorte(), caRepTmp.getMinVistos());
        } else {
            reporteTemporalGrafica.add(new CatReporteXlsEntry(sr.getEntryId(), sr.getNombreUnidad(),
                    sr.getNombreFabrica(), sr.getNombrePrograma(), cuenta, sr.getNombre(), sr.getTiempoVisto(),
                    ((sr.getTamanio().doubleValue() / 1028) / 1028), Long.parseLong(sr.getDuracion() + ""),
                    sr.getFechaCorte(), sr.getFechaCreacion(),
                    sr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN),
                    sr.getTamanio() * Double.parseDouble(valorUnitarioTam), 1L));

            mapaSerieTamanio.put(sr.getFechaCorte(), ((sr.getTamanio().doubleValue() / 1028) / 1028));
            mapaSerieTiempoVisto.put(sr.getFechaCorte(), sr.getTiempoVisto());
        }

    }
    int cortes = 1;
    //        mapaSerieTamanio = new HashMap<>();
    if (fechaInicio != null && fechaFin != null) {
        cortes = consultasBDService.findCorteByFecha(fechaInicio, fechaFin).size();
    } else {
        cortes = consultasBDService.findCorteB().size();
    }

    for (CatReporteXlsEntry crtsxx : reporteTemporalGrafica) {
        BigDecimal prod;
        if (crtsxx.getTamUni() == 0) {
            prod = new BigDecimal(-1);
        } else {
            prod = new BigDecimal(crtsxx.getMinVisUni() - crtsxx.getTamUni());
            prod = prod.divide(new BigDecimal(crtsxx.getTamUni()), MathContext.DECIMAL128);
        }
        mapaSerieProductividad.put(crtsxx.getFechaCorte(), prod);
    }

    for (CatReporteXls crxls : reporteTemporal) {
        crxls.setTamanio(crxls.getTamanio().divide(new BigDecimal(cortes), MathContext.DECIMAL128));
        crxls.setTamUni(crxls.getTamUni().divide(new BigDecimal(cortes), MathContext.DECIMAL128));

    }
    //        for(CatReporteXlsEntry crxe:reporteTemporalGrafica){
    //            mapaSerieTamanio.put(crxe., cortes)
    //        }
    chartProductividad.setData(mapaSerieProductividad);
    chartStorage.setData(mapaSerieTamanio);
    chartTiempoVisto.setData(mapaSerieTiempoVisto);
    graficaProductividad.addSeries(chartProductividad);
    graficaStorage.addSeries(chartStorage);
    graficaTiempoVisto.addSeries(chartTiempoVisto);
    ReporteGeneralGranulado repGenGra = new ReporteGeneralGranulado(reporteTemporal, graficaStorage,
            graficaTiempoVisto, graficaProductividad);
    return repGenGra;
}

From source file:com.marcosanta.service.impl.KalturaServiceImpl.java

@Override
public ReporteGeneralGranulado calculoReporteGlobal(Date fechaInicio, Date fechaFin, String valorUnitarioTam,
        String valorUnitarioMIN, String tipoReporte, String cuenta, String unidad, String fabrica,
        int novistos) {
    ChartSeries chartStorage = new ChartSeries();
    ChartSeries chartTiempoVisto = new ChartSeries();
    ChartSeries chartProductividad = new ChartSeries();
    CartesianChartModel graficaStorage = new CartesianChartModel();
    CartesianChartModel graficaTiempoVisto = new CartesianChartModel();
    CartesianChartModel graficaProductividad = new CartesianChartModel();
    Map<Object, Number> mapaSerieTamanio = new HashMap<>();
    Map<Object, Number> mapaSerieProductividad = new HashMap<>();
    Map<Object, Number> mapaSerieTiempoVisto = new HashMap<>();
    List<CatReporteXls> reporteGlobal = new ArrayList<>();
    List<SistemaSubReporte> listaTemportalSubReporteGlobal = new ArrayList<>();
    if (fechaInicio != null && fechaFin != null) {
        if (cuenta != null && unidad == null && fabrica == null) {
            listaTemportalSubReporteGlobal = consultasBDService.findReportByFechaCorteNivelUnidad(fechaInicio,
                    fechaFin, tipoReporte, cuenta, novistos);
        } else if (cuenta != null && unidad != null) {
            listaTemportalSubReporteGlobal = consultasBDService.findReportByFechaCorteNivelFabrica(fechaInicio,
                    fechaFin, tipoReporte, cuenta, unidad, novistos);
        } else if (cuenta != null && fabrica != null) {
            listaTemportalSubReporteGlobal = consultasBDService.findSubReportByFechaCorteNivelPrograma(
                    fechaInicio, fechaFin, tipoReporte, cuenta, fabrica, novistos);
        } else {/*from   www .j a  va  2  s .c o  m*/
            listaTemportalSubReporteGlobal = consultasBDService.findSubReporteByFechasAndTipo(fechaInicio,
                    fechaFin, tipoReporte, novistos);
        }
    } else {
        if (cuenta != null && unidad == null && fabrica == null) {
            listaTemportalSubReporteGlobal = consultasBDService.findReportNivelUnidad(tipoReporte, cuenta,
                    novistos);
        } else if (cuenta != null && unidad != null) {
            listaTemportalSubReporteGlobal = consultasBDService.findReportNivelFabrica(tipoReporte, cuenta,
                    unidad, novistos);
        } else if (cuenta != null && fabrica != null) {
            listaTemportalSubReporteGlobal = consultasBDService.findReportNivelPrograma(tipoReporte, cuenta,
                    fabrica, novistos);
        } else {
            listaTemportalSubReporteGlobal = consultasBDService.findSubReporteByTipo(tipoReporte, novistos);
        }
    }
    if (!listaTemportalSubReporteGlobal.isEmpty()) {
        for (SistemaSubReporte ssr : listaTemportalSubReporteGlobal) {
            if (reporteGlobal.contains(new CatReporteXls(ssr.getNombre()))) {
                CatReporteXls caRepTmp = reporteGlobal
                        .get(reporteGlobal.indexOf(new CatReporteXls(ssr.getNombre())));
                caRepTmp.setMinVistos(caRepTmp.getMinVistos().add(new BigDecimal(ssr.getTiempoVisto())));
                caRepTmp.setDuration(caRepTmp.getDuration().add(new BigDecimal(ssr.getDuracion())));
                caRepTmp.setTamanio(caRepTmp.getTamanio().add(new BigDecimal(ssr.getTamanio())));
                caRepTmp.setTamUni(caRepTmp.getTamUni()
                        .add(new BigDecimal((ssr.getTamanio() * Double.parseDouble(valorUnitarioTam)))));
                caRepTmp.setMinVisUni(caRepTmp.getMinVisUni()
                        .add(new BigDecimal((ssr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN)))));
                if (caRepTmp.getTotalEntrys().longValue() < ssr.getTotalEntrys()) {
                    caRepTmp.setTotalEntrys(new BigDecimal(ssr.getTotalEntrys()));
                }
                mapaSerieTamanio.put(ssr.getNombre(),
                        mapaSerieTamanio.get(ssr.getNombre()).doubleValue() + ssr.getTamanio());
                mapaSerieTiempoVisto.put(ssr.getNombre(),
                        mapaSerieTiempoVisto.get(ssr.getNombre()).longValue() + ssr.getTiempoVisto());
            } else {
                reporteGlobal.add(new CatReporteXls(ssr.getNombre(), new BigDecimal(ssr.getTiempoVisto()),
                        new BigDecimal(ssr.getTamanio()), new BigDecimal(ssr.getDuracion()),
                        ssr.getFechaCorte(),
                        new BigDecimal(ssr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN)),
                        new BigDecimal(ssr.getTamanio() * Double.parseDouble(valorUnitarioTam)),
                        new BigDecimal(ssr.getTotalEntrys())));
                mapaSerieTamanio.put(ssr.getNombre(), ssr.getTamanio());
                mapaSerieTiempoVisto.put(ssr.getNombre(), ssr.getTiempoVisto());
            }
        }
    }
    int cortes = 1;
    mapaSerieTamanio = new HashMap<>();
    if (fechaInicio != null && fechaFin != null) {
        cortes = consultasBDService.findCorteByFechaSubReporte(fechaInicio, fechaFin).size();
    } else {
        cortes = consultasBDService.findCorteB().size();
    }

    for (CatReporteXls crxls : reporteGlobal) {
        crxls.setTamanio(crxls.getTamanio().divide(new BigDecimal(cortes), MathContext.DECIMAL128));
        crxls.setTamUni(crxls.getTamUni().divide(new BigDecimal(cortes), MathContext.DECIMAL128));
        mapaSerieTamanio.put(crxls.getNombre(), crxls.getTamanio());
        BigDecimal prod;

        if (crxls.getTamUni().compareTo(BigDecimal.ZERO) == 0) {
            prod = new BigDecimal(-1);
        } else {
            prod = crxls.getMinVisUni().subtract(crxls.getTamUni());
            prod = prod.divide(crxls.getTamUni(), MathContext.DECIMAL128);
        }
        mapaSerieProductividad.put(crxls.getNombre(), prod);
    }
    chartProductividad.setData(mapaSerieProductividad);
    chartStorage.setData(mapaSerieTamanio);
    chartTiempoVisto.setData(mapaSerieTiempoVisto);
    graficaProductividad.addSeries(chartProductividad);
    graficaStorage.addSeries(chartStorage);
    graficaTiempoVisto.addSeries(chartTiempoVisto);
    ReporteGeneralGranulado repGenGra = new ReporteGeneralGranulado(reporteGlobal, graficaStorage,
            graficaTiempoVisto, graficaProductividad);
    return repGenGra;
}

From source file:org.kuali.coeus.common.budget.impl.calculator.BudgetPeriodCalculator.java

public boolean syncToPeriodCostLimit(Budget budget, BudgetPeriod budgetPeriodBean,
        BudgetLineItem budgetDetailBean) {

    // If total_cost equals total_cost_limit, disp msg "Cost limit and total cost for this period is already in sync."
    ScaleTwoDecimal costLimit = budgetPeriodBean.getTotalCostLimit();
    ScaleTwoDecimal periodTotal = budgetPeriodBean.getTotalCost();

    // Set the Difference as TotalCostLimit minus TotalCost.
    BigDecimal difference = costLimit.subtract(periodTotal).bigDecimalValue();
    ScaleTwoDecimal lineItemCost = budgetDetailBean.getLineItemCost();
    BigDecimal multifactor;/*  ww  w .  ja  v  a 2 s  . c  o m*/

    // If line_item_cost is 0 then set the value of line_item_cost in line_items to 10000.
    if (lineItemCost.equals(ScaleTwoDecimal.ZERO)) {
        budgetDetailBean.setLineItemCost(new ScaleTwoDecimal(10000));
    }

    calculate(budget, budgetPeriodBean);

    QueryList<BudgetLineItemCalculatedAmount> vecCalAmts = new QueryList<BudgetLineItemCalculatedAmount>(
            budgetDetailBean.getBudgetLineItemCalculatedAmounts());

    resetRateClassTypeIfNeeded(vecCalAmts);

    ScaleTwoDecimal totalNOHCalcAmount = vecCalAmts.sumObjects("calculatedCost",
            new NotEquals("rateClassType", RateClassType.OVERHEAD.getRateClassType()));
    ScaleTwoDecimal totalOHCalcAmount = vecCalAmts.sumObjects("calculatedCost",
            new Equals("rateClassType", RateClassType.OVERHEAD.getRateClassType()));

    BigDecimal totalCost = budgetDetailBean.getLineItemCost().add(totalNOHCalcAmount).add(totalOHCalcAmount)
            .bigDecimalValue();

    // If the lineItemCost <> 0, set multifactor to TotalCost divided by lineItemCost otherwise multifactor is TotalCost divided
    // by 10000
    if (!lineItemCost.equals(ScaleTwoDecimal.ZERO)) {
        multifactor = totalCost.divide(lineItemCost.bigDecimalValue(), RoundingMode.HALF_UP);
    } else {
        multifactor = totalCost.divide(new ScaleTwoDecimal(10000).bigDecimalValue(), RoundingMode.HALF_UP);
        budgetDetailBean.setLineItemCost(ScaleTwoDecimal.ZERO);
        calculate(budget, budgetPeriodBean);
        totalCost = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
    }

    if (isProposalBudget(budget)
            && new ScaleTwoDecimal(totalCost.add(difference)).isLessEqual(ScaleTwoDecimal.ZERO)) {
        return false;
    }

    // Set New Cost
    ScaleTwoDecimal newCost = lineItemCost
            .add(new ScaleTwoDecimal(difference.divide(multifactor, RoundingMode.HALF_UP)));
    budgetDetailBean.setLineItemCost(newCost);
    calculate(budget, budgetPeriodBean);
    return true;
}

From source file:org.mifosplatform.portfolio.savings.domain.SavingsAccountCharge.java

private BigDecimal percentageOf(final BigDecimal value, final BigDecimal percentage) {

    BigDecimal percentageOf = BigDecimal.ZERO;

    if (isGreaterThanZero(value)) {
        final MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
        final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc);
        percentageOf = value.multiply(multiplicand, mc);
    }//from  ww  w  .  ja  va 2 s. c  o  m

    return percentageOf;
}

From source file:org.ofbiz.order.shoppingcart.ShoppingCartServices.java

public static Map<String, Object> loadCartFromQuote(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();

    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String quoteId = (String) context.get("quoteId");
    String applyQuoteAdjustmentsString = (String) context.get("applyQuoteAdjustments");
    Locale locale = (Locale) context.get("locale");

    boolean applyQuoteAdjustments = applyQuoteAdjustmentsString == null
            || "true".equals(applyQuoteAdjustmentsString);

    // get the quote header
    GenericValue quote = null;/*www.ja v a 2 s  .c  o  m*/
    try {
        quote = delegator.findOne("Quote", UtilMisc.toMap("quoteId", quoteId), false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    // initial require cart info
    String productStoreId = quote.getString("productStoreId");
    String currency = quote.getString("currencyUomId");

    // create the cart
    ShoppingCart cart = new ShoppingCart(delegator, productStoreId, locale, currency);
    // set shopping cart type
    if ("PURCHASE_QUOTE".equals(quote.getString("quoteTypeId"))) {
        cart.setOrderType("PURCHASE_ORDER");
        cart.setBillFromVendorPartyId(quote.getString("partyId"));
    }
    try {
        cart.setUserLogin(userLogin, dispatcher);
    } catch (CartItemModifyException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    cart.setQuoteId(quoteId);
    cart.setOrderName(quote.getString("quoteName"));
    cart.setChannelType(quote.getString("salesChannelEnumId"));

    List<GenericValue> quoteItems = null;
    List<GenericValue> quoteAdjs = null;
    List<GenericValue> quoteRoles = null;
    List<GenericValue> quoteAttributes = null;
    List<GenericValue> quoteTerms = null;
    try {
        quoteItems = quote.getRelated("QuoteItem", null, UtilMisc.toList("quoteItemSeqId"), false);
        quoteAdjs = quote.getRelated("QuoteAdjustment", null, null, false);
        quoteRoles = quote.getRelated("QuoteRole", null, null, false);
        quoteAttributes = quote.getRelated("QuoteAttribute", null, null, false);
        quoteTerms = quote.getRelated("QuoteTerm", null, null, false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    // set the role information
    cart.setOrderPartyId(quote.getString("partyId"));
    if (UtilValidate.isNotEmpty(quoteRoles)) {
        for (GenericValue quoteRole : quoteRoles) {
            String quoteRoleTypeId = quoteRole.getString("roleTypeId");
            String quoteRolePartyId = quoteRole.getString("partyId");
            if ("PLACING_CUSTOMER".equals(quoteRoleTypeId)) {
                cart.setPlacingCustomerPartyId(quoteRolePartyId);
            } else if ("BILL_TO_CUSTOMER".equals(quoteRoleTypeId)) {
                cart.setBillToCustomerPartyId(quoteRolePartyId);
            } else if ("SHIP_TO_CUSTOMER".equals(quoteRoleTypeId)) {
                cart.setShipToCustomerPartyId(quoteRolePartyId);
            } else if ("END_USER_CUSTOMER".equals(quoteRoleTypeId)) {
                cart.setEndUserCustomerPartyId(quoteRolePartyId);
            } else if ("BILL_FROM_VENDOR".equals(quoteRoleTypeId)) {
                cart.setBillFromVendorPartyId(quoteRolePartyId);
            } else {
                cart.addAdditionalPartyRole(quoteRolePartyId, quoteRoleTypeId);
            }
        }
    }

    // set the order term
    if (UtilValidate.isNotEmpty(quoteTerms)) {
        // create order term from quote term
        for (GenericValue quoteTerm : quoteTerms) {
            BigDecimal termValue = BigDecimal.ZERO;
            if (UtilValidate.isNotEmpty(quoteTerm.getString("termValue"))) {
                termValue = new BigDecimal(quoteTerm.getString("termValue"));
            }
            long termDays = 0;
            if (UtilValidate.isNotEmpty(quoteTerm.getString("termDays"))) {
                termDays = Long.parseLong(quoteTerm.getString("termDays").trim());
            }
            String orderItemSeqId = quoteTerm.getString("quoteItemSeqId");
            cart.addOrderTerm(quoteTerm.getString("termTypeId"), orderItemSeqId, termValue, termDays,
                    quoteTerm.getString("textValue"), quoteTerm.getString("description"));
        }
    }

    // set the attribute information
    if (UtilValidate.isNotEmpty(quoteAttributes)) {
        for (GenericValue quoteAttribute : quoteAttributes) {
            cart.setOrderAttribute(quoteAttribute.getString("attrName"), quoteAttribute.getString("attrValue"));
        }
    }

    // Convert the quote adjustment to order header adjustments and
    // put them in a map: the key/values pairs are quoteItemSeqId/List of
    // adjs
    Map<String, List<GenericValue>> orderAdjsMap = FastMap.newInstance();
    for (GenericValue quoteAdj : quoteAdjs) {
        List<GenericValue> orderAdjs = orderAdjsMap
                .get(UtilValidate.isNotEmpty(quoteAdj.getString("quoteItemSeqId"))
                        ? quoteAdj.getString("quoteItemSeqId")
                        : quoteId);
        if (orderAdjs == null) {
            orderAdjs = FastList.newInstance();
            orderAdjsMap.put(UtilValidate.isNotEmpty(quoteAdj.getString("quoteItemSeqId"))
                    ? quoteAdj.getString("quoteItemSeqId")
                    : quoteId, orderAdjs);
        }
        // convert quote adjustments to order adjustments
        GenericValue orderAdj = delegator.makeValue("OrderAdjustment");
        orderAdj.put("orderAdjustmentId", quoteAdj.get("quoteAdjustmentId"));
        orderAdj.put("orderAdjustmentTypeId", quoteAdj.get("quoteAdjustmentTypeId"));
        orderAdj.put("orderItemSeqId", quoteAdj.get("quoteItemSeqId"));
        orderAdj.put("comments", quoteAdj.get("comments"));
        orderAdj.put("description", quoteAdj.get("description"));
        orderAdj.put("amount", quoteAdj.get("amount"));
        orderAdj.put("productPromoId", quoteAdj.get("productPromoId"));
        orderAdj.put("productPromoRuleId", quoteAdj.get("productPromoRuleId"));
        orderAdj.put("productPromoActionSeqId", quoteAdj.get("productPromoActionSeqId"));
        orderAdj.put("productFeatureId", quoteAdj.get("productFeatureId"));
        orderAdj.put("correspondingProductId", quoteAdj.get("correspondingProductId"));
        orderAdj.put("sourceReferenceId", quoteAdj.get("sourceReferenceId"));
        orderAdj.put("sourcePercentage", quoteAdj.get("sourcePercentage"));
        orderAdj.put("customerReferenceId", quoteAdj.get("customerReferenceId"));
        orderAdj.put("primaryGeoId", quoteAdj.get("primaryGeoId"));
        orderAdj.put("secondaryGeoId", quoteAdj.get("secondaryGeoId"));
        orderAdj.put("exemptAmount", quoteAdj.get("exemptAmount"));
        orderAdj.put("taxAuthGeoId", quoteAdj.get("taxAuthGeoId"));
        orderAdj.put("taxAuthPartyId", quoteAdj.get("taxAuthPartyId"));
        orderAdj.put("overrideGlAccountId", quoteAdj.get("overrideGlAccountId"));
        orderAdj.put("includeInTax", quoteAdj.get("includeInTax"));
        orderAdj.put("includeInShipping", quoteAdj.get("includeInShipping"));
        orderAdj.put("createdDate", quoteAdj.get("createdDate"));
        orderAdj.put("createdByUserLogin", quoteAdj.get("createdByUserLogin"));
        orderAdjs.add(orderAdj);
    }

    long nextItemSeq = 0;
    if (UtilValidate.isNotEmpty(quoteItems)) {
        for (GenericValue quoteItem : quoteItems) {
            // get the next item sequence id
            String orderItemSeqId = quoteItem.getString("quoteItemSeqId");
            orderItemSeqId = orderItemSeqId.replaceAll("\\P{Digit}", "");
            try {
                long seq = Long.parseLong(orderItemSeqId);
                if (seq > nextItemSeq) {
                    nextItemSeq = seq;
                }
            } catch (NumberFormatException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(e.getMessage());
            }

            boolean isPromo = quoteItem.get("isPromo") != null && "Y".equals(quoteItem.getString("isPromo"));
            if (isPromo && !applyQuoteAdjustments) {
                // do not include PROMO items
                continue;
            }

            // not a promo item; go ahead and add it in
            BigDecimal amount = quoteItem.getBigDecimal("selectedAmount");
            if (amount == null) {
                amount = BigDecimal.ZERO;
            }
            BigDecimal quantity = quoteItem.getBigDecimal("quantity");
            if (quantity == null) {
                quantity = BigDecimal.ZERO;
            }
            BigDecimal quoteUnitPrice = quoteItem.getBigDecimal("quoteUnitPrice");
            if (quoteUnitPrice == null) {
                quoteUnitPrice = BigDecimal.ZERO;
            }
            if (amount.compareTo(BigDecimal.ZERO) > 0) {
                // If, in the quote, an amount is set, we need to
                // pass to the cart the quoteUnitPrice/amount value.
                quoteUnitPrice = quoteUnitPrice.divide(amount, generalRounding);
            }

            // rental product data
            Timestamp reservStart = quoteItem.getTimestamp("reservStart");
            BigDecimal reservLength = quoteItem.getBigDecimal("reservLength");
            BigDecimal reservPersons = quoteItem.getBigDecimal("reservPersons");
            // String accommodationMapId =
            // quoteItem.getString("accommodationMapId");
            // String accommodationSpotId =
            // quoteItem.getString("accommodationSpotId");

            int itemIndex = -1;
            if (quoteItem.get("productId") == null) {
                // non-product item
                String desc = quoteItem.getString("comments");
                try {
                    // note that passing in null for itemGroupNumber as
                    // there is no real grouping concept in the quotes right
                    // now
                    itemIndex = cart.addNonProductItem(null, desc, null, null, quantity, null, null, null,
                            dispatcher);
                } catch (CartItemModifyException e) {
                    Debug.logError(e, module);
                    return ServiceUtil.returnError(e.getMessage());
                }
            } else {
                // product item
                String productId = quoteItem.getString("productId");
                ProductConfigWrapper configWrapper = null;
                if (UtilValidate.isNotEmpty(quoteItem.getString("configId"))) {
                    configWrapper = ProductConfigWorker.loadProductConfigWrapper(delegator, dispatcher,
                            quoteItem.getString("configId"), productId, productStoreId, null, null, currency,
                            locale, userLogin);
                }
                try {
                    itemIndex = cart.addItemToEnd(productId, amount, quantity, quoteUnitPrice, reservStart,
                            reservLength, reservPersons, null, null, null, null, null, configWrapper, null,
                            dispatcher, new Boolean(!applyQuoteAdjustments),
                            new Boolean(quoteUnitPrice.compareTo(BigDecimal.ZERO) == 0), Boolean.FALSE,
                            Boolean.FALSE);

                } catch (ItemNotFoundException e) {
                    Debug.logError(e, module);
                    return ServiceUtil.returnError(e.getMessage());
                } catch (CartItemModifyException e) {
                    Debug.logError(e, module);
                    return ServiceUtil.returnError(e.getMessage());
                }
            }

            // flag the item w/ the orderItemSeqId so we can reference it
            ShoppingCartItem cartItem = cart.findCartItem(itemIndex);
            cartItem.setOrderItemSeqId(orderItemSeqId);
            // attach additional item information
            cartItem.setItemComment(quoteItem.getString("comments"));
            cartItem.setQuoteId(quoteItem.getString("quoteId"));
            cartItem.setQuoteItemSeqId(quoteItem.getString("quoteItemSeqId"));
            cartItem.setIsPromo(isPromo);
            // cartItem.setDesiredDeliveryDate(quoteItem.getTimestamp("estimatedDeliveryDate"));
            // cartItem.setStatusId(quoteItem.getString("statusId"));
            // cartItem.setItemType(quoteItem.getString("orderItemTypeId"));
            // cartItem.setProductCategoryId(quoteItem.getString("productCategoryId"));
            // cartItem.setShoppingList(quoteItem.getString("shoppingListId"),
            // quoteItem.getString("shoppingListItemSeqId"));
        }

    }

    // If applyQuoteAdjustments is set to false then standard cart
    // adjustments are used.
    if (applyQuoteAdjustments) {
        // The cart adjustments, derived from quote adjustments, are added
        // to the cart

        // Tax adjustments should be added to the shipping group and
        // shipping group item info
        // Other adjustments like promotional price should be added to the
        // cart independent of
        // the ship group.
        // We're creating the cart right now using data from the quote, so
        // there cannot yet be more than one ship group.

        List<GenericValue> cartAdjs = cart.getAdjustments();
        CartShipInfo shipInfo = cart.getShipInfo(0);

        List<GenericValue> adjs = orderAdjsMap.get(quoteId);

        if (adjs != null) {
            for (GenericValue adj : adjs) {
                if (isTaxAdjustment(adj))
                    shipInfo.shipTaxAdj.add(adj);
                else
                    cartAdjs.add(adj);
            }
        }

        // The cart item adjustments, derived from quote item adjustments,
        // are added to the cart
        if (quoteItems != null) {
            for (ShoppingCartItem item : cart) {
                String orderItemSeqId = item.getOrderItemSeqId();
                if (orderItemSeqId != null) {
                    adjs = orderAdjsMap.get(orderItemSeqId);
                } else {
                    adjs = null;
                }
                if (adjs != null) {
                    for (GenericValue adj : adjs) {
                        if (isTaxAdjustment(adj)) {
                            CartShipItemInfo csii = shipInfo.getShipItemInfo(item);

                            if (csii.itemTaxAdj == null)
                                shipInfo.setItemInfo(item, UtilMisc.toList(adj));
                            else
                                csii.itemTaxAdj.add(adj);
                        } else
                            item.addAdjustment(adj);
                    }
                }
            }
        }
    }

    // set the item seq in the cart
    if (nextItemSeq > 0) {
        try {
            cart.setNextItemSeq(nextItemSeq + 1);
        } catch (GeneralException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shoppingCart", cart);
    return result;
}