Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:la2launcher.MainFrame.java

private void processValidation(boolean full) {
    final long initTime = new Date().getTime();
    final String patcherUrl = "http://" + updateHost + "/hf/updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000)
    final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS,
            new ArrayBlockingQueue<Runnable>(10000));
    tpe.execute(new Runnable() {
        @Override/*from   www .  j a v a 2  s.c  om*/
        public void run() {
            jTextArea2.setText("");
            try {
                if (full) {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n?  ");
                } else {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n?  system");
                }
                File patcher = File.createTempFile("la2", "la2");
                patcher.deleteOnExit();
                File patcherExt = File.createTempFile("la2", "la2");
                patcherExt.deleteOnExit();
                FileOutputStream fos = new FileOutputStream(patcher);
                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(patcherUrl);
                CloseableHttpResponse response1 = httpclient.execute(httpGet);

                HttpEntity entity1 = response1.getEntity();
                copyStream(entity1.getContent(), fos, null);
                response1.close();
                fos.close();
                jTextArea2.setText(jTextArea2.getText()
                        + "\r\n??  ? ?: " + patcherUrl);

                fixBzip2File(patcher);
                jTextArea2.setText(jTextArea2.getText() + "\r\n ?");

                BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(patcher));
                OutputStream pout = new FileOutputStream(patcherExt);
                copyStream(bz, pout, new CopyListener() {
                    @Override
                    public void transfered(int n) {
                        bytesRecieved += n;
                        bytesRecievedTotal += n;
                    }
                });
                pout.close();
                bz.close();
                jTextArea2.setText(jTextArea2.getText() + "\r\n? ?");

                if (full) {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n  ");
                } else {
                    jTextArea2.setText(jTextArea2.getText()
                            + "\r\n     system");
                }

                DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
                model.setRowCount(0);

                int filesCount = scanSumFilesCount(patcherExt, full);
                jProgressBar1.setMinimum(0);
                jProgressBar1.setMaximum(filesCount);
                jProgressBar1.setValue(0);
                jLabel4.setText("0/" + filesCount);
                scanSumFile(patcherExt, new SumHandler() {

                    private ReentrantLock lock = new ReentrantLock();

                    @Override
                    public void handle(MDNamePair pair) {
                        try {
                            jProgressBar1.setIndeterminate(false);
                            //lock.unlock();
                            tpe.execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        lock.lock();
                                        //printMsg(pair.filename);
                                        String crc = digest(new File(gamePath + pair.filename));
                                        //printMsg("    : " + pair.crc);
                                        //printMsg("   ? ? : " + crc);
                                        if (!pair.crc.equals(crc)) {
                                            DefaultTableModel dtm = (DefaultTableModel) jTable2.getModel();
                                            dtm.addRow(new Object[] { pair.filename, false });
                                        }
                                        jProgressBar1.setValue(jProgressBar1.getValue() + 1);
                                        jLabel4.setText(jProgressBar1.getValue() + "/" + filesCount);
                                        lock.unlock();
                                    } catch (NoSuchAlgorithmException ex) {
                                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                                    } catch (IOException ex) {
                                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                                    } finally {
                                        //if (lock.isLocked()) lock.unlock();
                                    }
                                }
                            });
                        } finally {
                            //if (lock.isLocked()) lock.unlock();
                        }
                    }
                }, full);
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    jButton5.setEnabled(false);
    jButton6.setEnabled(false);
    jButton7.setEnabled(false);
    jButton8.setEnabled(false);
    jButton10.setEnabled(false);
    jProgressBar1.setIndeterminate(true);
    new Thread() {
        @Override
        public void run() {
            do {
                long millis = new Date().getTime();
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                millis = new Date().getTime() - millis;
                BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0));
                totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING);
                jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : "
                        + totBig + " MB");
                bytesRecieved = 0;
            } while (tpe.getActiveCount() > 0);
            tpe.shutdown();
            jButton5.setEnabled(true);
            jButton6.setEnabled(true);
            jButton7.setEnabled(true);
            jButton8.setEnabled(true);
            jButton10.setEnabled(true);
            jProgressBar1.setIndeterminate(false);
            printMsg("  " + (new Date().getTime() - initTime)
                    + " ?.");
        }
    }.start();
}

