Example usage for org.joda.time.format DateTimeFormat forPattern

List of usage examples for org.joda.time.format DateTimeFormat forPattern

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormat forPattern.

Prototype

public static DateTimeFormatter forPattern(String pattern) 

Source Link

Document

Factory to create a formatter from a pattern string.

Usage

From source file:com.gst.infrastructure.reportmailingjob.validation.ReportMailingJobValidator.java

License:Apache License

/** 
 * validate the request to create a new report mailing job 
 * //  w  w  w  .  j  av a  2  s  .c  o m
 * @param jsonCommand -- the JSON command object (instance of the JsonCommand class)
 * @return None
 **/
public void validateCreateRequest(final JsonCommand jsonCommand) {
    final String jsonString = jsonCommand.json();
    final JsonElement jsonElement = jsonCommand.parsedJson();

    if (StringUtils.isBlank(jsonString)) {
        throw new InvalidJsonException();
    }

    final Type typeToken = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString,
            ReportMailingJobConstants.CREATE_REQUEST_PARAMETERS);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors)
            .resource(StringUtils.lowerCase(ReportMailingJobConstants.REPORT_MAILING_JOB_RESOURCE_NAME));

    final String name = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.NAME_PARAM_NAME,
            jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.NAME_PARAM_NAME).value(name).notBlank()
            .notExceedingLengthOf(100);

    final String startDateTime = this.fromJsonHelper
            .extractStringNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME)
            .value(startDateTime).notBlank();

    final Integer stretchyReportId = this.fromJsonHelper.extractIntegerWithLocaleNamed(
            ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME)
            .value(stretchyReportId).notNull().integerGreaterThanZero();

    final String emailRecipients = this.fromJsonHelper
            .extractStringNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME)
            .value(emailRecipients).notBlank();

    final String emailSubject = this.fromJsonHelper
            .extractStringNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME)
            .value(emailSubject).notBlank().notExceedingLengthOf(100);

    final String emailMessage = this.fromJsonHelper
            .extractStringNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME)
            .value(emailMessage).notBlank();

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) {
        final Boolean isActive = this.fromJsonHelper
                .extractBooleanNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME).value(isActive)
                .notNull();
    }

    final Integer emailAttachmentFileFormatId = this.fromJsonHelper.extractIntegerSansLocaleNamed(
            ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement);
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
            .value(emailAttachmentFileFormatId).notNull();

    if (emailAttachmentFileFormatId != null) {
        dataValidatorBuilder.reset()
                .parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
                .value(emailAttachmentFileFormatId)
                .isOneOfTheseValues(ReportMailingJobEmailAttachmentFileFormat.validIds());
    }

    final String dateFormat = jsonCommand.dateFormat();
    dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME).value(dateFormat)
            .notBlank();

    if (StringUtils.isNotEmpty(dateFormat)) {

        try {
            final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat)
                    .withLocale(jsonCommand.extractLocale());

            // try to parse the date time string
            LocalDateTime.parse(startDateTime, dateTimeFormatter);
        }

        catch (IllegalArgumentException ex) {
            dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME)
                    .value(dateFormat).failWithCode("invalid.date.format");
        }
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:com.gst.infrastructure.reportmailingjob.validation.ReportMailingJobValidator.java

License:Apache License

/** 
 * validate the request to update a report mailing job 
 * //from   w  w w  .  ja va  2  s.c  om
 * @param jsonCommand -- the JSON command object (instance of the JsonCommand class)
 * @return None
 **/
