Example usage for com.google.gson JsonArray size

List of usage examples for com.google.gson JsonArray size

Introduction

In this page you can find the example usage for com.google.gson JsonArray size.

Prototype

public int size() 

Source Link

Document

Returns the number of elements in the array.

Usage

From source file:com.gst.portfolio.interestratechart.domain.InterestRateChartSlab.java

License:Apache License

public void updateIncentives(JsonCommand command, final Map<String, Object> actualChanges,
        final DataValidatorBuilder baseDataValidator, final InterestRateChartSlab chartSlab,
        final Locale locale) {
    final Map<String, Object> deleteIncentives = new HashMap<>();
    final Map<String, Object> IncentiveChanges = new HashMap<>();
    if (command.hasParameter(InterestRateChartSlabApiConstants.incentivesParamName)) {
        final JsonArray array = command
                .arrayOfParameterNamed(InterestRateChartSlabApiConstants.incentivesParamName);
        if (array != null) {
            for (int i = 0; i < array.size(); i++) {
                final JsonObject incentiveElement = array.get(i).getAsJsonObject();
                JsonCommand incentivesCommand = JsonCommand.fromExistingCommand(command, incentiveElement);
                if (incentivesCommand.parameterExists(InterestIncentiveApiConstants.idParamName)) {
                    final Long interestIncentiveId = incentivesCommand
                            .longValueOfParameterNamed(InterestIncentiveApiConstants.idParamName);
                    final InterestIncentives interestIncentives = chartSlab
                            .findInterestIncentive(interestIncentiveId);
                    if (interestIncentives == null) {
                        baseDataValidator.parameter(InterestIncentiveApiConstants.idParamName)
                                .value(interestIncentiveId)
                                .failWithCode("no.interest.incentive.associated.with.id");
                    } else if (incentivesCommand.parameterExists(deleteParamName)) {
                        if (chartSlab.removeInterestIncentive(interestIncentives)) {
                            deleteIncentives.put(idParamName, interestIncentiveId);
                        }/*from  w w w  .  j  a  v  a  2  s  . c  o m*/
                    } else {
                        interestIncentives.update(incentivesCommand, IncentiveChanges, baseDataValidator,
                                locale);
                    }
                } else {
                    Integer entityType = incentivesCommand.integerValueOfParameterNamed(entityTypeParamName,
                            locale);
                    Integer conditionType = incentivesCommand
                            .integerValueOfParameterNamed(conditionTypeParamName, locale);
                    Integer attributeName = incentivesCommand
                            .integerValueOfParameterNamed(attributeNameParamName, locale);
                    String attributeValue = incentivesCommand
                            .stringValueOfParameterNamed(attributeValueParamName);
                    Integer incentiveType = incentivesCommand
                            .integerValueOfParameterNamed(incentiveTypeparamName, locale);
                    BigDecimal amount = incentivesCommand.bigDecimalValueOfParameterNamed(amountParamName,
                            locale);
                    InterestIncentivesFields incentivesFields = InterestIncentivesFields.createNew(entityType,
                            attributeName, conditionType, attributeValue, incentiveType, amount,
                            baseDataValidator);
                    InterestIncentives incentives = new InterestIncentives(chartSlab, incentivesFields);
                    chartSlab.addInterestIncentive(incentives);
                }
            }
        }
        // add chart slab changes to actual changes list.
        if (!IncentiveChanges.isEmpty()) {
            actualChanges.put(InterestRateChartSlabApiConstants.incentivesParamName, IncentiveChanges);
        }

        // add deleted chart Slabs to actual changes
        if (!deleteIncentives.isEmpty()) {
            actualChanges.put("deletedIncentives", deleteIncentives);
        }

    }
}

From source file:com.gst.portfolio.interestratechart.service.InterestIncentiveAssembler.java

License:Apache License

public Collection<InterestIncentives> assembleIncentivesFrom(final JsonElement element,
        InterestRateChartSlab interestRateChartSlab, final Locale locale) {
    final Collection<InterestIncentives> interestIncentivesSet = new HashSet<>();

    if (element.isJsonObject()) {
        final JsonObject topLevelJsonElement = element.getAsJsonObject();
        if (topLevelJsonElement.has(incentivesParamName)
                && topLevelJsonElement.get(incentivesParamName).isJsonArray()) {
            final JsonArray array = topLevelJsonElement.get(incentivesParamName).getAsJsonArray();
            for (int i = 0; i < array.size(); i++) {
                final JsonObject incentiveElement = array.get(i).getAsJsonObject();
                final InterestIncentives incentives = this.assembleFrom(incentiveElement, interestRateChartSlab,
                        locale);/*from ww  w .  ja va  2s.  com*/
                interestIncentivesSet.add(incentives);
            }
        }
    }

    return interestIncentivesSet;
}

From source file:com.gst.portfolio.interestratechart.service.InterestRateChartSlabAssembler.java

License:Apache License

public Collection<InterestRateChartSlab> assembleChartSlabsFrom(final JsonElement element,
        String currencyCode) {/* w  w  w  .j a va2 s. c om*/
    final Collection<InterestRateChartSlab> interestRateChartSlabsSet = new HashSet<>();

    if (element.isJsonObject()) {
        final JsonObject topLevelJsonElement = element.getAsJsonObject();
        final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
        if (topLevelJsonElement.has(chartSlabs) && topLevelJsonElement.get(chartSlabs).isJsonArray()) {
            final JsonArray array = topLevelJsonElement.get(chartSlabs).getAsJsonArray();
            for (int i = 0; i < array.size(); i++) {
                final JsonObject interstRateChartElement = array.get(i).getAsJsonObject();
                final InterestRateChartSlab chartSlab = this.assembleChartSlabs(null, interstRateChartElement,
                        currencyCode, locale);
                interestRateChartSlabsSet.add(chartSlab);
            }
        }
    }

    return interestRateChartSlabsSet;
}

From source file:com.gst.portfolio.loanaccount.domain.Loan.java

License:Apache License