From source file:org.codecover.eclipse.views.RedundancyGraphView.java

private final void calculateSuiteRedundancy(String Criterion) {
    Set<CoverableItem> coverableItemSet = createCoverableItemSet(Criterion);
    Set<CoverableItem> mainSet = new HashSet<CoverableItem>(coverableItemSet);
    Set<CoverableItem> otherTestSet = new HashSet<CoverableItem>();
    if (Criterion.compareTo("Condition") != 0) {
        for (int i = 0; i < this.wholeTestCases.size(); i++) {
            TestCase currentTestCase = this.wholeTestCases.get(i);
            Set<CoverableItem> currentCoveredSet = new HashSet<CoverableItem>(
                    currentTestCase.getCoverageData().keySet());
            currentCoveredSet.retainAll(mainSet);
            int ts = currentCoveredSet.size();
            otherTestSet.clear();//from  w  w  w .ja v a2 s .c o  m
            for (int a = 0; a < this.wholeTestCases.size(); a++) {
                if (a != i) {
                    TestCase secondTestCase = this.wholeTestCases.get(a);
                    if (!this.RedundantTestCases.contains(secondTestCase)) {
                        Set<CoverableItem> secondSet = new HashSet<CoverableItem>(
                                secondTestCase.getCoverageData().keySet());
                        secondSet.retainAll(mainSet);
                        otherTestSet.addAll(secondSet);
                    }
                }
            }

            currentCoveredSet.retainAll(otherTestSet);
            double rts = currentCoveredSet.size();
            Double SuiteR = 0.0D;
            if (ts != 0.0D) {
                SuiteR = rts / ts;
            } else {
                SuiteR = (0.0D / 0.0D);
            }

            if (!SuiteR.isNaN()) {
                BigDecimal bd = new BigDecimal(SuiteR);
                bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                SuiteR = bd.doubleValue();
            }
            if (this.RedundantTestCases.contains(currentTestCase)) {
                this.SuiteRedundancy.put(currentTestCase.getName(), 1.0);
            } else {
                this.SuiteRedundancy.put(currentTestCase.getName(), SuiteR);
            }
        }
    } else {
        for (int i = 0; i < this.wholeTestCases.size(); i++) {
            TestCase currentTestCase = this.wholeTestCases.get(i);
            Set<CoverableItem> currentCoveredSet = new HashSet<CoverableItem>(
                    currentTestCase.getAssignmentsMap().keySet());
            currentCoveredSet.retainAll(mainSet);
            int amountFirstTestCase = 0;
            for (CoverableItem item : currentCoveredSet) {
                BooleanAssignmentMap map = currentTestCase.getAssignmentsMap().get(item);
                amountFirstTestCase += map.getEvaluatedAssignments().size();
            }

            int ts = amountFirstTestCase;
            int amountIntersection = 0;
            for (CoverableItem item : currentCoveredSet) {
                BooleanAssignmentMap map1 = currentTestCase.getAssignmentsMap().get(item);
                Set<BooleanAssignment> sharedAssignments = new HashSet<BooleanAssignment>(
                        map1.getEvaluatedAssignments());
                Set<BooleanAssignment> otherAssignments = new HashSet<BooleanAssignment>();
                for (int a = 0; a < this.wholeTestCases.size(); a++) {
                    if (a != i) {
                        TestCase secondTestCase = this.wholeTestCases.get(a);
                        if (!this.RedundantTestCases.contains(secondTestCase)) {
                            Set<CoverableItem> secondSet = new HashSet<CoverableItem>(
                                    secondTestCase.getAssignmentsMap().keySet());
                            secondSet.retainAll(mainSet);
                            if (secondSet.contains(item)) {
                                BooleanAssignmentMap map2 = secondTestCase.getAssignmentsMap().get(item);
                                otherAssignments.addAll(map2.getEvaluatedAssignments());
                            }
                        }
                    }
                }

                sharedAssignments.retainAll(otherAssignments);
                amountIntersection += sharedAssignments.size();
            }

            double rts = amountIntersection;
            Double SuiteR = 0.0D;
            if (ts != 0.0D) {
                SuiteR = rts / ts;
            } else {
                SuiteR = (0.0D / 0.0D);
            }

            if (!SuiteR.isNaN()) {
                BigDecimal bd = new BigDecimal(SuiteR);
                bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                SuiteR = bd.doubleValue();
            }
            this.SuiteRedundancy.put(currentTestCase.getName(), SuiteR);
        }
    }
}

