Example usage for org.joda.time LocalDate toString

List of usage examples for org.joda.time LocalDate toString

Introduction

In this page you can find the example usage for org.joda.time LocalDate toString.

Prototype

public String toString(String pattern) 

Source Link

Document

Output the date using the specified format pattern.

Usage

From source file:org.mifosplatform.portfolio.loanaccount.rescheduleloan.service.LoanRescheduleRequestWritePlatformServiceImpl.java

License:Mozilla Public License

@Override
@Transactional//from   ww  w .j  a v  a  2s .  c om
public CommandProcessingResult approve(JsonCommand jsonCommand) {

    try {
        final Long loanRescheduleRequestId = jsonCommand.entityId();

        final LoanRescheduleRequest loanRescheduleRequest = this.loanRescheduleRequestRepository
                .findOne(loanRescheduleRequestId);

        if (loanRescheduleRequest == null) {
            throw new LoanRescheduleRequestNotFoundException(loanRescheduleRequestId);
        }

        // validate the request in the JsonCommand object passed as
        // parameter
        this.loanRescheduleRequestDataValidator.validateForApproveAction(jsonCommand, loanRescheduleRequest);

        final AppUser appUser = this.platformSecurityContext.authenticatedUser();
        final Map<String, Object> changes = new LinkedHashMap<>();

        LocalDate approvedOnDate = jsonCommand.localDateValueOfParameterNamed("approvedOnDate");
        final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(jsonCommand.dateFormat())
                .withLocale(jsonCommand.extractLocale());

        changes.put("locale", jsonCommand.locale());
        changes.put("dateFormat", jsonCommand.dateFormat());
        changes.put("approvedOnDate", approvedOnDate.toString(dateTimeFormatter));
        changes.put("approvedByUserId", appUser.getId());

        if (!changes.isEmpty()) {
            Loan loan = loanRescheduleRequest.getLoan();
            final LoanSummary loanSummary = loan.getSummary();

            final boolean isHolidayEnabled = this.configurationDomainService
                    .isRescheduleRepaymentsOnHolidaysEnabled();
            final List<Holiday> holidays = this.holidayRepository
                    .findByOfficeIdAndGreaterThanDate(loan.getOfficeId(), loan.getDisbursementDate().toDate());
            final WorkingDays workingDays = this.workingDaysRepository.findOne();
            final LoanProductMinimumRepaymentScheduleRelatedDetail loanProductRelatedDetail = loan
                    .getLoanRepaymentScheduleDetail();
            final MonetaryCurrency currency = loanProductRelatedDetail.getCurrency();
            final ApplicationCurrency applicationCurrency = this.applicationCurrencyRepository
                    .findOneWithNotFoundDetection(currency);

            final InterestMethod interestMethod = loan.getLoanRepaymentScheduleDetail().getInterestMethod();
            final RoundingMode roundingMode = RoundingMode.HALF_EVEN;
            final MathContext mathContext = new MathContext(8, roundingMode);

            Collection<LoanRepaymentScheduleHistory> loanRepaymentScheduleHistoryList = this.loanScheduleHistoryWritePlatformService
                    .createLoanScheduleArchive(loan.getRepaymentScheduleInstallments(), loan,
                            loanRescheduleRequest);

            HolidayDetailDTO holidayDetailDTO = new HolidayDetailDTO(isHolidayEnabled, holidays, workingDays);
            CalendarInstance restCalendarInstance = null;
            CalendarInstance compoundingCalendarInstance = null;
            if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) {
                restCalendarInstance = calendarInstanceRepository.findCalendarInstaneByEntityId(
                        loan.loanInterestRecalculationDetailId(),
                        CalendarEntityType.LOAN_RECALCULATION_REST_DETAIL.getValue());
                compoundingCalendarInstance = calendarInstanceRepository.findCalendarInstaneByEntityId(
                        loan.loanInterestRecalculationDetailId(),
                        CalendarEntityType.LOAN_RECALCULATION_COMPOUNDING_DETAIL.getValue());
            }
            LoanRescheduleModel loanRescheduleModel = new DefaultLoanReschedulerFactory().reschedule(
                    mathContext, interestMethod, loanRescheduleRequest, applicationCurrency, holidayDetailDTO,
                    restCalendarInstance, compoundingCalendarInstance);

            final Collection<LoanRescheduleModelRepaymentPeriod> periods = loanRescheduleModel.getPeriods();
            List<LoanRepaymentScheduleInstallment> repaymentScheduleInstallments = loan
                    .getRepaymentScheduleInstallments();
            Collection<LoanCharge> waiveLoanCharges = new ArrayList<>();

            for (LoanRescheduleModelRepaymentPeriod period : periods) {

                if (period.isNew()) {
                    LoanRepaymentScheduleInstallment repaymentScheduleInstallment = new LoanRepaymentScheduleInstallment(
                            loan, period.periodNumber(), period.periodFromDate(), period.periodDueDate(),
                            period.principalDue(), period.interestDue(), BigDecimal.ZERO, BigDecimal.ZERO,
                            false);

                    repaymentScheduleInstallments.add(repaymentScheduleInstallment);
                }

                else {
                    for (LoanRepaymentScheduleInstallment repaymentScheduleInstallment : repaymentScheduleInstallments) {

                        if (repaymentScheduleInstallment.getInstallmentNumber()
                                .equals(period.oldPeriodNumber())) {

                            LocalDate periodDueDate = repaymentScheduleInstallment.getDueDate();
                            Money zeroAmount = Money.of(currency, new BigDecimal(0));

                            repaymentScheduleInstallment.updateInstallmentNumber(period.periodNumber());
                            repaymentScheduleInstallment.updateFromDate(period.periodFromDate());
                            repaymentScheduleInstallment.updateDueDate(period.periodDueDate());
                            repaymentScheduleInstallment.updatePrincipal(period.principalDue());
                            repaymentScheduleInstallment.updateInterestCharged(period.interestDue());

                            if (Money.of(currency, period.principalDue()).isZero()
                                    && Money.of(currency, period.interestDue()).isZero()
                                    && repaymentScheduleInstallment.isNotFullyPaidOff()) {

                                if (repaymentScheduleInstallment.getPenaltyChargesOutstanding(currency)
                                        .isGreaterThan(zeroAmount)
                                        || repaymentScheduleInstallment.getFeeChargesOutstanding(currency)
                                                .isGreaterThan(zeroAmount)) {

                                    waiveLoanCharges.addAll(loan.getLoanCharges(periodDueDate));
                                }
                            }

                            break;
                        }
                    }
                }
            }

            for (LoanRepaymentScheduleHistory loanRepaymentScheduleHistory : loanRepaymentScheduleHistoryList) {
                this.loanRepaymentScheduleHistoryRepository.save(loanRepaymentScheduleHistory);
            }

            loan.updateRescheduledByUser(appUser);
            loan.updateRescheduledOnDate(new LocalDate());

            // waive all loan charges of zero instalments
            waiveLoanCharges(loan, waiveLoanCharges);

            // update the Loan summary
            loanSummary.updateSummary(currency, loan.getPrincpal(), repaymentScheduleInstallments,
                    new LoanSummaryWrapper(), true);

            // update the total number of schedule repayments
            loan.updateNumberOfRepayments(periods.size());

            // update the loan term frequency (loan term frequency = number
            // of repayments)
            loan.updateTermFrequency(periods.size());

            // update the status of the request
            loanRescheduleRequest.approve(appUser, approvedOnDate);

            // update the derived fields of each loan repayments schedule
            // instalments
            for (final LoanRepaymentScheduleInstallment repaymentScheduleInstallment : repaymentScheduleInstallments) {
                repaymentScheduleInstallment.updateDerivedFields(currency, new LocalDate());
            }

            // update the loan object
            this.loanRepository.save(loan);
        }

        return new CommandProcessingResultBuilder().withCommandId(jsonCommand.commandId())
                .withEntityId(loanRescheduleRequestId).withLoanId(loanRescheduleRequest.getLoan().getId())
                .with(changes).build();
    }

    catch (final DataIntegrityViolationException dve) {
        // handle the data integrity violation
        handleDataIntegrityViolation(dve);

        // return an empty command processing result object
        return CommandProcessingResult.empty();
    }
}

