Example usage for java.math RoundingMode HALF_EVEN

List of usage examples for java.math RoundingMode HALF_EVEN

Introduction

In this page you can find the example usage for java.math RoundingMode HALF_EVEN.

Prototype

RoundingMode HALF_EVEN

To view the source code for java.math RoundingMode HALF_EVEN.

Click Source Link

Document

Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.

Usage

From source file:org.mifosplatform.portfolio.loanaccount.domain.LoanCharge.java

public static BigDecimal percentageOf(final BigDecimal value, final BigDecimal percentage) {

    BigDecimal percentageOf = BigDecimal.ZERO;

    if (isGreaterThanZero(value)) {
        final MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN);
        final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc);
        percentageOf = value.multiply(multiplicand, mc);
    }/*from   w  w w . j  av a  2s.  com*/
    return percentageOf;
}

From source file:org.mifosplatform.portfolio.savings.service.SavingsAccountWritePlatformServiceJpaRepositoryImpl.java

@Override
public CommandProcessingResult adjustSavingsTransaction(final Long savingsId, final Long transactionId,
        final JsonCommand command) {

    final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository
            .findOneByIdAndSavingsAccountId(transactionId, savingsId);
    if (savingsAccountTransaction == null) {
        throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId);
    }/*from   w  ww  .  j  ava 2 s.  c o  m*/

    if (!(savingsAccountTransaction.isDeposit() || savingsAccountTransaction.isWithdrawal())
            || savingsAccountTransaction.isReversed()) {
        throw new TransactionUpdateNotAllowedException(savingsId, transactionId);
    }

    if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId,
            PortfolioAccountType.SAVINGS)) {
        throw new PlatformServiceUnavailableException(
                "error.msg.saving.account.transfer.transaction.update.not.allowed",
                "Savings account transaction:" + transactionId
                        + " update not allowed as it involves in account transfer",
                transactionId);
    }

    this.savingsAccountTransactionDataValidator.validate(command);

    final LocalDate today = DateUtils.getLocalDateOfTenant();

    final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId);
    if (account.isNotActive()) {
        throwValidationForActiveStatus(SavingsApiConstants.adjustTransactionAction);
    }
    final Set<Long> existingTransactionIds = new HashSet<Long>();
    final Set<Long> existingReversedTransactionIds = new HashSet<Long>();
    updateExistingTransactionsDetails(account, existingTransactionIds, existingReversedTransactionIds);

    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
    final LocalDate transactionDate = command
            .localDateValueOfParameterNamed(SavingsApiConstants.transactionDateParamName);
    final BigDecimal transactionAmount = command
            .bigDecimalValueOfParameterNamed(SavingsApiConstants.transactionAmountParamName);
    final Map<String, Object> changes = new LinkedHashMap<String, Object>();
    final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService
            .createAndPersistPaymentDetail(command, changes);

    final MathContext mc = new MathContext(10, RoundingMode.HALF_EVEN);
    account.undoTransaction(transactionId);

    // for undo withdrawal fee
    final SavingsAccountTransaction nextSavingsAccountTransaction = this.savingsAccountTransactionRepository
            .findOneByIdAndSavingsAccountId(transactionId + 1, savingsId);
    if (nextSavingsAccountTransaction != null
            && nextSavingsAccountTransaction.isWithdrawalFeeAndNotReversed()) {
        account.undoTransaction(transactionId + 1);
    }

    SavingsAccountTransaction transaction = null;
    if (savingsAccountTransaction.isDeposit()) {
        final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt,
                transactionDate, transactionAmount, paymentDetail);
        transaction = account.deposit(transactionDTO);
    } else {
        final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt,
                transactionDate, transactionAmount, paymentDetail);
        transaction = account.withdraw(transactionDTO, true);
    }
    final Long newtransactionId = saveTransactionToGenerateTransactionId(transaction);

    if (account.isBeforeLastPostingPeriod(transactionDate)
            || account.isBeforeLastPostingPeriod(savingsAccountTransaction.transactionLocalDate())) {
        account.postInterest(mc, today);
    } else {
        account.calculateInterestUsing(mc, today);
    }
    account.validateAccountBalanceDoesNotBecomeNegative(SavingsApiConstants.adjustTransactionAction);
    account.activateAccountBasedOnBalance();
    postJournalEntries(account, existingTransactionIds, existingReversedTransactionIds);
    return new CommandProcessingResultBuilder() //
            .withEntityId(newtransactionId) //
            .withOfficeId(account.officeId()) //
            .withClientId(account.clientId()) //
            .withGroupId(account.groupId()) //
            .withSavingsId(savingsId) //
            .with(changes)//
            .build();
}