public Map<String, Object> loanApplicationModification(final JsonCommand command,
        final Set<LoanCharge> possiblyModifedLoanCharges,
        final Set<LoanCollateral> possiblyModifedLoanCollateralItems, final AprCalculator aprCalculator,
        boolean isChargesModified) {

    final Map<String, Object> actualChanges = this.loanRepaymentScheduleDetail
            .updateLoanApplicationAttributes(command, aprCalculator);
    if (!actualChanges.isEmpty()) {
        final boolean recalculateLoanSchedule = !(actualChanges.size() == 1
                && actualChanges.containsKey("inArrearsTolerance"));
        actualChanges.put("recalculateLoanSchedule", recalculateLoanSchedule);
        isChargesModified = true;//from  w  w w  .  j ava  2  s.  c  o m
    }

    final String dateFormatAsInput = command.dateFormat();
    final String localeAsInput = command.locale();

    final String accountNoParamName = "accountNo";
    if (command.isChangeInStringParameterNamed(accountNoParamName, this.accountNumber)) {
        final String newValue = command.stringValueOfParameterNamed(accountNoParamName);
        actualChanges.put(accountNoParamName, newValue);
        this.accountNumber = StringUtils.defaultIfEmpty(newValue, null);
    }

    final String createSiAtDisbursementParameterName = "createStandingInstructionAtDisbursement";
    if (command.isChangeInBooleanParameterNamed(createSiAtDisbursementParameterName,
            shouldCreateStandingInstructionAtDisbursement())) {
        final Boolean valueAsInput = command
                .booleanObjectValueOfParameterNamed(createSiAtDisbursementParameterName);
        actualChanges.put(createSiAtDisbursementParameterName, valueAsInput);
        this.createStandingInstructionAtDisbursement = valueAsInput;
    }

    final String externalIdParamName = "externalId";
    if (command.isChangeInStringParameterNamed(externalIdParamName, this.externalId)) {
        final String newValue = command.stringValueOfParameterNamed(externalIdParamName);
        actualChanges.put(externalIdParamName, newValue);
        this.externalId = StringUtils.defaultIfEmpty(newValue, null);
    }

    // add clientId, groupId and loanType changes to actual changes

    final String clientIdParamName = "clientId";
    final Long clientId = this.client == null ? null : this.client.getId();
    if (command.isChangeInLongParameterNamed(clientIdParamName, clientId)) {
        final Long newValue = command.longValueOfParameterNamed(clientIdParamName);
        actualChanges.put(clientIdParamName, newValue);
    }

    // FIXME: AA - We may require separate api command to move loan from one
    // group to another
    final String groupIdParamName = "groupId";
    final Long groupId = this.group == null ? null : this.group.getId();
    if (command.isChangeInLongParameterNamed(groupIdParamName, groupId)) {
        final Long newValue = command.longValueOfParameterNamed(groupIdParamName);
        actualChanges.put(groupIdParamName, newValue);
    }

    final String productIdParamName = "productId";
    if (command.isChangeInLongParameterNamed(productIdParamName, this.loanProduct.getId())) {
        final Long newValue = command.longValueOfParameterNamed(productIdParamName);
        actualChanges.put(productIdParamName, newValue);
        actualChanges.put("recalculateLoanSchedule", true);
    }

    final String isFloatingInterestRateParamName = "isFloatingInterestRate";
    if (command.isChangeInBooleanParameterNamed(isFloatingInterestRateParamName, this.isFloatingInterestRate)) {
        final Boolean newValue = command.booleanObjectValueOfParameterNamed(isFloatingInterestRateParamName);
        actualChanges.put(isFloatingInterestRateParamName, newValue);
        this.isFloatingInterestRate = newValue;
    }

    final String interestRateDifferentialParamName = "interestRateDifferential";
    if (command.isChangeInBigDecimalParameterNamed(interestRateDifferentialParamName,
            this.interestRateDifferential)) {
        final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(interestRateDifferentialParamName);
        actualChanges.put(interestRateDifferentialParamName, newValue);
        this.interestRateDifferential = newValue;
    }

    Long existingFundId = null;
    if (this.fund != null) {
        existingFundId = this.fund.getId();
    }
    final String fundIdParamName = "fundId";
    if (command.isChangeInLongParameterNamed(fundIdParamName, existingFundId)) {
        final Long newValue = command.longValueOfParameterNamed(fundIdParamName);
        actualChanges.put(fundIdParamName, newValue);
    }

    Long existingLoanOfficerId = null;
    if (this.loanOfficer != null) {
        existingLoanOfficerId = this.loanOfficer.getId();
    }
    final String loanOfficerIdParamName = "loanOfficerId";
    if (command.isChangeInLongParameterNamed(loanOfficerIdParamName, existingLoanOfficerId)) {
        final Long newValue = command.longValueOfParameterNamed(loanOfficerIdParamName);
        actualChanges.put(loanOfficerIdParamName, newValue);
    }

    Long existingLoanPurposeId = null;
    if (this.loanPurpose != null) {
        existingLoanPurposeId = this.loanPurpose.getId();
    }
    final String loanPurposeIdParamName = "loanPurposeId";
    if (command.isChangeInLongParameterNamed(loanPurposeIdParamName, existingLoanPurposeId)) {
        final Long newValue = command.longValueOfParameterNamed(loanPurposeIdParamName);
        actualChanges.put(loanPurposeIdParamName, newValue);
    }

    final String strategyIdParamName = "transactionProcessingStrategyId";
    if (command.isChangeInLongParameterNamed(strategyIdParamName, this.transactionProcessingStrategy.getId())) {
        final Long newValue = command.longValueOfParameterNamed(strategyIdParamName);
        actualChanges.put(strategyIdParamName, newValue);
    }

    final String submittedOnDateParamName = "submittedOnDate";
    if (command.isChangeInLocalDateParameterNamed(submittedOnDateParamName, getSubmittedOnDate())) {
        final String valueAsInput = command.stringValueOfParameterNamed(submittedOnDateParamName);
        actualChanges.put(submittedOnDateParamName, valueAsInput);
        actualChanges.put("dateFormat", dateFormatAsInput);
        actualChanges.put("locale", localeAsInput);

        final LocalDate newValue = command.localDateValueOfParameterNamed(submittedOnDateParamName);
        this.submittedOnDate = newValue.toDate();
    }

    final String expectedDisbursementDateParamName = "expectedDisbursementDate";
    if (command.isChangeInLocalDateParameterNamed(expectedDisbursementDateParamName,
            getExpectedDisbursedOnLocalDate())) {
        final String valueAsInput = command.stringValueOfParameterNamed(expectedDisbursementDateParamName);
        actualChanges.put(expectedDisbursementDateParamName, valueAsInput);
        actualChanges.put("dateFormat", dateFormatAsInput);
        actualChanges.put("locale", localeAsInput);
        actualChanges.put("recalculateLoanSchedule", true);

        final LocalDate newValue = command.localDateValueOfParameterNamed(expectedDisbursementDateParamName);
        this.expectedDisbursementDate = newValue.toDate();
        removeFirstDisbursementTransaction();
    }

    final String repaymentsStartingFromDateParamName = "repaymentsStartingFromDate";
    if (command.isChangeInLocalDateParameterNamed(repaymentsStartingFromDateParamName,
            getExpectedFirstRepaymentOnDate())) {
        final String valueAsInput = command.stringValueOfParameterNamed(repaymentsStartingFromDateParamName);
        actualChanges.put(repaymentsStartingFromDateParamName, valueAsInput);
        actualChanges.put("dateFormat", dateFormatAsInput);
        actualChanges.put("locale", localeAsInput);
        actualChanges.put("recalculateLoanSchedule", true);

        final LocalDate newValue = command.localDateValueOfParameterNamed(repaymentsStartingFromDateParamName);
        if (newValue != null) {
            this.expectedFirstRepaymentOnDate = newValue.toDate();
        } else {
            this.expectedFirstRepaymentOnDate = null;
        }
    }

    final String syncDisbursementParameterName = "syncDisbursementWithMeeting";
    if (command.isChangeInBooleanParameterNamed(syncDisbursementParameterName,
            isSyncDisbursementWithMeeting())) {
        final Boolean valueAsInput = command.booleanObjectValueOfParameterNamed(syncDisbursementParameterName);
        actualChanges.put(syncDisbursementParameterName, valueAsInput);
        this.syncDisbursementWithMeeting = valueAsInput;
    }

    final String interestChargedFromDateParamName = "interestChargedFromDate";
    if (command.isChangeInLocalDateParameterNamed(interestChargedFromDateParamName,
            getInterestChargedFromDate())) {
        final String valueAsInput = command.stringValueOfParameterNamed(interestChargedFromDateParamName);
        actualChanges.put(interestChargedFromDateParamName, valueAsInput);
        actualChanges.put("dateFormat", dateFormatAsInput);
        actualChanges.put("locale", localeAsInput);
        actualChanges.put("recalculateLoanSchedule", true);

        final LocalDate newValue = command.localDateValueOfParameterNamed(interestChargedFromDateParamName);
        if (newValue != null) {
            this.interestChargedFromDate = newValue.toDate();
        } else {
            this.interestChargedFromDate = null;
        }
    }

    // the comparison should be done with the tenant date
    // (DateUtils.getLocalDateOfTenant()) and not the server date (new
    // LocalDate())
    if (getSubmittedOnDate().isAfter(DateUtils.getLocalDateOfTenant())) {
        final String errorMessage = "The date on which a loan is submitted cannot be in the future.";
        throw new InvalidLoanStateTransitionException("submittal", "cannot.be.a.future.date", errorMessage,
                getSubmittedOnDate());
    }

    if (!(this.client == null)) {
        if (getSubmittedOnDate().isBefore(this.client.getActivationLocalDate())) {
            final String errorMessage = "The date on which a loan is submitted cannot be earlier than client's activation date.";
            throw new InvalidLoanStateTransitionException("submittal",
                    "cannot.be.before.client.activation.date", errorMessage, getSubmittedOnDate());
        }
    } else if (!(this.group == null)) {
        if (getSubmittedOnDate().isBefore(this.group.getActivationLocalDate())) {
            final String errorMessage = "The date on which a loan is submitted cannot be earlier than groups's activation date.";
            throw new InvalidLoanStateTransitionException("submittal", "cannot.be.before.group.activation.date",
                    errorMessage, getSubmittedOnDate());
        }
    }

    if (getSubmittedOnDate().isAfter(getExpectedDisbursedOnLocalDate())) {
        final String errorMessage = "The date on which a loan is submitted cannot be after its expected disbursement date: "
                + getExpectedDisbursedOnLocalDate().toString();
        throw new InvalidLoanStateTransitionException("submittal", "cannot.be.after.expected.disbursement.date",
                errorMessage, getSubmittedOnDate(), getExpectedDisbursedOnLocalDate());
    }

    final String chargesParamName = "charges";

    if (isChargesModified) {
        actualChanges.put(chargesParamName, getLoanCharges(possiblyModifedLoanCharges));
        actualChanges.put("recalculateLoanSchedule", true);
    }

    final String collateralParamName = "collateral";
    if (command.parameterExists(collateralParamName)) {

        if (!possiblyModifedLoanCollateralItems.equals(this.collateral)) {
            actualChanges.put(collateralParamName,
                    listOfLoanCollateralData(possiblyModifedLoanCollateralItems));
        }
    }

    final String loanTermFrequencyParamName = "loanTermFrequency";
    if (command.isChangeInIntegerParameterNamed(loanTermFrequencyParamName, this.termFrequency)) {
        final Integer newValue = command.integerValueOfParameterNamed(loanTermFrequencyParamName);
        actualChanges.put(externalIdParamName, newValue);
        this.termFrequency = newValue;
    }

    final String loanTermFrequencyTypeParamName = "loanTermFrequencyType";
    if (command.isChangeInIntegerParameterNamed(loanTermFrequencyTypeParamName, this.termPeriodFrequencyType)) {
        final Integer newValue = command.integerValueOfParameterNamed(loanTermFrequencyTypeParamName);
        final PeriodFrequencyType newTermPeriodFrequencyType = PeriodFrequencyType.fromInt(newValue);
        actualChanges.put(loanTermFrequencyTypeParamName, newTermPeriodFrequencyType.getValue());
        this.termPeriodFrequencyType = newValue;
    }

    final String principalParamName = "principal";
    if (command.isChangeInBigDecimalParameterNamed(principalParamName, this.approvedPrincipal)) {
        final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(principalParamName);
        this.approvedPrincipal = newValue;
    }

    if (command.isChangeInBigDecimalParameterNamed(principalParamName, this.proposedPrincipal)) {
        final BigDecimal newValue = command.bigDecimalValueOfParameterNamed(principalParamName);
        this.proposedPrincipal = newValue;
    }

    if (loanProduct.isMultiDisburseLoan()) {
        updateDisbursementDetails(command, actualChanges);
        if (command.isChangeInBigDecimalParameterNamed(LoanApiConstants.maxOutstandingBalanceParameterName,
                this.maxOutstandingLoanBalance)) {
            this.maxOutstandingLoanBalance = command
                    .bigDecimalValueOfParameterNamed(LoanApiConstants.maxOutstandingBalanceParameterName);
        }
        final JsonArray disbursementDataArray = command
                .arrayOfParameterNamed(LoanApiConstants.disbursementDataParameterName);

        if (disbursementDataArray == null || disbursementDataArray.size() == 0) {
            final String errorMessage = "For this loan product, disbursement details must be provided";
            throw new MultiDisbursementDataRequiredException(LoanApiConstants.disbursementDataParameterName,
                    errorMessage);
        }
        if (disbursementDataArray.size() > loanProduct.maxTrancheCount()) {
            final String errorMessage = "Number of tranche shouldn't be greter than "
                    + loanProduct.maxTrancheCount();
            throw new ExceedingTrancheCountException(LoanApiConstants.disbursementDataParameterName,
                    errorMessage, loanProduct.maxTrancheCount(), disbursementDetails.size());
        }
    } else {
        this.disbursementDetails.clear();
    }

    if (loanProduct.isMultiDisburseLoan() || loanProduct.canDefineInstallmentAmount()) {
        if (command.isChangeInBigDecimalParameterNamed(LoanApiConstants.emiAmountParameterName,
                this.fixedEmiAmount)) {
            this.fixedEmiAmount = command
                    .bigDecimalValueOfParameterNamed(LoanApiConstants.emiAmountParameterName);
            actualChanges.put(LoanApiConstants.emiAmountParameterName, this.fixedEmiAmount);
            actualChanges.put("recalculateLoanSchedule", true);
        }
    } else {
        this.fixedEmiAmount = null;
    }

    return actualChanges;
}