From source file:org.mifosplatform.portfolio.pgs.pgsclient.domain.PGSClient.java

License:Mozilla Public License

public void activate(final AppUser currentUser, final DateTimeFormatter formatter,
        final LocalDate activationLocalDate) {

    if (isActive()) {
        final String defaultUserMessage = "Cannot activate PGS client. Client is already active.";
        final ApiParameterError error = ApiParameterError.parameterError("error.msg.clients.already.active",
                defaultUserMessage, PGSClientApiConstants.activationDateParamName,
                activationLocalDate.toString(formatter));

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException(dataValidationErrors);
    }//from www  .  j av a  2s .  com

    this.activationDate = activationLocalDate.toDate();
    this.activatedBy = currentUser;
    this.officeJoiningDate = this.activationDate;
    this.status = PGSClientStatus.ACTIVE.getValue();

    validate();
}

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

License:Mozilla Public License

public void payCharge(final SavingsAccountCharge savingsAccountCharge, final BigDecimal amountPaid,
        final LocalDate transactionDate, final DateTimeFormatter formatter, final AppUser user) {

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource(SAVINGS_ACCOUNT_RESOURCE_NAME);

    if (isClosed()) {
        baseDataValidator.reset()/*  w  w w  . j a  v  a  2 s. c o  m*/
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.closed");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    if (isNotActive()) {
        baseDataValidator.reset()
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.is.not.active");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    if (savingsAccountCharge.isNotActive()) {
        baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("charge.is.not.active");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    if (getActivationLocalDate() != null && transactionDate.isBefore(getActivationLocalDate())) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName)
                .value(getActivationLocalDate().toString(formatter))
                .failWithCodeNoParameterAddedToErrorCode("transaction.before.activationDate");
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    if (DateUtils.isDateInTheFuture(transactionDate)) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName)
                .value(getSubmittedOnLocalDate().toString(formatter))
                .failWithCodeNoParameterAddedToErrorCode("transaction.is.futureDate");
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    if (savingsAccountCharge.isSavingsActivation()) {
        baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(
                "transaction.not.valid.cannot.pay.activation.time.charge.is.automated");
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    if (savingsAccountCharge.isAnnualFee()) {
        final LocalDate annualFeeDueDate = savingsAccountCharge.getDueLocalDate();
        if (annualFeeDueDate == null) {
            baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("no.annualfee.settings");
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }

        if (!annualFeeDueDate.equals(transactionDate)) {
            baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode("invalid.date");
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }

        Date currentAnnualFeeNextDueDate = findLatestAnnualFeeTransactionDueDate();
        if (currentAnnualFeeNextDueDate != null
                && new LocalDate(currentAnnualFeeNextDueDate).isEqual(transactionDate)) {
            baseDataValidator.reset().parameter("dueDate").value(transactionDate.toString(formatter))
                    .failWithCodeNoParameterAddedToErrorCode("transaction.exists.on.date");

            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    // validate charge is not already paid or waived
    if (savingsAccountCharge.isWaived()) {
        baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(
                "transaction.invalid.account.charge.is.already.waived");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    } else if (savingsAccountCharge.isPaid()) {
        baseDataValidator.reset()
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.account.charge.is.paid");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    final Money chargePaid = Money.of(currency, amountPaid);
    if (!savingsAccountCharge.getAmountOutstanding(getCurrency()).isGreaterThanOrEqualTo(chargePaid)) {
        baseDataValidator.reset()
                .failWithCodeNoParameterAddedToErrorCode("transaction.invalid.charge.amount.paid.in.access");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    this.payCharge(savingsAccountCharge, chargePaid, transactionDate, user);
}

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

License:Mozilla Public License

@Override
public CommandProcessingResult payCharge(final Long savingsAccountId, final Long savingsAccountChargeId,
        final JsonCommand command, @SuppressWarnings("unused") final DepositAccountType depositAccountType) {

    this.context.authenticatedUser();

    this.savingsAccountChargeDataValidator.validatePayCharge(command.json());
    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
    final BigDecimal amountPaid = command.bigDecimalValueOfParameterNamed(amountParamName);
    final LocalDate transactionDate = command.localDateValueOfParameterNamed(dueAsOfDateParamName);

    final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository
            .findOneWithNotFoundDetection(savingsAccountChargeId, savingsAccountId);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource(SAVINGS_ACCOUNT_RESOURCE_NAME);

    // transaction date should not be on a holiday or non working day
    if (!this.holidayWritePlatformService.isTransactionAllowedOnHoliday() && this.holidayWritePlatformService
            .isHoliday(savingsAccountCharge.savingsAccount().officeId(), transactionDate)) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName).value(transactionDate.toString(fmt))
                .failWithCodeNoParameterAddedToErrorCode(
                        "transaction.not.allowed.transaction.date.is.on.holiday");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }/*w ww. ja v a 2s. c  om*/
    }

    if (!this.workingDaysWritePlatformService.isTransactionAllowedOnNonWorkingDay()
            && !this.workingDaysWritePlatformService.isWorkingDay(transactionDate)) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName).value(transactionDate.toString(fmt))
                .failWithCodeNoParameterAddedToErrorCode(
                        "transaction.not.allowed.transaction.date.is.a.nonworking.day");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    this.payCharge(savingsAccountCharge, transactionDate, amountPaid, fmt);
    return new CommandProcessingResultBuilder() //
            .withEntityId(savingsAccountCharge.getId()) //
            .withOfficeId(savingsAccountCharge.savingsAccount().officeId()) //
            .withClientId(savingsAccountCharge.savingsAccount().clientId()) //
            .withGroupId(savingsAccountCharge.savingsAccount().groupId()) //
            .withSavingsId(savingsAccountCharge.savingsAccount().getId()) //
            .build();

}

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

