Search in sources :

Example 16 with MessageBuilder

use of org.springframework.binding.message.MessageBuilder in project head by mifos.

the class UserFormBean method validateEnterUserDetailsStep.

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION", justification = "should be the exception thrown by jodatime but not sure what it is right now.")
public void validateEnterUserDetailsStep(ValidationContext context) {
    MessageContext messages = context.getMessageContext();
    validator.validate(this, messages);
    try {
        this.dateOfBirth = new DateTime().withDate(this.dateOfBirthYear.intValue(), this.dateOfBirthMonth.intValue(), this.dateOfBirthDay.intValue());
    } catch (Exception e) {
        messages.addMessage(new MessageBuilder().error().source("dateOfBrith").code("NotValid.UserFormBean.dateOfBrith").defaultText("dateOfBirth is not valid").build());
    }
    try {
        this.passwordExpirationDate = new DateTime().withDate(this.passwordExpirationDateYear.intValue(), this.passwordExpirationDateMonth.intValue(), this.passwordExpirationDateDay.intValue());
    } catch (Exception e) {
        messages.addMessage(new MessageBuilder().error().source("passwordExpirationDate").code("NotValid.UserFormBean.passwordExpirationDate").defaultText("Password expiration date is not valid").build());
    }
    try {
        this.mfiJoiningDate = new DateTime().withDate(this.mfiJoiningDateYear.intValue(), this.mfiJoiningDateMonth.intValue(), this.mfiJoiningDateDay.intValue());
    } catch (Exception e) {
        messages.addMessage(new MessageBuilder().error().source("mfiJoiningDate").code("NotValid.UserFormBean.mfiJoiningDate").defaultText("mfiJoiningDate is not valid").build());
    }
    if (this.password.trim().isEmpty() || this.confirmedPassword.trim().isEmpty()) {
        messages.addMessage(new MessageBuilder().error().source("password").code("NotEmpty.UserFormBean.password").defaultText("password is not correct.").build());
    } else if (this.password.trim().length() < 6) {
        messages.addMessage(new MessageBuilder().error().source("password").code("Min.UserFormBean.password").defaultText("password must have six characters at least.").build());
    } else if (!this.password.equals(this.confirmedPassword)) {
        messages.addMessage(new MessageBuilder().error().source("password").code("NotEqual.UserFormBean.password").defaultText("password is not correct.").build());
    }
    this.address.validate(messages, "UserFormBean");
    // validate additional fields
    for (CustomFieldDto additionalField : this.customFields) {
        switch(additionalField.getFieldType().intValue()) {
            case 0:
                break;
            case 1:
                validateNumericField(messages, additionalField);
                break;
            case 2:
                validateIfMandatoryField(messages, additionalField);
                break;
            case 3:
                for (DateFieldBean dateFieldBean : this.customDateFields) {
                    if (dateFieldBean.getId().equals(additionalField.getFieldId())) {
                        validateAndBindDateField(messages, additionalField, dateFieldBean);
                    }
                }
                break;
            default:
                break;
        }
    }
    if (messages.hasErrorMessages()) {
        this.prepateForReEdit();
    }
}
Also used : MessageBuilder(org.springframework.binding.message.MessageBuilder) CustomFieldDto(org.mifos.dto.domain.CustomFieldDto) MessageContext(org.springframework.binding.message.MessageContext) DateTime(org.joda.time.DateTime)

Example 17 with MessageBuilder

use of org.springframework.binding.message.MessageBuilder in project head by mifos.

the class LoanRepaymentController method applyPayment.

