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:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java

@Override
public List<ScheduledPaymentDTO> calculatePaymentProjection(final ProjectionDTO params) {
    getProjectionValidator().validate(params);

    final LocalSettings localSettings = settingsService.getLocalSettings();

    final int paymentCount = params.getPaymentCount();
    final TimePeriod recurrence = params.getRecurrence();
    final BigDecimal totalAmount = params.getAmount();
    final BigDecimal paymentAmount = localSettings.round(totalAmount
            .divide(CoercionHelper.coerce(BigDecimal.class, paymentCount), localSettings.getMathContext()));
    BigDecimal accumulatedAmount = BigDecimal.ZERO;
    Calendar currentDate = DateHelper.truncate(params.getFirstExpirationDate());
    final List<ScheduledPaymentDTO> payments = new ArrayList<ScheduledPaymentDTO>(paymentCount);
    for (int i = 0; i < paymentCount; i++) {
        final ScheduledPaymentDTO dto = new ScheduledPaymentDTO();
        dto.setDate(currentDate);/*from  w w  w  . jav  a 2s . c  o  m*/
        dto.setAmount(i == paymentCount - 1 ? totalAmount.subtract(accumulatedAmount) : paymentAmount);
        payments.add(dto);
        accumulatedAmount = accumulatedAmount.add(dto.getAmount(), localSettings.getMathContext());
        currentDate = recurrence.add(currentDate);
    }
    return payments;
}

From source file:org.egov.ptis.service.es.CollectionIndexElasticSearchService.java

private void setDemandAmountsForTableData(String name, CollTableData collIndData, BigDecimal totalAssessments,
        BigDecimal currentYearTotalDemand, int noOfMonths, Map<String, BigDecimal> totalDemandMap) {
    BigDecimal variance;// w  w w .j  a  va 2  s.  c  o  m
    // Proportional Demand = (totalDemand/12)*noOfmonths
    BigDecimal cytdDmd = (currentYearTotalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP))
            .multiply(BigDecimal.valueOf(noOfMonths));
    collIndData.setCytdDmd(cytdDmd);
    if (cytdDmd != BigDecimal.valueOf(0)) {
        BigDecimal balance = cytdDmd.subtract(collIndData.getCytdColl());
        BigDecimal performance = (collIndData.getCytdColl().multiply(PropertyTaxConstants.BIGDECIMAL_100))
                .divide(cytdDmd, 1, BigDecimal.ROUND_HALF_UP);
        collIndData.setPerformance(performance);
        collIndData.setCytdBalDmd(balance);
    }
    collIndData.setTotalDmd(totalDemandMap.get(name) == null ? BigDecimal.ZERO : totalDemandMap.get(name));
    collIndData.setDayTargetDemand(collIndData.getTotalDmd().compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO
            : collIndData.getTotalDmd().divide(new BigDecimal("365"), 0, BigDecimal.ROUND_HALF_UP));
    collIndData.setTotalAssessments(totalAssessments);
    // variance = ((currentYearCollection - lastYearCollection)*100)/lastYearCollection
    if (collIndData.getLytdColl().compareTo(BigDecimal.ZERO) == 0)
        variance = PropertyTaxConstants.BIGDECIMAL_100;
    else
        variance = ((collIndData.getCytdColl().subtract(collIndData.getLytdColl()))
                .multiply(PropertyTaxConstants.BIGDECIMAL_100)).divide(collIndData.getLytdColl(), 1,
                        BigDecimal.ROUND_HALF_UP);
    collIndData.setLyVar(variance);
}

From source file:org.efaps.esjp.accounting.transaction.evaluation.DocumentInfo_Base.java

/**
 * Apply exchange gain loss.//ww w. ja va2s  .com
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @throws EFapsException on error
 */