public void validateUpdateRequest(final JsonCommand jsonCommand) {
    final String jsonString = jsonCommand.json();
    final JsonElement jsonElement = jsonCommand.parsedJson();

    if (StringUtils.isBlank(jsonString)) {
        throw new InvalidJsonException();
    }

    final Type typeToken = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString,
            ReportMailingJobConstants.UPDATE_REQUEST_PARAMETERS);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors)
            .resource(StringUtils.lowerCase(ReportMailingJobConstants.REPORT_MAILING_JOB_RESOURCE_NAME));

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.NAME_PARAM_NAME, jsonElement)) {
        final String name = this.fromJsonHelper.extractStringNamed(ReportMailingJobConstants.NAME_PARAM_NAME,
                jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.NAME_PARAM_NAME).value(name).notBlank()
                .notExceedingLengthOf(100);
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME,
            jsonElement)) {
        final Integer stretchyReportId = this.fromJsonHelper.extractIntegerWithLocaleNamed(
                ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.STRETCHY_REPORT_ID_PARAM_NAME)
                .value(stretchyReportId).notNull().integerGreaterThanZero();
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME,
            jsonElement)) {
        final String emailRecipients = this.fromJsonHelper
                .extractStringNamed(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_RECIPIENTS_PARAM_NAME)
                .value(emailRecipients).notBlank();
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement)) {
        final String emailSubject = this.fromJsonHelper
                .extractStringNamed(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_SUBJECT_PARAM_NAME)
                .value(emailSubject).notBlank().notExceedingLengthOf(100);
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement)) {
        final String emailMessage = this.fromJsonHelper
                .extractStringNamed(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.EMAIL_MESSAGE_PARAM_NAME)
                .value(emailMessage).notBlank();
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement)) {
        final Boolean isActive = this.fromJsonHelper
                .extractBooleanNamed(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.IS_ACTIVE_PARAM_NAME).value(isActive)
                .notNull();
    }

    if (this.fromJsonHelper.parameterExists(
            ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement)) {
        final Integer emailAttachmentFileFormatId = this.fromJsonHelper.extractIntegerSansLocaleNamed(
                ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset()
                .parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
                .value(emailAttachmentFileFormatId).notNull();

        if (emailAttachmentFileFormatId != null) {
            dataValidatorBuilder.reset()
                    .parameter(ReportMailingJobConstants.EMAIL_ATTACHMENT_FILE_FORMAT_ID_PARAM_NAME)
                    .value(emailAttachmentFileFormatId)
                    .isOneOfTheseValues(ReportMailingJobEmailAttachmentFileFormat.validIds());
        }
    }

    if (this.fromJsonHelper.parameterExists(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME,
            jsonElement)) {
        final String dateFormat = jsonCommand.dateFormat();
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME)
                .value(dateFormat).notBlank();

        final String startDateTime = this.fromJsonHelper
                .extractStringNamed(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME, jsonElement);
        dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.START_DATE_TIME_PARAM_NAME)
                .value(startDateTime).notBlank();

        if (StringUtils.isNotEmpty(dateFormat)) {

            try {
                final DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(dateFormat)
                        .withLocale(jsonCommand.extractLocale());

                // try to parse the date time string
                LocalDateTime.parse(startDateTime, dateTimeFormatter);
            }

            catch (IllegalArgumentException ex) {
                dataValidatorBuilder.reset().parameter(ReportMailingJobConstants.DATE_FORMAT_PARAM_NAME)
                        .value(dateFormat).failWithCode("invalid.date.format");
            }
        }
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:com.gst.portfolio.account.service.AccountTransfersWritePlatformServiceImpl.java

License:Apache License