From source file:com.gst.portfolio.loanaccount.domain.Loan.java

License:Apache License

public void updateDisbursementDetails(final JsonCommand jsonCommand, final Map<String, Object> actualChanges) {

    List<Long> disbursementList = fetchDisbursementIds();
    List<Long> loanChargeIds = fetchLoanTrancheChargeIds();
    int chargeIdLength = loanChargeIds.size();
    String chargeIds = null;//from w w  w  .  j  a  va2 s. c o m
    // From modify application page, if user removes all charges, we should
    // get empty array.
    // So we need to remove all charges applied for this loan
    boolean removeAllChages = false;
    if (jsonCommand.parameterExists(LoanApiConstants.chargesParameterName)) {
        JsonArray chargesArray = jsonCommand.arrayOfParameterNamed(LoanApiConstants.chargesParameterName);
        if (chargesArray.size() == 0)
            removeAllChages = true;
    }

    if (jsonCommand.parameterExists(LoanApiConstants.disbursementDataParameterName)) {
        final JsonArray disbursementDataArray = jsonCommand
                .arrayOfParameterNamed(LoanApiConstants.disbursementDataParameterName);
        if (disbursementDataArray != null && disbursementDataArray.size() > 0) {
            String dateFormat = null;
            Locale locale = null;
            // Gets date format and locate
            Map<String, String> dateAndLocale = getDateFormatAndLocale(jsonCommand);
            dateFormat = dateAndLocale.get(LoanApiConstants.dateFormatParameterName);
            if (dateAndLocale.containsKey(LoanApiConstants.localeParameterName)) {
                locale = JsonParserHelper
                        .localeFromString(dateAndLocale.get(LoanApiConstants.localeParameterName));
            }
            for (JsonElement jsonElement : disbursementDataArray) {
                final JsonObject jsonObject = jsonElement.getAsJsonObject();
                Map<String, Object> parsedDisbursementData = parseDisbursementDetails(jsonObject, dateFormat,
                        locale);
                Date expectedDisbursementDate = (Date) parsedDisbursementData
                        .get(LoanApiConstants.disbursementDateParameterName);
                BigDecimal principal = (BigDecimal) parsedDisbursementData
                        .get(LoanApiConstants.disbursementPrincipalParameterName);
                Long disbursementID = (Long) parsedDisbursementData
                        .get(LoanApiConstants.disbursementIdParameterName);
                chargeIds = (String) parsedDisbursementData.get(LoanApiConstants.loanChargeIdParameterName);
                if (chargeIds != null) {
                    if (chargeIds.indexOf(",") != -1) {
                        String[] chargeId = chargeIds.split(",");
                        for (String loanChargeId : chargeId) {
                            loanChargeIds.remove(Long.parseLong(loanChargeId));
                        }
                    } else {
                        loanChargeIds.remove(Long.parseLong(chargeIds));
                    }
                }
                createOrUpdateDisbursementDetails(disbursementID, actualChanges, expectedDisbursementDate,
                        principal, disbursementList);
            }
            removeDisbursementAndAssociatedCharges(actualChanges, disbursementList, loanChargeIds,
                    chargeIdLength, removeAllChages);
        }
    }
}

From source file:com.gst.portfolio.loanaccount.loanschedule.service.LoanScheduleAssembler.java

License:Apache License

private List<DisbursementData> fetchDisbursementData(final JsonObject command) {
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(command);
    final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(command);
    List<DisbursementData> disbursementDatas = new ArrayList<>();
    if (command.has(LoanApiConstants.disbursementDataParameterName)) {
        final JsonArray disbursementDataArray = command
                .getAsJsonArray(LoanApiConstants.disbursementDataParameterName);
        if (disbursementDataArray != null && disbursementDataArray.size() > 0) {
            int i = 0;
            do {//from w  ww.j a  va 2s .  c om
                final JsonObject jsonObject = disbursementDataArray.get(i).getAsJsonObject();
                LocalDate expectedDisbursementDate = null;
                BigDecimal principal = null;

                if (jsonObject.has(LoanApiConstants.disbursementDateParameterName)) {
                    expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed(
                            LoanApiConstants.disbursementDateParameterName, jsonObject, dateFormat, locale);
                }
                if (jsonObject.has(LoanApiConstants.disbursementPrincipalParameterName)
                        && jsonObject.get(LoanApiConstants.disbursementPrincipalParameterName).isJsonPrimitive()
                        && StringUtils.isNotBlank((jsonObject
                                .get(LoanApiConstants.disbursementPrincipalParameterName).getAsString()))) {
                    principal = jsonObject
                            .getAsJsonPrimitive(LoanApiConstants.disbursementPrincipalParameterName)
                            .getAsBigDecimal();
                }
                disbursementDatas
                        .add(new DisbursementData(null, expectedDisbursementDate, null, principal, null, null));
                i++;
            } while (i < disbursementDataArray.size());
        }
    }
    return disbursementDatas;
}

From source file:com.gst.portfolio.loanaccount.loanschedule.service.LoanScheduleAssembler.java

License:Apache License