// called by spring webflow
public String applyPayment(final String loanGlobalAccountNumber, LoanRepaymentFormBean loanRepaymentFormBean, MessageContext messageContext) {
    String returnCode = "";
    try {
        BigDecimal repaymentAmount = BigDecimal.valueOf(loanRepaymentFormBean.getPaymentAmount().doubleValue());
        this.loanAccountServiceFacade.applyLoanRepayment(loanGlobalAccountNumber, loanRepaymentFormBean.getPaymentDate(), repaymentAmount, loanRepaymentFormBean.getReceiptId(), loanRepaymentFormBean.getReceiptDate(), loanRepaymentFormBean.getPaymentTypeId());
        returnCode = "success";
        if (loanRepaymentFormBean.getPrintReceipt()) {
            returnCode = "printPaymentReceipt";
        }
    } catch (BusinessRuleException e) {
        MessageBuilder builder = new MessageBuilder().error().source("paymentAmount").codes(Arrays.asList(e.getMessageKey()).toArray(new String[1])).defaultText(e.getMessage()).args(e.getMessageValues());
        messageContext.addMessage(builder.build());
        returnCode = "error";
    }
    return returnCode;
}
Also used : BusinessRuleException(org.mifos.service.BusinessRuleException) MessageBuilder(org.springframework.binding.message.MessageBuilder) BigDecimal(java.math.BigDecimal)

Example 18 with MessageBuilder

use of org.springframework.binding.message.MessageBuilder in project head by mifos.

the class QuestionnaireController method constructErrorMessage.

protected void constructErrorMessage(MessageContext context, String code, String source, String message) {
    MessageResolver messageResolver = new MessageBuilder().error().code(code).source(source).defaultText(message).build();
    context.addMessage(messageResolver);
}
Also used : MessageResolver(org.springframework.binding.message.MessageResolver) MessageBuilder(org.springframework.binding.message.MessageBuilder)

Example 19 with MessageBuilder

use of org.springframework.binding.message.MessageBuilder in project head by mifos.

the class LoanAccountFormBean method validateEnterAccountDetailsStep.