@Transactional
@Override/*from  ww  w  . j  a  va  2s.c om*/
public CommandProcessingResult create(final JsonCommand command) {
    boolean isRegularTransaction = true;

    this.accountTransfersDataValidator.validate(command);

    final LocalDate transactionDate = command.localDateValueOfParameterNamed(transferDateParamName);
    final BigDecimal transactionAmount = command.bigDecimalValueOfParameterNamed(transferAmountParamName);

    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);

    final Integer fromAccountTypeId = command.integerValueSansLocaleOfParameterNamed(fromAccountTypeParamName);
    final PortfolioAccountType fromAccountType = PortfolioAccountType.fromInt(fromAccountTypeId);

    final Integer toAccountTypeId = command.integerValueSansLocaleOfParameterNamed(toAccountTypeParamName);
    final PortfolioAccountType toAccountType = PortfolioAccountType.fromInt(toAccountTypeId);

    final PaymentDetail paymentDetail = null;
    Long fromSavingsAccountId = null;
    Long transferDetailId = null;
    boolean isInterestTransfer = false;
    boolean isAccountTransfer = true;
    Long fromLoanAccountId = null;
    boolean isWithdrawBalance = false;

    if (isSavingsToSavingsAccountTransfer(fromAccountType, toAccountType)) {

        fromSavingsAccountId = command.longValueOfParameterNamed(fromAccountIdParamName);
        final SavingsAccount fromSavingsAccount = this.savingsAccountAssembler
                .assembleFrom(fromSavingsAccountId);

        final SavingsTransactionBooleanValues transactionBooleanValues = new SavingsTransactionBooleanValues(
                isAccountTransfer, isRegularTransaction,
                fromSavingsAccount.isWithdrawalFeeApplicableForTransfer(), isInterestTransfer,
                isWithdrawBalance);
        final SavingsAccountTransaction withdrawal = this.savingsAccountDomainService.handleWithdrawal(
                fromSavingsAccount, fmt, transactionDate, transactionAmount, paymentDetail,
                transactionBooleanValues);

        final Long toSavingsId = command.longValueOfParameterNamed(toAccountIdParamName);
        final SavingsAccount toSavingsAccount = this.savingsAccountAssembler.assembleFrom(toSavingsId);

        final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(
                toSavingsAccount, fmt, transactionDate, transactionAmount, paymentDetail, isAccountTransfer,
                isRegularTransaction);

        final AccountTransferDetails accountTransferDetails = this.accountTransferAssembler
                .assembleSavingsToSavingsTransfer(command, fromSavingsAccount, toSavingsAccount, withdrawal,
                        deposit);
        this.accountTransferDetailRepository.saveAndFlush(accountTransferDetails);
        transferDetailId = accountTransferDetails.getId();

    } else if (isSavingsToLoanAccountTransfer(fromAccountType, toAccountType)) {
        //
        fromSavingsAccountId = command.longValueOfParameterNamed(fromAccountIdParamName);
        final SavingsAccount fromSavingsAccount = this.savingsAccountAssembler
                .assembleFrom(fromSavingsAccountId);

        final SavingsTransactionBooleanValues transactionBooleanValues = new SavingsTransactionBooleanValues(
                isAccountTransfer, isRegularTransaction,
                fromSavingsAccount.isWithdrawalFeeApplicableForTransfer(), isInterestTransfer,
                isWithdrawBalance);
        final SavingsAccountTransaction withdrawal = this.savingsAccountDomainService.handleWithdrawal(
                fromSavingsAccount, fmt, transactionDate, transactionAmount, paymentDetail,
                transactionBooleanValues);

        final Long toLoanAccountId = command.longValueOfParameterNamed(toAccountIdParamName);
        final Loan toLoanAccount = this.loanAccountAssembler.assembleFrom(toLoanAccountId);

        final Boolean isHolidayValidationDone = false;
        final HolidayDetailDTO holidayDetailDto = null;
        final boolean isRecoveryRepayment = false;
        final LoanTransaction loanRepaymentTransaction = this.loanAccountDomainService.makeRepayment(
                toLoanAccount, new CommandProcessingResultBuilder(), transactionDate, transactionAmount,
                paymentDetail, null, null, isRecoveryRepayment, isAccountTransfer, holidayDetailDto,
                isHolidayValidationDone);

        final AccountTransferDetails accountTransferDetails = this.accountTransferAssembler
                .assembleSavingsToLoanTransfer(command, fromSavingsAccount, toLoanAccount, withdrawal,
                        loanRepaymentTransaction);
        this.accountTransferDetailRepository.saveAndFlush(accountTransferDetails);
        transferDetailId = accountTransferDetails.getId();

    } else if (isLoanToSavingsAccountTransfer(fromAccountType, toAccountType)) {
        // FIXME - kw - ADD overpaid loan to savings account transfer
        // support.

        fromLoanAccountId = command.longValueOfParameterNamed(fromAccountIdParamName);
        final Loan fromLoanAccount = this.loanAccountAssembler.assembleFrom(fromLoanAccountId);

        final LoanTransaction loanRefundTransaction = this.loanAccountDomainService.makeRefund(
                fromLoanAccountId, new CommandProcessingResultBuilder(), transactionDate, transactionAmount,
                paymentDetail, null, null);

        final Long toSavingsAccountId = command.longValueOfParameterNamed(toAccountIdParamName);
        final SavingsAccount toSavingsAccount = this.savingsAccountAssembler.assembleFrom(toSavingsAccountId);

        final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(
                toSavingsAccount, fmt, transactionDate, transactionAmount, paymentDetail, isAccountTransfer,
                isRegularTransaction);

        final AccountTransferDetails accountTransferDetails = this.accountTransferAssembler
                .assembleLoanToSavingsTransfer(command, fromLoanAccount, toSavingsAccount, deposit,
                        loanRefundTransaction);
        this.accountTransferDetailRepository.saveAndFlush(accountTransferDetails);
        transferDetailId = accountTransferDetails.getId();

    } else {

    }

    final CommandProcessingResultBuilder builder = new CommandProcessingResultBuilder()
            .withEntityId(transferDetailId);

    if (fromAccountType.isSavingsAccount()) {
        builder.withSavingsId(fromSavingsAccountId);
    }
    if (fromAccountType.isLoanAccount()) {
        builder.withLoanId(fromLoanAccountId);
    }

    return builder.build();
}

From source file:com.gst.portfolio.account.service.AccountTransfersWritePlatformServiceImpl.java

License:Apache License