public void applyExchangeGainLoss(final Parameter _parameter) throws EFapsException {
    final AccountInfo gainAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGEGAIN);
    final AccountInfo lossAcc = AccountInfo.get4Config(_parameter, AccountingSettings.PERIOD_EXCHANGELOSS);

    if (gainAcc != null && lossAcc != null) {
        final QueryBuilder queryBldr = new QueryBuilder(CISales.Payment);
        queryBldr.addWhereAttrEqValue(CISales.Payment.TargetDocument, getInstance());
        final MultiPrintQuery multi = queryBldr.getPrint();
        final SelectBuilder selDocInst = new SelectBuilder().linkto(CISales.Payment.FromAbstractLink)
                .instance();
        final SelectBuilder selCurInst = new SelectBuilder().linkto(CISales.Payment.CurrencyLink).instance();
        multi.addSelect(selDocInst, selCurInst);
        multi.addAttribute(CISales.Payment.Amount, CISales.Payment.Date);
        multi.execute();
        while (multi.next()) {
            final Instance docInst = multi.getSelect(selDocInst);
            final PrintQuery print = new PrintQuery(docInst);
            final SelectBuilder selDocCurInst = new SelectBuilder()
                    .linkto(CISales.DocumentSumAbstract.RateCurrencyId).instance();
            print.addSelect(selDocCurInst);
            print.addAttribute(CIERP.DocumentAbstract.Date);
            print.execute();
            final Instance curInst = multi.getSelect(selCurInst);
            final Instance docCurInst = print.getSelect(selDocCurInst);
            final DateTime docDate = print.getAttribute(CIERP.DocumentAbstract.Date);
            final DateTime dateTmp = multi.getAttribute(CISales.Payment.Date);
            final BigDecimal amountTmp = multi.getAttribute(CISales.Payment.Amount);

            if (!curInst.equals(Currency.getBaseCurrency()) || !docCurInst.equals(Currency.getBaseCurrency())) {
                final Currency currency = new Currency();
                final RateInfo[] rateInfos1 = currency.evaluateRateInfos(_parameter, dateTmp, curInst,
                        docCurInst);
                final RateInfo[] rateInfos2 = currency.evaluateRateInfos(_parameter, docDate, curInst,
                        docCurInst);
                final int idx;
                // payment in BaseCurreny ==> Document was not BaseCurrency therefore current against target
                if (curInst.equals(Currency.getBaseCurrency())) {
                    idx = 2;
                    // Document in  BaseCurrency ==> payment was not BaseCurrency therefore current against base
                } else if (docCurInst.equals(Currency.getBaseCurrency())) {
                    idx = 0;
                    // neither Document nor payment are BaseCurrency but are the same
                } else if (curInst.equals(docCurInst)) {
                    idx = 0;
                } else {
                    idx = 0;
                }

                final BigDecimal rate1 = RateInfo.getRate(_parameter, rateInfos1[idx],
                        docInst.getType().getName());
                final BigDecimal rate2 = RateInfo.getRate(_parameter, rateInfos2[idx],
                        docInst.getType().getName());
                if (rate1.compareTo(rate2) != 0) {
                    final BigDecimal amount1 = amountTmp.divide(rate1, BigDecimal.ROUND_HALF_UP);
                    final BigDecimal amount2 = amountTmp.divide(rate2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal gainLoss = amount1.subtract(amount2);
                    if (idx == 2) {
                        gainLoss = gainLoss.multiply(rate1);
                    }
                    if (gainLoss.compareTo(BigDecimal.ZERO) != 0) {
                        final boolean out = getInstance().getType()
                                .isKindOf(CISales.PaymentDocumentOutAbstract);
                        if (out) {
                            final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) > 0;
                            for (final AccountInfo accinfo : getCreditAccounts()) {
                                if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) {
                                    final BigDecimal accAmount;
                                    if (accinfo.getRateInfo().getCurrencyInstance()
                                            .equals(Currency.getBaseCurrency())) {
                                        accAmount = gainLoss;
                                    } else {
                                        accAmount = gainLoss.multiply(accinfo.getRate(_parameter));
                                    }
                                    accinfo.addAmount(accAmount.negate());
                                }
                            }
                            if (gain) {
                                gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addCredit(gainAcc);
                            } else {
                                lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addDebit(lossAcc);
                            }
                        } else {
                            final boolean gain = gainLoss.compareTo(BigDecimal.ZERO) < 0;
                            for (final AccountInfo accinfo : getDebitAccounts()) {
                                if (accinfo.getDocLink() != null && accinfo.getDocLink().equals(docInst)) {
                                    final BigDecimal accAmount;
                                    if (!accinfo.getRateInfo().getCurrencyInstance()
                                            .equals(Currency.getBaseCurrency())) {
                                        accAmount = gainLoss;
                                    } else {
                                        accAmount = gainLoss.multiply(accinfo.getRate(_parameter));
                                    }
                                    accinfo.addAmount(accAmount);
                                }
                            }
                            if (gain) {
                                gainAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addDebit(gainAcc);
                            } else {
                                lossAcc.setAmount(gainLoss.abs()).setRateInfo(RateInfo.getDummyRateInfo(),
                                        getInstance().getType().getName());
                                addCredit(lossAcc);
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.sakaiproject.tool.gradebook.Category.java

public void calculateStatisticsPerStudent(final List<AssignmentGradeRecord> gradeRecords,
        final String studentUid) {
    getGradebook().getGrade_type();/*from  w ww. java 2  s. c om*/
    int numScored = 0;
    int numOfAssignments = 0;
    BigDecimal total = new BigDecimal("0");
    BigDecimal totalPossible = new BigDecimal("0");

    if (gradeRecords == null) {
        setAverageScore(null);
        setAverageTotalPoints(null);
        setMean(null);
        setTotalPointsEarned(null);
        setTotalPointsPossible(null);
        return;
    }

    for (final AssignmentGradeRecord gradeRecord : gradeRecords) {
        if (gradeRecord != null && gradeRecord.getStudentId().equals(studentUid)) {
            final GradebookAssignment assignment = gradeRecord.getAssignment();
            if (assignment.isCounted() && !assignment.getUngraded()
                    && assignment.getPointsPossible().doubleValue() > 0.0
                    && !gradeRecord.getDroppedFromGrade()) {

                final Category assignCategory = assignment.getCategory();
                if (assignCategory != null && assignCategory.getId().equals(this.id)) {
                    final Double score = gradeRecord.getPointsEarned();
                    if (score != null) {
                        final BigDecimal bdScore = new BigDecimal(score.toString());
                        total = total.add(bdScore);
                        if (assignment.getPointsPossible() != null && !assignment.isExtraCredit()) {
                            final BigDecimal bdPointsPossible = new BigDecimal(
                                    assignment.getPointsPossible().toString());
                            totalPossible = totalPossible.add(bdPointsPossible);
                            numOfAssignments++;
                        }
                        if (!assignment.isExtraCredit()) {
                            numScored++;
                        }
                    }
                }
            }
        }
    }

    // if totalPossible is 0, this prevents a division by zero scenario likely from
    // an adjustment item being the only thing graded.
    if (numScored == 0 || numOfAssignments == 0 || totalPossible.doubleValue() == 0) {
        this.averageScore = null;
        this.averageTotalPoints = null;
        this.mean = null;
        this.totalPointsEarned = null;
        this.totalPointsPossible = null;
    } else {
        final BigDecimal bdNumScored = new BigDecimal(numScored);
        final BigDecimal bdNumAssign = new BigDecimal(numOfAssignments);
        this.averageScore = Double
                .valueOf(total.divide(bdNumScored, GradebookService.MATH_CONTEXT).doubleValue());
        this.averageTotalPoints = Double
                .valueOf(totalPossible.divide(bdNumAssign, GradebookService.MATH_CONTEXT).doubleValue());
        final BigDecimal value = total.divide(bdNumScored, GradebookService.MATH_CONTEXT)
                .divide((totalPossible.divide(bdNumAssign, GradebookService.MATH_CONTEXT)),
                        GradebookService.MATH_CONTEXT)
                .multiply(new BigDecimal("100"));

        this.mean = Double.valueOf(value.doubleValue());
    }
}

From source file:loci.formats.in.MetamorphReader.java

@Override
protected void initFile(String id) throws FormatException, IOException {
    if (checkSuffix(id, ND_SUFFIX)) {
        LOGGER.info("Initializing " + id);
        // find an associated STK file
        String stkFile = id.substring(0, id.lastIndexOf("."));
        if (stkFile.indexOf(File.separatorChar) != -1) {
            stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1);
        }/*from   w ww  .  ja  va2s. c o  m*/
        Location parent = new Location(id).getAbsoluteFile().getParentFile();
        LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath());
        String[] dirList = parent.list(true);
        Arrays.sort(dirList);
        for (String f : dirList) {
            int underscore = f.indexOf('_');
            if (underscore < 0)
                underscore = f.indexOf('.');
            if (underscore < 0)
                underscore = f.length();
            String prefix = f.substring(0, underscore);

            if ((f.equals(stkFile) || stkFile.startsWith(prefix)) && checkSuffix(f, STK_SUFFIX)) {
                stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath();
                break;
            }
        }

        if (!checkSuffix(stkFile, STK_SUFFIX)) {
            throw new FormatException("STK file not found in " + parent.getAbsolutePath() + ".");
        }

        super.initFile(stkFile);
    } else
        super.initFile(id);

    Location ndfile = null;

    if (checkSuffix(id, ND_SUFFIX))
        ndfile = new Location(id);
    else if (canLookForND && isGroupFiles()) {
        // an STK file was passed to initFile
        // let's check the parent directory for an .nd file
        Location stk = new Location(id).getAbsoluteFile();
        String stkName = stk.getName();
        String stkPrefix = stkName;
        if (stkPrefix.indexOf('_') >= 0) {
            stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf('_') + 1);
        }
        Location parent = stk.getParentFile();
        String[] list = parent.list(true);
        int matchingChars = 0;
        for (String f : list) {
            if (checkSuffix(f, ND_SUFFIX)) {
                String prefix = f.substring(0, f.lastIndexOf("."));
                if (prefix.indexOf('_') >= 0) {
                    prefix = prefix.substring(0, prefix.indexOf('_') + 1);
                }
                if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) {
                    int charCount = 0;
                    for (int i = 0; i < f.length(); i++) {
                        if (i >= stkName.length()) {
                            break;
                        }
                        if (f.charAt(i) == stkName.charAt(i)) {
                            charCount++;
                        } else {
                            break;
                        }
                    }

                    if (charCount > matchingChars
                            || (charCount == matchingChars && f.charAt(charCount) == '.')) {
                        ndfile = new Location(parent, f).getAbsoluteFile();
                        matchingChars = charCount;
                    }
                }
            }
        }
    }

    String creationTime = null;

    if (ndfile != null && ndfile.exists()
            && (fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles())) {
        // parse key/value pairs from .nd file

        int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT();
        int nstages = 0;
        String z = null, c = null, t = null;
        final List<Boolean> hasZ = new ArrayList<Boolean>();
        waveNames = new ArrayList<String>();
        stageNames = new ArrayList<String>();
        boolean useWaveNames = true;

        ndFilename = ndfile.getAbsolutePath();
        String[] lines = DataTools.readFile(ndFilename).split("\n");

        boolean globalDoZ = true;
        boolean doTimelapse = false;

        StringBuilder currentValue = new StringBuilder();
        String key = "";

        for (String line : lines) {
            int comma = line.indexOf(',');
            if (comma <= 0) {
                currentValue.append("\n");
                currentValue.append(line);
                continue;
            }

            String value = currentValue.toString();
            addGlobalMeta(key, value);
            if (key.equals("NZSteps"))
                z = value;
            else if (key.equals("DoTimelapse")) {
                doTimelapse = Boolean.parseBoolean(value);
            } else if (key.equals("NWavelengths"))
                c = value;
            else if (key.equals("NTimePoints"))
                t = value;
            else if (key.startsWith("WaveDoZ")) {
                hasZ.add(Boolean.parseBoolean(value));
            } else if (key.startsWith("WaveName")) {
                String waveName = value.substring(1, value.length() - 1);
                if (waveName.equals("Both lasers") || waveName.startsWith("DUAL")) {
                    bizarreMultichannelAcquisition = true;
                }
                waveNames.add(waveName);
            } else if (key.startsWith("Stage")) {
                stageNames.add(value);
            } else if (key.startsWith("StartTime")) {
                creationTime = value;
            } else if (key.equals("ZStepSize")) {
                value = value.replace(',', '.');
                stepSize = Double.parseDouble(value);
            } else if (key.equals("NStagePositions")) {
                nstages = Integer.parseInt(value);
            } else if (key.equals("WaveInFileName")) {
                useWaveNames = Boolean.parseBoolean(value);
            } else if (key.equals("DoZSeries")) {
                globalDoZ = Boolean.parseBoolean(value);
            }

            key = line.substring(1, comma - 1).trim();
            currentValue.delete(0, currentValue.length());
            currentValue.append(line.substring(comma + 1).trim());
        }

        if (!globalDoZ) {
            for (int i = 0; i < hasZ.size(); i++) {
                hasZ.set(i, false);
            }
        }

        // figure out how many files we need

        if (z != null)
            zc = Integer.parseInt(z);
        if (c != null)
            cc = Integer.parseInt(c);
        if (t != null)
            tc = Integer.parseInt(t);
        else if (!doTimelapse) {
            tc = 1;
        }

        if (cc == 0)
            cc = 1;
        if (cc == 1 && bizarreMultichannelAcquisition) {
            cc = 2;
        }
        if (tc == 0) {
            tc = 1;
        }

        int numFiles = cc * tc;
        if (nstages > 0)
            numFiles *= nstages;

        // determine series count
        int stagesCount = nstages == 0 ? 1 : nstages;
        int seriesCount = stagesCount;
        firstSeriesChannels = new boolean[cc];
        Arrays.fill(firstSeriesChannels, true);
        boolean differentZs = false;
        for (int i = 0; i < cc; i++) {
            boolean hasZ1 = i < hasZ.size() && hasZ.get(i);
            boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) && hasZ.get(i - 1);
            if (i > 0 && hasZ1 != hasZ2 && globalDoZ) {
                if (!differentZs)
                    seriesCount *= 2;
                differentZs = true;
            }
        }

        int channelsInFirstSeries = cc;
        if (differentZs) {
            channelsInFirstSeries = 0;
            for (int i = 0; i < cc; i++) {
                if ((!hasZ.get(0) && i == 0) || (hasZ.get(0) && hasZ.get(i))) {
                    channelsInFirstSeries++;
                } else
                    firstSeriesChannels[i] = false;
            }
        }

        stks = new String[seriesCount][];
        if (seriesCount == 1)
            stks[0] = new String[numFiles];
        else if (differentZs) {
            for (int i = 0; i < stagesCount; i++) {
                stks[i * 2] = new String[channelsInFirstSeries * tc];
                stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc];
            }
        } else {
            for (int i = 0; i < stks.length; i++) {
                stks[i] = new String[numFiles / stks.length];
            }
        }

        String prefix = ndfile.getPath();
        prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1, prefix.lastIndexOf("."));

        // build list of STK files

        boolean anyZ = hasZ.contains(Boolean.TRUE);
        int[] pt = new int[seriesCount];
        for (int i = 0; i < tc; i++) {
            for (int s = 0; s < stagesCount; s++) {
                for (int j = 0; j < cc; j++) {
                    boolean validZ = j >= hasZ.size() || hasZ.get(j);
                    int seriesNdx = s * (seriesCount / stagesCount);

                    if ((seriesCount != 1 && (!validZ || (hasZ.size() > 0 && !hasZ.get(0))))
                            || (nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1))) {
                        if (anyZ && j > 0 && seriesNdx < seriesCount - 1 && (!validZ || !hasZ.get(0))) {
                            seriesNdx++;
                        }
                    }
                    if (seriesNdx >= stks.length || seriesNdx >= pt.length
                            || pt[seriesNdx] >= stks[seriesNdx].length) {
                        continue;
                    }
                    stks[seriesNdx][pt[seriesNdx]] = prefix;
                    if (j < waveNames.size() && waveNames.get(j) != null) {
                        stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1);
                        if (useWaveNames) {
                            String waveName = waveNames.get(j);
                            // If there are underscores in the wavelength name, translate
                            // them to hyphens. (See #558)
                            waveName = waveName.replace('_', '-');
                            // If there are slashes (forward or backward) in the wavelength
                            // name, translate them to hyphens. (See #5922)
                            waveName = waveName.replace('/', '-');
                            waveName = waveName.replace('\\', '-');
                            waveName = waveName.replace('(', '-');
                            waveName = waveName.replace(')', '-');
                            stks[seriesNdx][pt[seriesNdx]] += waveName;
                        }
                    }
                    if (nstages > 0) {
                        stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1);
                    }
                    if (tc > 1 || doTimelapse) {
                        stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK";
                    } else
                        stks[seriesNdx][pt[seriesNdx]] += ".STK";
                    pt[seriesNdx]++;
                }
            }
        }

        ndfile = ndfile.getAbsoluteFile();

        // check that each STK file exists

        for (int s = 0; s < stks.length; s++) {
            for (int f = 0; f < stks[s].length; f++) {
                Location l = new Location(ndfile.getParent(), stks[s][f]);
                stks[s][f] = getRealSTKFile(l);
            }
        }

        String file = locateFirstValidFile();
        if (file == null) {
            throw new FormatException("Unable to locate at least one valid STK file!");
        }

        RandomAccessInputStream s = new RandomAccessInputStream(file, 16);
        TiffParser tp = new TiffParser(s);
        IFD ifd = tp.getFirstIFD();
        CoreMetadata ms0 = core.get(0);
        s.close();
        ms0.sizeX = (int) ifd.getImageWidth();
        ms0.sizeY = (int) ifd.getImageLength();

        if (bizarreMultichannelAcquisition) {
            ms0.sizeX /= 2;
        }

        ms0.sizeZ = hasZ.size() > 0 && !hasZ.get(0) ? 1 : zc;
        ms0.sizeC = cc;
        ms0.sizeT = tc;
        ms0.imageCount = getSizeZ() * getSizeC() * getSizeT();
        if (isRGB()) {
            ms0.sizeC *= 3;
        }
        ms0.dimensionOrder = "XYZCT";

        if (stks != null && stks.length > 1) {
            // Note that core can't be replaced with newCore until the end of this block.
            ArrayList<CoreMetadata> newCore = new ArrayList<CoreMetadata>();
            for (int i = 0; i < stks.length; i++) {
                CoreMetadata ms = new CoreMetadata();
                newCore.add(ms);
                ms.sizeX = getSizeX();
                ms.sizeY = getSizeY();
                ms.sizeZ = getSizeZ();
                ms.sizeC = getSizeC();
                ms.sizeT = getSizeT();
                ms.pixelType = getPixelType();
                ms.imageCount = getImageCount();
                ms.dimensionOrder = getDimensionOrder();
                ms.rgb = isRGB();
                ms.littleEndian = isLittleEndian();
                ms.interleaved = isInterleaved();
                ms.orderCertain = true;
            }
            if (stks.length > nstages) {
                for (int j = 0; j < stagesCount; j++) {
                    int idx = j * 2 + 1;
                    CoreMetadata midx = newCore.get(idx);
                    CoreMetadata pmidx = newCore.get(j * 2);
                    pmidx.sizeC = stks[j * 2].length / getSizeT();
                    midx.sizeC = stks[idx].length / midx.sizeT;
                    midx.sizeZ = hasZ.size() > 1 && hasZ.get(1) && core.get(0).sizeZ == 1 ? zc : 1;
                    pmidx.imageCount = pmidx.sizeC * pmidx.sizeT * pmidx.sizeZ;
                    midx.imageCount = midx.sizeC * midx.sizeT * midx.sizeZ;
                }
            }
            core = newCore;
        }
    }

    if (stks == null) {
        stkReaders = new MetamorphReader[1][1];
        stkReaders[0][0] = new MetamorphReader();
        stkReaders[0][0].setCanLookForND(false);
    } else {
        stkReaders = new MetamorphReader[stks.length][];
        for (int i = 0; i < stks.length; i++) {
            stkReaders[i] = new MetamorphReader[stks[i].length];
            for (int j = 0; j < stkReaders[i].length; j++) {
                stkReaders[i][j] = new MetamorphReader();
                stkReaders[i][j].setCanLookForND(false);
                if (j > 0) {
                    stkReaders[i][j].setMetadataOptions(new DynamicMetadataOptions(MetadataLevel.MINIMUM));
                }
            }
        }
    }

    // check stage labels for plate data

    int rows = 0;
    int cols = 0;
    Map<String, Integer> rowMap = null;
    Map<String, Integer> colMap = null;
    isHCS = true;
    if (null == stageLabels) {
        isHCS = false;
    } else {
        Set<Map.Entry<Integer, Integer>> uniqueWells = new HashSet<Map.Entry<Integer, Integer>>();
        rowMap = new HashMap<String, Integer>();
        colMap = new HashMap<String, Integer>();
        for (String label : stageLabels) {
            if (null == label) {
                isHCS = false;
                break;
            }
            Map.Entry<Integer, Integer> wellCoords = getWellCoords(label);
            if (null == wellCoords) {
                isHCS = false;
                break;
            }
            uniqueWells.add(wellCoords);
            rowMap.put(label, wellCoords.getKey());
            colMap.put(label, wellCoords.getValue());
        }
        if (uniqueWells.size() != stageLabels.length) {
            isHCS = false;
        } else {
            rows = Collections.max(rowMap.values());
            cols = Collections.max(colMap.values());
            CoreMetadata c = core.get(0);
            core.clear();
            c.sizeZ = 1;
            c.sizeT = 1;
            c.imageCount = 1;
            for (int s = 0; s < uniqueWells.size(); s++) {
                CoreMetadata toAdd = new CoreMetadata(c);
                if (s > 0) {
                    toAdd.seriesMetadata.clear();
                }
                core.add(toAdd);
            }
            seriesToIFD = true;
        }
    }

    List<String> timestamps = null;
    MetamorphHandler handler = null;

    MetadataStore store = makeFilterMetadata();
    MetadataTools.populatePixels(store, this, true);

    if (isHCS) {
        store.setPlateID(MetadataTools.createLSID("Plate", 0), 0);
        store.setPlateRows(new PositiveInteger(rows), 0);
        store.setPlateColumns(new PositiveInteger(cols), 0);
        store.setPlateRowNamingConvention(NamingConvention.LETTER, 0);
        store.setPlateColumnNamingConvention(NamingConvention.NUMBER, 0);
    }

    int nextObjective = 0;
    String instrumentID = MetadataTools.createLSID("Instrument", 0);
    String detectorID = MetadataTools.createLSID("Detector", 0, 0);

    store.setInstrumentID(instrumentID, 0);
    store.setDetectorID(detectorID, 0, 0);
    store.setDetectorType(getDetectorType("Other"), 0, 0);

    for (int i = 0; i < getSeriesCount(); i++) {
        setSeries(i);
        // do not reparse the same XML for every well
        if (i == 0 || !isHCS) {
            handler = new MetamorphHandler(getSeriesMetadata());
        }

        if (isHCS) {
            String label = stageLabels[i];
            String wellID = MetadataTools.createLSID("Well", 0, i);
            store.setWellID(wellID, 0, i);
            store.setWellColumn(new NonNegativeInteger(colMap.get(label)), 0, i);
            store.setWellRow(new NonNegativeInteger(rowMap.get(label)), 0, i);
            store.setWellSampleID(MetadataTools.createLSID("WellSample", 0, i, 0), 0, i, 0);
            store.setWellSampleImageRef(MetadataTools.createLSID("Image", i), 0, i, 0);
            store.setWellSampleIndex(new NonNegativeInteger(i), 0, i, 0);
        }

        store.setImageInstrumentRef(instrumentID, i);

        String comment = getFirstComment(i);
        if (i == 0 || !isHCS) {
            if (comment != null && comment.startsWith("<MetaData>")) {
                try {
                    XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler);
                } catch (IOException e) {
                }
            }
        }

        if (creationTime != null) {
            String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT, ".");
            if (date != null) {
                store.setImageAcquisitionDate(new Timestamp(date), 0);
            }
        }

        store.setImageName(makeImageName(i).trim(), i);

        if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
            continue;
        }
        store.setImageDescription("", i);

        store.setImagingEnvironmentTemperature(new Temperature(handler.getTemperature(), UNITS.CELSIUS), i);

        if (sizeX == null)
            sizeX = handler.getPixelSizeX();
        if (sizeY == null)
            sizeY = handler.getPixelSizeY();

        Length physicalSizeX = FormatTools.getPhysicalSizeX(sizeX);
        Length physicalSizeY = FormatTools.getPhysicalSizeY(sizeY);
        if (physicalSizeX != null) {
            store.setPixelsPhysicalSizeX(physicalSizeX, i);
        }
        if (physicalSizeY != null) {
            store.setPixelsPhysicalSizeY(physicalSizeY, i);
        }
        if (zDistances != null) {
            stepSize = zDistances[0];
        } else {
            List<Double> zPositions = new ArrayList<Double>();
            final List<Double> uniqueZ = new ArrayList<Double>();

            for (IFD ifd : ifds) {
                MetamorphHandler zPlaneHandler = new MetamorphHandler();

                String zComment = ifd.getComment();
                if (zComment != null && zComment.startsWith("<MetaData>")) {
                    try {
                        XMLTools.parseXML(XMLTools.sanitizeXML(zComment), zPlaneHandler);
                    } catch (IOException e) {
                    }
                }

                zPositions = zPlaneHandler.getZPositions();
                for (Double z : zPositions) {
                    if (!uniqueZ.contains(z))
                        uniqueZ.add(z);
                }
            }
            if (uniqueZ.size() > 1 && uniqueZ.size() == getSizeZ()) {
                BigDecimal lastZ = BigDecimal.valueOf(uniqueZ.get(uniqueZ.size() - 1));
                BigDecimal firstZ = BigDecimal.valueOf(uniqueZ.get(0));
                BigDecimal zRange = (lastZ.subtract(firstZ)).abs();
                BigDecimal zSize = BigDecimal.valueOf((double) (getSizeZ() - 1));
                MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
                stepSize = zRange.divide(zSize, mc).doubleValue();
            }
        }

        Length physicalSizeZ = FormatTools.getPhysicalSizeZ(stepSize);
        if (physicalSizeZ != null) {
            store.setPixelsPhysicalSizeZ(physicalSizeZ, i);
        }

        if (handler.getLensNA() != 0 || handler.getLensRI() != 0) {
            String objectiveID = MetadataTools.createLSID("Objective", 0, nextObjective);
            store.setObjectiveID(objectiveID, 0, nextObjective);
            if (handler.getLensNA() != 0) {
                store.setObjectiveLensNA(handler.getLensNA(), 0, nextObjective);
            }
            store.setObjectiveSettingsID(objectiveID, i);
            if (handler.getLensRI() != 0) {
                store.setObjectiveSettingsRefractiveIndex(handler.getLensRI(), i);
            }
            nextObjective++;
        }

        int waveIndex = 0;
        for (int c = 0; c < getEffectiveSizeC(); c++) {
            if (firstSeriesChannels == null || (stageNames != null && stageNames.size() == getSeriesCount())) {
                waveIndex = c;
            } else if (firstSeriesChannels != null) {
                int s = i % 2;
                while (firstSeriesChannels[waveIndex] == (s == 1) && waveIndex < firstSeriesChannels.length) {
                    waveIndex++;
                }
            }

            if (waveNames != null && waveIndex < waveNames.size()) {
                store.setChannelName(waveNames.get(waveIndex).trim(), i, c);
            }
            if (handler.getBinning() != null)
                binning = handler.getBinning();
            if (binning != null) {
                store.setDetectorSettingsBinning(getBinning(binning), i, c);
            }
            if (handler.getReadOutRate() != 0) {
                store.setDetectorSettingsReadOutRate(new Frequency(handler.getReadOutRate(), UNITS.HERTZ), i,
                        c);
            }

            if (gain == null) {
                gain = handler.getGain();
            }

            if (gain != null) {
                store.setDetectorSettingsGain(gain, i, c);
            }
            store.setDetectorSettingsID(detectorID, i, c);

            if (wave != null && waveIndex < wave.length) {
                Length wavelength = FormatTools.getWavelength(wave[waveIndex]);

                if ((int) wave[waveIndex] >= 1) {
                    // link LightSource to Image
                    int laserIndex = i * getEffectiveSizeC() + c;
                    String lightSourceID = MetadataTools.createLSID("LightSource", 0, laserIndex);
                    store.setLaserID(lightSourceID, 0, laserIndex);
                    store.setChannelLightSourceSettingsID(lightSourceID, i, c);
                    store.setLaserType(getLaserType("Other"), 0, laserIndex);
                    store.setLaserLaserMedium(getLaserMedium("Other"), 0, laserIndex);

                    if (wavelength != null) {
                        store.setChannelLightSourceSettingsWavelength(wavelength, i, c);
                    }
                }
            }
            waveIndex++;
        }

        timestamps = handler.getTimestamps();

        for (int t = 0; t < timestamps.size(); t++) {
            String date = DateTools.convertDate(DateTools.getTime(timestamps.get(t), SHORT_DATE_FORMAT, "."),
                    DateTools.UNIX, SHORT_DATE_FORMAT + ".SSS");
            addSeriesMetaList("timestamp", date);
        }

        long startDate = 0;
        if (timestamps.size() > 0) {
            startDate = DateTools.getTime(timestamps.get(0), SHORT_DATE_FORMAT, ".");
        }

        final Length positionX = handler.getStagePositionX();
        final Length positionY = handler.getStagePositionY();
        final List<Double> exposureTimes = handler.getExposures();
        if (exposureTimes.size() == 0) {
            for (int p = 0; p < getImageCount(); p++) {
                exposureTimes.add(exposureTime);
            }
        } else if (exposureTimes.size() == 1 && exposureTimes.size() < getEffectiveSizeC()) {
            for (int c = 1; c < getEffectiveSizeC(); c++) {
                MetamorphHandler channelHandler = new MetamorphHandler();

                String channelComment = getComment(i, c);
                if (channelComment != null && channelComment.startsWith("<MetaData>")) {
                    try {
                        XMLTools.parseXML(XMLTools.sanitizeXML(channelComment), channelHandler);
                    } catch (IOException e) {
                    }
                }

                final List<Double> channelExpTime = channelHandler.getExposures();
                exposureTimes.add(channelExpTime.get(0));
            }
        }

        int lastFile = -1;
        IFDList lastIFDs = null;
        IFD lastIFD = null;

        double distance = zStart;
        TiffParser tp = null;
        RandomAccessInputStream stream = null;

        for (int p = 0; p < getImageCount(); p++) {
            int[] coords = getZCTCoords(p);
            Double deltaT = 0d;
            Double expTime = exposureTime;
            Double xmlZPosition = null;

            int fileIndex = getIndex(0, coords[1], coords[2]) / getSizeZ();
            if (fileIndex >= 0) {
                String file = stks == null ? currentId : stks[i][fileIndex];
                if (file != null) {
                    if (fileIndex != lastFile) {
                        if (stream != null) {
                            stream.close();
                        }
                        stream = new RandomAccessInputStream(file, 16);
                        tp = new TiffParser(stream);
                        tp.checkHeader();
                        IFDList f = tp.getMainIFDs();
                        if (f.size() > 0) {
                            lastFile = fileIndex;
                            lastIFDs = f;
                        } else {
                            file = null;
                            stks[i][fileIndex] = null;
                        }
                    }
                }

                if (file != null) {
                    lastIFD = lastIFDs.get(p % lastIFDs.size());
                    Object commentEntry = lastIFD.get(IFD.IMAGE_DESCRIPTION);
                    if (commentEntry != null) {
                        if (commentEntry instanceof String) {
                            comment = (String) commentEntry;
                        } else if (commentEntry instanceof TiffIFDEntry) {
                            comment = tp.getIFDValue((TiffIFDEntry) commentEntry).toString();
                        }
                    }
                    if (comment != null)
                        comment = comment.trim();
                    if (comment != null && comment.startsWith("<MetaData>")) {
                        String[] lines = comment.split("\n");

                        timestamps = new ArrayList<String>();

                        for (String line : lines) {
                            line = line.trim();
                            if (line.startsWith("<prop")) {
                                int firstQuote = line.indexOf("\"") + 1;
                                int lastQuote = line.lastIndexOf("\"");
                                String key = line.substring(firstQuote, line.indexOf("\"", firstQuote));
                                String value = line.substring(line.lastIndexOf("\"", lastQuote - 1) + 1,
                                        lastQuote);

                                if (key.equals("z-position")) {
                                    xmlZPosition = new Double(value);
                                } else if (key.equals("acquisition-time-local")) {
                                    timestamps.add(value);
                                }
                            }
                        }
                    }
                }
            }

            int index = 0;

            if (timestamps.size() > 0) {
                if (coords[2] < timestamps.size())
                    index = coords[2];
                String stamp = timestamps.get(index);
                long ms = DateTools.getTime(stamp, SHORT_DATE_FORMAT, ".");
                deltaT = (ms - startDate) / 1000.0;
            } else if (internalStamps != null && p < internalStamps.length) {
                long delta = internalStamps[p] - internalStamps[0];
                deltaT = delta / 1000.0;
                if (coords[2] < exposureTimes.size())
                    index = coords[2];
            }

            if (index == 0 && p > 0 && exposureTimes.size() > 0) {
                index = coords[1] % exposureTimes.size();
            }

            if (index < exposureTimes.size()) {
                expTime = exposureTimes.get(index);
            }
            if (deltaT != null) {
                store.setPlaneDeltaT(new Time(deltaT, UNITS.SECOND), i, p);
            }
            if (expTime != null) {
                store.setPlaneExposureTime(new Time(expTime, UNITS.SECOND), i, p);
            }

            if (stageX != null && p < stageX.length) {
                store.setPlanePositionX(stageX[p], i, p);
            } else if (positionX != null) {
                store.setPlanePositionX(positionX, i, p);
            }
            if (stageY != null && p < stageY.length) {
                store.setPlanePositionY(stageY[p], i, p);
            } else if (positionY != null) {
                store.setPlanePositionY(positionY, i, p);
            }
            if (zDistances != null && p < zDistances.length) {
                if (p > 0) {
                    if (zDistances[p] != 0d)
                        distance += zDistances[p];
                    else
                        distance += zDistances[0];
                }
                final Length zPos = new Length(distance, UNITS.REFERENCEFRAME);
                store.setPlanePositionZ(zPos, i, p);
            } else if (xmlZPosition != null) {
                final Length zPos = new Length(xmlZPosition, UNITS.REFERENCEFRAME);
                store.setPlanePositionZ(zPos, i, p);
            }
        }

        if (stream != null) {
            stream.close();
        }
    }
    setSeries(0);
}