private void extractLoanTermVariations(final Loan loan, final String dateFormat, final Locale locale,
        final JsonArray modificationsArray, final boolean isInsertInstallment,
        final boolean isDeleteInstallment, final List<LoanTermVariations> loanTermVariations) {
    for (int i = 1; i <= modificationsArray.size(); i++) {
        final JsonObject arrayElement = modificationsArray.get(i - 1).getAsJsonObject();
        BigDecimal decimalValue = null;
        LoanTermVariationType decimalValueVariationType = LoanTermVariationType.INVALID;
        if (loan.getLoanProductRelatedDetail().getAmortizationMethod().isEqualInstallment()
                && loan.getLoanProductRelatedDetail().getInterestMethod().isDecliningBalnce()) {
            decimalValue = this.fromApiJsonHelper
                    .extractBigDecimalNamed(LoanApiConstants.installmentAmountParamName, arrayElement, locale);
            decimalValueVariationType = LoanTermVariationType.EMI_AMOUNT;
        } else {// w ww .j  ava 2 s . com
            decimalValue = this.fromApiJsonHelper.extractBigDecimalNamed(LoanApiConstants.principalParamName,
                    arrayElement, locale);
            decimalValueVariationType = LoanTermVariationType.PRINCIPAL_AMOUNT;
        }

        LocalDate duedateLocalDate = this.fromApiJsonHelper
                .extractLocalDateNamed(LoanApiConstants.dueDateParamName, arrayElement, dateFormat, locale);
        Date dueDate = duedateLocalDate.toDate();

        LocalDate modifiedDuedateLocalDate = this.fromApiJsonHelper.extractLocalDateNamed(
                LoanApiConstants.modifiedDueDateParamName, arrayElement, dateFormat, locale);
        Date modifiedDuedate = null;
        if (modifiedDuedateLocalDate != null) {
            modifiedDuedate = modifiedDuedateLocalDate.toDate();
        }
        boolean isSpecificToInstallment = true;
        if (isInsertInstallment) {
            LoanTermVariations data = new LoanTermVariations(
                    LoanTermVariationType.INSERT_INSTALLMENT.getValue(), dueDate, decimalValue, modifiedDuedate,
                    isSpecificToInstallment, loan);
            loanTermVariations.add(data);
        } else if (isDeleteInstallment) {
            LoanTermVariations data = new LoanTermVariations(
                    LoanTermVariationType.DELETE_INSTALLMENT.getValue(), dueDate, decimalValue, modifiedDuedate,
                    isSpecificToInstallment, loan);
            loanTermVariations.add(data);
        } else {
            if (modifiedDuedate != null) {
                BigDecimal amountData = null;
                LoanTermVariations data = new LoanTermVariations(LoanTermVariationType.DUE_DATE.getValue(),
                        dueDate, amountData, modifiedDuedate, isSpecificToInstallment, loan);
                loanTermVariations.add(data);
            }
            if (decimalValue != null) {
                if (modifiedDuedate == null) {
                    modifiedDuedate = dueDate;
                }
                Date date = null;
                LoanTermVariations data = new LoanTermVariations(decimalValueVariationType.getValue(),
                        modifiedDuedate, decimalValue, date, isSpecificToInstallment, loan);
                loanTermVariations.add(data);
            }
        }

    }
}

From source file:com.gst.portfolio.loanaccount.serialization.LoanApplicationCommandFromApiJsonHelper.java

License:Apache License