@Override
@Transactional/*from   w w w .j  av  a 2  s  . co m*/
public CommandProcessingResult refundByTransfer(JsonCommand command) {
    // TODO Auto-generated method stub
    this.accountTransfersDataValidator.validate(command);

    final LocalDate transactionDate = command.localDateValueOfParameterNamed(transferDateParamName);
    final BigDecimal transactionAmount = command.bigDecimalValueOfParameterNamed(transferAmountParamName);

    final Locale locale = command.extractLocale();
    final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);

    final PaymentDetail paymentDetail = null;
    Long transferTransactionId = null;

    final Long fromLoanAccountId = command.longValueOfParameterNamed(fromAccountIdParamName);
    final Loan fromLoanAccount = this.loanAccountAssembler.assembleFrom(fromLoanAccountId);

    BigDecimal overpaid = this.loanReadPlatformService.retrieveTotalPaidInAdvance(fromLoanAccountId)
            .getPaidInAdvance();

    if (overpaid == null || overpaid.equals(BigDecimal.ZERO)
            || transactionAmount.floatValue() > overpaid.floatValue()) {
        if (overpaid == null)
            overpaid = BigDecimal.ZERO;
        throw new InvalidPaidInAdvanceAmountException(overpaid.toPlainString());
    }

    final LoanTransaction loanRefundTransaction = this.loanAccountDomainService.makeRefundForActiveLoan(
            fromLoanAccountId, new CommandProcessingResultBuilder(), transactionDate, transactionAmount,
            paymentDetail, null, null);

    final Long toSavingsAccountId = command.longValueOfParameterNamed(toAccountIdParamName);
    final SavingsAccount toSavingsAccount = this.savingsAccountAssembler.assembleFrom(toSavingsAccountId);

    final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(toSavingsAccount,
            fmt, transactionDate, transactionAmount, paymentDetail, true, true);

    final AccountTransferDetails accountTransferDetails = this.accountTransferAssembler
            .assembleLoanToSavingsTransfer(command, fromLoanAccount, toSavingsAccount, deposit,
                    loanRefundTransaction);
    this.accountTransferDetailRepository.saveAndFlush(accountTransferDetails);
    transferTransactionId = accountTransferDetails.getId();

    final CommandProcessingResultBuilder builder = new CommandProcessingResultBuilder()
            .withEntityId(transferTransactionId);

    // if (fromAccountType.isSavingsAccount()) {

    builder.withSavingsId(toSavingsAccountId);
    // }

    return builder.build();
}

From source file:com.gst.portfolio.address.domain.Address.java

License:Apache License

public static Address fromJsonObject(final JsonObject jsonObject, final CodeValue state_province,
        final CodeValue country) {
    String street = "";
    String addressLine1 = "";
    String addressLine2 = "";
    String addressLine3 = "";
    String townVillage = "";
    String city = "";
    String countyDistrict = "";
    String postalCode = "";
    BigDecimal latitude = BigDecimal.ZERO;
    BigDecimal longitude = BigDecimal.ZERO;
    String createdBy = "";
    Locale locale = Locale.ENGLISH;
    String updatedBy = "";
    LocalDate updatedOnDate = null;
    LocalDate createdOnDate = null;

    if (jsonObject.has("street")) {
        street = jsonObject.get("street").getAsString();

    }/*ww w .j av a 2  s  .c o  m*/

    if (jsonObject.has("addressLine1")) {
        addressLine1 = jsonObject.get("addressLine1").getAsString();
    }
    if (jsonObject.has("addressLine2")) {

        addressLine2 = jsonObject.get("addressLine2").getAsString();
    }
    if (jsonObject.has("addressLine3")) {
        addressLine3 = jsonObject.get("addressLine3").getAsString();
    }
    if (jsonObject.has("townVillage")) {
        townVillage = jsonObject.get("townVillage").getAsString();
    }
    if (jsonObject.has("city")) {
        city = jsonObject.get("city").getAsString();
    }
    if (jsonObject.has("countyDistrict")) {
        countyDistrict = jsonObject.get("countyDistrict").getAsString();
    }
    if (jsonObject.has("postalCode")) {

        postalCode = jsonObject.get("postalCode").getAsString();
    }
    if (jsonObject.has("latitude")) {

        latitude = jsonObject.get("latitude").getAsBigDecimal();
    }
    if (jsonObject.has("longitude")) {

        longitude = jsonObject.get("longitude").getAsBigDecimal();
    }

    if (jsonObject.has("createdBy")) {
        createdBy = jsonObject.get("createdBy").getAsString();
    }
    if (jsonObject.has("createdOn")) {
        String createdOn = jsonObject.get("createdOn").getAsString();
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        createdOnDate = LocalDate.parse(createdOn, formatter);

    }
    if (jsonObject.has("updatedBy")) {
        updatedBy = jsonObject.get("updatedBy").getAsString();
    }
    if (jsonObject.has("updatedOn")) {
        String updatedOn = jsonObject.get("updatedOn").getAsString();
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
        updatedOnDate = LocalDate.parse(updatedOn, formatter);
    }

    return new Address(street, addressLine1, addressLine2, addressLine3, townVillage, city, countyDistrict,
            state_province, country, postalCode, latitude, longitude, createdBy, createdOnDate, updatedBy,
            updatedOnDate);
}