From source file:org.codecover.eclipse.views.RedundancyGraphView.java

private final void calculatePairRedundancy(String Criterion) {
    Set<CoverableItem> coverableItemSet = createCoverableItemSet(Criterion);
    Set<CoverableItem> mainSet = new HashSet<CoverableItem>(coverableItemSet);
    if (Criterion.compareTo("Condition") != 0) {
        for (int i = 0; i < this.wholeTestCases.size(); i++) {
            TestCase currentTestCase = this.wholeTestCases.get(i);
            Set<CoverableItem> currentCoveredSet = new HashSet<CoverableItem>(
                    currentTestCase.getCoverageData().keySet());
            currentCoveredSet.retainAll(mainSet);
            double ts = currentCoveredSet.size();

            double rts;
            Double PairR = 0.0D;//from   w  ww .  j  a  va  2 s . c o m
            for (int a = 0; a < this.wholeTestCases.size(); a++) {
                if (a != i) {
                    TestCase secondTestCase = this.wholeTestCases.get(a);
                    Set<CoverableItem> secondSet = new HashSet<CoverableItem>(
                            secondTestCase.getCoverageData().keySet());
                    secondSet.retainAll(mainSet);
                    secondSet.retainAll(currentCoveredSet);
                    rts = secondSet.size();
                    PairR = 0.0D;
                    if (ts != 0.0D) {
                        PairR = rts / ts;
                    } else {
                        PairR = (0.0D / 0.0D);
                    }
                    TestCasePair tcp = new TestCasePair();
                    tcp.CurrentTest = currentTestCase.getName();
                    tcp.WithRespectTo = secondTestCase.getName();
                    if (this.selectedTestCases.contains(currentTestCase)) {
                        tcp.selected = true;
                    } else {
                        tcp.selected = false;
                    }
                    if (!PairR.isNaN()) {
                        BigDecimal bd = new BigDecimal(PairR);
                        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                        PairR = bd.doubleValue();
                    }
                    this.PairRedundancy.put(tcp, PairR);
                }
            }
        }
    } else {
        Map<TestCase, Integer> totalCoverableItemCount = new HashMap<TestCase, Integer>();
        for (int i = 0; i < this.wholeTestCases.size(); i++) {
            TestCase currentTestCase = this.wholeTestCases.get(i);
            Set<CoverableItem> currentCoveredSet = new HashSet<CoverableItem>(
                    currentTestCase.getAssignmentsMap().keySet());
            currentCoveredSet.retainAll(mainSet);
            int amountFirstTestCase = 0;
            for (CoverableItem item : currentCoveredSet) {
                BooleanAssignmentMap map = currentTestCase.getAssignmentsMap().get(item);
                amountFirstTestCase += map.getEvaluatedAssignments().size();
            }

            double ts = amountFirstTestCase;
            totalCoverableItemCount.put(currentTestCase, Integer.valueOf(amountFirstTestCase));
            for (int a = 0; a < this.wholeTestCases.size(); a++) {
                if (a != i) {
                    TestCase secondTestCase = this.wholeTestCases.get(a);
                    Set<CoverableItem> secondSet = new HashSet<CoverableItem>(
                            secondTestCase.getAssignmentsMap().keySet());
                    secondSet.retainAll(mainSet);
                    secondSet.retainAll(currentCoveredSet);
                    int amountIntersection = 0;
                    for (CoverableItem item : secondSet) {
                        BooleanAssignmentMap map1 = currentTestCase.getAssignmentsMap().get(item);
                        BooleanAssignmentMap map2 = secondTestCase.getAssignmentsMap().get(item);
                        Set<BooleanAssignment> sharedAssignments = new HashSet<BooleanAssignment>(
                                map1.getEvaluatedAssignments());
                        sharedAssignments.retainAll(map2.getEvaluatedAssignments());
                        amountIntersection += sharedAssignments.size();
                    }

                    double rts = amountIntersection;
                    Double PairR = 0.0D;
                    if (ts != 0.0D) {
                        PairR = rts / ts;
                    } else {
                        PairR = (0.0D / 0.0D);
                    }
                    TestCasePair tcp = new TestCasePair();
                    tcp.CurrentTest = currentTestCase.getName();
                    tcp.WithRespectTo = secondTestCase.getName();
                    if (!PairR.isNaN()) {
                        BigDecimal bd = new BigDecimal(PairR);
                        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                        PairR = bd.doubleValue();
                    }
                    this.PairRedundancy.put(tcp, PairR);
                }
            }
        }
    }
}