License:Mozilla Public License

@Override
public CommandProcessingResult payCharge(final Long savingsAccountId, final Long savingsAccountChargeId,
        final JsonCommand command) {

    AppUser user = getAppUserIfPresent();

    this.savingsAccountChargeDataValidator.validatePayCharge(command.json());
    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
    final BigDecimal amountPaid = command.bigDecimalValueOfParameterNamed(amountParamName);
    final LocalDate transactionDate = command.localDateValueOfParameterNamed(dueAsOfDateParamName);

    final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository
            .findOneWithNotFoundDetection(savingsAccountChargeId, savingsAccountId);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource(SAVINGS_ACCOUNT_RESOURCE_NAME);

    // transaction date should not be on a holiday or non working day
    if (!this.holidayWritePlatformService.isTransactionAllowedOnHoliday() && this.holidayWritePlatformService
            .isHoliday(savingsAccountCharge.savingsAccount().officeId(), transactionDate)) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName).value(transactionDate.toString(fmt))
                .failWithCodeNoParameterAddedToErrorCode(
                        "transaction.not.allowed.transaction.date.is.on.holiday");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }//w w w.  j  a v a 2s  .c om
    }

    if (!this.workingDaysWritePlatformService.isTransactionAllowedOnNonWorkingDay()
            && !this.workingDaysWritePlatformService.isWorkingDay(transactionDate)) {
        baseDataValidator.reset().parameter(dueAsOfDateParamName).value(transactionDate.toString(fmt))
                .failWithCodeNoParameterAddedToErrorCode(
                        "transaction.not.allowed.transaction.date.is.a.nonworking.day");
        if (!dataValidationErrors.isEmpty()) {
            throw new PlatformApiDataValidationException(dataValidationErrors);
        }
    }

    this.payCharge(savingsAccountCharge, transactionDate, amountPaid, fmt, user);
    return new CommandProcessingResultBuilder() //
            .withEntityId(savingsAccountCharge.getId()) //
            .withOfficeId(savingsAccountCharge.savingsAccount().officeId()) //
            .withClientId(savingsAccountCharge.savingsAccount().clientId()) //
            .withGroupId(savingsAccountCharge.savingsAccount().groupId()) //
            .withSavingsId(savingsAccountCharge.savingsAccount().getId()) //
            .build();

}