From source file:com.gst.portfolio.calendar.service.CalendarUtils.java

License:Apache License

public static String getRRuleReadable(final LocalDate startDate, final String recurringRule) {

    String humanReadable = "";

    RRule rrule;//from w w  w  .jav  a2s.  c om
    Recur recur = null;
    try {
        rrule = new RRule(recurringRule);
        rrule.validate();
        recur = rrule.getRecur();
    } catch (final ValidationException e) {
        throw new PlatformDataIntegrityException("error.msg.invalid.recurring.rule",
                "The Recurring Rule value: " + recurringRule + " is not valid.", "recurrence", recurringRule);
    } catch (final ParseException e) {
        throw new PlatformDataIntegrityException("error.msg.recurring.rule.parsing.error",
                "Error in pasring the Recurring Rule value: " + recurringRule, "recurrence", recurringRule);
    }

    if (recur == null) {
        return humanReadable;
    }

    if (recur.getFrequency().equals(Recur.DAILY)) {
        if (recur.getInterval() == 1) {
            humanReadable = "Daily";
        } else {
            humanReadable = "Every " + recur.getInterval() + " days";
        }
    } else if (recur.getFrequency().equals(Recur.WEEKLY)) {
        if (recur.getInterval() == 1 || recur.getInterval() == -1) {
            humanReadable = "Weekly";
        } else {
            humanReadable = "Every " + recur.getInterval() + " weeks";
        }

        humanReadable += " on ";
        final WeekDayList weekDayList = recur.getDayList();

        for (@SuppressWarnings("rawtypes")
        final Iterator iterator = weekDayList.iterator(); iterator.hasNext();) {
            final WeekDay weekDay = (WeekDay) iterator.next();
            humanReadable += DayNameEnum.from(weekDay.getDay()).getCode();
        }

    } else if (recur.getFrequency().equals(Recur.MONTHLY)) {
        NumberList nthDays = recur.getSetPosList();
        Integer nthDay = null;
        if (!nthDays.isEmpty())
            nthDay = (Integer) nthDays.get(0);
        NumberList monthDays = recur.getMonthDayList();
        Integer monthDay = null;
        if (!monthDays.isEmpty())
            monthDay = (Integer) monthDays.get(0);
        WeekDayList weekdays = recur.getDayList();
        WeekDay weekDay = null;
        if (!weekdays.isEmpty())
            weekDay = (WeekDay) weekdays.get(0);
        if (nthDay != null && weekDay != null) {
            NthDayType nthDayType = NthDayType.fromInt(nthDay);
            NthDayNameEnum nthDayName = NthDayNameEnum.from(nthDayType.toString());
            DayNameEnum weekdayType = DayNameEnum.from(weekDay.getDay());
            if (recur.getInterval() == 1 || recur.getInterval() == -1) {
                humanReadable = "Monthly on " + nthDayName.getCode().toLowerCase() + " "
                        + weekdayType.getCode().toLowerCase();
            } else {
                humanReadable = "Every " + recur.getInterval() + " months on "
                        + nthDayName.getCode().toLowerCase() + " " + weekdayType.getCode().toLowerCase();
            }
        } else if (monthDay != null) {
            if (monthDay == -1) {
                if (recur.getInterval() == 1 || recur.getInterval() == -1) {
                    humanReadable = "Monthly on last day";
                } else {
                    humanReadable = "Every " + recur.getInterval() + " months on last day";
                }
            } else {
                if (recur.getInterval() == 1 || recur.getInterval() == -1) {
                    humanReadable = "Monthly on day " + monthDay;
                } else {
                    humanReadable = "Every " + recur.getInterval() + " months on day " + monthDay;
                }
            }
        } else {
            if (recur.getInterval() == 1 || recur.getInterval() == -1) {
                humanReadable = "Monthly on day " + startDate.getDayOfMonth();
            } else {
                humanReadable = "Every " + recur.getInterval() + " months on day " + startDate.getDayOfMonth();
            }
        }
    } else if (recur.getFrequency().equals(Recur.YEARLY)) {
        if (recur.getInterval() == 1) {
            humanReadable = "Annually on " + startDate.toString("MMM") + " " + startDate.getDayOfMonth();
        } else {
            humanReadable = "Every " + recur.getInterval() + " years on " + startDate.toString("MMM") + " "
                    + startDate.getDayOfMonth();
        }
    }

    if (recur.getCount() > 0) {
        if (recur.getCount() == 1) {
            humanReadable = "Once";
        }
        humanReadable += ", " + recur.getCount() + " times";
    }

    final Date endDate = recur.getUntil();
    final LocalDate date = new LocalDate(endDate);
    final DateTimeFormatter fmt = DateTimeFormat.forPattern("dd MMMM YY");
    final String formattedDate = date.toString(fmt);
    if (endDate != null) {
        humanReadable += ", until " + formattedDate;
    }

    return humanReadable;
}