From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java

private Validator getPaymentValidator(final DoPaymentDTO payment) {
    final Validator validator = new Validator("transfer");
    Collection<TransactionContext> possibleContexts = new ArrayList<TransactionContext>();
    possibleContexts.add(TransactionContext.PAYMENT);
    if (LoggedUser.isWebService() || LoggedUser.isSystem()) {
        possibleContexts.add(TransactionContext.AUTOMATIC);
    } else {//from ww  w .  ja  v  a  2  s.c o  m
        possibleContexts.add(TransactionContext.SELF_PAYMENT);
    }
    validator.property("context").required().anyOf(possibleContexts);
    validator.property("to").required().key("payment.recipient");
    // as currency is maybe not set on the DTO, we get it from the TT in stead of directly from the DTO
    final TransferType tt = fetchService.fetch(payment.getTransferType(), Relationships.TRANSACTION_FEES,
            RelationshipHelper.nested(TransferType.Relationships.FROM, TransferType.Relationships.TO,
                    AccountType.Relationships.CURRENCY, Currency.Relationships.A_RATE_PARAMETERS),
            RelationshipHelper.nested(TransferType.Relationships.FROM, TransferType.Relationships.TO,
                    AccountType.Relationships.CURRENCY, Currency.Relationships.D_RATE_PARAMETERS));
    final Currency currency = tt == null ? null : tt.getCurrency();
    if (currency != null && (currency.isEnableARate() || currency.isEnableDRate())) {
        // if the date is not null at this moment, it is in the past, which is not allowed with rates.
        if (payment.getDate() != null) {
            validator.general(new NoPastDateWithRatesValidator());
        }
    } else {
        validator.property("date").key("payment.manualDate").past();
    }

    validator.property("ticket").add(new TicketValidation());

    addAmountValidator(validator, tt);
    validator.property("transferType").key("transfer.type").required();
    validator.property("description").maxLength(1000);
    validator.general(new SchedulingValidator());
    validator.general(new PendingContractValidator());
    if (payment.getTransferType() != null && payment.getTo() != null && payment.getAmount() != null) {

        /*
         * For user validation, we need to check if the transaction amount is high enough to cover all fees. This depends on all fees, but only in
         * case of fixed fees it makes sense to increase the transaction amount. The formula for this is: given transactionamount > (sum of fixed
         * fees )/ (1 minus sum of percentage fees expressed as fractions). This of course only applies for fees with deductAmount; fees which are
         * not deducted are excluded from this calculation.
         */
        final TransactionFeePreviewDTO preview = transactionFeeService.preview(payment.getFrom(),
                payment.getTo(), tt, payment.getAmount());
        final Property amount = validator.property("amount");
        final Collection<? extends TransactionFee> fees = preview.getFees().keySet();
        BigDecimal sumOfFixedFees = BigDecimal.ZERO;
        BigDecimal sumOfPercentageFees = BigDecimal.ZERO;
        for (final TransactionFee fee : fees) {
            if (fee.isDeductAmount()) {
                if (fee.getChargeType() == ChargeType.FIXED) {
                    sumOfFixedFees = sumOfFixedFees.add(preview.getFees().get(fee));
                } else {
                    sumOfPercentageFees = sumOfPercentageFees.add(preview.getFees().get(fee));
                }
            }
        }
        // Show a warning if there are fixed fees and if the amount is not enough to cover them
        if (sumOfFixedFees.signum() == 1) {
            final int scale = LocalSettings.MAX_PRECISION;
            final MathContext mc = new MathContext(scale);
            final BigDecimal sumOfPercentages = sumOfPercentageFees.divide(payment.getAmount(), mc);
            final BigDecimal minimalAmount = sumOfFixedFees.divide((BigDecimal.ONE.subtract(sumOfPercentages)),
                    mc);
            amount.comparable(minimalAmount, ">", new ValidationError("errors.greaterThan",
                    messageResolver.message("transactionFee.invalidChargeValue", minimalAmount)));
        } else if (preview.getFinalAmount().signum() == -1) {
            validator.general(new FinalAmountValidator());
        }

        // Custom fields
        validator.chained(new DelegatingValidator(new DelegatingValidator.DelegateSource() {
            @Override
            public Validator getValidator() {
                return paymentCustomFieldService.getValueValidator(payment.getTransferType());
            }
        }));
    }
    return validator;
}