From source file:org.kalypso.kalypsomodel1d2d.ui.map.flowrel.FlowRelationshipCalcOperation.java

private QIntervallResult runCalculation(final TuhhCalculation templateCalculation,
        final IFlowRelation1D flowRel, final IProfile[] profiles, final IProgressMonitor monitor)
        throws InvocationTargetException {
    File tmpDir = null;/*from   w  w w . j  a va  2 s  .  co  m*/
    try {
        tmpDir = SimulationUtilitites.createSimulationTmpDir("" + System.currentTimeMillis()); //$NON-NLS-1$

        final TuhhCalculation calculation = createCalculation(flowRel, templateCalculation, profiles);

        // Prepare wspm model
        final File modelFile = new File(tmpDir, "modell.gml"); //$NON-NLS-1$
        final GMLWorkspace calcWorkspace = calculation.getWorkspace();
        GmlSerializer.serializeWorkspace(modelFile, calcWorkspace, Charset.defaultCharset().name());

        // prepare calcjob
        final WspmTuhhCalcJob wspmTuhhCalcJob = new WspmTuhhCalcJob(new PrintStream(m_outputStream));
        final DefaultSimulationDataProvider inputProvider = new DefaultSimulationDataProvider();
        inputProvider.put(WspmTuhhCalcJob.INPUT_MODELL_GML, modelFile.toURI().toURL());
        inputProvider.put(WspmTuhhCalcJob.INPUT_CALC_PATH, new GMLXPath(calculation).toString());
        // eps-thinning is big, as we do not need the tin result and bigger is faster
        inputProvider.put(WspmTuhhCalcJob.INPUT_EPS_THINNING, "100.0"); //$NON-NLS-1$

        final DefaultSimulationResultEater resultEater = new DefaultSimulationResultEater();
        final NullSimulationMonitorExtension simMonitor = new NullSimulationMonitorExtension(monitor);

        wspmTuhhCalcJob.run(tmpDir, inputProvider, resultEater, simMonitor);

        if (simMonitor.getFinishStatus() != IStatus.OK)
            throw new CoreException(new Status(simMonitor.getFinishStatus(), KalypsoModel1D2DPlugin.PLUGIN_ID,
                    simMonitor.getFinishText()));

        // read simulation log
        final File logFile = (File) resultEater.getResult(WspmTuhhCalcJob.OUTPUT_SIMULATION_LOG);
        m_consoleText = FileUtils.readFileToString(logFile, Charset.defaultCharset().name());

        // read interval results and remember them
        final File qintervallFile = (File) resultEater.getResult(WspmTuhhCalcJob.OUTPUT_QINTERVALL_RESULT);
        final GMLWorkspace qresultsWorkspace = GmlSerializer.createGMLWorkspace(qintervallFile,
                calcWorkspace.getFeatureProviderFactory());
        final QIntervallResultCollection qResultCollection = (QIntervallResultCollection) qresultsWorkspace
                .getRootFeature();

        final IFeatureBindingCollection<QIntervallResult> resultList = qResultCollection.getQIntervalls();
        for (final QIntervallResult qresult : resultList) {
            final BigDecimal flowStation = flowRel.getStation();
            if (flowStation == null) {
                final String message = String.format(Messages.getString("FlowRelationshipCalcOperation.0"), //$NON-NLS-1$
                        flowRel.getName());
                throw new CoreException(
                        new Status(IStatus.ERROR, KalypsoModel1D2DPlugin.PLUGIN_ID, message, null)); //$NON-NLS-1$
            }

            // HACK: we set a scale here in order to get a right comparison with the station value that was read from the
            // profile. if a rounded station value occurs in the flow relation, the result of the comparison is always
            // false, because the station value of the flow relation gets rounded and the one of the profile gets not
            // rounded (read from string with fixed length).
            // TODO: implement the right setting of the station value for the flow relation with a fixed scale of 4!
            final BigDecimal station = flowStation.setScale(4, BigDecimal.ROUND_HALF_UP);

            // FIXME: why do we use the station defined in the relation at all -> the calculation uses the station defined
            // in the profile anyways

            // REMARK: sometimes it could be, that the user wants to assign a profile to a new created flow relation. in
            // this case he is able to to this and to calculate the data, but the assignment will never happen, if the
            // station is not equal to the station of the assigned profile.
            if (ObjectUtils.equals(station, qresult.getStation()))
                return qresult;
        }

        final String message = Messages
                .getString("org.kalypso.kalypsomodel1d2d.ui.map.flowrel.FlowRelationshipCalcOperation.14"); //$NON-NLS-1$
        throw new CoreException(new Status(IStatus.ERROR, KalypsoModel1D2DPlugin.PLUGIN_ID, message));
    } catch (final InvocationTargetException e) {
        throw e;
    } catch (final GMLSchemaException e) {
        throw new InvocationTargetException(e);
    } catch (final IOException e) {
        throw new InvocationTargetException(e);
    } catch (final GmlSerializeException e) {
        throw new InvocationTargetException(e);
    } catch (final SimulationException e) {
        throw new InvocationTargetException(e);
    } catch (final GMLXPathException e) {
        throw new InvocationTargetException(e);
    } catch (final Exception e) {
        throw new InvocationTargetException(e);
    } finally {
        SimulationUtilitites.clearTmpDir(tmpDir);
    }
}

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