@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "")
public void validateEnterAccountDetailsStep(ValidationContext context) {
    MessageContext messageContext = context.getMessageContext();
    Errors errors = validator.checkConstraints(this);
    // handle data binding errors that may of occurred
    if (messageContext.hasErrorMessages()) {
        Message[] errorMessages = messageContext.getMessagesByCriteria(new MessageCriteria() {

            @Override
            public boolean test(@SuppressWarnings("unused") Message message) {
                return true;
            }
        });
        messageContext.clearMessages();
        for (Message message : errorMessages) {
            handleDataMappingError(errors, message);
        }
    }
    if (this.glimApplicable || this.groupLoanWithMembersEnabled) {
        int index = 0;
        int selectedCount = 0;
        for (Boolean clientSelected : this.clientSelectForGroup) {
            if (clientSelected != null && clientSelected.booleanValue()) {
                Number clientAmount = this.clientAmount[index];
                if (clientAmount == null || exceedsMinOrMax(clientAmount, Integer.valueOf(1), this.maxAllowedAmount)) {
                    String defaultErrorMessage = "Please specify valid Amount.";
                    rejectGlimClientAmountField(index + 1, errors, defaultErrorMessage);
                }
                if (clientAmount != null) {
                    BigDecimal amountAsDecimal = new BigDecimal(clientAmount.toString()).stripTrailingZeros();
                    int places = amountAsDecimal.scale();
                    if (places > this.digitsAfterDecimalForMonetaryAmounts) {
                        String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number.";
                        rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsAfterDecimal.invalid", new Object[] { index + 1, this.digitsAfterDecimalForMonetaryAmounts });
                    }
                    int digitsBefore = amountAsDecimal.toBigInteger().toString().length();
                    if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) {
                        String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number.";
                        rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsBeforeDecimal.invalid", new Object[] { index + 1, this.digitsBeforeDecimalForMonetaryAmounts });
                    }
                }
                // check error message of loan purpose for each client when its mandatory..
                Integer clientLoanPurposeId = this.clientLoanPurposeId[index];
                if (this.purposeOfLoanMandatory && isInvalidSelection(clientLoanPurposeId)) {
                    errors.rejectValue("clientLoanPurposeId", "loanAccountFormBean.glim.purposeOfLoan.invalid", new Object[] { index + 1 }, "Please specify loan purpose.");
                    this.clientLoanPurposeId[index] = 0;
                } else {
                    // needed so attempt in freemarker(ftl) to display loan purpose doesnt fall over.
                    if (clientLoanPurposeId == null) {
                        this.clientLoanPurposeId[index] = 0;
                    }
                }
                selectedCount++;
            } else {
                Number clientAmount = this.clientAmount[index];
                Integer clientLoanPurposeId = this.clientLoanPurposeId[index];
                if (clientAmount != null || clientLoanPurposeId != null) {
                    String defaultErrorMessage = "You have entered details for a member you have not selected. Select the checkbox in front of the member's name in order to include him or her in the loan.";
                    rejectUnselectedGlimClientAmountField(index + 1, errors, defaultErrorMessage);
                }
            }
            index++;
        }
        if (selectedCount < 2) {
            String defaultErrorMessage = "Not enough clients for group loan.";
            rejectGroupLoanWithTooFewClients(errors, defaultErrorMessage);
        }
    }
    if (this.amount == null || exceedsMinOrMax(this.amount, this.minAllowedAmount, this.maxAllowedAmount)) {
        String defaultErrorMessage = "Please specify valid Amount.";
        if (glimApplicable) {
            defaultErrorMessage = "The sum of the amounts specified for each member is outside the allowable total amount for this loan product.";
            rejectGlimTotalAmountField(errors, defaultErrorMessage);
        } else {
            rejectAmountField(errors, defaultErrorMessage);
        }
    }
    if (this.amount != null) {
        BigDecimal amountAsDecimal = new BigDecimal(this.amount.toString()).stripTrailingZeros();
        int places = amountAsDecimal.scale();
        if (places > this.digitsAfterDecimalForMonetaryAmounts) {
            String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsAfterDecimal.invalid", new Object[] { this.digitsAfterDecimalForMonetaryAmounts });
        }
        int digitsBefore = amountAsDecimal.toBigInteger().toString().length();
        if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) {
            String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsBeforeDecimal.invalid", new Object[] { this.digitsBeforeDecimalForMonetaryAmounts });
        }
    }
    if (this.interestRate == null || exceedsMinOrMax(this.interestRate, this.minAllowedInterestRate, this.maxAllowedInterestRate)) {
        String defaultErrorMessage = "Please specify valid Interest rate.";
        rejectInterestRateField(errors, defaultErrorMessage);
    }
    if (this.interestRate != null) {
        BigDecimal interestRateAsDecimal = new BigDecimal(this.interestRate.toString()).stripTrailingZeros();
        int places = interestRateAsDecimal.scale();
        if (places > this.digitsAfterDecimalForInterest) {
            String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsAfterDecimalForInterest.invalid", new Object[] { this.digitsAfterDecimalForInterest });
        }
        int digitsBefore = interestRateAsDecimal.toBigInteger().toString().length();
        if (digitsBefore > this.digitsBeforeDecimalForInterest) {
            String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number.";
            rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsBeforeDecimalForInterest.invalid", new Object[] { this.digitsBeforeDecimalForInterest });
        }
    }
    if (this.numberOfInstallments == null || exceedsMinOrMax(this.numberOfInstallments, this.minNumberOfInstallments, this.maxNumberOfInstallments)) {
        String defaultErrorMessage = "Please specify valid number of installments.";
        rejectNumberOfInstallmentsField(errors, defaultErrorMessage);
    }
    if (this.graceDuration == null || this.graceDuration.intValue() < 0) {
        if (!errors.hasFieldErrors("graceDuration")) {
            String defaultErrorMessage = "Please specify valid Grace period for repayments. Grace period should be a value less than " + numberOfInstallments.intValue() + ".";
            rejectGraceDurationField(errors, defaultErrorMessage);
        }
    } else {
        if (this.graceDuration.intValue() > this.maxGraceDuration.intValue()) {
            String defaultErrorMessage = "The Grace period cannot be greater than in loan product definition.";
            errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDuration.invalid", defaultErrorMessage);
        }
        if (this.numberOfInstallments != null && (this.graceDuration.intValue() >= this.numberOfInstallments.intValue())) {
            String defaultErrorMessage = "Grace period for repayments must be less than number of loan installments.";
            errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDurationInRelationToInstallments.invalid", defaultErrorMessage);
        }
    }
    if (dateValidator == null) {
        dateValidator = new DateValidator();
    }
    if (!dateValidator.formsValidDate(this.disbursementDateDD, this.disbursementDateMM, this.disbursementDateYY)) {
        String defaultErrorMessage = "Please specify valid disbursal date.";
        rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", "loanAccountFormBean.DisbursalDate.invalid", "");
    } else {
        LocalDate validDate = new DateTime().withDate(disbursementDateYY.intValue(), disbursementDateMM.intValue(), disbursementDateDD.intValue()).toLocalDate();
        org.mifos.platform.validations.Errors disbursementDateErrors = new org.mifos.platform.validations.Errors();
        if (this.redoLoanAccount) {
            disbursementDateErrors = loanDisbursementDateValidationServiceFacade.validateLoanWithBackdatedPaymentsDisbursementDate(validDate, customerId, productId);
        } else {
            disbursementDateErrors = loanDisbursementDateValidationServiceFacade.validateLoanDisbursementDate(validDate, customerId, productId);
        }
        for (ErrorEntry entry : disbursementDateErrors.getErrorEntries()) {
            String defaultErrorMessage = "The disbursal date is invalid.";
            rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", entry.getErrorCode(), entry.getArgs().get(0));
        }
    }
    if (this.sourceOfFundsMandatory && isInvalidSelection(this.fundId)) {
        errors.rejectValue("fundId", "loanAccountFormBean.SourceOfFunds.invalid", "Please specify source of funds.");
    }
    if (this.externalIdMandatory && StringUtils.isBlank(this.externalId)) {
        errors.rejectValue("externalId", "loanAccountFormBean.externalid.invalid", "Please specify required external id.");
    }
    if (!this.glimApplicable && this.purposeOfLoanMandatory && isInvalidSelection(this.loanPurposeId)) {
        errors.rejectValue("loanPurposeId", "loanAccountFormBean.PurposeOfLoan.invalid", "Please specify loan purpose.");
    }
    validateAdministrativeAndAdditionalFees(errors);
    if (this.repaymentScheduleIndependentOfCustomerMeeting) {
        if (isInvalidRecurringFrequency(this.repaymentRecursEvery)) {
            errors.rejectValue("repaymentRecursEvery", "loanAccountFormBean.repaymentDay.recursEvery.invalid", "Please specify a valid recurring frequency for repayment day.");
        }
        if (this.weekly) {
            if (isInvalidDayOfWeekSelection()) {
                errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.weekly.dayOfWeek.invalid", "Please select a day of the week for repayment day.");
            }
        } else if (this.monthly) {
            if (this.monthlyDayOfMonthOptionSelected) {
                if (isInvalidDayOfMonthEntered()) {
                    errors.rejectValue("repaymentDayOfMonth", "loanAccountFormBean.repaymentDay.monthly.dayOfMonth.invalid", "Please select a day of the month for repayment day.");
                }
            } else if (this.monthlyWeekOfMonthOptionSelected) {
                if (isInvalidWeekOfMonthSelection()) {
                    errors.rejectValue("repaymentWeekOfMonth", "loanAccountFormBean.repaymentDay.monthly.weekOfMonth.invalid", "Please select a week of the month for repayment day.");
                }
                if (isInvalidDayOfWeekSelection()) {
                    errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.monthly.dayOfWeek.invalid", "Please select a day of the week for repayment day.");
                }
            }
        }
        if (this.variableInstallmentsAllowed) {
            if (this.selectedFeeId != null) {
                for (Number feeId : this.selectedFeeId) {
                    if (feeId != null) {
                        VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade.validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue());
                        if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) {
                            errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments.");
                        }
                    }
                }
            }
            int defaultFeeIndex = 0;
            if (this.defaultFeeId != null) {
                for (Number feeId : this.defaultFeeId) {
                    if (feeId != null) {
                        Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex];
                        if (feeSelectedForRemoval == null || !feeSelectedForRemoval) {
                            VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade.validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue());
                            if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) {
                                errors.rejectValue("selectedFeeId", "loanAccountFormBean.defaultfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments.");
                            }
                        }
                    }
                    defaultFeeIndex++;
                }
            }
        }
    }
    if (errors.hasErrors()) {
        for (FieldError fieldError : errors.getFieldErrors()) {
            MessageBuilder builder = new MessageBuilder().error().source(fieldError.getField()).codes(fieldError.getCodes()).defaultText(fieldError.getDefaultMessage()).args(fieldError.getArguments());
            messageContext.addMessage(builder.build());
        }
    }
}
Also used : Message(org.springframework.binding.message.Message) VariableInstallmentWithFeeValidationResult(org.mifos.clientportfolio.newloan.applicationservice.VariableInstallmentWithFeeValidationResult) FieldError(org.springframework.validation.FieldError) LocalDate(org.joda.time.LocalDate) ErrorEntry(org.mifos.platform.validations.ErrorEntry) BigDecimal(java.math.BigDecimal) DateTime(org.joda.time.DateTime) Errors(org.springframework.validation.Errors) MessageBuilder(org.springframework.binding.message.MessageBuilder) MessageCriteria(org.springframework.binding.message.MessageCriteria) MessageContext(org.springframework.binding.message.MessageContext)