From source file:module.workingCapital.presentationTier.action.WorkingCapitalAction.java

private ActionForward exportInfoToExcel(Set<WorkingCapitalProcess> processes, WorkingCapitalContext context,
        HttpServletResponse response) throws Exception {

    final Integer year = context.getWorkingCapitalYear().getYear();
    SheetData<WorkingCapitalProcess> sheetData = new SheetData<WorkingCapitalProcess>(processes) {
        @Override/*from  ww w .java2s  .co  m*/
        protected void makeLine(WorkingCapitalProcess workingCapitalProcess) {
            if (workingCapitalProcess == null) {
                return;
            }
            final WorkingCapital workingCapital = workingCapitalProcess.getWorkingCapital();
            final WorkingCapitalInitialization initialization = workingCapital
                    .getWorkingCapitalInitialization();
            final AccountingUnit accountingUnit = workingCapital.getAccountingUnit();

            addCell(getLocalizedMessate("label.module.workingCapital.year"), year);
            addCell(getLocalizedMessate("label.module.workingCapital"),
                    workingCapitalProcess.getWorkingCapital().getUnit().getPresentationName());
            addCell(getLocalizedMessate("WorkingCapitalProcessState"),
                    workingCapitalProcess.getPresentableAcquisitionProcessState().getLocalizedName());
            addCell(getLocalizedMessate("label.module.workingCapital.unit.responsible"),
                    getUnitResponsibles(workingCapital));
            addCell(getLocalizedMessate("label.module.workingCapital.initialization.accountingUnit"),
                    accountingUnit == null ? "" : accountingUnit.getName());

            addCell(getLocalizedMessate("label.module.workingCapital.requestingDate"),
                    initialization.getRequestCreation().toString("yyyy-MM-dd HH:mm:ss"));
            addCell(getLocalizedMessate("label.module.workingCapital.requester"),
                    initialization.getRequestor().getName());
            final Person movementResponsible = workingCapital.getMovementResponsible();
            addCell(getLocalizedMessate("label.module.workingCapital.movementResponsible"),
                    movementResponsible == null ? "" : movementResponsible.getName());
            addCell(getLocalizedMessate("label.module.workingCapital.fiscalId"), initialization.getFiscalId());
            addCell(getLocalizedMessate("label.module.workingCapital.internationalBankAccountNumber"),
                    initialization.getInternationalBankAccountNumber());
            addCell(getLocalizedMessate("label.module.workingCapital.fundAllocationId"),
                    initialization.getFundAllocationId());
            final Money requestedAnualValue = initialization.getRequestedAnualValue();
            addCell(getLocalizedMessate("label.module.workingCapital.requestedAnualValue.requested"),
                    requestedAnualValue);
            addCell(getLocalizedMessate("label.module.workingCapital.requestedMonthlyValue.requested"),
                    requestedAnualValue.divideAndRound(new BigDecimal(6)));
            final Money authorizedAnualValue = initialization.getAuthorizedAnualValue();
            addCell(getLocalizedMessate("label.module.workingCapital.authorizedAnualValue"),
                    authorizedAnualValue == null ? "" : authorizedAnualValue);
            final Money maxAuthorizedAnualValue = initialization.getMaxAuthorizedAnualValue();
            addCell(getLocalizedMessate("label.module.workingCapital.maxAuthorizedAnualValue"),
                    maxAuthorizedAnualValue == null ? "" : maxAuthorizedAnualValue);
            final DateTime lastSubmission = initialization.getLastSubmission();
            addCell(getLocalizedMessate("label.module.workingCapital.initialization.lastSubmission"),
                    lastSubmission == null ? "" : lastSubmission.toString("yyyy-MM-dd"));
            final DateTime refundRequested = initialization.getRefundRequested();
            addCell(getLocalizedMessate("label.module.workingCapital.initialization.refundRequested"),
                    refundRequested == null ? "" : refundRequested.toString("yyyy-MM-dd"));

            final WorkingCapitalTransaction lastTransaction = workingCapital.getLastTransaction();
            if (lastTransaction == null) {
                addCell(getLocalizedMessate("label.module.workingCapital.transaction.accumulatedValue"),
                        Money.ZERO);
                addCell(getLocalizedMessate("label.module.workingCapital.transaction.balance"), Money.ZERO);
                addCell(getLocalizedMessate("label.module.workingCapital.transaction.debt"), Money.ZERO);
            } else {
                addCell(getLocalizedMessate("label.module.workingCapital.transaction.accumulatedValue"),
                        lastTransaction.getAccumulatedValue());
                addCell(getLocalizedMessate("label.module.workingCapital.transaction.balance"),
                        lastTransaction.getBalance());
                addCell(getLocalizedMessate("label.module.workingCapital.transaction.debt"),
                        lastTransaction.getDebt());
            }

            for (final AcquisitionClassification classification : WorkingCapitalSystem.getInstance()
                    .getAcquisitionClassificationsSet()) {
                final String description = classification.getDescription();
                final String pocCode = classification.getPocCode();
                final String key = pocCode + " - " + description;

                final Money value = calculateValueForClassification(workingCapital, classification);

                addCell(key, value);
            }

        }

        private Money calculateValueForClassification(final WorkingCapital workingCapital,
                final AcquisitionClassification classification) {
            Money result = Money.ZERO;
            for (final WorkingCapitalTransaction transaction : workingCapital
                    .getWorkingCapitalTransactionsSet()) {
                if (transaction.isAcquisition()) {
                    final WorkingCapitalAcquisitionTransaction acquisitionTransaction = (WorkingCapitalAcquisitionTransaction) transaction;
                    final WorkingCapitalAcquisition acquisition = acquisitionTransaction
                            .getWorkingCapitalAcquisition();
                    final AcquisitionClassification acquisitionClassification = acquisition
                            .getAcquisitionClassification();
                    if (acquisitionClassification == classification) {
                        result = result.add(acquisition.getValueAllocatedToSupplier());
                    }
                }
            }
            return result;
        }

        private String getUnitResponsibles(final WorkingCapital workingCapital) {
            final StringBuilder builder = new StringBuilder();
            final SortedMap<Person, Set<Authorization>> authorizations = workingCapital
                    .getSortedAuthorizations();
            if (!authorizations.isEmpty()) {
                for (final Entry<Person, Set<Authorization>> entry : authorizations.entrySet()) {
                    if (builder.length() > 0) {
                        builder.append("; ");
                    }
                    builder.append(entry.getKey().getName());
                }
            }

            return builder.toString();
        }

    };

    final LocalDate currentLocalDate = new LocalDate();
    final SpreadsheetBuilder builder = new SpreadsheetBuilder();
    builder.addConverter(Money.class, new CellConverter() {

        @Override
        public Object convert(final Object source) {
            final Money money = (Money) source;
            return money == null ? null
                    : new Double(
                            money.getValue().round(new MathContext(2, RoundingMode.HALF_EVEN)).doubleValue());
        }

    });

    builder.addSheet(getLocalizedMessate("label.module.workingCapital") + " " + year + " - "
            + currentLocalDate.toString(), sheetData);

    final List<WorkingCapitalTransaction> transactions = new ArrayList<WorkingCapitalTransaction>();
    for (final WorkingCapitalProcess process : processes) {
        final WorkingCapital workingCapital = process.getWorkingCapital();
        transactions.addAll(workingCapital.getSortedWorkingCapitalTransactions());
    }
    final SheetData<WorkingCapitalTransaction> transactionsSheet = new SheetData<WorkingCapitalTransaction>(
            transactions) {
        @Override
        protected void makeLine(WorkingCapitalTransaction transaction) {
            final WorkingCapital workingCapital = transaction.getWorkingCapital();
            final WorkingCapitalProcess workingCapitalProcess = workingCapital.getWorkingCapitalProcess();

            addCell(getLocalizedMessate("label.module.workingCapital.year"), year);
            addCell(getLocalizedMessate("label.module.workingCapital"),
                    workingCapitalProcess.getWorkingCapital().getUnit().getPresentationName());
            addCell(getLocalizedMessate("label.module.workingCapital.transaction.number"),
                    transaction.getNumber());
            addCell(getLocalizedMessate("WorkingCapitalProcessState.CANCELED"),
                    transaction.isCanceledOrRejected() ? getLocalizedMessate("label.yes")
                            : getLocalizedMessate("label.no"));
            addCell(getLocalizedMessate("label.module.workingCapital.transaction.description") + " "
                    + getLocalizedMessate("label.module.workingCapital.transaction.number"),
                    transaction.getDescription());
            addCell(getLocalizedMessate("label.module.workingCapital.transaction.approval"),
                    approvalLabel(transaction));
            addCell(getLocalizedMessate("label.module.workingCapital.transaction.verification"),
                    verificationLabel(transaction));
            addCell(getLocalizedMessate("label.module.workingCapital.transaction.value"),
                    transaction.getValue());
            addCell(getLocalizedMessate("label.module.workingCapital.transaction.accumulatedValue"),
                    transaction.getAccumulatedValue());
            addCell(getLocalizedMessate("label.module.workingCapital.transaction.balance"),
                    transaction.getBalance());
            addCell(getLocalizedMessate("label.module.workingCapital.transaction.debt"), transaction.getDebt());

            if (transaction.isAcquisition()) {
                final WorkingCapitalAcquisitionTransaction acquisitionTx = (WorkingCapitalAcquisitionTransaction) transaction;
                final WorkingCapitalAcquisition acquisition = acquisitionTx.getWorkingCapitalAcquisition();
                final AcquisitionClassification acquisitionClassification = acquisition
                        .getAcquisitionClassification();
                final String economicClassification = acquisitionClassification.getEconomicClassification();
                final String pocCode = acquisitionClassification.getPocCode();
                addCell(getLocalizedMessate(
                        "label.module.workingCapital.configuration.acquisition.classifications.economicClassification"),
                        economicClassification);
                addCell(getLocalizedMessate(
                        "label.module.workingCapital.configuration.acquisition.classifications.pocCode"),
                        pocCode);
                addCell(getLocalizedMessate(
                        "label.module.workingCapital.configuration.acquisition.classifications.description"),
                        acquisition.getDescription());
            }
        }

        private Object verificationLabel(final WorkingCapitalTransaction transaction) {
            if (transaction.isAcquisition()) {
                final WorkingCapitalAcquisitionTransaction acquisition = (WorkingCapitalAcquisitionTransaction) transaction;
                if (acquisition.getWorkingCapitalAcquisition().getVerified() != null) {
                    return getLocalizedMessate("label.verified");
                }
                if (acquisition.getWorkingCapitalAcquisition().getNotVerified() != null) {
                    return getLocalizedMessate("label.notVerified");
                }
            }
            return "-";
        }

        private String approvalLabel(final WorkingCapitalTransaction transaction) {
            if (transaction.isAcquisition()) {
                final WorkingCapitalAcquisitionTransaction acquisition = (WorkingCapitalAcquisitionTransaction) transaction;
                if (acquisition.getWorkingCapitalAcquisition().getApproved() != null) {
                    return getLocalizedMessate("label.approved");
                }
                if (acquisition.getWorkingCapitalAcquisition().getRejectedApproval() != null) {
                    return getLocalizedMessate("label.rejected");
                }
            }
            return "-";
        }

    };
    builder.addSheet(getLocalizedMessate("label.module.workingCapital.transactions"), transactionsSheet);

    return streamSpreadsheet(response, "FundosManeio_" + year + "-" + currentLocalDate.getDayOfMonth() + "-"
            + currentLocalDate.getMonthOfYear() + "-" + currentLocalDate.getYear(), builder);

}