From source file:org.egov.ptis.service.es.CollectionIndexElasticSearchService.java

/**
 * Provides week wise DCB details across all ULBs
 * @param collectionDetailsRequest/* w  w w  .  j ava2s.c om*/
 * @param intervalType
 * @return list
 */
public List<WeeklyDCB> getWeekwiseDCBDetailsAcrossCities(
        final CollectionDetailsRequest collectionDetailsRequest, final String intervalType) {
    final List<WeeklyDCB> ulbWiseDetails = new ArrayList<>();
    Date fromDate = null;
    Date toDate = null;
    String weekName;
    Sum aggregateSum;
    String aggregationField = StringUtils.EMPTY;
    Map<String, Object[]> weekwiseColl;
    final Map<String, Map<String, Object[]>> weeklyCollMap = new LinkedHashMap<>();
    Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>();
    if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD);
        toDate = DateUtils
                .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1);
    }
    if (StringUtils.isNotBlank(collectionDetailsRequest.getType()))
        aggregationField = getAggregrationField(collectionDetailsRequest);
    if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType()))
        wardWiseBillCollectors = getWardWiseBillCollectors(collectionDetailsRequest);

    final Map<String, BigDecimal> totalDemandMap = getCollectionAndDemandValues(collectionDetailsRequest,
            fromDate, toDate, PROPERTY_TAX_INDEX_NAME, TOTAL_DEMAND, aggregationField);
    final Aggregations collAggr = getMonthwiseCollectionsForConsecutiveYears(collectionDetailsRequest, fromDate,
            toDate, true, intervalType, aggregationField);
    final StringTerms cityaggr = collAggr.get(BY_CITY);
    BigDecimal totalDemand;
    BigDecimal weeklyDemand;
    int noOfWeeks;
    Object[] demandCollValues;
    for (final Terms.Bucket cityDetailsentry : cityaggr.getBuckets()) {
        weekwiseColl = new LinkedHashMap<>();
        final String ulbName = cityDetailsentry.getKeyAsString();
        noOfWeeks = 0;
        totalDemand = totalDemandMap.get(ulbName) == null ? BigDecimal.ZERO : totalDemandMap.get(ulbName);

        final Histogram dateaggs = cityDetailsentry.getAggregations().get(DATE_AGG);
        for (final Histogram.Bucket entry : dateaggs.getBuckets()) {
            if (noOfWeeks == 0)
                noOfWeeks = 1;
            demandCollValues = new Object[53];
            if (totalDemand.compareTo(BigDecimal.ZERO) == 0)
                weeklyDemand = BigDecimal.ZERO;
            else
                weeklyDemand = totalDemand.divide(BigDecimal.valueOf(52), BigDecimal.ROUND_HALF_UP)
                        .multiply(BigDecimal.valueOf(noOfWeeks));
            weekName = "Week " + noOfWeeks;
            aggregateSum = entry.getAggregations().get(CURRENT_TOTAL);
            if (BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)
                    .compareTo(BigDecimal.ZERO) > 0) {
                demandCollValues[0] = BigDecimal.valueOf(aggregateSum.getValue()).setScale(0,
                        BigDecimal.ROUND_HALF_UP);
                demandCollValues[1] = weeklyDemand;
                weekwiseColl.put(weekName, demandCollValues);
            }
            noOfWeeks++;
        }
        weeklyCollMap.put(ulbName, weekwiseColl);
    }
    setWeeklyDCBValues(ulbWiseDetails, weeklyCollMap, wardWiseBillCollectors);
    return ulbWiseDetails;

}

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