From source file:com.gst.portfolio.calendar.service.CalendarWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

@Override
public CommandProcessingResult createCalendar(final JsonCommand command) {

    this.fromApiJsonDeserializer.validateForCreate(command.json());
    Long entityId = null;/*from w  w  w .j  a  v a  2  s.  c om*/
    CalendarEntityType entityType = CalendarEntityType.INVALID;
    LocalDate entityActivationDate = null;
    Group centerOrGroup = null;
    if (command.getGroupId() != null) {
        centerOrGroup = this.groupRepository.findOneWithNotFoundDetection(command.getGroupId());
        entityActivationDate = centerOrGroup.getActivationLocalDate();
        entityType = centerOrGroup.isCenter() ? CalendarEntityType.CENTERS : CalendarEntityType.GROUPS;
        entityId = command.getGroupId();
    } else if (command.getLoanId() != null) {
        final Loan loan = this.loanRepositoryWrapper.findOneWithNotFoundDetection(command.getLoanId(), true);
        entityActivationDate = (loan.getApprovedOnDate() == null) ? loan.getSubmittedOnDate()
                : loan.getApprovedOnDate();
        entityType = CalendarEntityType.LOANS;
        entityId = command.getLoanId();
    } else if (command.getClientId() != null) {
        final Client client = this.clientRepository.findOneWithNotFoundDetection(command.getClientId());
        entityActivationDate = client.getActivationLocalDate();
        entityType = CalendarEntityType.CLIENTS;
        entityId = command.getClientId();
    }

    final Integer entityTypeId = entityType.getValue();
    final Calendar newCalendar = Calendar.fromJson(command);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("calendar");
    if (entityActivationDate == null || newCalendar.getStartDateLocalDate().isBefore(entityActivationDate)) {
        final DateTimeFormatter formatter = DateTimeFormat.forPattern(command.dateFormat())
                .withLocale(command.extractLocale());
        String dateAsString = "";
        if (entityActivationDate != null)
            dateAsString = formatter.print(entityActivationDate);

        final String errorMessage = "cannot.be.before." + entityType.name().toLowerCase() + ".activation.date";
        baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.START_DATE.getValue())
                .value(dateAsString).failWithCodeNoParameterAddedToErrorCode(errorMessage);
    }

    if (centerOrGroup != null) {
        Long centerOrGroupId = centerOrGroup.getId();
        Integer centerOrGroupEntityTypeId = entityType.getValue();

        final Group parent = centerOrGroup.getParent();
        if (parent != null) {
            centerOrGroupId = parent.getId();
            centerOrGroupEntityTypeId = CalendarEntityType.CENTERS.getValue();
        }

        final CalendarInstance collectionCalendarInstance = this.calendarInstanceRepository
                .findByEntityIdAndEntityTypeIdAndCalendarTypeId(centerOrGroupId, centerOrGroupEntityTypeId,
                        CalendarType.COLLECTION.getValue());
        if (collectionCalendarInstance != null) {
            final String errorMessage = "multiple.collection.calendar.not.supported";
            baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(errorMessage);
        }
    }

    if (!dataValidationErrors.isEmpty()) {
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }

    this.calendarRepository.save(newCalendar);

    final CalendarInstance newCalendarInstance = CalendarInstance.from(newCalendar, entityId, entityTypeId);
    this.calendarInstanceRepository.save(newCalendarInstance);

    return new CommandProcessingResultBuilder() //
            .withCommandId(command.commandId()) //
            .withEntityId(newCalendar.getId()) //
            .withClientId(command.getClientId()) //
            .withGroupId(command.getGroupId()) //
            .withLoanId(command.getLoanId()) //
            .build();

}

From source file:com.gst.portfolio.client.service.ClientChargeWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