From source file:org.fenixedu.treasury.services.integration.erp.ERPExporter.java

private WorkDocument convertToSAFTWorkDocument(Invoice document,
        Map<String, oecd.standardauditfile_tax.pt_1.Customer> baseCustomers,
        Map<String, oecd.standardauditfile_tax.pt_1.Product> baseProducts) {
    WorkDocument workDocument = new WorkDocument();

    // Find the Customer in BaseCustomers
    oecd.standardauditfile_tax.pt_1.Customer customer = null;

    if (baseCustomers.containsKey(document.getDebtAccount().getCustomer().getCode())) {
        customer = baseCustomers.get(document.getDebtAccount().getCustomer().getCode());
    } else {/*from  www. jav  a 2s. c  o m*/
        // If not found, create a new one and add it to baseCustomers
        customer = convertCustomerToSAFTCustomer(document.getDebtAccount().getCustomer());
        baseCustomers.put(customer.getCustomerID(), customer);
    }

    //check the PayorDebtAccount
    if (document.getPayorDebtAccount() != null) {
        if (baseCustomers.containsKey(document.getPayorDebtAccount().getCustomer().getCode())) {
            //do nothing
        } else {
            // If not found, create a new one and add it to baseCustomers
            oecd.standardauditfile_tax.pt_1.Customer payorCustomer = convertCustomerToSAFTCustomer(
                    document.getPayorDebtAccount().getCustomer());
            baseCustomers.put(payorCustomer.getCustomerID(), payorCustomer);
        }
    }

    // MovementDate
    DatatypeFactory dataTypeFactory;
    try {
        dataTypeFactory = DatatypeFactory.newInstance();
        DateTime documentDate = document.getDocumentDate();

        // SystemEntryDate
        workDocument.setSystemEntryDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        workDocument.setWorkDate(convertToXMLDateTime(dataTypeFactory, documentDate));

        // DocumentNumber
        workDocument.setDocumentNumber(document.getUiDocumentNumber());

        // CustomerID
        workDocument.setCustomerID(document.getDebtAccount().getCustomer().getCode());

        //PayorID
        if (document.getPayorDebtAccount() != null) {
            workDocument.setPayorCustomerID(document.getPayorDebtAccount().getCustomer().getCode());
        }

        // DocumentStatus
        /*
         * Deve ser preenchido com: ?N? ? Normal; Texto 1 ?T? ? Por conta de
         * terceiros; ?A? ? Documento anulado.
         */
        SourceDocuments.WorkingDocuments.WorkDocument.DocumentStatus status = new SourceDocuments.WorkingDocuments.WorkDocument.DocumentStatus();
        if (document.isAnnulled()) {
            status.setWorkStatus("A");
        } else {
            status.setWorkStatus("N");
        }

        status.setWorkStatusDate(workDocument.getSystemEntryDate());
        // status.setReason("");
        // Utilizador responsvel pelo estado atual do docu-mento.
        status.setSourceID(document.getVersioningUpdatedBy());
        // Deve ser preenchido com:
        // 'P' - Documento produzido na aplicacao;
        if (Boolean.TRUE.equals(document.getDocumentNumberSeries().getSeries().getExternSeries())) {
            status.setSourceBilling(SAFTPTSourceBilling.I);
        } else {
            status.setSourceBilling(SAFTPTSourceBilling.P);
        }

        workDocument.setDocumentStatus(status);

        // DocumentTotals
        SourceDocuments.WorkingDocuments.WorkDocument.DocumentTotals docTotals = new SourceDocuments.WorkingDocuments.WorkDocument.DocumentTotals();
        docTotals.setGrossTotal(document.getTotalAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setNetTotal(document.getTotalNetAmount().setScale(2, RoundingMode.HALF_EVEN));
        docTotals.setTaxPayable(document.getTotalAmount().subtract(document.getTotalNetAmount()).setScale(2,
                RoundingMode.HALF_EVEN));
        workDocument.setDocumentTotals(docTotals);

        // WorkType
        /*
         * Deve ser preenchido com: Texto 2 "DC"  Documentos emitidos que
         * sejam suscetiveis de apresentacao ao cliente para conferencia de
         * entrega de mercadorias ou da prestacao de servicos. "FC"  Fatura
         * de consignacao nos termos do artigo 38 do codigo do IVA.
         */
        workDocument.setWorkType("DC");

        // Period
        /*
         * Per?odo contabil?stico (Period) . . . . . . . . . . Deve ser
         * indicado o n?mero do m?s do per?odo de tributa??o, de ?1? a ?12?,
         * contado desde a data do in?cio. Pode ainda ser preenchido com
         * ?13?, ?14?, ?15? ou ?16? para movimentos efectuados no ?ltimo m?s
         * do per?odo de tributa??o, relacionados com o apuramento do
         * resultado. Ex.: movimentos de apuramentos de invent?rios,
         * deprecia??es, ajustamentos ou apuramentos de resultados.
         */
        workDocument.setPeriod(document.getDocumentDate().getMonthOfYear());

        // SourceID
        /*
         * C?digo do utilizador que registou o movimento (SourceID).
         */
        workDocument.setSourceID(document.getVersioningCreator());

    } catch (DatatypeConfigurationException e) {

        e.printStackTrace();
    }

    List<oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line> productLines = workDocument
            .getLine();

    // Process individual
    BigInteger i = BigInteger.ONE;
    for (FinantialDocumentEntry docLine : document.getFinantialDocumentEntriesSet()) {
        InvoiceEntry orderNoteLine = (InvoiceEntry) docLine;
        oecd.standardauditfile_tax.pt_1.SourceDocuments.WorkingDocuments.WorkDocument.Line line = convertToSAFTWorkDocumentLine(
                orderNoteLine, baseProducts);

        // LineNumber
        line.setLineNumber(i);

        // Add to productLines
        i = i.add(BigInteger.ONE);
        productLines.add(line);
    }

    return workDocument;
}

From source file:org.gnucash.android.ui.transaction.TransactionFormFragment.java

/**
 * Parse an input string into a {@link BigDecimal}
 * This method expects the amount including the decimal part
 * @param amountString String with amount information
 * @return BigDecimal with the amount parsed from <code>amountString</code>
 *///from   w w w.ja  va 2s .c o  m
public BigDecimal parseInputToDecimal(String amountString) {
    String clean = stripCurrencyFormatting(amountString);
    //all amounts are input to 2 decimal places, so after removing decimal separator, divide by 100
    BigDecimal amount = new BigDecimal(clean).setScale(2, RoundingMode.HALF_EVEN).divide(new BigDecimal(100), 2,
            RoundingMode.HALF_EVEN);
    if (mTransactionTypeButton.isChecked() && amount.doubleValue() > 0)
        amount = amount.negate();
    return amount;
}

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;//w ww  .  j ava 2 s. c  o m
            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:module.siadap.domain.wrappers.UnitSiadapWrapper.java

public BigDecimal getExcellencyEvaluationPercentage() {
    int totalPeopleWorkingForUnit = getUnitEmployees(true).size();
    Collection<PersonSiadapWrapper> excellentEvaluationPersons = getUnitEmployees(true, new Predicate() {

        @Override//from   ww  w .j  av a 2 s.c  o  m
        public boolean evaluate(Object personObject) {
            PersonSiadapWrapper personWrapper = (PersonSiadapWrapper) personObject;
            if (personWrapper.getSiadap() == null
                    || personWrapper.getSiadap().getDefaultSiadapEvaluationUniverse() == null) {
                return false;
            }
            return personWrapper.getSiadap().getDefaultSiadapEvaluationUniverse().hasExcellencyAwarded();
        }
    });
    int excellentCount = excellentEvaluationPersons.size();
    if ((excellentCount == 0) || (totalPeopleWorkingForUnit == 0)) {
        return BigDecimal.ZERO;
    }

    return new BigDecimal(excellentCount)
            .divide(new BigDecimal(totalPeopleWorkingForUnit), UnitSiadapWrapper.SCALE, RoundingMode.HALF_EVEN)
            .multiply(new BigDecimal(100), new MathContext(UnitSiadapWrapper.SCALE));
}

From source file:org.openhab.binding.proserv.internal.ProservBinding.java

public void postUpdateSingleValueFunction(int x, int y, int z, byte[] dataValue) {
    int startDatapoint = (48 * x) + (y * 3) + 1;
    int Id = proservData.getFunctionMapId(x, y, z);

    switch ((int) proservData.getFunctionCodes(x, y) & 0xFF) {
    case 0x01://from ww  w . j a v a2 s . c o  m
    case 0x02:
    case 0x04:
    case 0x05: {
        boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), b ? OnOffType.ON : OnOffType.OFF);
    }
        break;
    case 0x11:
    case 0x12:
    case 0x13: {
        boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
        if (proservData.getFunctionStateIsInverted(x, y))
            b = !b;
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), b ? OnOffType.ON : OnOffType.OFF);
    }
        break;
    case 0x21:
    case 0x31: {
        boolean b = proservData.parse1ByteBooleanValue(dataValue[0]);
        if (proservData.getFunctionStateIsInverted(x, y))
            b = !b;
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), b ? OnOffType.ON : OnOffType.OFF);
    }
        break;
    case 0x26:
    case 0x34: {
        float f = proservData.parse2ByteFloatValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
    }
        break;
    case 0x38: {
        float f = proservData.parse4ByteFloatValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
    }
        break;
    case 0x32:
    case 0x91: {
        int i = proservData.parse1BytePercentValue(dataValue[0]);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
    }
        break;

    case 0x33:
    case 0x92: {
        int i = proservData.parse1ByteUnsignedValue(dataValue[0]);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(i));
    }
        break;
    case 0x94: {
        float f = proservData.parse2ByteFloatValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
    }
        break;
    case 0x35:
    case 0x95: {
        long uint32 = proservData.parse4ByteUnsignedValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(uint32));
    }
        break;
    case 0x36:
    case 0x96: {
        long int32 = proservData.parse4ByteSignedValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id), new DecimalType(int32));
    }
        break;
    case 0x97: {
        float f = proservData.parse4ByteFloatValue(dataValue, 0);
        eventPublisher.postUpdate("itemProServLog" + Integer.toString(Id),
                new DecimalType(new BigDecimal(f).setScale(2, RoundingMode.HALF_EVEN)));
    }
        break;
    default:
        logger.debug("proServ binding, unhandled functioncode 0x{}",
                Integer.toHexString(((int) proservData.getFunctionCodes(x, y) & 0xFF)));
    }
    shortDelayBetweenBusEvents();
}