/**
 * Add agreement order term *//from   w w w  . j  a  va 2s . c  o m
 */
public static String addAgreementOrderTerm(HttpServletRequest request, HttpServletResponse response) {

    ShoppingCart cart = getCartObject(request);
    Locale locale = UtilHttp.getLocale(request);

    cart.removeOrderTerms();

    String termTypeId = request.getParameter("termTypeId");
    String termValueStr = request.getParameter("termValue");
    String termDaysStr = request.getParameter("termDays");
    String textValue = request.getParameter("textValue");

    String textValueCodeudor = request.getParameter("textValueCodeudor");
    String termValueAnticipo = request.getParameter("termValueAnticipo");
    String termValueCuotas = request.getParameter("termValueCuotas");
    String textValueDate = request.getParameter("textValueDate");
    String termValueVencimiento = request.getParameter("termValueVencimiento");
    String textValueRefNom1 = request.getParameter("textValueRefNom1");
    String termValueRefTel1 = request.getParameter("termValueRefTel1");
    String textValueRefNom2 = request.getParameter("textValueRefNom2");
    String termValueRefTel2 = request.getParameter("termValueRefTel2");

    // ANTICIPO

    termTypeId = "CRD_ANTICIPO";
    termValueStr = termValueAnticipo;

    GenericValue termType = null;
    Delegator delegator = (Delegator) request.getAttribute("delegator");

    BigDecimal termValue = null;
    Long termDays = null;
    Long DiaVencimiento = null;

    Timestamp termDate = null;

    Timestamp termDateIni = null;

    Long termSec = Long.valueOf(0);

    termSec++;

    if (UtilValidate.isNotEmpty(termValueStr)) {

        //           if (UtilValidate.isEmpty(termTypeId)) {
        //               request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //               return "error";
        //           }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        //           if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr)) || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId")) && UtilValidate.isEmpty(termDaysStr))) {
        //               request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
        //               return "error";
        //           }
        //   
        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);
    }
    //

    //----------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_CODEUDOR";
    textValue = textValueCodeudor;

    termType = null;
    termValue = null;
    termDays = null;

    termSec++;

    if (UtilValidate.isNotEmpty(textValueCodeudor)) {
        //           if (UtilValidate.isEmpty(termTypeId)) {
        //               request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //               return "error";
        //           }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr))
                || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId"))
                        && UtilValidate.isEmpty(termDaysStr))) {
            request.setAttribute("_ERROR_MESSAGE_",
                    UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
            return "error";
        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);
    }

    //----------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_REFERENCIA";
    textValue = textValueRefNom1.toUpperCase();
    termValueStr = termValueRefTel1;

    termType = null;
    termValue = null;
    termDays = null;

    termSec++;

    if (UtilValidate.isNotEmpty(textValueRefNom1)) {

        //        if (UtilValidate.isEmpty(termTypeId)) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //            return "error";
        //        }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr))
                || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId"))
                        && UtilValidate.isEmpty(termDaysStr))) {
            request.setAttribute("_ERROR_MESSAGE_",
                    UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
            return "error";
        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

    }

    //----------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_REFERENCIA";
    textValue = textValueRefNom2.toUpperCase();
    termValueStr = termValueRefTel2;

    termType = null;
    termValue = null;
    termDays = null;

    termSec++;

    if (UtilValidate.isNotEmpty(textValueRefNom2))

    {
        //        if (UtilValidate.isEmpty(termTypeId)) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //            return "error";
        //        }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr))
                || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId"))
                        && UtilValidate.isEmpty(termDaysStr))) {
            request.setAttribute("_ERROR_MESSAGE_",
                    UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
            return "error";
        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

    }

    //----------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_FECHA_INI";
    textValue = textValueDate;

    termType = null;
    termValue = null;
    termDays = null;

    termSec++;

    if (UtilValidate.isNotEmpty(textValueDate)) {

        //        if (UtilValidate.isEmpty(termTypeId)) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //            return "error";
        //        }

        textValueDate = textValueDate + " 00:00:00";
        termDate = Timestamp.valueOf(textValueDate);
        termDateIni = termDate;

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        //        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr)) || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId")) && UtilValidate.isEmpty(termDaysStr))) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
        //            return "error";
        //        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        //cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

    } else {
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "Debe Cargar Fecha",
                UtilMisc.toMap("textValueDate", textValueDate), locale));
        return "error";
    }
    //

    //---------------------------------------------------------------//

    termTypeId = null;
    termValueStr = null;
    termDaysStr = null;
    textValue = null;

    termTypeId = "CRD_DIA_VENCIMIENTO";
    termDaysStr = termValueVencimiento;

    termType = null;
    termValue = null;
    termDays = null;
    termDate = null;

    termSec++;

    if (UtilValidate.isNotEmpty(termValueVencimiento)) {

        //        if (UtilValidate.isEmpty(termTypeId)) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
        //            return "error";
        //        }

        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        //        if (("FIN_PAYMENT_TERM".equals(termTypeId) && UtilValidate.isEmpty(termDaysStr)) || (UtilValidate.isNotEmpty(termType) && "FIN_PAYMENT_TERM".equals(termType.get("parentTypeId")) && UtilValidate.isEmpty(termDaysStr))) {
        //            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error, "OrderOrderTermDaysIsRequired", locale));
        //            return "error";
        //        }

        if (UtilValidate.isNotEmpty(termValueStr)) {
            try {
                termValue = new BigDecimal(termValueStr);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        if (UtilValidate.isNotEmpty(termDaysStr)) {
            try {
                termDays = Long.valueOf(termDaysStr);
                DiaVencimiento = termDays;
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermDaysError", UtilMisc.toMap("orderTermDays", termDaysStr), locale));
                return "error";
            }
        }

        //removeOrderTerm(request, response);

        //cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

    } else {
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                "Debe Cargar Vencimiento", UtilMisc.toMap("textValueDate", textValueDate), locale));
        return "error";
    }
    //

    //---------------------------------------------------------------//

    int Cuotas = 0;
    BigDecimal MtTotal = null;
    BigDecimal MtAnticipo = null;
    BigDecimal MtCuota = null;
    BigDecimal CantCuotas = null;

    if (cart.getOrderType().equals("PURCHASE_ORDER")) {
        MtTotal = cart.getDisplayGrandTotal();// Para tomar el que tiene IVA
    } else {
        MtTotal = cart.getGrandTotal();
    }

    if (UtilValidate.isNotEmpty(termValueCuotas)) {
        //           if (UtilValidate.isNotEmpty(termValueCuotas)) {
        try {
            CantCuotas = new BigDecimal(termValueCuotas);
        } catch (NumberFormatException e) {
            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                    "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
            return "error";
        }
        //           }

        if (UtilValidate.isNotEmpty(termValueAnticipo)) {
            try {
                MtAnticipo = new BigDecimal(termValueAnticipo);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }

            MtTotal = MtTotal.subtract(MtAnticipo);
        }

        //CODIGOLINUX Redondea sin decimal
        MtCuota = MtTotal.divide(CantCuotas, generalRounding).setScale(0, ROUNDING);

        if (UtilValidate.isNotEmpty(termValueCuotas)) {
            try {
                Cuotas = Integer.parseInt(termValueCuotas);
            } catch (NumberFormatException e) {
                request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                        "OrderOrderTermValueError", UtilMisc.toMap("orderTermValue", termValueStr), locale));
                return "error";
            }
        }

        termTypeId = "CRD_CUOTA";
        if (UtilValidate.isEmpty(termTypeId)) {
            request.setAttribute("_ERROR_MESSAGE_",
                    UtilProperties.getMessage(resource_error, "OrderOrderTermTypeIsRequired", locale));
            return "error";
        }
        try {
            termType = delegator.findOne("TermType", UtilMisc.toMap("termTypeId", termTypeId), false);
        } catch (GenericEntityException gee) {
            request.setAttribute("_ERROR_MESSAGE_", gee.getMessage());
            return "error";
        }

        termValueStr = null;
        termDaysStr = null;
        textValue = null;

        termType = null;
        termValue = null;
        termDays = null;

        // termValue = BigDecimal.valueOf(x);

        //CODIGOLINUX
        TimeZone timeZone = UtilHttp.getTimeZone(request);

        termValue = MtCuota;

        termDate = termDateIni;

        int ultimoDiaProximoMes = 0;
        int sumar_dias = 1;
        Timestamp proximoMes = null;

        proximoMes = UtilDateTime.nowTimestamp();

        for (int x = 1; x <= Cuotas; x++) {

            textValue = textValueDate;

            textValue = "Nro." + String.valueOf(x);

            termDays = (long) x;

            termSec++;

            //removeOrderTerm(request, response);

            cart.addOrderTerm(termTypeId, termValue, termDays, textValue, termDate, termSec);

            termDate = UtilDateTime.getMonthEnd(termDate, timeZone, locale);

            proximoMes = UtilDateTime.addDaysToTimestamp(termDate, sumar_dias);

            termDate = UtilDateTime.getMonthEnd(proximoMes, timeZone, locale);

            ultimoDiaProximoMes = UtilDateTime.getDayOfMonth(termDate, timeZone, locale);

            if (ultimoDiaProximoMes > DiaVencimiento) {
                //termDate=UtilDateTime.adjustTimestamp(termDate, Calendar.DAY_OF_MONTH, DiaVencimiento.intValue(), timeZone, locale);
                //termDate=UtilDateTime.adjustTimestamp(termDate, Calendar.DAY_OF_MONTH, DiaVencimiento.intValue());

                termDate = UtilDateTime.toTimestamp(UtilDateTime.getMonth(proximoMes, timeZone, locale) + 1,
                        DiaVencimiento.intValue(), UtilDateTime.getYear(termDate, timeZone, locale), 0, 0, 0);
            } else {
                termDate = UtilDateTime.toTimestamp(UtilDateTime.getMonth(proximoMes, timeZone, locale) + 1,
                        ultimoDiaProximoMes, UtilDateTime.getYear(termDate, timeZone, locale), 0, 0, 0);
            }
        }
    } else {
        request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(resource_error,
                "Debe Ingresar Numero de Cuotas", UtilMisc.toMap("termValueCuotas", termValueCuotas), locale));
        return "error";
    }

    //---------------------------------------------------------------//

    return "success";
}