From source file:org.mousephenotype.dcc.exportlibrary.datastructure.converters.DatatypeConverter.java

License:Apache License

public static String printDate(Calendar date) {
    if (date == null) {
        logger.trace("date is null");
        return null;
    }//from   ww w.ja v  a 2  s.  com
    logger.trace("printing dateTime {}", date.toString());
    LocalDate localDate = new LocalDate(date, ISOChronology.getInstance());
    return localDate.toString(dateXMLpattern);
}

From source file:org.mpardalos.homework_plus.TaskAdd.java

License:Open Source License

public void onDateEntered(LocalDate date) {
    EditText dateInput = (EditText) findViewById(R.id.due_date_input);
    DateTimeFormatter df = DateTimeFormat.fullDate().withLocale(Locale.getDefault());
    dateInput.setText(date.toString(df));
    dateInput.setTag(R.id.due_date, date);
}

From source file:org.mpardalos.homework_plus.TaskDatabaseHelper.java

License:Open Source License

public void insertTask(Task task) throws IllegalArgumentException {
    String description = task.getDescription();
    LocalDate dueDate = task.getDueDate();
    String subject = task.getSubject();
    String photoPath = null;//w w  w.ja  va2s .  com
    if (task.getPhotoFile() != null) {
        photoPath = task.getPhotoFile().getAbsolutePath();
    }

    if (description == null || dueDate == null || subject == null) {
        throw new IllegalArgumentException("All arguments must be non null");
    }

    SQLiteDatabase db = getWritableDatabase();
    DateTimeFormatter dbDateFormat = DateTimeFormat
            .forPattern(mContext.getResources().getString(R.string.database_date_format));

    ContentValues taskCV = new ContentValues();
    taskCV.put(TASK_DESCRIPTION, description);
    taskCV.put(DUE_DATE, dueDate.toString(dbDateFormat));
    taskCV.put(SUBJECT_ID, getSubjectId(subject));
    taskCV.put(TASK_DONE, false);
    taskCV.put(TASK_PHOTO_LOCATION, photoPath);

    db.insert(TASKS_TABLE, null, taskCV);
}