Example 20 with MessageBuilder

use of org.springframework.binding.message.MessageBuilder in project head by mifos.

the class CashFlowSummaryFormBean method addErrorMessageToContext.

private void addErrorMessageToContext(MessageContext messageContext, ErrorEntry fieldError) {
    String[] errorCodes = new String[1];
    errorCodes[0] = fieldError.getErrorCode();
    List<Object> args = new ArrayList<Object>();
    if (fieldError.hasErrorArgs()) {
        args = new ArrayList<Object>(fieldError.getArgs());
    }
    MessageBuilder builder = new MessageBuilder().error().source(fieldError.getFieldName()).codes(errorCodes).defaultText(fieldError.getDefaultMessage()).args(args.toArray());
    messageContext.addMessage(builder.build());
}
Also used : MessageBuilder(org.springframework.binding.message.MessageBuilder) ArrayList(java.util.ArrayList)

Aggregations

MessageBuilder (org.springframework.binding.message.MessageBuilder)24 MessageContext (org.springframework.binding.message.MessageContext)6 MessageResolver (org.springframework.binding.message.MessageResolver)6 BigDecimal (java.math.BigDecimal)4 DateTime (org.joda.time.DateTime)3 ArrayList (java.util.ArrayList)2 ErrorEntry (org.mifos.platform.validations.ErrorEntry)2 BusinessRuleException (org.mifos.service.BusinessRuleException)2 ReportServiceLocatorException (org.opennms.reporting.core.svclayer.ReportServiceLocatorException)2 SchedulerException (org.quartz.SchedulerException)2 EventFactorySupport (org.springframework.webflow.action.EventFactorySupport)2 ParseException (java.text.ParseException)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)1 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)1 AuthenticationResultBuilder (org.apereo.cas.authentication.AuthenticationResultBuilder)1 Credential (org.apereo.cas.authentication.Credential)1 UsernamePasswordCredential (org.apereo.cas.authentication.UsernamePasswordCredential)1 Service (org.apereo.cas.authentication.principal.Service)1