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.accounting.producttoaccountmapping.service.ProductToGLAccountMappingHelper.java

License:Apache License

/**
 * @param command/*from  w  w w.java2s .  c  o  m*/
 * @param element
 * @param productId
 * @param changes
 */
public void updatePaymentChannelToFundSourceMappings(final JsonCommand command, final JsonElement element,
        final Long productId, final Map<String, Object> changes,
        final PortfolioProductType portfolioProductType) {
    // find all existing payment Channel to Fund source Mappings
    final List<ProductToGLAccountMapping> existingPaymentChannelToFundSourceMappings = this.accountMappingRepository
            .findAllPaymentTypeToFundSourceMappings(productId, portfolioProductType.getValue());
    final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed(
            LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element);
    /**
     * Variable stores a map representation of Payment channels (key) and
     * their fund sources (value) extracted from the passed in Jsoncommand
     **/
    final Map<Long, Long> inputPaymentChannelFundSourceMap = new HashMap<>();
    /***
     * Variable stores all payment types which have already been mapped to
     * Fund Sources in the system
     **/
    final Set<Long> existingPaymentTypes = new HashSet<>();
    if (paymentChannelMappingArray != null && paymentChannelMappingArray.size() > 0) {
        if (changes != null) {
            changes.put(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(),
                    command.jsonFragment(
                            LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue()));
        }

        for (int i = 0; i < paymentChannelMappingArray.size(); i++) {
            final JsonObject jsonObject = paymentChannelMappingArray.get(i).getAsJsonObject();
            final Long paymentTypeId = jsonObject.get(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.getValue())
                    .getAsLong();
            final Long paymentSpecificFundAccountId = jsonObject
                    .get(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).getAsLong();
            inputPaymentChannelFundSourceMap.put(paymentTypeId, paymentSpecificFundAccountId);
        }

        // If input map is empty, delete all existing mappings
        if (inputPaymentChannelFundSourceMap.size() == 0) {
            this.accountMappingRepository.deleteInBatch(existingPaymentChannelToFundSourceMappings);
        } /**
          * Else, <br/>
          * update existing mappings OR <br/>
          * delete old mappings (which re already present, but not passed in
          * as a part of Jsoncommand)<br/>
          * Create new mappings for payment types that are passed in as a
          * part of the Jsoncommand but not already present
          * 
          **/
        else {
            for (final ProductToGLAccountMapping existingPaymentChannelToFundSourceMapping : existingPaymentChannelToFundSourceMappings) {
                final Long currentPaymentChannelId = existingPaymentChannelToFundSourceMapping.getPaymentType()
                        .getId();
                existingPaymentTypes.add(currentPaymentChannelId);
                // update existing mappings (if required)
                if (inputPaymentChannelFundSourceMap.containsKey(currentPaymentChannelId)) {
                    final Long newGLAccountId = inputPaymentChannelFundSourceMap.get(currentPaymentChannelId);
                    if (newGLAccountId != existingPaymentChannelToFundSourceMapping.getGlAccount().getId()) {
                        final GLAccount glAccount = getAccountByIdAndType(
                                LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), GLAccountType.ASSET,
                                newGLAccountId);
                        existingPaymentChannelToFundSourceMapping.setGlAccount(glAccount);
                        this.accountMappingRepository.save(existingPaymentChannelToFundSourceMapping);
                    }
                } // deleted payment type
                else {
                    this.accountMappingRepository.delete(existingPaymentChannelToFundSourceMapping);
                }
            }
            // create new mappings
            final Set<Long> incomingPaymentTypes = inputPaymentChannelFundSourceMap.keySet();
            incomingPaymentTypes.removeAll(existingPaymentTypes);
            // incomingPaymentTypes now only contains the newly added
            // payment Type mappings
            for (final Long newPaymentType : incomingPaymentTypes) {
                final Long newGLAccountId = inputPaymentChannelFundSourceMap.get(newPaymentType);
                savePaymentChannelToFundSourceMapping(productId, newPaymentType, newGLAccountId,
                        portfolioProductType);
            }
        }
    }
}

From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java

License:Apache License

public String[] extractArrayNamed(final String parameterName, final JsonElement element,
        final Set<String> parametersPassedInRequest) {
    String[] arrayValue = null;//from  www .  jav a 2 s  .c  om
    if (element.isJsonObject()) {
        final JsonObject object = element.getAsJsonObject();
        if (object.has(parameterName)) {
            parametersPassedInRequest.add(parameterName);
            final JsonArray array = object.get(parameterName).getAsJsonArray();
            arrayValue = new String[array.size()];
            for (int i = 0; i < array.size(); i++) {
                arrayValue[i] = array.get(i).getAsString();
            }
        }
    }
    return arrayValue;
}