/**
 * @see org.kuali.kfs.module.purap.service.PurapAccountingService#convertMoneyToPercent(org.kuali.kfs.module.purap.document.PaymentRequestDocument)
 *///from  www .j  a v a2 s  .  c o  m
@Override
public void convertMoneyToPercent(PaymentRequestDocument pr) {
    LOG.debug("convertMoneyToPercent() started");

    int itemNbr = 0;

    for (Iterator<PaymentRequestItem> iter = pr.getItems().iterator(); iter.hasNext();) {
        PaymentRequestItem item = iter.next();

        itemNbr++;
        String identifier = item.getItemIdentifierString();

        if (item.getTotalAmount() != null && item.getTotalAmount().isNonZero()) {
            int numOfAccounts = item.getSourceAccountingLines().size();
            BigDecimal percentTotal = BigDecimal.ZERO;
            BigDecimal percentTotalRoundUp = BigDecimal.ZERO;
            KualiDecimal accountTotal = KualiDecimal.ZERO;
            int accountIdentifier = 0;

            for (Iterator<PurApAccountingLine> iterator = item.getSourceAccountingLines().iterator(); iterator
                    .hasNext();) {
                accountIdentifier++;
                PaymentRequestAccount account = (PaymentRequestAccount) iterator.next();

                // account.getAmount returns the wrong value for trade in source accounting lines...
                KualiDecimal accountAmount = KualiDecimal.ZERO;
                if (ObjectUtils.isNotNull(account.getAmount())) {
                    accountAmount = account.getAmount();
                }

                BigDecimal tmpPercent = BigDecimal.ZERO;
                KualiDecimal extendedPrice = item.getTotalAmount();
                tmpPercent = accountAmount.bigDecimalValue().divide(extendedPrice.bigDecimalValue(),
                        PurapConstants.CREDITMEMO_PRORATION_SCALE.intValue(), KualiDecimal.ROUND_BEHAVIOR);

                if (accountIdentifier == numOfAccounts) {
                    // if on last account, calculate the percent by subtracting current percent total from 1
                    tmpPercent = BigDecimal.ONE.subtract(percentTotal);
                }

                // test that the above amount is correct, if so just check that the total of all these matches the item total
                BigDecimal calcAmountBd = tmpPercent.multiply(extendedPrice.bigDecimalValue());
                calcAmountBd = calcAmountBd.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR);
                KualiDecimal calcAmount = new KualiDecimal(calcAmountBd);
                if (calcAmount.compareTo(accountAmount) != 0) {
                    // rounding error
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("convertMoneyToPercent() Rounding error on " + account);
                    }
                    String param1 = identifier + "." + accountIdentifier;
                    String param2 = calcAmount.bigDecimalValue().subtract(accountAmount.bigDecimalValue())
                            .toString();
                    GlobalVariables.getMessageMap().putError(item.getItemIdentifierString(),
                            PurapKeyConstants.ERROR_ITEM_ACCOUNTING_ROUNDING, param1, param2);
                    account.setAmount(calcAmount);
                }

                // update percent
                if (LOG.isDebugEnabled()) {
                    LOG.debug("convertMoneyToPercent() updating percent to " + tmpPercent);
                }
                account.setAccountLinePercent(tmpPercent.multiply(new BigDecimal(100)));
                // handle 33.33% issue
                if (accountIdentifier == numOfAccounts) {
                    account.setAccountLinePercent(new BigDecimal(100).subtract(percentTotalRoundUp));
                }

                // check total based on adjusted amount
                accountTotal = accountTotal.add(calcAmount);
                percentTotal = percentTotal.add(tmpPercent);
                percentTotalRoundUp = percentTotalRoundUp.add(account.getAccountLinePercent());
            }
        }
    }
}