public void validateForCreate(final String json, final boolean isMeetingMandatoryForJLGLoans,
        final LoanProduct loanProduct) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }//from  www  . j a v a2 s .c  om

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);

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

    final JsonElement element = this.fromApiJsonHelper.parse(json);

    final String loanTypeParameterName = "loanType";
    final String loanTypeStr = this.fromApiJsonHelper.extractStringNamed(loanTypeParameterName, element);
    baseDataValidator.reset().parameter(loanTypeParameterName).value(loanTypeStr).notNull();

    if (!StringUtils.isBlank(loanTypeStr)) {
        final AccountType loanType = AccountType.fromName(loanTypeStr);
        baseDataValidator.reset().parameter(loanTypeParameterName).value(loanType.getValue()).inMinMaxRange(1,
                3);

        final Long clientId = this.fromApiJsonHelper.extractLongNamed("clientId", element);
        final Long groupId = this.fromApiJsonHelper.extractLongNamed("groupId", element);
        if (loanType.isIndividualAccount()) {
            baseDataValidator.reset().parameter("clientId").value(clientId).notNull().longGreaterThanZero();
            baseDataValidator.reset().parameter("groupId").value(groupId)
                    .mustBeBlankWhenParameterProvided("clientId", clientId);
        }

        if (loanType.isGroupAccount()) {
            baseDataValidator.reset().parameter("groupId").value(groupId).notNull().longGreaterThanZero();
            baseDataValidator.reset().parameter("clientId").value(clientId)
                    .mustBeBlankWhenParameterProvided("groupId", groupId);
        }

        if (loanType.isJLGAccount()) {
            baseDataValidator.reset().parameter("clientId").value(clientId).notNull().integerGreaterThanZero();
            baseDataValidator.reset().parameter("groupId").value(groupId).notNull().longGreaterThanZero();

            // if it is JLG loan that must have meeting details
            if (isMeetingMandatoryForJLGLoans) {
                final String calendarIdParameterName = "calendarId";
                final Long calendarId = this.fromApiJsonHelper.extractLongNamed(calendarIdParameterName,
                        element);
                baseDataValidator.reset().parameter(calendarIdParameterName).value(calendarId).notNull()
                        .integerGreaterThanZero();

                // if it is JLG loan then must have a value for
                // syncDisbursement passed in
                String syncDisbursementParameterName = "syncDisbursementWithMeeting";
                final Boolean syncDisbursement = this.fromApiJsonHelper
                        .extractBooleanNamed(syncDisbursementParameterName, element);

                if (syncDisbursement == null) {
                    baseDataValidator.reset().parameter(syncDisbursementParameterName).value(syncDisbursement)
                            .trueOrFalseRequired(false);
                }
            }

        }

    }

    final Long productId = this.fromApiJsonHelper.extractLongNamed("productId", element);
    baseDataValidator.reset().parameter("productId").value(productId).notNull().integerGreaterThanZero();

    final String accountNoParameterName = "accountNo";
    if (this.fromApiJsonHelper.parameterExists(accountNoParameterName, element)) {
        final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParameterName, element);
        baseDataValidator.reset().parameter(accountNoParameterName).value(accountNo).ignoreIfNull()
                .notExceedingLengthOf(20);
    }

    final String externalIdParameterName = "externalId";
    if (this.fromApiJsonHelper.parameterExists(externalIdParameterName, element)) {
        final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParameterName, element);
        baseDataValidator.reset().parameter(externalIdParameterName).value(externalId).ignoreIfNull()
                .notExceedingLengthOf(100);
    }

    final String fundIdParameterName = "fundId";
    if (this.fromApiJsonHelper.parameterExists(fundIdParameterName, element)) {
        final Long fundId = this.fromApiJsonHelper.extractLongNamed(fundIdParameterName, element);
        baseDataValidator.reset().parameter(fundIdParameterName).value(fundId).ignoreIfNull()
                .integerGreaterThanZero();
    }

    final String loanOfficerIdParameterName = "loanOfficerId";
    if (this.fromApiJsonHelper.parameterExists(loanOfficerIdParameterName, element)) {
        final Long loanOfficerId = this.fromApiJsonHelper.extractLongNamed(loanOfficerIdParameterName, element);
        baseDataValidator.reset().parameter(loanOfficerIdParameterName).value(loanOfficerId).ignoreIfNull()
                .integerGreaterThanZero();
    }

    final String loanPurposeIdParameterName = "loanPurposeId";
    if (this.fromApiJsonHelper.parameterExists(loanPurposeIdParameterName, element)) {
        final Long loanPurposeId = this.fromApiJsonHelper.extractLongNamed(loanPurposeIdParameterName, element);
        baseDataValidator.reset().parameter(loanPurposeIdParameterName).value(loanPurposeId).ignoreIfNull()
                .integerGreaterThanZero();
    }

    final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element);
    baseDataValidator.reset().parameter("principal").value(principal).notNull().positiveAmount();

    final String loanTermFrequencyParameterName = "loanTermFrequency";
    final Integer loanTermFrequency = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(loanTermFrequencyParameterName, element);
    baseDataValidator.reset().parameter(loanTermFrequencyParameterName).value(loanTermFrequency).notNull()
            .integerGreaterThanZero();

    final String loanTermFrequencyTypeParameterName = "loanTermFrequencyType";
    final Integer loanTermFrequencyType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(loanTermFrequencyTypeParameterName, element);
    baseDataValidator.reset().parameter(loanTermFrequencyTypeParameterName).value(loanTermFrequencyType)
            .notNull().inMinMaxRange(0, 3);

    final String numberOfRepaymentsParameterName = "numberOfRepayments";
    final Integer numberOfRepayments = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element);
    baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments).notNull()
            .integerGreaterThanZero();

    final String repaymentEveryParameterName = "repaymentEvery";
    final Integer repaymentEvery = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(repaymentEveryParameterName, element);
    baseDataValidator.reset().parameter(repaymentEveryParameterName).value(repaymentEvery).notNull()
            .integerGreaterThanZero();

    final String repaymentEveryFrequencyTypeParameterName = "repaymentFrequencyType";
    final Integer repaymentEveryType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(repaymentEveryFrequencyTypeParameterName, element);
    baseDataValidator.reset().parameter(repaymentEveryFrequencyTypeParameterName).value(repaymentEveryType)
            .notNull().inMinMaxRange(0, 3);

    final String repaymentFrequencyNthDayTypeParameterName = "repaymentFrequencyNthDayType";
    final String repaymentFrequencyDayOfWeekTypeParameterName = "repaymentFrequencyDayOfWeekType";
    CalendarUtils.validateNthDayOfMonthFrequency(baseDataValidator, repaymentFrequencyNthDayTypeParameterName,
            repaymentFrequencyDayOfWeekTypeParameterName, element, this.fromApiJsonHelper);
    final String interestTypeParameterName = "interestType";
    final Integer interestType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(interestTypeParameterName,
            element);
    baseDataValidator.reset().parameter(interestTypeParameterName).value(interestType).notNull()
            .inMinMaxRange(0, 1);

    final String interestCalculationPeriodTypeParameterName = "interestCalculationPeriodType";
    final Integer interestCalculationPeriodType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(interestCalculationPeriodTypeParameterName, element);
    baseDataValidator.reset().parameter(interestCalculationPeriodTypeParameterName)
            .value(interestCalculationPeriodType).notNull().inMinMaxRange(0, 1);

    if (loanProduct.isLinkedToFloatingInterestRate()) {
        if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode(
                    "not.supported.loanproduct.linked.to.floating.rate",
                    "interestRatePerPeriod param is not supported, selected Loan Product is linked with floating interest rate.");
        }

        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isFloatingInterestRate, element)) {
            final Boolean isFloatingInterestRate = this.fromApiJsonHelper
                    .extractBooleanNamed(LoanApiConstants.isFloatingInterestRate, element);
            if (isFloatingInterestRate != null && isFloatingInterestRate
                    && !loanProduct.getFloatingRates().isFloatingInterestRateCalculationAllowed()) {
                baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode(
                        "true.not.supported.for.selected.loanproduct",
                        "isFloatingInterestRate value of true not supported for selected Loan Product.");
            }
        } else {
            baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate)
                    .trueOrFalseRequired(false);
        }

        if (interestType != null && interestType.equals(InterestMethod.FLAT.getValue())) {
            baseDataValidator.reset().parameter(interestTypeParameterName).failWithCode(
                    "should.be.0.for.selected.loan.product",
                    "interestType should be DECLINING_BALANCE for selected Loan Product as it is linked to floating rates.");
        }

        final String interestRateDifferentialParameterName = LoanApiConstants.interestRateDifferential;
        final BigDecimal interestRateDifferential = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(interestRateDifferentialParameterName, element);
        baseDataValidator.reset().parameter(interestRateDifferentialParameterName)
                .value(interestRateDifferential).notNull().zeroOrPositiveAmount()
                .inMinAndMaxAmountRange(loanProduct.getFloatingRates().getMinDifferentialLendingRate(),
                        loanProduct.getFloatingRates().getMaxDifferentialLendingRate());

    } else {

        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isFloatingInterestRate, element)) {
            baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode(
                    "not.supported.loanproduct.not.linked.to.floating.rate",
                    "isFloatingInterestRate param is not supported, selected Loan Product is not linked with floating interest rate.");
        }
        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.interestRateDifferential, element)) {
            baseDataValidator.reset().parameter(LoanApiConstants.interestRateDifferential).failWithCode(
                    "not.supported.loanproduct.not.linked.to.floating.rate",
                    "interestRateDifferential param is not supported, selected Loan Product is not linked with floating interest rate.");
        }

        final String interestRatePerPeriodParameterName = "interestRatePerPeriod";
        final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, element);
        baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
                .notNull().zeroOrPositiveAmount();

    }

    final String amortizationTypeParameterName = "amortizationType";
    final Integer amortizationType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(amortizationTypeParameterName, element);
    baseDataValidator.reset().parameter(amortizationTypeParameterName).value(amortizationType).notNull()
            .inMinMaxRange(0, 1);

    final String expectedDisbursementDateParameterName = "expectedDisbursementDate";
    final LocalDate expectedDisbursementDate = this.fromApiJsonHelper
            .extractLocalDateNamed(expectedDisbursementDateParameterName, element);
    baseDataValidator.reset().parameter(expectedDisbursementDateParameterName).value(expectedDisbursementDate)
            .notNull();

    // grace validation
    final Integer graceOnPrincipalPayment = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element);
    baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment)
            .zeroOrPositiveAmount();

    final Integer graceOnInterestPayment = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("graceOnInterestPayment", element);
    baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment)
            .zeroOrPositiveAmount();

    final Integer graceOnInterestCharged = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("graceOnInterestCharged", element);
    baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged)
            .zeroOrPositiveAmount();

    final Integer graceOnArrearsAgeing = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(LoanProductConstants.graceOnArrearsAgeingParameterName, element);
    baseDataValidator.reset().parameter(LoanProductConstants.graceOnArrearsAgeingParameterName)
            .value(graceOnArrearsAgeing).zeroOrPositiveAmount();

    final String interestChargedFromDateParameterName = "interestChargedFromDate";
    if (this.fromApiJsonHelper.parameterExists(interestChargedFromDateParameterName, element)) {
        final LocalDate interestChargedFromDate = this.fromApiJsonHelper
                .extractLocalDateNamed(interestChargedFromDateParameterName, element);
        baseDataValidator.reset().parameter(interestChargedFromDateParameterName).value(interestChargedFromDate)
                .ignoreIfNull().notNull();
    }

    final String repaymentsStartingFromDateParameterName = "repaymentsStartingFromDate";
    if (this.fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) {
        final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper
                .extractLocalDateNamed(repaymentsStartingFromDateParameterName, element);
        baseDataValidator.reset().parameter(repaymentsStartingFromDateParameterName)
                .value(repaymentsStartingFromDate).ignoreIfNull().notNull();
    }

    final String inArrearsToleranceParameterName = "inArrearsTolerance";
    if (this.fromApiJsonHelper.parameterExists(inArrearsToleranceParameterName, element)) {
        final BigDecimal inArrearsTolerance = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(inArrearsToleranceParameterName, element);
        baseDataValidator.reset().parameter(inArrearsToleranceParameterName).value(inArrearsTolerance)
                .ignoreIfNull().zeroOrPositiveAmount();
    }

    final String submittedOnDateParameterName = "submittedOnDate";
    final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParameterName,
            element);
    if (submittedOnDate == null) {
        baseDataValidator.reset().parameter(submittedOnDateParameterName).value(submittedOnDate).notNull();
    }

    final String submittedOnNoteParameterName = "submittedOnNote";
    if (this.fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) {
        final String submittedOnNote = this.fromApiJsonHelper.extractStringNamed(submittedOnNoteParameterName,
                element);
        baseDataValidator.reset().parameter(submittedOnNoteParameterName).value(submittedOnNote).ignoreIfNull()
                .notExceedingLengthOf(500);
    }

    final String transactionProcessingStrategyIdParameterName = "transactionProcessingStrategyId";
    final Long transactionProcessingStrategyId = this.fromApiJsonHelper
            .extractLongNamed(transactionProcessingStrategyIdParameterName, element);
    baseDataValidator.reset().parameter(transactionProcessingStrategyIdParameterName)
            .value(transactionProcessingStrategyId).notNull().integerGreaterThanZero();

    final String linkAccountIdParameterName = "linkAccountId";
    if (this.fromApiJsonHelper.parameterExists(linkAccountIdParameterName, element)) {
        final Long linkAccountId = this.fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element);
        baseDataValidator.reset().parameter(linkAccountIdParameterName).value(linkAccountId).ignoreIfNull()
                .longGreaterThanZero();
    }

    final String createSiAtDisbursementParameterName = "createStandingInstructionAtDisbursement";
    if (this.fromApiJsonHelper.parameterExists(createSiAtDisbursementParameterName, element)) {
        final Boolean createStandingInstructionAtDisbursement = this.fromApiJsonHelper
                .extractBooleanNamed(createSiAtDisbursementParameterName, element);
        final Long linkAccountId = this.fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element);

        if (createStandingInstructionAtDisbursement) {
            baseDataValidator.reset().parameter(linkAccountIdParameterName).value(linkAccountId).notNull()
                    .longGreaterThanZero();
        }
    }

    // charges
    final String chargesParameterName = "charges";
    if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(chargesParameterName, element)) {
        final JsonObject topLevelJsonElement = element.getAsJsonObject();
        final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement);
        final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);

        if (topLevelJsonElement.get(chargesParameterName).isJsonArray()) {
            final Type arrayObjectParameterTypeOfMap = new TypeToken<Map<String, Object>>() {
            }.getType();
            final Set<String> supportedParameters = new HashSet<>(Arrays.asList("id", "chargeId", "amount",
                    "chargeTimeType", "chargeCalculationType", "dueDate"));

            final JsonArray array = topLevelJsonElement.get("charges").getAsJsonArray();
            for (int i = 1; i <= array.size(); i++) {

                final JsonObject loanChargeElement = array.get(i - 1).getAsJsonObject();
                final String arrayObjectJson = this.fromApiJsonHelper.toJson(loanChargeElement);
                this.fromApiJsonHelper.checkForUnsupportedParameters(arrayObjectParameterTypeOfMap,
                        arrayObjectJson, supportedParameters);

                final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement);
                baseDataValidator.reset().parameter("charges").parameterAtIndexArray("chargeId", i)
                        .value(chargeId).notNull().integerGreaterThanZero();

                final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount",
                        loanChargeElement, locale);
                baseDataValidator.reset().parameter("charges").parameterAtIndexArray("amount", i).value(amount)
                        .notNull().positiveAmount();

                this.fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale);
            }
        }
    }

    // collateral
    final String collateralParameterName = "collateral";
    if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(collateralParameterName, element)) {
        final JsonObject topLevelJsonElement = element.getAsJsonObject();
        final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
        if (topLevelJsonElement.get("collateral").isJsonArray()) {

            final Type collateralParameterTypeOfMap = new TypeToken<Map<String, Object>>() {
            }.getType();
            final Set<String> supportedParameters = new HashSet<>(
                    Arrays.asList("id", "type", "value", "description"));
            final JsonArray array = topLevelJsonElement.get("collateral").getAsJsonArray();
            for (int i = 1; i <= array.size(); i++) {
                final JsonObject collateralItemElement = array.get(i - 1).getAsJsonObject();

                final String collateralJson = this.fromApiJsonHelper.toJson(collateralItemElement);
                this.fromApiJsonHelper.checkForUnsupportedParameters(collateralParameterTypeOfMap,
                        collateralJson, supportedParameters);

                final Long collateralTypeId = this.fromApiJsonHelper.extractLongNamed("type",
                        collateralItemElement);
                baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("type", i)
                        .value(collateralTypeId).notNull().integerGreaterThanZero();

                final BigDecimal collateralValue = this.fromApiJsonHelper.extractBigDecimalNamed("value",
                        collateralItemElement, locale);
                baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("value", i)
                        .value(collateralValue).ignoreIfNull().positiveAmount();

                final String description = this.fromApiJsonHelper.extractStringNamed("description",
                        collateralItemElement);
                baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("description", i)
                        .value(description).notBlank().notExceedingLengthOf(500);

            }
        } else {
            baseDataValidator.reset().parameter(collateralParameterName).expectedArrayButIsNot();
        }
    }

    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.emiAmountParameterName, element)) {
        if (!(loanProduct.canDefineInstallmentAmount() || loanProduct.isMultiDisburseLoan())) {
            List<String> unsupportedParameterList = new ArrayList<>();
            unsupportedParameterList.add(LoanApiConstants.emiAmountParameterName);
            throw new UnsupportedParameterException(unsupportedParameterList);
        }
        final BigDecimal emiAnount = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(LoanApiConstants.emiAmountParameterName, element);
        baseDataValidator.reset().parameter(LoanApiConstants.emiAmountParameterName).value(emiAnount)
                .ignoreIfNull().positiveAmount();
    }
    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.maxOutstandingBalanceParameterName, element)) {
        final BigDecimal maxOutstandingBalance = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(LoanApiConstants.maxOutstandingBalanceParameterName, element);
        baseDataValidator.reset().parameter(LoanApiConstants.maxOutstandingBalanceParameterName)
                .value(maxOutstandingBalance).ignoreIfNull().positiveAmount();
    }

    if (loanProduct.canUseForTopup()) {
        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isTopup, element)) {
            final Boolean isTopup = this.fromApiJsonHelper.extractBooleanNamed(LoanApiConstants.isTopup,
                    element);
            baseDataValidator.reset().parameter(LoanApiConstants.isTopup).value(isTopup)
                    .validateForBooleanValue();

            if (isTopup != null && isTopup) {
                final Long loanId = this.fromApiJsonHelper.extractLongNamed(LoanApiConstants.loanIdToClose,
                        element);
                baseDataValidator.reset().parameter(LoanApiConstants.loanIdToClose).value(loanId).notNull()
                        .longGreaterThanZero();
            }
        }
    }
    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.datatables, element)) {
        final JsonArray datatables = this.fromApiJsonHelper.extractJsonArrayNamed(LoanApiConstants.datatables,
                element);
        baseDataValidator.reset().parameter(LoanApiConstants.datatables).value(datatables).notNull()
                .jsonArrayNotEmpty();
    }

    validateLoanMultiDisbursementdate(element, baseDataValidator, expectedDisbursementDate, principal);
    validatePartialPeriodSupport(interestCalculationPeriodType, baseDataValidator, element, loanProduct);
    if (!dataValidationErrors.isEmpty()) {
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }
}