From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java

License:Apache License

/**
 * Used with the local date is in array format
 *//*from   w ww.j av a  2  s.  co  m*/
public LocalDate extractLocalDateAsArrayNamed(final String parameterName, final JsonElement element,
        final Set<String> parametersPassedInCommand) {
    LocalDate value = null;
    if (element.isJsonObject()) {
        final JsonObject object = element.getAsJsonObject();

        if (object.has(parameterName) && object.get(parameterName).isJsonArray()) {

            parametersPassedInCommand.add(parameterName);

            final JsonArray dateArray = object.get(parameterName).getAsJsonArray();

            final Integer year = dateArray.get(0).getAsInt();
            final Integer month = dateArray.get(1).getAsInt();
            final Integer day = dateArray.get(2).getAsInt();

            value = new LocalDate().withYearOfEra(year).withMonthOfYear(month).withDayOfMonth(day);
        }

    }
    return value;
}

From source file:com.gst.infrastructure.dataqueries.service.ReportWritePlatformServiceImpl.java

License:Apache License

private Set<ReportParameterUsage> assembleSetOfReportParameterUsages(final Report report,
        final JsonCommand command) {

    Set<ReportParameterUsage> reportParameterUsages = null;

    if (command.parameterExists("reportParameters")) {
        final JsonArray reportParametersArray = command.arrayOfParameterNamed("reportParameters");
        if (reportParametersArray != null) {

            reportParameterUsages = new HashSet<>();

            for (int i = 0; i < reportParametersArray.size(); i++) {

                final JsonObject jsonObject = reportParametersArray.get(i).getAsJsonObject();

                Long id = null;/*from w w  w.j a va2s.c o m*/
                ReportParameterUsage reportParameterUsageItem = null;
                ReportParameter reportParameter = null;
                String reportParameterName = null;

                if (jsonObject.has("id")) {
                    final String idStr = jsonObject.get("id").getAsString();
                    if (StringUtils.isNotBlank(idStr)) {
                        id = Long.parseLong(idStr);
                    }
                }

                if (id != null) {
                    // existing report parameter usage
                    reportParameterUsageItem = this.reportParameterUsageRepository.findOne(id);
                    if (reportParameterUsageItem == null) {
                        throw new ReportParameterNotFoundException(id);
                    }

                    // check parameter
                    if (jsonObject.has("parameterId")) {
                        final Long parameterId = jsonObject.get("parameterId").getAsLong();
                        reportParameter = this.reportParameterRepository.findOne(parameterId);
                        if (reportParameter == null
                                || !reportParameterUsageItem.hasParameterIdOf(parameterId)) {
                            //
                            throw new ReportParameterNotFoundException(parameterId);
                        }
                    }

                    if (jsonObject.has("reportParameterName")) {
                        reportParameterName = jsonObject.get("reportParameterName").getAsString();
                        reportParameterUsageItem.updateParameterName(reportParameterName);
                    }
                } else {
                    // new report parameter usage
                    if (jsonObject.has("parameterId")) {
                        final Long parameterId = jsonObject.get("parameterId").getAsLong();
                        reportParameter = this.reportParameterRepository.findOne(parameterId);
                        if (reportParameter == null) {
                            throw new ReportParameterNotFoundException(parameterId);
                        }
                    } else {
                        throw new PlatformDataIntegrityException(
                                "error.msg.parameter.id.mandatory.in.report.parameter",
                                "parameterId column is mandatory in Report Parameter Entry");
                    }

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

                    reportParameterUsageItem = new ReportParameterUsage(report, reportParameter,
                            reportParameterName);
                }

                reportParameterUsages.add(reportParameterUsageItem);
            }
        }
    }

    return reportParameterUsages;
}

From source file:com.gst.infrastructure.hooks.service.HookWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

private Set<HookResource> assembleSetOfEvents(final JsonArray eventsArray) {

    final Set<HookResource> allEvents = new HashSet<>();

    for (int i = 0; i < eventsArray.size(); i++) {

        final JsonObject eventElement = eventsArray.get(i).getAsJsonObject();

        final String entityName = this.fromApiJsonHelper.extractStringNamed(entityNameParamName, eventElement);
        final String actionName = this.fromApiJsonHelper.extractStringNamed(actionNameParamName, eventElement);
        final HookResource event = HookResource.createNewWithoutHook(entityName, actionName);
        allEvents.add(event);//from  w ww . j  a  va 2s .c  om
    }

    return allEvents;
}