From source file:de.appsolve.padelcampus.utils.BookingUtil.java

public List<TimeSlot> getTimeSlotsForDate(LocalDate selectedDate, List<CalendarConfig> allCalendarConfigs,
        List<Booking> existingBookings, Boolean onlyFutureTimeSlots, Boolean preventOverlapping)
        throws CalendarConfigException {

    List<CalendarConfig> calendarConfigs = calendarConfigUtil.getCalendarConfigsMatchingDate(allCalendarConfigs,
            selectedDate);/*from   w  w  w. j  a v  a  2  s.c om*/
    Iterator<CalendarConfig> iterator = calendarConfigs.iterator();
    while (iterator.hasNext()) {
        CalendarConfig calendarConfig = iterator.next();
        if (isHoliday(selectedDate, calendarConfig)) {
            iterator.remove();
        }
    }

    List<TimeSlot> timeSlots = new ArrayList<>();
    if (calendarConfigs.size() > 0) {
        LocalDate today = new LocalDate(DEFAULT_TIMEZONE);

        //sort all calendar configurations for selected date by start time
        Collections.sort(calendarConfigs);

        CalendarConfig previousConfig = null;
        LocalDateTime time = null;
        LocalDateTime now = new LocalDateTime(DEFAULT_TIMEZONE);

        //generate list of bookable time slots
        int i = 0;
        for (CalendarConfig config : calendarConfigs) {
            i++;
            LocalDateTime startDateTime = getLocalDateTime(selectedDate, config.getStartTime());
            if (time == null) {
                //on first iteration
                time = startDateTime;
            } else if (!time.plusMinutes(previousConfig.getMinInterval()).equals(startDateTime)) {
                //reset basePriceLastConfig as this is a non contiguous offer
                previousConfig = null;
                time = startDateTime;
            }
            LocalDateTime endDateTime = getLocalDateTime(selectedDate, config.getEndTime());
            while (time.plusMinutes(config.getMinDuration()).compareTo(endDateTime) <= 0) {
                BigDecimal pricePerMinDuration;
                if (previousConfig == null) {
                    pricePerMinDuration = config.getBasePrice();
                } else {
                    BigDecimal previousConfigBasePricePerMinute = getPricePerMinute(previousConfig);
                    pricePerMinDuration = previousConfigBasePricePerMinute
                            .multiply(new BigDecimal(previousConfig.getMinInterval()), MathContext.DECIMAL128);
                    BigDecimal basePricePerMinute = getPricePerMinute(config);
                    pricePerMinDuration = pricePerMinDuration.add(basePricePerMinute.multiply(
                            new BigDecimal(config.getMinDuration() - previousConfig.getMinInterval()),
                            MathContext.DECIMAL128));
                    previousConfig = null;
                }
                pricePerMinDuration = pricePerMinDuration.setScale(2, RoundingMode.HALF_EVEN);
                if (onlyFutureTimeSlots) {
                    if (selectedDate.isAfter(today) || time.isAfter(now)) {
                        addTimeSlot(timeSlots, time, config, pricePerMinDuration);
                    }
                } else {
                    addTimeSlot(timeSlots, time, config, pricePerMinDuration);
                }
                time = time.plusMinutes(config.getMinInterval());
            }
            //make sure to display the last min interval of the day
            if (config.getMinInterval() < config.getMinDuration() && i == calendarConfigs.size()) {
                if (time.plusMinutes(config.getMinInterval()).compareTo(endDateTime) <= 0) {
                    addTimeSlot(timeSlots, time, config, null);
                }
            }
            previousConfig = config;
        }
        //sort time slots by time
        Collections.sort(timeSlots);

        //decrease court count for every blocking booking
        for (TimeSlot timeSlot : timeSlots) {
            checkForBookedCourts(timeSlot, existingBookings, preventOverlapping);
        }
    }
    return timeSlots;
}