From source file:org.egov.ptis.service.es.CollectionIndexElasticSearchService.java

/**
 * Provides month wise DCB details across all ULBs
 * @param collectionDetailsRequest//  w  w  w .j a  v a2  s .  co  m
 * @param intervalType
 * @return list
 */
public List<MonthlyDCB> getMonthwiseDCBDetailsAcrossCities(
        final CollectionDetailsRequest collectionDetailsRequest, final String intervalType) {
    final List<MonthlyDCB> ulbWiseDetails = new ArrayList<>();
    Date fromDate = null;
    Date toDate = null;
    String monthName;
    Sum aggregateSum;
    Integer month;
    String aggregationField = StringUtils.EMPTY;
    Map<String, Object[]> monthwiseColl;
    Map<Integer, String> monthValuesMap = DateUtils.getAllMonthsWithFullNames();
    Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>();
    if (StringUtils.isNotBlank(collectionDetailsRequest.getType()))
        aggregationField = getAggregrationField(collectionDetailsRequest);

    if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType()))
        wardWiseBillCollectors = getWardWiseBillCollectors(collectionDetailsRequest);
    final Map<String, Map<String, Object[]>> ulbwiseMonthlyCollMap = new HashMap<>();
    if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD);
        toDate = DateUtils
                .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1);
    }

    final Map<String, BigDecimal> totalDemandMap = getCollectionAndDemandValues(collectionDetailsRequest,
            fromDate, toDate, PROPERTY_TAX_INDEX_NAME, TOTAL_DEMAND, aggregationField);
    final Aggregations collAggr = getMonthwiseCollectionsForConsecutiveYears(collectionDetailsRequest, fromDate,
            toDate, true, intervalType, aggregationField);
    final StringTerms cityaggr = collAggr.get(BY_CITY);
    BigDecimal totalDemand;
    BigDecimal monthlyDemand;
    int noOfMonths;
    Object[] demandCollValues;

    for (final Terms.Bucket cityDetailsentry : cityaggr.getBuckets()) {
        monthwiseColl = new LinkedHashMap<>();
        final String ulbName = cityDetailsentry.getKeyAsString();
        noOfMonths = 0;
        totalDemand = totalDemandMap.get(ulbName);

        if (totalDemand == null)
            totalDemand = BigDecimal.ZERO;
        final Histogram dateaggs = cityDetailsentry.getAggregations().get(DATE_AGG);
        for (final Histogram.Bucket entry : dateaggs.getBuckets()) {
            if (noOfMonths == 0)
                noOfMonths = 1;
            demandCollValues = new Object[12];
            String[] dateArr = entry.getKeyAsString().split("T");
            month = Integer.valueOf(dateArr[0].split("-", 3)[1]);
            monthName = monthValuesMap.get(month);
            monthlyDemand = totalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP)
                    .multiply(BigDecimal.valueOf(noOfMonths));
            aggregateSum = entry.getAggregations().get(CURRENT_TOTAL);

            if (BigDecimal.valueOf(aggregateSum.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP)
                    .compareTo(BigDecimal.ZERO) > 0) {
                demandCollValues[0] = BigDecimal.valueOf(aggregateSum.getValue()).setScale(0,
                        BigDecimal.ROUND_HALF_UP);
                demandCollValues[1] = monthlyDemand;
                monthwiseColl.put(monthName, demandCollValues);
            }
            noOfMonths++;
        }
        ulbwiseMonthlyCollMap.put(ulbName, monthwiseColl);
    }
    setMonthlyDCBValues(ulbWiseDetails, ulbwiseMonthlyCollMap, wardWiseBillCollectors);
    return ulbWiseDetails;
}