From source file:com.gst.organisation.holiday.data.HolidayDataValidator.java

License:Apache License

public void validateForCreate(final String json) {

    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }/*from  w ww  . ja v  a 2 s.c  o m*/

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
            HolidayApiConstants.HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS);
    final JsonElement element = this.fromApiJsonHelper.parse(json);

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

    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource(HolidayApiConstants.HOLIDAY_RESOURCE_NAME);

    final String name = this.fromApiJsonHelper.extractStringNamed(HolidayApiConstants.nameParamName, element);
    baseDataValidator.reset().parameter(HolidayApiConstants.nameParamName).value(name).notNull()
            .notExceedingLengthOf(100);

    final LocalDate fromDate = this.fromApiJsonHelper
            .extractLocalDateNamed(HolidayApiConstants.fromDateParamName, element);
    baseDataValidator.reset().parameter(HolidayApiConstants.fromDateParamName).value(fromDate).notNull();

    final LocalDate toDate = this.fromApiJsonHelper.extractLocalDateNamed(HolidayApiConstants.toDateParamName,
            element);
    baseDataValidator.reset().parameter(HolidayApiConstants.toDateParamName).value(toDate).notNull();

    final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper
            .extractLocalDateNamed(HolidayApiConstants.repaymentsRescheduledToParamName, element);
    baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledToParamName)
            .value(repaymentsRescheduledTo).notNull();

    Set<Long> offices = null;
    final JsonObject topLevelJsonElement = element.getAsJsonObject();

    if (topLevelJsonElement.has(HolidayApiConstants.officesParamName)
            && topLevelJsonElement.get(HolidayApiConstants.officesParamName).isJsonArray()) {

        final JsonArray array = topLevelJsonElement.get(HolidayApiConstants.officesParamName).getAsJsonArray();
        if (array.size() > 0) {
            offices = new HashSet<>(array.size());
            for (int i = 0; i < array.size(); i++) {
                final JsonObject officeElement = array.get(i).getAsJsonObject();
                final Long officeId = this.fromApiJsonHelper
                        .extractLongNamed(HolidayApiConstants.officeIdParamName, officeElement);
                baseDataValidator.reset().parameter(HolidayApiConstants.officesParamName).value(officeId)
                        .notNull();
                offices.add(officeId);
            }
        }
    }
    baseDataValidator.reset().parameter(HolidayApiConstants.officesParamName).value(offices).notNull();
    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:com.gst.organisation.holiday.data.HolidayDataValidator.java

License:Apache License

public void validateForUpdate(final String json) {

    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }// ww  w  . j  a v  a 2s . c o m

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json,
            HolidayApiConstants.HOLIDAY_CREATE_OR_UPDATE_REQUEST_DATA_PARAMETERS);
    final JsonElement element = this.fromApiJsonHelper.parse(json);

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

    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource(HolidayApiConstants.HOLIDAY_RESOURCE_NAME);

    if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.nameParamName, element)) {
        final String name = this.fromApiJsonHelper.extractStringNamed(HolidayApiConstants.nameParamName,
                element);
        baseDataValidator.reset().parameter(HolidayApiConstants.nameParamName).value(name).notNull()
                .notExceedingLengthOf(100);
    }

    if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.fromDateParamName, element)) {
        final LocalDate fromDate = this.fromApiJsonHelper
                .extractLocalDateNamed(HolidayApiConstants.fromDateParamName, element);
        baseDataValidator.reset().parameter(HolidayApiConstants.fromDateParamName).value(fromDate).notNull();
    }

    if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.toDateParamName, element)) {
        final LocalDate toDate = this.fromApiJsonHelper
                .extractLocalDateNamed(HolidayApiConstants.toDateParamName, element);
        baseDataValidator.reset().parameter(HolidayApiConstants.toDateParamName).value(toDate).notNull();
    }

    if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.repaymentsRescheduledToParamName, element)) {
        final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper
                .extractLocalDateNamed(HolidayApiConstants.repaymentsRescheduledToParamName, element);
        baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledToParamName)
                .value(repaymentsRescheduledTo).notNull();
    }

    Set<Long> offices = null;
    final JsonObject topLevelJsonElement = element.getAsJsonObject();
    if (this.fromApiJsonHelper.parameterExists(HolidayApiConstants.officesParamName, element)) {
        if (topLevelJsonElement.has(HolidayApiConstants.officesParamName)
                && topLevelJsonElement.get(HolidayApiConstants.officesParamName).isJsonArray()) {

            final JsonArray array = topLevelJsonElement.get(HolidayApiConstants.officesParamName)
                    .getAsJsonArray();
            if (array.size() > 0) {
                offices = new HashSet<>(array.size());
                for (int i = 0; i < array.size(); i++) {
                    final JsonObject officeElement = array.get(i).getAsJsonObject();
                    final Long officeId = this.fromApiJsonHelper
                            .extractLongNamed(HolidayApiConstants.officeIdParamName, officeElement);
                    baseDataValidator.reset().parameter(HolidayApiConstants.officesParamName).value(officeId)
                            .notNull();
                    offices.add(officeId);
                }
            }
        }
        baseDataValidator.reset().parameter(HolidayApiConstants.officesParamName).value(offices).notNull();
        throwExceptionIfValidationWarningsExist(dataValidationErrors);
    }
}