From source file:org.kawanfw.sql.jdbc.CallableStatementHttp.java

@Override
public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException {
    testIfClosed();//from   w  w w. j a  va 2s .c o m

    if (scale < 0) {
        throw new SQLException("invalid scale: " + scale + ". Scale must be >= 0");
    }

    BigDecimal bd = (BigDecimal) callableStatementHolder.getParameter(parameterIndex);

    if (bd != null) {
        bd = bd.setScale(scale, BigDecimal.ROUND_DOWN);
    }

    return bd;

}

From source file:eu.europa.ec.fisheries.uvms.rules.service.business.AbstractFact.java

public int numberOfDecimals(BigDecimal value) {
    if (value == null) {
        return -1;
    }/*from   ww w. j  a va 2s.  c  o  m*/

    int i = value.subtract(value.setScale(0, RoundingMode.FLOOR)).movePointRight(value.scale()).intValue();
    return Integer.toString(i).length();
}

From source file:org.libreplan.business.orders.entities.OrderElement.java

public boolean isFinishedAdvance() {
    BigDecimal measuredProgress = getAdvancePercentage();
    measuredProgress = measuredProgress.setScale(0, BigDecimal.ROUND_UP).multiply(new BigDecimal(100));

    return measuredProgress.compareTo(new BigDecimal(100)) == 0;
}

