Example usage for java.math BigDecimal multiply

List of usage examples for java.math BigDecimal multiply

Introduction

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

Prototype

private static long multiply(long x, long y) 

Source Link

Usage

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

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

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

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

        if (!isTjDivisable) {
            cyclesPerOperation = cyclesPerOperation.setScale(0, RoundingMode.CEILING);
        }/*www .  j a v a  2s  .com*/
    }

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

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

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

    return operationTime;
}

From source file: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  ww w  . ja  va2 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:de.appsolve.padelcampus.utils.BookingUtil.java

public OfferDurationPrice getOfferDurationPrice(List<CalendarConfig> configs, List<Booking> confirmedBookings,
        LocalDate selectedDate, LocalTime selectedTime, Offer selectedOffer) throws CalendarConfigException {
    List<TimeSlot> timeSlotsForDate = getTimeSlotsForDate(selectedDate, configs, confirmedBookings,
            Boolean.TRUE, Boolean.TRUE);
    boolean validStartTime = false;
    for (TimeSlot timeSlot : timeSlotsForDate) {
        if (timeSlot.getStartTime().equals(selectedTime)) {
            validStartTime = true;//from   w  ww .  ja  v  a 2s .com
            break;
        }
    }

    OfferDurationPrice offerDurationPrices = null;
    if (validStartTime) {
        //convert to required data structure
        Map<Offer, List<CalendarConfig>> offerConfigMap = new HashMap<>();
        for (CalendarConfig config : configs) {
            for (Offer offer : config.getOffers()) {
                if (offer.equals(selectedOffer)) {
                    List<CalendarConfig> list = offerConfigMap.get(offer);
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    list.add(config);

                    //sort by start time
                    Collections.sort(list);
                    offerConfigMap.put(offer, list);
                }
            }
        }

        Iterator<Map.Entry<Offer, List<CalendarConfig>>> iterator = offerConfigMap.entrySet().iterator();
        //for every offer
        while (iterator.hasNext()) {
            Map.Entry<Offer, List<CalendarConfig>> entry = iterator.next();
            Offer offer = entry.getKey();
            List<CalendarConfig> configsForOffer = entry.getValue();

            //make sure the first configuration starts before the requested booking time
            if (selectedTime.compareTo(configsForOffer.get(0).getStartTime()) < 0) {
                continue;
            }

            LocalDateTime endTime = null;
            Integer duration = configsForOffer.get(0).getMinDuration();
            BigDecimal pricePerMinute;
            BigDecimal price = null;
            CalendarConfig previousConfig = null;
            Map<Integer, BigDecimal> durationPriceMap = new TreeMap<>();
            Boolean isContiguous = true;
            for (CalendarConfig config : configsForOffer) {

                //make sure there is no gap between calendar configurations
                if (endTime == null) {
                    //first run
                    endTime = getLocalDateTime(selectedDate, selectedTime).plusMinutes(config.getMinDuration());
                } else {
                    //break if there are durations available and calendar configs are not contiguous
                    if (!durationPriceMap.isEmpty()) {
                        //we substract min interval before the comparison as it has been added during the last iteration
                        LocalDateTime configStartDateTime = getLocalDateTime(selectedDate,
                                config.getStartTime());
                        if (!endTime.minusMinutes(config.getMinInterval()).equals(configStartDateTime)) {
                            break;
                        }
                    }
                }

                Integer interval = config.getMinInterval();

                pricePerMinute = getPricePerMinute(config);

                //as long as the endTime is before the end time configured in the calendar
                LocalDateTime configEndDateTime = getLocalDateTime(selectedDate, config.getEndTime());
                while (endTime.compareTo(configEndDateTime) <= 0) {
                    TimeSlot timeSlot = new TimeSlot();
                    timeSlot.setDate(selectedDate);
                    timeSlot.setStartTime(selectedTime);
                    timeSlot.setEndTime(endTime.toLocalTime());
                    timeSlot.setConfig(config);
                    Long bookingSlotsLeft = getBookingSlotsLeft(timeSlot, offer, confirmedBookings);

                    //we only allow contiguous bookings for any given offer
                    if (bookingSlotsLeft < 1) {
                        isContiguous = false;
                        break;
                    }

                    if (price == null) {
                        //see if previousConfig endTime - minInterval matches the selected time. if so, take half of the previous config price as a basis
                        if (previousConfig != null && previousConfig.getEndTime()
                                .minusMinutes(previousConfig.getMinInterval()).equals(selectedTime)) {
                            BigDecimal previousConfigPricePerMinute = getPricePerMinute(previousConfig);
                            price = previousConfigPricePerMinute.multiply(
                                    new BigDecimal(previousConfig.getMinInterval()), MathContext.DECIMAL128);
                            price = price.add(pricePerMinute.multiply(
                                    new BigDecimal(duration - previousConfig.getMinInterval()),
                                    MathContext.DECIMAL128));
                        } else {
                            price = pricePerMinute.multiply(new BigDecimal(duration.toString()),
                                    MathContext.DECIMAL128);
                        }
                    } else {
                        //add price for additional interval
                        price = price.add(pricePerMinute.multiply(new BigDecimal(interval.toString()),
                                MathContext.DECIMAL128));
                    }
                    price = price.setScale(2, RoundingMode.HALF_EVEN);
                    durationPriceMap.put(duration, price);

                    //increase the duration by the configured minimum interval and determine the new end time for the next iteration
                    duration += interval;
                    endTime = endTime.plusMinutes(interval);
                }

                if (!durationPriceMap.isEmpty()) {
                    OfferDurationPrice odp = new OfferDurationPrice();
                    odp.setOffer(offer);
                    odp.setDurationPriceMap(durationPriceMap);
                    odp.setConfig(config);
                    offerDurationPrices = odp;
                }

                if (!isContiguous) {
                    //we only allow coniguous bookings for one offer. process next offer
                    break;
                }
                previousConfig = config;

            }
        }
    }
    return offerDurationPrices;
}

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

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

    BigDecimal percentageOf = BigDecimal.ZERO;

    if (isGreaterThanZero(value)) {
        final MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
        final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc);
        percentageOf = value.multiply(multiplicand, mc);
    }/*ww  w .  j a v  a2s . c  o m*/

    return percentageOf;
}