From source file:module.siadap.domain.wrappers.UnitSiadapWrapper.java

public BigDecimal getRelevantEvaluationPercentage() {
    int totalPeopleWorkingForUnit = getUnitEmployees(true).size();
    Collection<PersonSiadapWrapper> relevantEvaluationPersons = getUnitEmployees(true, new Predicate() {

        @Override// ww  w.j  a  va 2s.c  om
        public boolean evaluate(Object personObject) {
            PersonSiadapWrapper personWrapper = (PersonSiadapWrapper) personObject;
            if (personWrapper.getSiadap() == null
                    || personWrapper.getSiadap().getDefaultSiadapEvaluationUniverse() == null) {
                return false;
            }
            return personWrapper.getSiadap().getDefaultSiadapEvaluationUniverse().hasRelevantEvaluation();
        }

    });
    int relevantCount = relevantEvaluationPersons.size();

    if ((relevantCount == 0) || (totalPeopleWorkingForUnit == 0)) {
        return BigDecimal.ZERO;
    }

    return new BigDecimal(relevantCount)
            .divide(new BigDecimal(totalPeopleWorkingForUnit), UnitSiadapWrapper.SCALE, RoundingMode.HALF_EVEN)
            .multiply(new BigDecimal(100), new MathContext(UnitSiadapWrapper.SCALE));
}