From source file:com.gst.organisation.holiday.service.HolidayWritePlatformServiceJpaRepositoryImpl.java

License:Apache License

private Set<Office> getSelectedOffices(final JsonCommand command) {
    Set<Office> offices = null;
    final JsonObject topLevelJsonElement = this.fromApiJsonHelper.parse(command.json()).getAsJsonObject();
    if (topLevelJsonElement.has(HolidayApiConstants.officesParamName)
            && topLevelJsonElement.get(HolidayApiConstants.officesParamName).isJsonArray()) {

        final JsonArray array = topLevelJsonElement.get(HolidayApiConstants.officesParamName).getAsJsonArray();
        offices = new HashSet<>(array.size());
        for (int i = 0; i < array.size(); i++) {
            final JsonObject officeElement = array.get(i).getAsJsonObject();
            final Long officeId = this.fromApiJsonHelper.extractLongNamed(HolidayApiConstants.officeIdParamName,
                    officeElement);/* w  w w.  j a v a  2 s . com*/
            final Office office = this.officeRepositoryWrapper.findOneWithNotFoundDetection(officeId);
            offices.add(office);
        }
    }
    return offices;
}

From source file:com.gst.organisation.provisioning.serialization.ProvisioningCriteriaDefinitionJsonDeserializer.java

License:Apache License

public void validateForCreate(final String json) {
    if (StringUtils.isBlank(json)) {
        throw new ProvisioningCriteriaCannotBeCreatedException(
                "error.msg.provisioningcriteria.cannot.be.created",
                "criterianame, loanproducts[], provisioningcriteria[] params are missing in the request");

    }/*from  ww  w  .  j av  a2 s. c  o m*/
    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParametersForCreate);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("provisioningcriteria");
    final JsonElement element = this.fromApiJsonHelper.parse(json);
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject());
    final String name = this.fromApiJsonHelper
            .extractStringNamed(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, element);
    baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM).value(name)
            .notBlank().notExceedingLengthOf(200);

    // if the param present, then we should have the loan product ids. If
    // not we will load all loan products
    if (this.fromApiJsonHelper.parameterExists(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM,
            element)) {
        JsonArray jsonloanProducts = this.fromApiJsonHelper
                .extractJsonArrayNamed(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM, element);
        baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM)
                .value(jsonloanProducts).jsonArrayNotEmpty();
        // check for unsupported params
        int i = 0;
        for (JsonElement obj : jsonloanProducts) {
            this.fromApiJsonHelper.checkForUnsupportedParameters(obj.getAsJsonObject(),
                    loanProductSupportedParams);
            Long productId = this.fromApiJsonHelper.extractLongNamed("id", obj.getAsJsonObject());
            baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LOAN_PRODUCT_ID_PARAM, i + 1)
                    .value(productId).notNull().longGreaterThanZero();
            i++;
        }
    }

    if (this.fromApiJsonHelper
            .parameterExists(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element)) {
        JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper.extractJsonArrayNamed(
                ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element);
        baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM)
                .value(jsonProvisioningCriteria).jsonArrayNotEmpty();
        for (int i = 0; i < jsonProvisioningCriteria.size(); i++) {
            JsonObject jsonObject = jsonProvisioningCriteria.get(i).getAsJsonObject();
            this.fromApiJsonHelper.checkForUnsupportedParameters(jsonObject,
                    provisioningcriteriaSupportedParams);
            final Long categoryId = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, jsonObject);
            baseDataValidator.reset()
                    .parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, i + 1)
                    .value(categoryId).notNull().longGreaterThanZero();

            Long minimumAge = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, jsonObject);
            baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, i + 1)
                    .value(minimumAge).notNull().longZeroOrGreater();

            Long maximumAge = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, jsonObject);
            baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, i + 1)
                    .value(maximumAge).notNull().longGreaterThanNumber(
                            ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, minimumAge, (i + 1));

            BigDecimal provisioningpercentage = this.fromApiJsonHelper.extractBigDecimalNamed(
                    ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, jsonObject, locale);
            baseDataValidator.reset()
                    .parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM,
                            i + 1)
                    .value(provisioningpercentage).notNull().zeroOrPositiveAmount();

            Long liabilityAccountId = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject);
            baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, i + 1)
                    .value(liabilityAccountId).notNull().longGreaterThanZero();

            Long expenseAccountId = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject);
            baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, i + 1)
                    .value(expenseAccountId).notNull().longGreaterThanZero();
        }
    } else {
        baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM)
                .jsonArrayNotEmpty();
    }

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