From source file:org.ojbc.web.portal.controllers.dto.PersonFilterCommand.java

License:RPL License

private void computeDOBRangeFromAgeRange() {

    if (filterAgeRangeStart == null) {
        filterDOBStart = "";
        filterDOBEnd = "";
    } else {/*from  ww w .  j ava2  s . c  om*/
        LocalDate today = new LocalDate();

        LocalDate computedStartDOB = today.minusYears(filterAgeRangeEnd).minusYears(1).plusDays(1);
        filterDOBStart = computedStartDOB.toString("yyyy-MM-dd");

        LocalDate computedEndDOB = today.minusYears(filterAgeRangeStart);
        filterDOBEnd = computedEndDOB.toString("yyyy-MM-dd");
    }
}

From source file:org.projectbuendia.client.ui.chart.LocalizedChartDataGridAdapter.java

License:Apache License

private String formatColumnHeader(String columnId) {
    DateTime dateTime = DateTime.parse(columnId).withChronology(mChronology);
    LocalDate date = dateTime.toLocalDate();
    Resources res = mContext.getResources();

    int admitDay = Dates.dayNumberSince(mAdmissionDate, date);
    String admitDayLabel = (admitDay >= 1) ? res.getString(R.string.day_n, admitDay) : "";

    String dateString = date.toString("d MMM");
    String dateLabel = date.equals(mToday) ? res.getString(R.string.today_date, dateString) : dateString;

    // The column header has two lines of text: the first line gives the day number since
    // admission and the second line gives the calendar date.  Pending feedback from the field
    // on its importance, the symptom onset day number could also be shown in the column
    // header in a different colour.  This would be done by constructing HTML and using
    // Html.fromHtml() to produce a Spanned object that will be rendered by the TextView.
    return admitDayLabel + "\n" + dateLabel;
}