From source file:org.adempiere.webui.apps.graph.WGraph.java

private void renderTable(Component parent) {
    Div div = new Div();
    appendChild(div);/*from   w  w  w  .ja v a2s. c o  m*/
    div.setSclass("pa-content");
    parent.appendChild(div);

    Table table = new Table();
    table.setSclass("pa-dataGrid");
    div.appendChild(table);
    Tr tr = new Tr();
    table.appendChild(tr);
    Td td = new Td();
    td.setSclass("pa-label");
    tr.appendChild(td);
    Text text = new Text("Target");
    td.appendChild(text);
    td = new Td();
    td.setDynamicProperty("colspan", "2");
    td.setSclass("pa-tdcontent");
    tr.appendChild(td);
    text = new Text(
            builder.getMGoal().getMeasureTarget().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    td.appendChild(text);

    tr = new Tr();
    table.appendChild(tr);
    td = new Td();
    td.setSclass("pa-label");
    tr.appendChild(td);
    text = new Text("Actual");
    td.appendChild(text);
    td = new Td();
    td.setDynamicProperty("colspan", "2");
    td.setSclass("pa-tdcontent");
    tr.appendChild(td);
    text = new Text(
            builder.getMGoal().getMeasureActual().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    td.appendChild(text);

    GraphColumn[] bList = getGraphColumnList();

    tr = new Tr();
    table.appendChild(tr);
    td = new Td();
    tr.appendChild(td);
    td.setDynamicProperty("rowspan", bList.length);
    td.setSclass("pa-label");
    td.setDynamicProperty("valign", "top");
    text = new Text(builder.getMGoal().getXAxisText());
    td.appendChild(text);

    for (int k = 0; k < bList.length; k++) {
        GraphColumn bgc = bList[k];
        if (k > 0) {
            tr = new Tr();
            table.appendChild(tr);
        }

        td = new Td();
        td.setSclass("pa-tdlabel");
        tr.appendChild(td);
        text = new Text(bgc.getLabel());
        td.appendChild(text);
        td = new Td();
        td.setSclass("pa-tdvalue");
        tr.appendChild(td);
        BigDecimal value = new BigDecimal(bgc.getValue());
        if (bgc.getMQuery(builder.getMGoal()) != null) {
            A a = new A();
            a.setSclass("pa-hrefNode");
            td.appendChild(a);
            a.setId(ZOOM_KEY + k);
            a.addEventListener(Events.ON_CLICK, new EventListener() {
                public void onEvent(Event event) throws Exception {
                    Component comp = event.getTarget();
                    String id = comp.getId();
                    if (id.startsWith(ZOOM_KEY)) {
                        String ss = id.substring(ZOOM_KEY.length());
                        int index = Integer.parseInt(String.valueOf(ss));
                        GraphColumn[] colList = getGraphColumnList();
                        if ((index >= 0) && (index < colList.length))
                            AEnv.zoom(colList[index].getMQuery(builder.getMGoal()));
                    }
                }

            });
            a.setDynamicProperty("href", "javascript:;");
            text = new Text(value.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            a.appendChild(text);

        } else {
            text = new Text(value.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        }
    }
    tr = new Tr();
    table.appendChild(tr);
    td = new Td();
    td.setDynamicProperty("colspan", "3");
    tr.appendChild(td);
    text = new Text(builder.getMGoal().getDescription());
    td.appendChild(text);
    Br br = new Br();
    td.appendChild(br);
    text = new Text(stripHtml(builder.getMGoal().getColorSchema().getDescription(), true));
    td.appendChild(text);
}