From source file:org.sakaiproject.component.gradebook.GradebookServiceHibernateImpl.java

@Override
public Double calculateCategoryScore(Long categoryId,
        List<org.sakaiproject.service.gradebook.shared.Assignment> assignments, Map<Long, String> gradeMap) {

    int numScored = 0;
    int numOfAssignments = 0;
    BigDecimal totalEarned = new BigDecimal("0");
    BigDecimal totalPossible = new BigDecimal("0");

    for (org.sakaiproject.service.gradebook.shared.Assignment assignment : assignments) {

        if (categoryId != assignment.getCategoryId()) {
            log.error("Category id: " + categoryId + " did not match assignment categoryId: "
                    + assignment.getCategoryId());
            return null;
        }//w ww .  j a  va2s  .c o m

        Long assignmentId = assignment.getId();

        String grade = gradeMap.get(assignmentId);

        //only update the variables for the calculation if:
        // 1. the assignment has points to be assigned
        // 2. there is a grade for the student 
        // 3. it's included in course grade calculations
        // 4. it's released to the student (safety check against condition 3)
        if (assignment.getPoints() != null && StringUtils.isNotBlank(grade) && assignment.isCounted()
                && assignment.isReleased()) {
            totalPossible = totalPossible.add(new BigDecimal(assignment.getPoints().toString()));
            numOfAssignments++;
            numScored++;
        }

        //sanitise grade
        if (StringUtils.isBlank(grade)) {
            grade = "0";
        }

        //update total points earned
        totalEarned = totalEarned.add(new BigDecimal(grade));
    }

    if (numScored == 0 || numOfAssignments == 0 || totalPossible.doubleValue() == 0) {
        return null;
    }

    BigDecimal mean = totalEarned.divide(new BigDecimal(numScored), GradebookService.MATH_CONTEXT)
            .divide((totalPossible.divide(new BigDecimal(numOfAssignments), GradebookService.MATH_CONTEXT)),
                    GradebookService.MATH_CONTEXT)
            .multiply(new BigDecimal("100"));
    return Double.valueOf(mean.doubleValue());
}