From source file:jp.furplag.util.commons.NumberUtilsTest.java

/**
 * {@link jp.furplag.util.commons.NumberUtils#divide(java.lang.Object, java.lang.Number, java.lang.Number, java.math.RoundingMode, java.lang.Class)}.
 *//*from ww w .j  ava  2 s .com*/
@SuppressWarnings("unchecked")
@Test
public void testDivideTNumberNumberRoundingModeClassOfT() {
    assertEquals("null", null, divide(null, null, null, null, null));
    assertEquals("null", null, divide(10, 5, 0, null, null));
    assertEquals("null", null, divide(10, 5, null, null, null));
    assertEquals("null", null, divide(10, 3, 2, RoundingMode.DOWN, null));
    assertEquals("null", (Object) 3.33f, divide(10, 3, 2, RoundingMode.DOWN, float.class));
    try {
        for (Class<?> type : PRIMITIVES) {
            Object expected = ClassUtils.primitiveToWrapper(type).getMethod("valueOf", String.class)
                    .invoke(null, "0");
            assertEquals("fallback: " + type.getSimpleName(), expected,
                    divide(null, null, null, null, (Class<? extends Number>) type));
        }
        for (Class<?> type : NUMBERS) {
            Object expected = valueOf(3.33, (Class<? extends Number>) type);
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.DOWN, (Class<? extends Number>) type));
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.HALF_EVEN, (Class<? extends Number>) type));
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.HALF_UP, (Class<? extends Number>) type));
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.FLOOR, (Class<? extends Number>) type));
            expected = valueOf(3.34, (Class<? extends Number>) type);
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.UP, (Class<? extends Number>) type));
            assertEquals("10 / 3: " + type.getSimpleName(), expected,
                    divide(10, 3, 2, RoundingMode.CEILING, (Class<? extends Number>) type));
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\n" + Arrays.toString(e.getStackTrace()));
    }
}