From source file:com.gst.organisation.provisioning.serialization.ProvisioningCriteriaDefinitionJsonDeserializer.java

License:Apache License

public void validateForUpdate(final String json) {
    if (StringUtils.isBlank(json)) {
        throw new ProvisioningCriteriaCannotBeCreatedException(
                "error.msg.provisioningcriteria.cannot.be.updated", "update params are missing in the request");

    }//from  w w  w. java  2s . c  o m
    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParametersForUpdate);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("provisioningcriteria");
    final JsonElement element = this.fromApiJsonHelper.parse(json);
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(element.getAsJsonObject());

    if (this.fromApiJsonHelper.parameterExists(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM,
            element)) {
        final String name = this.fromApiJsonHelper
                .extractStringNamed(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM, element);
        baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_CRITERIANAME_PARAM).value(name)
                .notBlank().notExceedingLengthOf(200);
    }

    // if the param present, then we should have the loan product ids. If
    // not we will load all loan products
    if (this.fromApiJsonHelper.parameterExists(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM,
            element)) {
        JsonArray jsonloanProducts = this.fromApiJsonHelper
                .extractJsonArrayNamed(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM, element);
        baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM)
                .value(jsonloanProducts).jsonArrayNotEmpty();
        // check for unsupported params
        int i = 0;
        for (JsonElement obj : jsonloanProducts) {
            Long productId = this.fromApiJsonHelper.extractLongNamed("id", obj.getAsJsonObject());
            baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_LOANPRODUCTS_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LOAN_PRODUCT_ID_PARAM, i + 1)
                    .value(productId).notNull().longGreaterThanZero();
            i++;
        }
    }

    if (this.fromApiJsonHelper
            .parameterExists(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element)) {
        JsonArray jsonProvisioningCriteria = this.fromApiJsonHelper.extractJsonArrayNamed(
                ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM, element);
        baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM)
                .value(jsonProvisioningCriteria).jsonArrayNotEmpty();
        for (int i = 0; i < jsonProvisioningCriteria.size(); i++) {
            // check for unsupported params
            JsonObject jsonObject = jsonProvisioningCriteria.get(i).getAsJsonObject();
            final Long categoryId = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, jsonObject);
            baseDataValidator.reset()
                    .parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_CATEOGRYID_PARAM, i + 1)
                    .value(categoryId).notNull().longGreaterThanZero();

            Long minimumAge = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, jsonObject);
            baseDataValidator.reset()
                    .parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, i + 1)
                    .value(minimumAge).notNull().longZeroOrGreater();

            Long maximumAge = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, jsonObject);
            baseDataValidator.reset().parameter(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_MAXIMUM_AGE_PARAM, i + 1)
                    .value(maximumAge).notNull().longGreaterThanNumber(
                            ProvisioningCriteriaConstants.JSON_MINIMUM_AGE_PARAM, minimumAge, (i + 1));

            BigDecimal provisioningpercentage = this.fromApiJsonHelper.extractBigDecimalNamed(
                    ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM, jsonObject, locale);
            baseDataValidator.reset()
                    .parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_PROVISIONING_PERCENTAGE_PARAM,
                            i + 1)
                    .value(provisioningpercentage).notNull().zeroOrPositiveAmount();

            Long liabilityAccountId = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject);
            baseDataValidator.reset()
                    .parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, i + 1)
                    .value(liabilityAccountId).notNull().longGreaterThanZero();

            Long expenseAccountId = this.fromApiJsonHelper
                    .extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject);
            baseDataValidator.reset()
                    .parameter(ProvisioningCriteriaConstants.JSON_PROVISIONING_DEFINITIONS_PARAM)
                    .parameterAtIndexArray(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, i + 1)
                    .value(expenseAccountId).notNull().longGreaterThanZero();
        }
    }

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

}