Example usage for com.google.gson JsonArray get

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

Introduction

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

Prototype

public JsonElement get(int i) 

Source Link

Document

Returns the ith element of the array.

Usage

From source file:com.gst.portfolio.interestratechart.data.InterestRateChartSlabDataValidator.java

License:Apache License

private void validateIncentives(JsonElement element, DataValidatorBuilder baseDataValidator,
        final Locale locale) {

    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();
                if (this.fromApiJsonHelper.parameterExists(InterestIncentiveApiConstants.idParamName,
                        incentiveElement)) {
                    final Long id = this.fromApiJsonHelper
                            .extractLongNamed(InterestIncentiveApiConstants.idParamName, incentiveElement);
                    baseDataValidator.reset().parameter(InterestIncentiveApiConstants.idParamName).value(id)
                            .notNull().integerGreaterThanZero();
                    this.interestIncentiveDataValidator.validateIncentiveUpdate(incentiveElement,
                            baseDataValidator, locale);
                } else {
                    this.interestIncentiveDataValidator.validateIncentiveCreate(incentiveElement,
                            baseDataValidator, locale);
                }/*w w  w .  j  a v  a2 s  .  c  o m*/
            }
        }
    }
}

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

License:Apache License

public void updateChartSlabs(JsonCommand command, final Map<String, Object> actualChanges,
        final DataValidatorBuilder baseDataValidator, String currencyCode) {

    final Map<String, Object> deleteChartSlabs = new HashMap<>();
    final Map<String, Object> chartSlabsChanges = new HashMap<>();
    final Locale locale = command.extractLocale();
    if (command.hasParameter(InterestRateChartApiConstants.chartSlabs)) {
        final JsonArray array = command.arrayOfParameterNamed(InterestRateChartApiConstants.chartSlabs);
        if (array != null) {
            for (int i = 0; i < array.size(); i++) {
                final JsonObject chartSlabsElement = array.get(i).getAsJsonObject();
                JsonCommand chartSlabsCommand = JsonCommand.fromExistingCommand(command, chartSlabsElement);
                if (chartSlabsCommand.parameterExists(idParamName)) {
                    final Long chartSlabId = chartSlabsCommand.longValueOfParameterNamed(idParamName);
                    final InterestRateChartSlab chartSlab = this.findChartSlab(chartSlabId);
                    if (chartSlab == null) {
                        baseDataValidator.parameter(idParamName).value(chartSlabId)
                                .failWithCode("no.chart.slab.associated.with.id");
                    } else if (chartSlabsCommand.parameterExists(deleteParamName)) {
                        if (this.removeChartSlab(chartSlab)) {
                            deleteChartSlabs.put(idParamName, chartSlabId);
                        }//from   www.  j  a  va2  s.  c o  m
                    } else {
                        chartSlab.update(chartSlabsCommand, chartSlabsChanges, baseDataValidator, locale);
                    }
                } else {

                    /**
                     * TODO: AA: Move this code to
                     * InterestRateChartSlabAssembler
                     */
                    final String description = chartSlabsCommand
                            .stringValueOfParameterNamed(descriptionParamName);
                    final Integer periodTypeId = chartSlabsCommand
                            .integerValueOfParameterNamed(periodTypeParamName, locale);
                    final SavingsPeriodFrequencyType periodFrequencyType = SavingsPeriodFrequencyType
                            .fromInt(periodTypeId);
                    final Integer fromPeriod = chartSlabsCommand
                            .integerValueOfParameterNamed(fromPeriodParamName, locale);
                    final Integer toPeriod = chartSlabsCommand.integerValueOfParameterNamed(toPeriodParamName,
                            locale);
                    final BigDecimal amountRangeFrom = chartSlabsCommand
                            .bigDecimalValueOfParameterNamed(amountRangeFromParamName, locale);
                    final BigDecimal amountRangeTo = chartSlabsCommand
                            .bigDecimalValueOfParameterNamed(amountRangeToParamName, locale);
                    final BigDecimal annualInterestRate = chartSlabsCommand
                            .bigDecimalValueOfParameterNamed(annualInterestRateParamName, locale);

                    final InterestRateChartSlabFields slabFields = InterestRateChartSlabFields.createNew(
                            description, periodFrequencyType, fromPeriod, toPeriod, amountRangeFrom,
                            amountRangeTo, annualInterestRate, currencyCode);
                    final InterestRateChartSlab chartSlab = InterestRateChartSlab.createNew(slabFields, this);
                    chartSlab.slabFields().validateChartSlabPlatformRules(chartSlabsCommand, baseDataValidator,
                            locale);
                    chartSlab.updateIncentives(chartSlabsCommand, actualChanges, baseDataValidator, chartSlab,
                            locale);
                    this.addChartSlab(chartSlab);
                }
            }
        }
    }

    // add chart slab changes to actual changes list.
    if (!chartSlabsChanges.isEmpty()) {
        actualChanges.put(InterestRateChartApiConstants.chartSlabs, chartSlabsChanges);
    }

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

    this.validateChartSlabs(baseDataValidator);
}

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  ww  w.  j  av a 2s .  co 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 w ww .  j  a  v  a 2s. co m*/
                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) {/*from   ww w .jav  a  2 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.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  w w.  j  a v a 2  s  .  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 {//from w w  w.j av  a 2s.c  o m
            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();
    }//  ww w. j  av 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);

    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 w  w  . 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);
    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);
    }
}

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

License:Apache License

private void validateDisbursementsAreDatewiseOrdered(JsonElement element,
        final DataValidatorBuilder baseDataValidator) {
    final JsonObject topLevelJsonElement = element.getAsJsonObject();
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
    final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement);
    final JsonArray variationArray = this.fromApiJsonHelper
            .extractJsonArrayNamed(LoanApiConstants.disbursementDataParameterName, element);
    if (variationArray != null) {
        for (int i = 0; i < variationArray.size(); i++) {
            final JsonObject jsonObject1 = variationArray.get(i).getAsJsonObject();
            if (jsonObject1.has(LoanApiConstants.disbursementDateParameterName)) {
                LocalDate date1 = this.fromApiJsonHelper.extractLocalDateNamed(
                        LoanApiConstants.disbursementDateParameterName, jsonObject1, dateFormat, locale);

                for (int j = i + 1; j < variationArray.size(); j++) {
                    final JsonObject jsonObject2 = variationArray.get(j).getAsJsonObject();
                    if (jsonObject2.has(LoanApiConstants.disbursementDateParameterName)) {
                        LocalDate date2 = this.fromApiJsonHelper.extractLocalDateNamed(
                                LoanApiConstants.disbursementDateParameterName, jsonObject2, dateFormat,
                                locale);
                        if (date1.isAfter(date2)) {
                            baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName)
                                    .failWithCode(LoanApiConstants.DISBURSEMENT_DATES_NOT_IN_ORDER);
                        }//w ww. j a  va2 s .  c  o  m
                    }
                }
            }

        }
    }
}