@Override
public CommandProcessingResult addCharge(Long clientId, JsonCommand command) {
    try {/*ww  w  .j av a  2  s.  co  m*/
        this.clientChargeDataValidator.validateAdd(command.json());

        final Client client = clientRepository.getActiveClientInUserScope(clientId);

        final Long chargeDefinitionId = command.longValueOfParameterNamed(ClientApiConstants.chargeIdParamName);
        final Charge charge = this.chargeRepository.findOneWithNotFoundDetection(chargeDefinitionId);

        // validate for client charge
        if (!charge.isClientCharge()) {
            final String errorMessage = "Charge with identifier " + charge.getId()
                    + " cannot be applied to a Client";
            throw new ChargeCannotBeAppliedToException("client", errorMessage, charge.getId());
        }

        final ClientCharge clientCharge = ClientCharge.createNew(client, charge, command);
        final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat());
        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
                .resource(ClientApiConstants.CLIENT_CHARGES_RESOURCE_NAME);
        LocalDate activationDate = client.getActivationLocalDate();
        LocalDate dueDate = clientCharge.getDueLocalDate();
        if (dueDate.isBefore(activationDate)) {
            baseDataValidator.reset().parameter(ClientApiConstants.dueAsOfDateParamName)
                    .value(dueDate.toString(fmt))
                    .failWithCodeNoParameterAddedToErrorCode("dueDate.before.activationDate");

            if (!dataValidationErrors.isEmpty()) {
                throw new PlatformApiDataValidationException(dataValidationErrors);
            }
        }

        validateDueDateOnWorkingDay(clientCharge, fmt);
        this.clientChargeRepository.saveAndFlush(clientCharge);

        return new CommandProcessingResultBuilder() //
                .withEntityId(clientCharge.getId()) //
                .withOfficeId(clientCharge.getClient().getOffice().getId()) //
                .withClientId(clientCharge.getClient().getId()) //
                .build();
    } catch (DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(clientId, null, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.gst.portfolio.client.service.ClientChargeWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

@Override
public CommandProcessingResult payCharge(Long clientId, Long clientChargeId, JsonCommand command) {
    try {/*from  ww w  .ja  v a2s .c o  m*/
        this.clientChargeDataValidator.validatePayCharge(command.json());

        final Client client = this.clientRepository.getActiveClientInUserScope(clientId);

        final ClientCharge clientCharge = this.clientChargeRepository
                .findOneWithNotFoundDetection(clientChargeId);

        final Locale locale = command.extractLocale();
        final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
        final LocalDate transactionDate = command
                .localDateValueOfParameterNamed(ClientApiConstants.transactionDateParamName);
        final BigDecimal amountPaid = command
                .bigDecimalValueOfParameterNamed(ClientApiConstants.amountParamName);
        final Money chargePaid = Money.of(clientCharge.getCurrency(), amountPaid);

        // Validate business rules for payment
        validatePaymentTransaction(client, clientCharge, fmt, transactionDate, amountPaid);

        // pay the charge
        clientCharge.pay(chargePaid);

        // create Payment Transaction
        final Map<String, Object> changes = new LinkedHashMap<>();
        final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService
                .createAndPersistPaymentDetail(command, changes);

        ClientTransaction clientTransaction = ClientTransaction.payCharge(client, client.getOffice(),
                paymentDetail, transactionDate, chargePaid, clientCharge.getCurrency().getCode(),
                getAppUserIfPresent());
        this.clientTransactionRepository.saveAndFlush(clientTransaction);

        // update charge paid by associations
        final ClientChargePaidBy chargePaidBy = ClientChargePaidBy.instance(clientTransaction, clientCharge,
                amountPaid);
        clientTransaction.getClientChargePaidByCollection().add(chargePaidBy);

        // generate accounting entries
        generateAccountingEntries(clientTransaction);

        return new CommandProcessingResultBuilder() //
                .withTransactionId(clientTransaction.getId().toString())//
                .withEntityId(clientCharge.getId()) //
                .withOfficeId(clientCharge.getClient().getOffice().getId()) //
                .withClientId(clientCharge.getClient().getId()).build();
    } catch (DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(clientId, clientChargeId, dve);
        return CommandProcessingResult.empty();
    }

}

From source file:com.gst.portfolio.client.service.ClientWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

@Transactional
@Override/*from  w  w w . j a  va 2 s . c  o m*/
public CommandProcessingResult createClient(final JsonCommand command) {

    try {
        final AppUser currentUser = this.context.authenticatedUser();

        this.fromApiJsonDeserializer.validateForCreate(command.json());

        final GlobalConfigurationPropertyData configuration = this.configurationReadPlatformService
                .retrieveGlobalConfiguration("Enable-Address");

        final Boolean isAddressEnabled = configuration.isEnabled();

        final Long officeId = command.longValueOfParameterNamed(ClientApiConstants.officeIdParamName);

        final Office clientOffice = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);

        final Long groupId = command.longValueOfParameterNamed(ClientApiConstants.groupIdParamName);

        Group clientParentGroup = null;
        if (groupId != null) {
            clientParentGroup = this.groupRepository.findOne(groupId);
            if (clientParentGroup == null) {
                throw new GroupNotFoundException(groupId);
            }
        }

        Staff staff = null;
        final Long staffId = command.longValueOfParameterNamed(ClientApiConstants.staffIdParamName);
        if (staffId != null) {
            staff = this.staffRepository.findByOfficeHierarchyWithNotFoundDetection(staffId,
                    clientOffice.getHierarchy());
        }

        CodeValue gender = null;
        final Long genderId = command.longValueOfParameterNamed(ClientApiConstants.genderIdParamName);
        if (genderId != null) {
            gender = this.codeValueRepository
                    .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.GENDER, genderId);
        }

        CodeValue clientType = null;
        final Long clientTypeId = command.longValueOfParameterNamed(ClientApiConstants.clientTypeIdParamName);
        if (clientTypeId != null) {
            clientType = this.codeValueRepository
                    .findOneByCodeNameAndIdWithNotFoundDetection(ClientApiConstants.CLIENT_TYPE, clientTypeId);
        }

        CodeValue clientClassification = null;
        final Long clientClassificationId = command
                .longValueOfParameterNamed(ClientApiConstants.clientClassificationIdParamName);
        if (clientClassificationId != null) {
            clientClassification = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection(
                    ClientApiConstants.CLIENT_CLASSIFICATION, clientClassificationId);
        }

        final Long savingsProductId = command
                .longValueOfParameterNamed(ClientApiConstants.savingsProductIdParamName);
        if (savingsProductId != null) {
            SavingsProduct savingsProduct = this.savingsProductRepository.findOne(savingsProductId);
            if (savingsProduct == null) {
                throw new SavingsProductNotFoundException(savingsProductId);
            }
        }

        final Integer legalFormParamValue = command
                .integerValueOfParameterNamed(ClientApiConstants.legalFormIdParamName);
        boolean isEntity = false;
        Integer legalFormValue = null;
        if (legalFormParamValue != null) {
            LegalForm legalForm = LegalForm.fromInt(legalFormParamValue);
            if (legalForm != null) {
                legalFormValue = legalForm.getValue();
                isEntity = legalForm.isEntity();
            }
        }

        final Client newClient = Client.createNew(currentUser, clientOffice, clientParentGroup, staff,
                savingsProductId, gender, clientType, clientClassification, legalFormValue, command);
        this.clientRepository.save(newClient);
        boolean rollbackTransaction = false;
        if (newClient.isActive()) {
            validateParentGroupRulesBeforeClientActivation(newClient);
            runEntityDatatableCheck(newClient.getId());
            final CommandWrapper commandWrapper = new CommandWrapperBuilder().activateClient(null).build();
            rollbackTransaction = this.commandProcessingService.validateCommand(commandWrapper, currentUser);
        }

        this.clientRepository.save(newClient);
        if (newClient.isActive()) {
            this.businessEventNotifierService.notifyBusinessEventWasExecuted(BUSINESS_EVENTS.CLIENTS_ACTIVATE,
                    constructEntityMap(BUSINESS_ENTITY.CLIENT, newClient));
        }
        if (newClient.isAccountNumberRequiresAutoGeneration()) {
            AccountNumberFormat accountNumberFormat = this.accountNumberFormatRepository
                    .findByAccountType(EntityAccountType.CLIENT);
            newClient.updateAccountNo(accountNumberGenerator.generate(newClient, accountNumberFormat));
            this.clientRepository.save(newClient);
        }

        final Locale locale = command.extractLocale();
        final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
        CommandProcessingResult result = openSavingsAccount(newClient, fmt);
        if (result.getSavingsId() != null) {
            this.clientRepository.save(newClient);

        }

        if (isEntity) {
            extractAndCreateClientNonPerson(newClient, command);
        }

        if (isAddressEnabled) {
            this.addressWritePlatformService.addNewClientAddress(newClient, command);
        }

        if (command.parameterExists(ClientApiConstants.datatables)) {
            this.entityDatatableChecksWritePlatformService.saveDatatables(
                    StatusEnum.CREATE.getCode().longValue(), EntityTables.CLIENT.getName(), newClient.getId(),
                    null, command.arrayOfParameterNamed(ClientApiConstants.datatables));
        }

        this.entityDatatableChecksWritePlatformService.runTheCheck(newClient.getId(),
                EntityTables.CLIENT.getName(), StatusEnum.CREATE.getCode().longValue(),
                EntityTables.CLIENT.getForeignKeyColumnNameOnDatatable());

        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withOfficeId(clientOffice.getId()) //
                .withClientId(newClient.getId()) //
                .withGroupId(groupId) //
                .withEntityId(newClient.getId()) //
                .withSavingsId(result.getSavingsId())//
                .setRollbackTransaction(rollbackTransaction)//
                .setRollbackTransaction(result.isRollbackTransaction())//
                .build();
    } catch (final DataIntegrityViolationException dve) {
        handleDataIntegrityIssues(command, dve.getMostSpecificCause(), dve);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}