From source file:com.gst.portfolio.loanaccount.serialization.LoanApplicationCommandFromApiJsonHelper.java

License:Apache License

public void validateForModify(final String json, final LoanProduct loanProduct,
        final Loan existingLoanApplication) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }/*w ww. j a v  a 2  s  .c  o  m*/

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("loan");
    final JsonElement element = this.fromApiJsonHelper.parse(json);
    boolean atLeastOneParameterPassedForUpdate = false;

    final String clientIdParameterName = "clientId";
    if (this.fromApiJsonHelper.parameterExists(clientIdParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParameterName, element);
        baseDataValidator.reset().parameter(clientIdParameterName).value(clientId).notNull()
                .integerGreaterThanZero();
    }

    final String groupIdParameterName = "groupId";
    if (this.fromApiJsonHelper.parameterExists(groupIdParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Long groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParameterName, element);
        baseDataValidator.reset().parameter(groupIdParameterName).value(groupId).notNull()
                .integerGreaterThanZero();
    }

    final String productIdParameterName = "productId";
    if (this.fromApiJsonHelper.parameterExists(productIdParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParameterName, element);
        baseDataValidator.reset().parameter(productIdParameterName).value(productId).notNull()
                .integerGreaterThanZero();
    }

    final String accountNoParameterName = "accountNo";
    if (this.fromApiJsonHelper.parameterExists(accountNoParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParameterName, element);
        baseDataValidator.reset().parameter(accountNoParameterName).value(accountNo).notBlank()
                .notExceedingLengthOf(20);
    }

    final String externalIdParameterName = "externalId";
    if (this.fromApiJsonHelper.parameterExists(externalIdParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParameterName, element);
        baseDataValidator.reset().parameter(externalIdParameterName).value(externalId).ignoreIfNull()
                .notExceedingLengthOf(100);
    }

    final String fundIdParameterName = "fundId";
    if (this.fromApiJsonHelper.parameterExists(fundIdParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Long fundId = this.fromApiJsonHelper.extractLongNamed(fundIdParameterName, element);
        baseDataValidator.reset().parameter(fundIdParameterName).value(fundId).ignoreIfNull()
                .integerGreaterThanZero();
    }

    final String loanOfficerIdParameterName = "loanOfficerId";
    if (this.fromApiJsonHelper.parameterExists(loanOfficerIdParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Long loanOfficerId = this.fromApiJsonHelper.extractLongNamed(loanOfficerIdParameterName, element);
        baseDataValidator.reset().parameter(loanOfficerIdParameterName).value(loanOfficerId).ignoreIfNull()
                .integerGreaterThanZero();
    }

    final String transactionProcessingStrategyIdParameterName = "transactionProcessingStrategyId";
    if (this.fromApiJsonHelper.parameterExists(transactionProcessingStrategyIdParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Long transactionProcessingStrategyId = this.fromApiJsonHelper
                .extractLongNamed(transactionProcessingStrategyIdParameterName, element);
        baseDataValidator.reset().parameter(transactionProcessingStrategyIdParameterName)
                .value(transactionProcessingStrategyId).notNull().integerGreaterThanZero();
    }

    final String principalParameterName = "principal";
    BigDecimal principal = null;
    if (this.fromApiJsonHelper.parameterExists(principalParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName, element);
        baseDataValidator.reset().parameter(principalParameterName).value(principal).notNull().positiveAmount();
    }

    final String inArrearsToleranceParameterName = "inArrearsTolerance";
    if (this.fromApiJsonHelper.parameterExists(inArrearsToleranceParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final BigDecimal inArrearsTolerance = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(inArrearsToleranceParameterName, element);
        baseDataValidator.reset().parameter(inArrearsToleranceParameterName).value(inArrearsTolerance)
                .ignoreIfNull().zeroOrPositiveAmount();
    }

    final String loanTermFrequencyParameterName = "loanTermFrequency";
    if (this.fromApiJsonHelper.parameterExists(loanTermFrequencyParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Integer loanTermFrequency = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(loanTermFrequencyParameterName, element);
        baseDataValidator.reset().parameter(loanTermFrequencyParameterName).value(loanTermFrequency).notNull()
                .integerGreaterThanZero();
    }

    final String loanTermFrequencyTypeParameterName = "loanTermFrequencyType";
    if (this.fromApiJsonHelper.parameterExists(loanTermFrequencyTypeParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Integer loanTermFrequencyType = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(loanTermFrequencyTypeParameterName, element);
        baseDataValidator.reset().parameter(loanTermFrequencyTypeParameterName).value(loanTermFrequencyType)
                .notNull().inMinMaxRange(0, 3);
    }

    final String numberOfRepaymentsParameterName = "numberOfRepayments";
    if (this.fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Integer numberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element);
        baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments).notNull()
                .integerGreaterThanZero();
    }

    final String repaymentEveryParameterName = "repaymentEvery";
    if (this.fromApiJsonHelper.parameterExists(repaymentEveryParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Integer repaymentEvery = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(repaymentEveryParameterName, element);
        baseDataValidator.reset().parameter(repaymentEveryParameterName).value(repaymentEvery).notNull()
                .integerGreaterThanZero();
    }

    final String repaymentEveryTypeParameterName = "repaymentFrequencyType";
    if (this.fromApiJsonHelper.parameterExists(repaymentEveryTypeParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Integer repaymentEveryType = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(repaymentEveryTypeParameterName, element);
        baseDataValidator.reset().parameter(repaymentEveryTypeParameterName).value(repaymentEveryType).notNull()
                .inMinMaxRange(0, 3);
    }
    final String repaymentFrequencyNthDayTypeParameterName = "repaymentFrequencyNthDayType";
    final String repaymentFrequencyDayOfWeekTypeParameterName = "repaymentFrequencyDayOfWeekType";
    CalendarUtils.validateNthDayOfMonthFrequency(baseDataValidator, repaymentFrequencyNthDayTypeParameterName,
            repaymentFrequencyDayOfWeekTypeParameterName, element, this.fromApiJsonHelper);

    final String interestTypeParameterName = "interestType";
    Integer interestType = null;
    if (this.fromApiJsonHelper.parameterExists(interestTypeParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        interestType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(interestTypeParameterName, element);
        baseDataValidator.reset().parameter(interestTypeParameterName).value(interestType).notNull()
                .inMinMaxRange(0, 1);
    }

    if (loanProduct.isLinkedToFloatingInterestRate()) {
        if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode(
                    "not.supported.loanproduct.linked.to.floating.rate",
                    "interestRatePerPeriod param is not supported, selected Loan Product is linked with floating interest rate.");
        }

        Boolean isFloatingInterestRate = existingLoanApplication.getIsFloatingInterestRate();
        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isFloatingInterestRate, element)) {
            isFloatingInterestRate = this.fromApiJsonHelper
                    .extractBooleanNamed(LoanApiConstants.isFloatingInterestRate, element);
            atLeastOneParameterPassedForUpdate = true;
        }
        if (isFloatingInterestRate != null) {
            if (isFloatingInterestRate
                    && !loanProduct.getFloatingRates().isFloatingInterestRateCalculationAllowed()) {
                baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode(
                        "true.not.supported.for.selected.loanproduct",
                        "isFloatingInterestRate value of true not supported for selected Loan Product.");
            }
        } else {
            baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate)
                    .trueOrFalseRequired(false);
        }

        if (interestType == null) {
            interestType = existingLoanApplication.getLoanProductRelatedDetail().getInterestMethod().getValue();
        }
        if (interestType != null && interestType.equals(InterestMethod.FLAT.getValue())) {
            baseDataValidator.reset().parameter(interestTypeParameterName).failWithCode(
                    "should.be.0.for.selected.loan.product",
                    "interestType should be DECLINING_BALANCE for selected Loan Product as it is linked to floating rates.");
        }

        final String interestRateDifferentialParameterName = LoanApiConstants.interestRateDifferential;
        BigDecimal interestRateDifferential = existingLoanApplication.getInterestRateDifferential();
        if (this.fromApiJsonHelper.parameterExists(interestRateDifferentialParameterName, element)) {
            interestRateDifferential = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(interestRateDifferentialParameterName, element);
            atLeastOneParameterPassedForUpdate = true;
        }
        baseDataValidator.reset().parameter(interestRateDifferentialParameterName)
                .value(interestRateDifferential).notNull().zeroOrPositiveAmount()
                .inMinAndMaxAmountRange(loanProduct.getFloatingRates().getMinDifferentialLendingRate(),
                        loanProduct.getFloatingRates().getMaxDifferentialLendingRate());

    } else {

        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isFloatingInterestRate, element)) {
            baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode(
                    "not.supported.loanproduct.not.linked.to.floating.rate",
                    "isFloatingInterestRate param is not supported, selected Loan Product is not linked with floating interest rate.");
        }
        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.interestRateDifferential, element)) {
            baseDataValidator.reset().parameter(LoanApiConstants.interestRateDifferential).failWithCode(
                    "not.supported.loanproduct.not.linked.to.floating.rate",
                    "interestRateDifferential param is not supported, selected Loan Product is not linked with floating interest rate.");
        }

        final String interestRatePerPeriodParameterName = "interestRatePerPeriod";
        BigDecimal interestRatePerPeriod = existingLoanApplication.getLoanProductRelatedDetail()
                .getNominalInterestRatePerPeriod();
        if (this.fromApiJsonHelper.parameterExists(interestRatePerPeriodParameterName, element)) {
            this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName,
                    element);
            atLeastOneParameterPassedForUpdate = true;
        }
        baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
                .notNull().zeroOrPositiveAmount();

    }

    Integer interestCalculationPeriodType = loanProduct.getLoanProductRelatedDetail()
            .getInterestCalculationPeriodMethod().getValue();
    final String interestCalculationPeriodTypeParameterName = "interestCalculationPeriodType";
    if (this.fromApiJsonHelper.parameterExists(interestCalculationPeriodTypeParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        interestCalculationPeriodType = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(interestCalculationPeriodTypeParameterName, element);
        baseDataValidator.reset().parameter(interestCalculationPeriodTypeParameterName)
                .value(interestCalculationPeriodType).notNull().inMinMaxRange(0, 1);
    }

    final String amortizationTypeParameterName = "amortizationType";
    if (this.fromApiJsonHelper.parameterExists(amortizationTypeParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Integer amortizationType = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(amortizationTypeParameterName, element);
        baseDataValidator.reset().parameter(amortizationTypeParameterName).value(amortizationType).notNull()
                .inMinMaxRange(0, 1);
    }

    final String expectedDisbursementDateParameterName = "expectedDisbursementDate";
    LocalDate expectedDisbursementDate = null;
    if (this.fromApiJsonHelper.parameterExists(expectedDisbursementDateParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;

        final String expectedDisbursementDateStr = this.fromApiJsonHelper
                .extractStringNamed(expectedDisbursementDateParameterName, element);
        baseDataValidator.reset().parameter(expectedDisbursementDateParameterName)
                .value(expectedDisbursementDateStr).notBlank();

        expectedDisbursementDate = this.fromApiJsonHelper
                .extractLocalDateNamed(expectedDisbursementDateParameterName, element);
        baseDataValidator.reset().parameter(expectedDisbursementDateParameterName)
                .value(expectedDisbursementDate).notNull();
    }

    // grace validation
    if (this.fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) {
        final Integer graceOnPrincipalPayment = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element);
        baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment)
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("graceOnInterestPayment", element)) {
        final Integer graceOnInterestPayment = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("graceOnInterestPayment", element);
        baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment)
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("graceOnInterestCharged", element)) {
        final Integer graceOnInterestCharged = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("graceOnInterestCharged", element);
        baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged)
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.graceOnArrearsAgeingParameterName,
            element)) {
        final Integer graceOnArrearsAgeing = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(LoanProductConstants.graceOnArrearsAgeingParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.graceOnArrearsAgeingParameterName)
                .value(graceOnArrearsAgeing).zeroOrPositiveAmount();
    }

    final String interestChargedFromDateParameterName = "interestChargedFromDate";
    if (this.fromApiJsonHelper.parameterExists(interestChargedFromDateParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final LocalDate interestChargedFromDate = this.fromApiJsonHelper
                .extractLocalDateNamed(interestChargedFromDateParameterName, element);
        baseDataValidator.reset().parameter(interestChargedFromDateParameterName).value(interestChargedFromDate)
                .ignoreIfNull();
    }

    final String repaymentsStartingFromDateParameterName = "repaymentsStartingFromDate";
    if (this.fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper
                .extractLocalDateNamed(repaymentsStartingFromDateParameterName, element);
        baseDataValidator.reset().parameter(repaymentsStartingFromDateParameterName)
                .value(repaymentsStartingFromDate).ignoreIfNull();
        if (!existingLoanApplication.getLoanTermVariations().isEmpty()) {
            baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode(
                    "cannot.modify.application.due.to.variable.installments");
        }
    }

    final String submittedOnDateParameterName = "submittedOnDate";
    if (this.fromApiJsonHelper.parameterExists(submittedOnDateParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final LocalDate submittedOnDate = this.fromApiJsonHelper
                .extractLocalDateNamed(submittedOnDateParameterName, element);
        baseDataValidator.reset().parameter(submittedOnDateParameterName).value(submittedOnDate).notNull();
    }

    final String submittedOnNoteParameterName = "submittedOnNote";
    if (this.fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final String submittedOnNote = this.fromApiJsonHelper.extractStringNamed(submittedOnNoteParameterName,
                element);
        baseDataValidator.reset().parameter(submittedOnNoteParameterName).value(submittedOnNote).ignoreIfNull()
                .notExceedingLengthOf(500);
    }

    final String linkAccountIdParameterName = "linkAccountId";
    if (this.fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;
        final Long linkAccountId = this.fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element);
        baseDataValidator.reset().parameter(linkAccountIdParameterName).value(linkAccountId).ignoreIfNull()
                .longGreaterThanZero();
    }

    // charges
    final String chargesParameterName = "charges";
    if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(chargesParameterName, element)) {
        atLeastOneParameterPassedForUpdate = true;

        final JsonObject topLevelJsonElement = element.getAsJsonObject();
        final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement);
        final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);

        if (topLevelJsonElement.get(chargesParameterName).isJsonArray()) {
            final Type arrayObjectParameterTypeOfMap = new TypeToken<Map<String, Object>>() {
            }.getType();
            final Set<String> supportedParameters = new HashSet<>(Arrays.asList("id", "chargeId", "amount",
                    "chargeTimeType", "chargeCalculationType", "dueDate"));

            final JsonArray array = topLevelJsonElement.get("charges").getAsJsonArray();
            for (int i = 1; i <= array.size(); i++) {

                final JsonObject loanChargeElement = array.get(i - 1).getAsJsonObject();
                final String arrayObjectJson = this.fromApiJsonHelper.toJson(loanChargeElement);
                this.fromApiJsonHelper.checkForUnsupportedParameters(arrayObjectParameterTypeOfMap,
                        arrayObjectJson, supportedParameters);

                final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement);
                baseDataValidator.reset().parameter("charges").parameterAtIndexArray("chargeId", i)
                        .value(chargeId).notNull().integerGreaterThanZero();

                final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount",
                        loanChargeElement, locale);
                baseDataValidator.reset().parameter("charges").parameterAtIndexArray("amount", i).value(amount)
                        .notNull().positiveAmount();

                this.fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale);
            }
        }
    }

    // collateral
    final String collateralParameterName = "collateral";
    if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(collateralParameterName, element)) {
        final JsonObject topLevelJsonElement = element.getAsJsonObject();
        final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
        if (topLevelJsonElement.get("collateral").isJsonArray()) {

            final Type collateralParameterTypeOfMap = new TypeToken<Map<String, Object>>() {
            }.getType();
            final Set<String> supportedParameters = new HashSet<>(
                    Arrays.asList("id", "type", "value", "description"));
            final JsonArray array = topLevelJsonElement.get("collateral").getAsJsonArray();
            for (int i = 1; i <= array.size(); i++) {
                final JsonObject collateralItemElement = array.get(i - 1).getAsJsonObject();

                final String collateralJson = this.fromApiJsonHelper.toJson(collateralItemElement);
                this.fromApiJsonHelper.checkForUnsupportedParameters(collateralParameterTypeOfMap,
                        collateralJson, supportedParameters);

                final Long collateralTypeId = this.fromApiJsonHelper.extractLongNamed("type",
                        collateralItemElement);
                baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("type", i)
                        .value(collateralTypeId).notNull().integerGreaterThanZero();

                final BigDecimal collateralValue = this.fromApiJsonHelper.extractBigDecimalNamed("value",
                        collateralItemElement, locale);
                baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("value", i)
                        .value(collateralValue).ignoreIfNull().positiveAmount();

                final String description = this.fromApiJsonHelper.extractStringNamed("description",
                        collateralItemElement);
                baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("description", i)
                        .value(description).notBlank().notExceedingLengthOf(500);

            }
        } else {
            baseDataValidator.reset().parameter(collateralParameterName).expectedArrayButIsNot();
        }
    }

    boolean meetingIdRequired = false;
    // validate syncDisbursement
    final String syncDisbursementParameterName = "syncDisbursementWithMeeting";
    if (this.fromApiJsonHelper.parameterExists(syncDisbursementParameterName, element)) {
        final Boolean syncDisbursement = this.fromApiJsonHelper
                .extractBooleanNamed(syncDisbursementParameterName, element);
        if (syncDisbursement == null) {
            baseDataValidator.reset().parameter(syncDisbursementParameterName).value(syncDisbursement)
                    .trueOrFalseRequired(false);
        } else if (syncDisbursement.booleanValue()) {
            meetingIdRequired = true;
        }
    }

    final String calendarIdParameterName = "calendarId";
    // if disbursement is synced then must have a meeting (calendar)
    if (meetingIdRequired || this.fromApiJsonHelper.parameterExists(calendarIdParameterName, element)) {
        final Long calendarId = this.fromApiJsonHelper.extractLongNamed(calendarIdParameterName, element);
        baseDataValidator.reset().parameter(calendarIdParameterName).value(calendarId).notNull()
                .integerGreaterThanZero();
    }

    if (!atLeastOneParameterPassedForUpdate) {
        final Object forceError = null;
        baseDataValidator.reset().anyOfNotNull(forceError);
    }

    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.emiAmountParameterName, element)) {
        if (!(loanProduct.canDefineInstallmentAmount() || loanProduct.isMultiDisburseLoan())) {
            List<String> unsupportedParameterList = new ArrayList<>();
            unsupportedParameterList.add(LoanApiConstants.emiAmountParameterName);
            throw new UnsupportedParameterException(unsupportedParameterList);
        }
        final BigDecimal emiAnount = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(LoanApiConstants.emiAmountParameterName, element);
        baseDataValidator.reset().parameter(LoanApiConstants.emiAmountParameterName).value(emiAnount)
                .ignoreIfNull().positiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.maxOutstandingBalanceParameterName, element)) {
        final BigDecimal maxOutstandingBalance = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(LoanApiConstants.maxOutstandingBalanceParameterName, element);
        baseDataValidator.reset().parameter(LoanApiConstants.maxOutstandingBalanceParameterName)
                .value(maxOutstandingBalance).ignoreIfNull().positiveAmount();
    }

    if (loanProduct.canUseForTopup()) {
        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isTopup, element)) {
            final Boolean isTopup = this.fromApiJsonHelper.extractBooleanNamed(LoanApiConstants.isTopup,
                    element);
            baseDataValidator.reset().parameter(LoanApiConstants.isTopup).value(isTopup).ignoreIfNull()
                    .validateForBooleanValue();

            if (isTopup != null && isTopup) {
                final Long loanId = this.fromApiJsonHelper.extractLongNamed(LoanApiConstants.loanIdToClose,
                        element);
                baseDataValidator.reset().parameter(LoanApiConstants.loanIdToClose).value(loanId).notNull()
                        .longGreaterThanZero();
            }
        }
    }

    validateLoanMultiDisbursementdate(element, baseDataValidator, expectedDisbursementDate, principal);
    validatePartialPeriodSupport(interestCalculationPeriodType, baseDataValidator, element, loanProduct);

    if (!dataValidationErrors.isEmpty()) {
        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}