From source file:com.gst.portfolio.savings.domain.SavingsAccountCharge.java

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

    BigDecimal percentageOf = BigDecimal.ZERO;

    if (isGreaterThanZero(value)) {
        final MathContext mc = new MathContext(8, MoneyHelper.getRoundingMode());
        final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc);
        percentageOf = value.multiply(multiplicand, mc);
    }/*from ww  w.  j a  va2 s  .c  o  m*/

    return percentageOf;
}

From source file:org.mifosplatform.portfolio.loanaccount.service.LoanReadPlatformServiceImpl.java

private String exportToExcel(String jsonObjectInString) {

    int rownum = 0;

    JsonObject jsonObject = this.fromApiJsonHelper.parse(jsonObjectInString).getAsJsonObject();

    JsonArray array = jsonObject.getAsJsonArray("payTerms");

    JsonObject arrayFirstJson = array.get(0).getAsJsonObject();

    Set<Entry<String, JsonElement>> keys = arrayFirstJson.entrySet();

    ArrayList<String> arrayList = new ArrayList<String>();

    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Loan_Calculator");

    for (Entry<String, JsonElement> key : keys) {

        String keyval = key.getKey();
        arrayList.add(keyval);/*from   www  . j a v a 2 s.c  o m*/
        Row row = sheet.createRow(rownum);
        Cell cell = row.createCell(0);
        cell.setCellValue(keyval);
        rownum++;
    }

    for (int i = 1; i <= array.size(); i++) {

        JsonObject jsonObj = array.get(i - 1).getAsJsonObject();

        for (int j = 0; j < arrayList.size(); j++) {

            Row row = sheet.getRow(j);
            String keyName = arrayList.get(j);

            if (j == 0) {
                row.createCell(i).setCellValue(Integer.parseInt(jsonObj.get(keyName).toString()));
            } else {
                BigDecimal finalValue = jsonObj.get(keyName).getAsBigDecimal();
                if (keyName.equalsIgnoreCase("residualDeprecisation")
                        || keyName.equalsIgnoreCase("residualCost")) {
                    finalValue = finalValue.multiply(HUNDERED, mc).setScale(2, BigDecimal.ROUND_HALF_UP);
                    row.createCell(i).setCellValue(String.valueOf(finalValue) + "%");
                } else {
                    finalValue = finalValue.setScale(2, BigDecimal.ROUND_HALF_UP);
                    row.createCell(i).setCellValue(String.valueOf(finalValue));
                }
            }
        }
    }

    try {

        String location = getFileLocation(XLSX_FILE_EXTENSION);
        File file = new File(location);
        file.createNewFile();
        FileOutputStream out = new FileOutputStream(file);
        workbook.write(out);
        out.close();
        return location;

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.kuali.kpme.tklm.time.timeblock.service.TimeBlockServiceImpl.java

@Override
public List<TimeBlock> resetTimeHourDetail(List<TimeBlock> origTimeBlocks) {
    List<TimeBlockBo> originalBos = ModelObjectUtils.transform(origTimeBlocks, toTimeBlockBo);
    Collections.sort(originalBos, new Comparator<TimeBlockBo>() {

        @Override//from   w w  w  .j  ava 2 s. c  om
        public int compare(TimeBlockBo o1, TimeBlockBo o2) {
            return o1.getEndDateTime().compareTo(o2.getEndDateTime().toInstant());
        }

    });
    TimeBlockBo previousTimeBlock = null;
    for (TimeBlockBo tb : originalBos) {
        EarnCode earnCodeObj = HrServiceLocator.getEarnCodeService().getEarnCode(tb.getEarnCode(),
                tb.getBeginDateTime().toLocalDate());
        if (tb.getBeginTime() != null && tb.getEndTime() != null
                && StringUtils.equals(tb.getEarnCodeType(), HrConstants.EARN_CODE_TIME)) {
            BigDecimal hours = TKUtils.getHoursBetween(tb.getBeginDateTime().getMillis(),
                    tb.getEndDateTime().getMillis());

            //If earn code has an inflate min hours check if it is greater than zero
            //and compare if the hours specified is less than min hours awarded for this
            //earn code
            if (previousTimeBlock != null
                    && StringUtils.equals(earnCodeObj.getEarnCode(), previousTimeBlock.getEarnCode())
                    && (tb.getBeginTime().getMillisOfDay()
                            - previousTimeBlock.getEndTime().getMillisOfDay() == 0L)) {
                List<TimeHourDetailBo> newDetails = new ArrayList<TimeHourDetailBo>();
                BigDecimal prevTimeBlockHours = TKUtils.getHoursBetween(
                        previousTimeBlock.getBeginDateTime().getMillis(),
                        previousTimeBlock.getEndDateTime().getMillis());
                previousTimeBlock.setHours(prevTimeBlockHours);
                BigDecimal cummulativeHours = prevTimeBlockHours.add(hours, HrConstants.MATH_CONTEXT);
                //remove any inflation done when resetting the previous time block's hours.
                previousTimeBlock.setTimeHourDetails(this.createTimeHourDetails(earnCodeObj, prevTimeBlockHours,
                        previousTimeBlock.getAmount(), previousTimeBlock.getTkTimeBlockId(), false));

                if (earnCodeObj.getInflateMinHours() != null) {
                    if ((earnCodeObj.getInflateMinHours().compareTo(BigDecimal.ZERO) != 0)
                            && earnCodeObj.getInflateMinHours().compareTo(cummulativeHours) > 0) {
                        //if previous timeblock has no gap then assume its one block if the same earn code and divide inflated hours accordingly

                        //add previous time block's hours to this time blocks hours. If the cummulative hours is less than the value for inflate min,
                        //create time hour detail with hours equal to the hours needed to reach inflate min plus the hours for this time block.
                        if (earnCodeObj.getInflateMinHours().compareTo(cummulativeHours) > 0) {
                            //apply inflations to the cummulative hours
                            newDetails = this.createTimeHourDetails(earnCodeObj, cummulativeHours,
                                    tb.getAmount(), tb.getTkTimeBlockId(), false);
                            TimeHourDetailBo detail = newDetails.get(0);
                            //this detail's hours will be the cummulative inflated hours less the hours in previous time block detail's hours.
                            detail.setHours(earnCodeObj.getInflateMinHours().subtract(prevTimeBlockHours));
                            newDetails.clear();
                            newDetails.add(detail);
                            tb.setTimeHourDetails(newDetails);
                        }
                    }
                }
                //the hours for this time block may be under the inflate factor, but when combined with the hours from first "part"
                //of their shift, it is over, thus no inflation should be requested of the time hour detail's hours.
                if (earnCodeObj.getInflateFactor() != null
                        && earnCodeObj.getInflateFactor().compareTo(BigDecimal.ZERO) != 0) {
                    //apply inflate factor separately so as to not inflate "hours" if it is under the minimum
                    TimeHourDetailBo detail = new TimeHourDetailBo();
                    if (newDetails.isEmpty()) {
                        //populate some default values...
                        newDetails = this.createTimeHourDetails(earnCodeObj, hours, tb.getAmount(),
                                tb.getTkTimeBlockId(), false);
                    }
                    detail = newDetails.get(0);
                    BigDecimal newHours = detail.getHours().multiply(earnCodeObj.getInflateFactor(),
                            HrConstants.MATH_CONTEXT);
                    detail.setHours(newHours);
                    newDetails.clear();
                    newDetails.add(detail);
                    tb.setTimeHourDetails(newDetails);
                    newDetails = previousTimeBlock.getTimeHourDetails();
                    detail = newDetails.get(0);
                    detail.setHours(prevTimeBlockHours.multiply(earnCodeObj.getInflateFactor(),
                            HrConstants.MATH_CONTEXT));
                    newDetails.clear();
                    newDetails.add(detail);
                    previousTimeBlock.setTimeHourDetails(newDetails);
                }
            } else {
                tb.setTimeHourDetails(this.createTimeHourDetails(earnCodeObj, tb.getHours(), tb.getAmount(),
                        tb.getTkTimeBlockId(), true));
            }

            tb.setHours(hours);
        } else {
            // create new time hour details for earn codes of other types
            tb.setTimeHourDetails(this.createTimeHourDetails(earnCodeObj, tb.getHours(), tb.getAmount(),
                    tb.getTkTimeBlockId(), true));
        }
        //reset time block history details
        for (TimeBlockHistory tbh : tb.getTimeBlockHistories()) {
            TkServiceLocator.getTimeBlockHistoryService().addTimeBlockHistoryDetails(tbh, tb);
        }
        previousTimeBlock = tb;
    }
    return ModelObjectUtils.transform(originalBos, toTimeBlock);
}