public void validateForClose(final String json) {
    if (StringUtils.isBlank(json)) {
      throw new InvalidJsonException();
    }

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final Integer status =
        Integer.parseInt(fromApiJsonHelper.extractStringNamed("status", element));
    final String resolutionDescription =
        fromApiJsonHelper.extractStringNamed("resolutionDescription", element);

    baseDataValidator
        .reset()
        .parameter("status")
        .value(status)
        .notBlank()
        .notExceedingLengthOf(100);
    baseDataValidator
        .reset()
        .parameter("resolutionDescription")
        .value(resolutionDescription)
        .notBlank()
        .notExceedingLengthOf(100);

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForCreate(final String json) {

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

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

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

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

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

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

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

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

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

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

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

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

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

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

    if (fromApiJsonHelper.parameterExists("settlementSequenceData", element)) {

      final JsonArray ssDataArray =
          fromApiJsonHelper.extractJsonArrayNamed("settlementSequenceData", element);

      if (ssDataArray == null) {
        /*throw new PlatformDataIntegrityException("Please select channel partners", "Please select channel partners", "");*/
      }
      String[] ssStringArray = new String[ssDataArray.size()];

      for (int i = 0; i < ssDataArray.size(); i++) {
        ssStringArray[i] = ssDataArray.get(i).toString();
      }

      for (String s : ssStringArray) {

        final JsonElement el = fromApiJsonHelper.parse(s);
        final Long partnerType4 = fromApiJsonHelper.extractLongNamed("partnerType4", el);
        baseDataValidator.reset().parameter("partnerType4").value(partnerType4).notNull();

        final Long partnerType5 = fromApiJsonHelper.extractLongNamed("partnerType5", el);
        baseDataValidator.reset().parameter("partnerType5").value(partnerType5).notNull();

        final Long partnerType6 = fromApiJsonHelper.extractLongNamed("partnerType6", el);
        baseDataValidator.reset().parameter("partnerType6").value(partnerType6).notNull();

        /*final String channelPartnerAddress = fromApiJsonHelper.extractStringNamed("channelPartnerAddress", el);
        baseDataValidator.reset().parameter("channelPartnerAddress").value(channelPartnerAddress).notBlank();
        throwExceptionIfValidationWarningsExist(dataValidationErrors);*/
      }
    }
    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  @Override
  public RoleCommand commandFromApiJson(final String json) {

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);
    final String name = fromApiJsonHelper.extractStringNamed("name", element);
    final String description = fromApiJsonHelper.extractStringNamed("description", element);

    return new RoleCommand(name, description);
  }
  public void validateForCreatePartnerRevenue(String json) {

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final Long agreementCategory = fromApiJsonHelper.extractLongNamed("agreementCategory", element);
    baseDataValidator.reset().parameter("agreementCategory").value(agreementCategory).notBlank();

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForCreateCurrency(String json) {

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final Long sourceCurrency = fromApiJsonHelper.extractLongNamed("sourceCurrency", element);
    baseDataValidator.reset().parameter("sourceCurrency").value(sourceCurrency).notBlank();

    final Long targetCurrency = fromApiJsonHelper.extractLongNamed("targetCurrency", element);
    baseDataValidator.reset().parameter("targetCurrency").value(targetCurrency).notBlank();

    final BigDecimal exchangeRate =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("exchangeRate", element);
    baseDataValidator
        .reset()
        .parameter("exchangeRate")
        .value(exchangeRate)
        .notBlank()
        .notExceedingLengthOf(50);

    final LocalDate startDate = fromApiJsonHelper.extractLocalDateNamed("startDate", element);
    baseDataValidator.reset().parameter("startDate").value(startDate).notBlank();

    final LocalDate endDate = fromApiJsonHelper.extractLocalDateNamed("endDate", element);
    baseDataValidator.reset().parameter("endDate").value(endDate).notBlank();

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForCreateRoyalty(String json) {

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

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);
    final Long royaltyType = fromApiJsonHelper.extractLongNamed("royaltyType", element);
    baseDataValidator.reset().parameter("royaltyType").value(royaltyType).notBlank();
    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
 /** Validation for advanced accounting options */
 private void validatePaymentChannelFundSourceMappings(
     final DataValidatorBuilder baseDataValidator, final JsonElement element) {
   if (fromApiJsonHelper.parameterExists(
       SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(),
       element)) {
     JsonArray paymentChannelMappingArray =
         fromApiJsonHelper.extractJsonArrayNamed(
             SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(),
             element);
     if (paymentChannelMappingArray != null && paymentChannelMappingArray.size() > 0) {
       int i = 0;
       do {
         final JsonObject jsonObject = paymentChannelMappingArray.get(i).getAsJsonObject();
         final Long paymentTypeId =
             jsonObject.get(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.getValue()).getAsLong();
         final Long paymentSpecificFundAccountId =
             jsonObject.get(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).getAsLong();
         baseDataValidator
             .reset()
             .parameter(
                 SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue()
                     + "["
                     + i
                     + "]."
                     + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.toString())
             .value(paymentTypeId)
             .notNull()
             .integerGreaterThanZero();
         baseDataValidator
             .reset()
             .parameter(
                 SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue()
                     + "["
                     + i
                     + "]."
                     + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue())
             .value(paymentSpecificFundAccountId)
             .notNull()
             .integerGreaterThanZero();
         i++;
       } while (i < paymentChannelMappingArray.size());
     }
   }
 }
  public static OrderAddons fromJson(
      final JsonElement element,
      final FromJsonHelper fromJsonHelper,
      final Long orderId,
      LocalDate startDate,
      Long contractId) {

    final Long serviceId = fromJsonHelper.extractLongNamed("serviceId", element);
    return new OrderAddons(orderId, serviceId, contractId, startDate.toDate());
  }
  public LoanApplicationTerms assembleLoanTerms(final JsonElement element) {
    final Long loanProductId = fromApiJsonHelper.extractLongNamed("productId", element);

    final LoanProduct loanProduct = this.loanProductRepository.findOne(loanProductId);
    if (loanProduct == null) {
      throw new LoanProductNotFoundException(loanProductId);
    }

    return assembleLoanApplicationTermsFrom(element, loanProduct);
  }
  /** Validation for Create Ticket */
  public void validateForCreate(final String json) {

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

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final String priority = fromApiJsonHelper.extractStringNamed("priority", element);
    final String problemCode = fromApiJsonHelper.extractStringNamed("problemCode", element);
    final String description = fromApiJsonHelper.extractStringNamed("description", element);
    final String assignedTo = fromApiJsonHelper.extractStringNamed("assignedTo", element);

    baseDataValidator
        .reset()
        .parameter("problemCode")
        .value(problemCode)
        .notBlank()
        .notExceedingLengthOf(100);
    baseDataValidator
        .reset()
        .parameter("priority")
        .value(priority)
        .notBlank()
        .notExceedingLengthOf(100);
    baseDataValidator
        .reset()
        .parameter("assignedTo")
        .value(assignedTo)
        .notBlank()
        .notExceedingLengthOf(100);
    baseDataValidator.reset().parameter("description").value(description).notBlank();

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForUpdate(final String json) {
    if (StringUtils.isBlank(json)) {
      throw new InvalidJsonException();
    }

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);
    if (fromApiJsonHelper.parameterExists("name", element)) {
      final String name = fromApiJsonHelper.extractStringNamed("name", element);
      baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForUpdateDeductionCode(String json) {
    final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
    fromApiJsonHelper.checkForUnsupportedParameters(
        typeOfMap, json, supportedParametersForUpdateDeductionCode);

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final String deductionCode = fromApiJsonHelper.extractStringNamed("deductionCode", element);
    baseDataValidator.reset().parameter("deductionCode").value(deductionCode).notBlank();

    final BigDecimal deductionValue =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("deductionValue", element);
    baseDataValidator.reset().parameter("deductionValue").value(deductionValue).notBlank();

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForCreate(String json) {

    if (StringUtils.isBlank(json)) {
      throw new InvalidJsonException();
    }
    final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
    fromJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParams);

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

    final JsonElement element = fromJsonHelper.parse(json);

    final String supplierCode = fromJsonHelper.extractStringNamed("supplierCode", element);
    final String supplierDescription =
        fromJsonHelper.extractStringNamed("supplierDescription", element);
    final String supplierAddress = fromJsonHelper.extractStringNamed("supplierAddress", element);

    baseValidatorBuilder
        .reset()
        .parameter("supplierCode")
        .value(supplierCode)
        .notBlank()
        .notExceedingLengthOf(10);
    baseValidatorBuilder
        .reset()
        .parameter("supplierDescription")
        .value(supplierDescription)
        .notBlank()
        .notExceedingLengthOf(100);
    baseValidatorBuilder
        .reset()
        .parameter("supplierAddress")
        .value(supplierAddress)
        .notBlank()
        .notExceedingLengthOf(100);

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForPrice(final JsonElement jsonElement) {
    if (StringUtils.isBlank(jsonElement.toString())) {
      throw new InvalidJsonException();
    }

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {}.getType();
    fromApiJsonHelper.checkForUnsupportedParameters(
        typeOfMap, jsonElement.toString(), supportedParameters);
    // final JsonElement element = fromApiJsonHelper.parse(jsonElement);
    final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
    final DataValidatorBuilder baseDataValidator =
        new DataValidatorBuilder(dataValidationErrors).resource("onetimesale");
    final Integer totalPrice =
        fromApiJsonHelper.extractIntegerWithLocaleNamed("quantity", jsonElement);
    baseDataValidator
        .reset()
        .parameter("quantity")
        .value(totalPrice)
        .notNull()
        .integerGreaterThanZero();

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public LoanScheduleModel assembleLoanScheduleFrom(final JsonElement element) {
    // This method is getting called from calculate loan schedule.
    final LoanApplicationTerms loanApplicationTerms = assembleLoanTerms(element);
    // Get holiday details
    final boolean isHolidayEnabled =
        this.configurationDomainService.isRescheduleRepaymentsOnHolidaysEnabled();

    final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element);
    final Long groupId = fromApiJsonHelper.extractLongNamed("groupId", element);

    Client client = null;
    Group group = null;
    Long officeId = null;
    if (clientId != null) {
      client = this.clientRepository.findOneWithNotFoundDetection(clientId);
      officeId = client.getOffice().getId();
    } else if (groupId != null) {
      group = this.groupRepository.findOneWithNotFoundDetection(groupId);
      officeId = group.getOffice().getId();
    }

    final LocalDate expectedDisbursementDate =
        this.fromApiJsonHelper.extractLocalDateNamed("expectedDisbursementDate", element);
    final List<Holiday> holidays =
        this.holidayRepository.findByOfficeIdAndGreaterThanDate(
            officeId, expectedDisbursementDate.toDate());
    final WorkingDays workingDays = this.workingDaysRepository.findOne();

    validateDisbursementDateIsOnNonWorkingDay(
        loanApplicationTerms.getExpectedDisbursementDate(), workingDays);
    validateDisbursementDateIsOnHoliday(
        loanApplicationTerms.getExpectedDisbursementDate(), isHolidayEnabled, holidays);

    return assembleLoanScheduleFrom(
        loanApplicationTerms, isHolidayEnabled, holidays, workingDays, element);
  }
  public void validateForCreate(final String json) {
    if (StringUtils.isBlank(json)) {
      throw new InvalidJsonException();
    }

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final LocalDate saleDate = fromApiJsonHelper.extractLocalDateNamed("saleDate", element);
    baseDataValidator.reset().parameter("saleDate").value(saleDate).notBlank();
    final Long itemId = fromApiJsonHelper.extractLongNamed("itemId", element);
    baseDataValidator.reset().parameter("itemId").value(itemId).notNull();
    final String quantity = fromApiJsonHelper.extractStringNamed("quantity", element);
    baseDataValidator
        .reset()
        .parameter("quantity")
        .value(quantity)
        .notBlank()
        .integerGreaterThanZero()
        .notExceedingLengthOf(50);
    final Long discountId = fromApiJsonHelper.extractLongNamed("discountId", element);
    baseDataValidator.reset().parameter("discountId").value(discountId).notNull();
    final String chargeCode = fromApiJsonHelper.extractStringNamed("chargeCode", element);
    baseDataValidator.reset().parameter("chargeCode").value(chargeCode).notBlank();
    final BigDecimal totalPrice =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("totalPrice", element);
    baseDataValidator.reset().parameter("totalPrice").value(totalPrice).notNull();
    final BigDecimal unitPrice =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("unitPrice", element);
    baseDataValidator.reset().parameter("unitPrice").value(unitPrice).notNull();

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForCreateDeduction(String json) {

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

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

    final List<ApiParameterError> dataValidatorErrors = new ArrayList<ApiParameterError>();
    final DataValidatorBuilder baseDataValidator =
        new DataValidatorBuilder(dataValidatorErrors).resource("operator.deduction");

    final JsonElement element = fromApiJsonHelper.parse(json);

    final JsonArray deductionData =
        fromApiJsonHelper.extractJsonArrayNamed("deductionData", element);

    String[] chStringArray = new String[deductionData.size()];
    int chStringArraySize = deductionData.size();
    /*baseDataValidator.reset().parameter(null).value(chStringArraySize).integerGreaterThanZero();*/

    for (int i = 0; i < chStringArraySize; i++) {
      chStringArray[i] = deductionData.get(i).toString();
    }

    final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element);
    baseDataValidator.reset().parameter("clientId").value(clientId).notBlank();
    throwExceptionIfValidationWarningsExist(dataValidatorErrors);

    for (String s : chStringArray) {

      final JsonElement el = fromApiJsonHelper.parse(s);

      final String deductionCode = fromApiJsonHelper.extractStringNamed("deductionCode", el);
      baseDataValidator.reset().parameter("deductionCode").value(deductionCode).notBlank();

      final BigDecimal deductionValue =
          fromApiJsonHelper.extractBigDecimalWithLocaleNamed("deductionValue", el);
      baseDataValidator
          .reset()
          .parameter("deductionValue")
          .value(deductionValue)
          .notBlank()
          .inMinAndMaxAmountRange(BigDecimal.ZERO, BigDecimal.valueOf(100));

      throwExceptionIfValidationWarningsExist(dataValidatorErrors);
    }
  }
  public void validateForCreate(final String json) {
    if (StringUtils.isBlank(json)) {
      throw new InvalidJsonException();
    }

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

    final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
    final DataValidatorBuilder baseDataValidator =
        new DataValidatorBuilder(dataValidationErrors).resource("addons");
    final JsonElement element = fromApiJsonHelper.parse(json);
    final Long contractId = fromApiJsonHelper.extractLongNamed("contractId", element);
    baseDataValidator.reset().parameter("contractId").value(contractId).notNull();
    final LocalDate startDate = fromApiJsonHelper.extractLocalDateNamed("startDate", element);
    baseDataValidator.reset().parameter("startDate").value(startDate).notBlank();
    final JsonArray addonServicesArray =
        fromApiJsonHelper.extractJsonArrayNamed("addonServices", element);
    String[] serviceParameters = null;
    serviceParameters = new String[addonServicesArray.size()];
    int arraysize = addonServicesArray.size();
    baseDataValidator.reset().parameter(null).value(arraysize).integerGreaterThanZero();
    for (int i = 0; i < addonServicesArray.size(); i++) {
      serviceParameters[i] = addonServicesArray.get(i).toString();
    }

    for (String serviceParameter : serviceParameters) {

      final JsonElement attributeElement = fromApiJsonHelper.parse(serviceParameter);
      final Long serviceId = fromApiJsonHelper.extractLongNamed("serviceId", attributeElement);
      baseDataValidator.reset().parameter("serviceId").value(serviceId).notNull();
      final BigDecimal price =
          fromApiJsonHelper.extractBigDecimalWithLocaleNamed("price", attributeElement);
      baseDataValidator.reset().parameter("price").value(price).notNull();
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForCreate(final String json) {
    if (StringUtils.isBlank(json)) {
      throw new InvalidJsonException();
    }

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final String agentId = fromApiJsonHelper.extractStringNamed("agentId", element);
    baseDataValidator.reset().parameter("agentId").value(agentId).notNull();
    final String itemId = fromApiJsonHelper.extractStringNamed("itemId", element);
    baseDataValidator.reset().parameter("itemId").value(itemId).notNull();
    final LocalDate purchaseDate = fromApiJsonHelper.extractLocalDateNamed("purchaseDate", element);
    baseDataValidator.reset().parameter("purchaseDate").value(purchaseDate).notBlank();

    final Long orderQuantity = fromApiJsonHelper.extractLongNamed("orderQuantity", element);
    baseDataValidator
        .reset()
        .parameter("orderQuantity")
        .value(orderQuantity)
        .notNull()
        .integerGreaterThanZero();
    final BigDecimal chargeAmount =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("chargeAmount", element);
    baseDataValidator.reset().parameter("chargeAmount").value(chargeAmount).notNull();
    final BigDecimal taxAmount =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("taxAmount", element);
    baseDataValidator.reset().parameter("taxAmount").value(chargeAmount).notNull();

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  @Transactional
  @Override
  public CommandProcessingResult activationProcess(final JsonCommand command) {

    try {
      context.authenticatedUser();
      CommandProcessingResult resultClient = null;
      CommandProcessingResult resultSale = null;
      ///  CommandProcessingResult resultAllocate=null;
      CommandProcessingResult resultOrder = null;
      final JsonElement element = fromJsonHelper.parse(command.json());
      JsonArray clientData = fromJsonHelper.extractJsonArrayNamed("client", element);
      JsonArray saleData = fromJsonHelper.extractJsonArrayNamed("sale", element);
      JsonArray owndevices = fromJsonHelper.extractJsonArrayNamed("owndevice", element);
      // JsonArray allocateData = fromJsonHelper.extractJsonArrayNamed("allocate", element);
      JsonArray bookOrder = fromJsonHelper.extractJsonArrayNamed("bookorder", element);

      for (JsonElement j : clientData) {

        JsonCommand comm =
            new JsonCommand(
                null,
                j.toString(),
                j,
                fromJsonHelper,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);
        resultClient = this.clientWritePlatformService.createClient(comm);
      }

      //  Configuration
      // configuration=configurationRepository.findOneByName(ConfigurationConstants.CONFIG_PROPERTY_DEVICE_AGREMENT_TYPE);
      // if(configuration.getValue().equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_SALE)){
      if (saleData.size() != 0) {
        for (JsonElement sale : saleData) {
          JsonCommand comm =
              new JsonCommand(
                  null,
                  sale.toString(),
                  sale,
                  fromJsonHelper,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null);
          resultSale =
              this.oneTimeSaleWritePlatformService.createOneTimeSale(
                  comm, resultClient.getClientId());
        }
      } // else
      // if(configuration.getValue().equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_OWN)){
      else if (owndevices.size() != 0) {
        for (JsonElement ownDevice : owndevices) {

          JsonCommand comm =
              new JsonCommand(
                  null,
                  ownDevice.toString(),
                  ownDevice,
                  fromJsonHelper,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null,
                  null);
          resultSale =
              this.ownedHardwareWritePlatformService.createOwnedHardware(
                  comm, resultClient.getClientId());
        }
      }

      for (JsonElement order : bookOrder) {

        JsonCommand comm =
            new JsonCommand(
                null,
                order.toString(),
                order,
                fromJsonHelper,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);
        resultOrder = this.orderWritePlatformService.createOrder(resultClient.getClientId(), comm);
      }
      return resultClient;

    } catch (DataIntegrityViolationException dve) {

      handleDataIntegrityIssues(command, dve);
      return new CommandProcessingResult(Long.valueOf(-1));
    }
  }
  private LoanApplicationTerms assembleLoanApplicationTermsFrom(
      final JsonElement element, final LoanProduct loanProduct) {

    final MonetaryCurrency currency = loanProduct.getCurrency();
    final ApplicationCurrency applicationCurrency =
        this.applicationCurrencyRepository.findOneWithNotFoundDetection(currency);

    // loan terms
    final Integer loanTermFrequency =
        fromApiJsonHelper.extractIntegerWithLocaleNamed("loanTermFrequency", element);
    final Integer loanTermFrequencyType =
        fromApiJsonHelper.extractIntegerWithLocaleNamed("loanTermFrequencyType", element);
    final PeriodFrequencyType loanTermPeriodFrequencyType =
        PeriodFrequencyType.fromInt(loanTermFrequencyType);

    final Integer numberOfRepayments =
        fromApiJsonHelper.extractIntegerWithLocaleNamed("numberOfRepayments", element);
    final Integer repaymentEvery =
        fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element);
    final Integer repaymentFrequencyType =
        fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentFrequencyType", element);
    final PeriodFrequencyType repaymentPeriodFrequencyType =
        PeriodFrequencyType.fromInt(repaymentFrequencyType);

    final Integer amortizationType =
        fromApiJsonHelper.extractIntegerWithLocaleNamed("amortizationType", element);
    final AmortizationMethod amortizationMethod = AmortizationMethod.fromInt(amortizationType);

    // interest terms
    final Integer interestType =
        fromApiJsonHelper.extractIntegerWithLocaleNamed("interestType", element);
    final InterestMethod interestMethod = InterestMethod.fromInt(interestType);

    final Integer interestCalculationPeriodType =
        fromApiJsonHelper.extractIntegerWithLocaleNamed("interestCalculationPeriodType", element);
    final InterestCalculationPeriodMethod interestCalculationPeriodMethod =
        InterestCalculationPeriodMethod.fromInt(interestCalculationPeriodType);

    final BigDecimal interestRatePerPeriod =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element);
    final PeriodFrequencyType interestRatePeriodFrequencyType =
        loanProduct.getInterestPeriodFrequencyType();

    final BigDecimal annualNominalInterestRate =
        this.aprCalculator.calculateFrom(interestRatePeriodFrequencyType, interestRatePerPeriod);

    // disbursement details
    final BigDecimal principal =
        this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element);
    final Money principalMoney = Money.of(currency, principal);

    final LocalDate expectedDisbursementDate =
        this.fromApiJsonHelper.extractLocalDateNamed("expectedDisbursementDate", element);
    final LocalDate repaymentsStartingFromDate =
        this.fromApiJsonHelper.extractLocalDateNamed("repaymentsStartingFromDate", element);
    LocalDate calculatedRepaymentsStartingFromDate = repaymentsStartingFromDate;
    final Boolean synchDisbursement =
        fromApiJsonHelper.extractBooleanNamed("syncDisbursementWithMeeting", element);
    final Long calendarId = this.fromApiJsonHelper.extractLongNamed("calendarId", element);
    Calendar calendar = null;
    if ((synchDisbursement != null && synchDisbursement.booleanValue())
        || (calendarId != null && calendarId != 0)) {
      calendar = this.calendarRepository.findOne(calendarId);
      if (calendar == null) {
        throw new CalendarNotFoundException(calendarId);
      }

      // validate repayment frequency and interval with meeting frequency and interval
      PeriodFrequencyType meetingPeriodFrequency =
          CalendarHelper.getMeetingPeriodFrequencyType(calendar.getRecurrence());
      validateRepaymentFrequencyIsSameAsMeetingFrequency(
          meetingPeriodFrequency.getValue(),
          repaymentFrequencyType,
          CalendarHelper.getInterval(calendar.getRecurrence()),
          repaymentEvery);
    }

    if (synchDisbursement != null && synchDisbursement.booleanValue()) {
      validateDisbursementDateWithMeetingDates(expectedDisbursementDate, calendar);
    }

    // if calendar is attached (not null) then reschedule repayment dates according to meeting
    if (null != calendar) {
      // TODO : AA - Is it require to reset repaymentsStartingFromDate or
      // set only if it is not provided (or null)
      // Currently provided repaymentsStartingFromDate takes precedence over system generated next
      // meeting date
      if (calculatedRepaymentsStartingFromDate == null) {
        // FIXME: AA - Possibility of having next meeting date immediately after disbursement date,
        // need to have minimum number of days gap between disbursement and first repayment date.
        final String frequency =
            CalendarHelper.getMeetingFrequencyFromPeriodFrequencyType(repaymentPeriodFrequencyType);
        calculatedRepaymentsStartingFromDate =
            CalendarHelper.getFirstRepaymentMeetingDate(
                calendar, expectedDisbursementDate, repaymentEvery, frequency);
      } else { // validate user provided repaymentsStartFromDate
        validateRepaymentsStartDateWithMeetingDates(repaymentsStartingFromDate, calendar);
      }
    }
    // grace details
    final Integer graceOnPrincipalPayment =
        this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element);
    final Integer graceOnInterestPayment =
        this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element);
    final Integer graceOnInterestCharged =
        this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element);
    final LocalDate interestChargedFromDate =
        fromApiJsonHelper.extractLocalDateNamed("interestChargedFromDate", element);

    // other
    final BigDecimal inArrearsTolerance =
        this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element);
    final Money inArrearsToleranceMoney = Money.of(currency, inArrearsTolerance);

    return LoanApplicationTerms.assembleFrom(
        applicationCurrency,
        loanTermFrequency,
        loanTermPeriodFrequencyType,
        numberOfRepayments,
        repaymentEvery,
        repaymentPeriodFrequencyType,
        amortizationMethod,
        interestMethod,
        interestRatePerPeriod,
        interestRatePeriodFrequencyType,
        annualNominalInterestRate,
        interestCalculationPeriodMethod,
        principalMoney,
        expectedDisbursementDate,
        repaymentsStartingFromDate,
        calculatedRepaymentsStartingFromDate,
        graceOnPrincipalPayment,
        graceOnInterestPayment,
        graceOnInterestCharged,
        interestChargedFromDate,
        inArrearsToleranceMoney);
  }
  public void validateForCreate(final String json) {

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

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

    final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
    final DataValidatorBuilder baseDataValidator =
        new DataValidatorBuilder(dataValidationErrors).resource(SAVINGS_PRODUCT_RESOURCE_NAME);
    final JsonElement element = fromApiJsonHelper.parse(json);

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

    final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element);
    baseDataValidator
        .reset()
        .parameter(descriptionParamName)
        .value(description)
        .notBlank()
        .notExceedingLengthOf(500);

    final String currencyCode =
        fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element);
    baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank();

    final Integer digitsAfterDecimal =
        fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element);
    baseDataValidator
        .reset()
        .parameter(digitsAfterDecimalParamName)
        .value(digitsAfterDecimal)
        .notNull()
        .inMinMaxRange(0, 6);

    final Integer inMultiplesOf =
        fromApiJsonHelper.extractIntegerSansLocaleNamed(inMultiplesOfParamName, element);
    baseDataValidator
        .reset()
        .parameter(inMultiplesOfParamName)
        .value(inMultiplesOf)
        .ignoreIfNull()
        .integerZeroOrGreater();

    final BigDecimal nominalAnnualInterestRate =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed(
            nominalAnnualInterestRateParamName, element);
    baseDataValidator
        .reset()
        .parameter(nominalAnnualInterestRateParamName)
        .value(nominalAnnualInterestRate)
        .notNull()
        .zeroOrPositiveAmount();

    final Integer interestCompoundingPeriodType =
        fromApiJsonHelper.extractIntegerSansLocaleNamed(
            interestCompoundingPeriodTypeParamName, element);
    baseDataValidator
        .reset()
        .parameter(interestCompoundingPeriodTypeParamName)
        .value(interestCompoundingPeriodType)
        .notNull()
        .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues());

    final Integer interestPostingPeriodType =
        fromApiJsonHelper.extractIntegerSansLocaleNamed(
            interestPostingPeriodTypeParamName, element);
    baseDataValidator
        .reset()
        .parameter(interestPostingPeriodTypeParamName)
        .value(interestPostingPeriodType)
        .notNull()
        .isOneOfTheseValues(SavingsPostingInterestPeriodType.integerValues());

    final Integer interestCalculationType =
        fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element);
    baseDataValidator
        .reset()
        .parameter(interestCalculationTypeParamName)
        .value(interestCalculationType)
        .notNull()
        .isOneOfTheseValues(SavingsInterestCalculationType.integerValues());

    final Integer interestCalculationDaysInYearType =
        fromApiJsonHelper.extractIntegerSansLocaleNamed(
            interestCalculationDaysInYearTypeParamName, element);
    baseDataValidator
        .reset()
        .parameter(interestCalculationDaysInYearTypeParamName)
        .value(interestCalculationDaysInYearType)
        .notNull()
        .isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues());

    if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) {
      final BigDecimal minOpeningBalance =
          fromApiJsonHelper.extractBigDecimalWithLocaleNamed(
              minRequiredOpeningBalanceParamName, element);
      baseDataValidator
          .reset()
          .parameter(minRequiredOpeningBalanceParamName)
          .value(minOpeningBalance)
          .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) {

      final Integer lockinPeriodFrequency =
          fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element);
      baseDataValidator
          .reset()
          .parameter(lockinPeriodFrequencyParamName)
          .value(lockinPeriodFrequency)
          .integerZeroOrGreater();

      if (lockinPeriodFrequency != null) {
        final Integer lockinPeriodFrequencyType =
            fromApiJsonHelper.extractIntegerSansLocaleNamed(
                lockinPeriodFrequencyTypeParamName, element);
        baseDataValidator
            .reset()
            .parameter(lockinPeriodFrequencyTypeParamName)
            .value(lockinPeriodFrequencyType)
            .notNull()
            .inMinMaxRange(0, 3);
      }
    }

    if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) {
      final Integer lockinPeriodFrequencyType =
          fromApiJsonHelper.extractIntegerSansLocaleNamed(
              lockinPeriodFrequencyTypeParamName, element);
      baseDataValidator
          .reset()
          .parameter(lockinPeriodFrequencyTypeParamName)
          .value(lockinPeriodFrequencyType)
          .inMinMaxRange(0, 3);

      if (lockinPeriodFrequencyType != null) {
        final Integer lockinPeriodFrequency =
            fromApiJsonHelper.extractIntegerWithLocaleNamed(
                lockinPeriodFrequencyParamName, element);
        baseDataValidator
            .reset()
            .parameter(lockinPeriodFrequencyParamName)
            .value(lockinPeriodFrequency)
            .notNull()
            .integerZeroOrGreater();
      }
    }

    if (this.fromApiJsonHelper.parameterExists(withdrawalFeeAmountParamName, element)) {

      final BigDecimal withdrawalFeeAmount =
          fromApiJsonHelper.extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, element);
      baseDataValidator
          .reset()
          .parameter(withdrawalFeeAmountParamName)
          .value(withdrawalFeeAmount)
          .zeroOrPositiveAmount();

      if (withdrawalFeeAmount != null) {
        final Integer withdrawalFeeType =
            fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element);
        baseDataValidator
            .reset()
            .parameter(withdrawalFeeTypeParamName)
            .value(withdrawalFeeType)
            .isOneOfTheseValues(SavingsWithdrawalFeesType.integerValues());
      }
    }

    if (this.fromApiJsonHelper.parameterExists(withdrawalFeeTypeParamName, element)) {
      final Integer withdrawalFeeType =
          fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element);
      baseDataValidator
          .reset()
          .parameter(withdrawalFeeTypeParamName)
          .value(withdrawalFeeType)
          .ignoreIfNull()
          .isOneOfTheseValues(1, 2);

      if (withdrawalFeeType != null) {
        final BigDecimal withdrawalFeeAmount =
            fromApiJsonHelper.extractBigDecimalWithLocaleNamed(
                withdrawalFeeAmountParamName, element);
        baseDataValidator
            .reset()
            .parameter(withdrawalFeeAmountParamName)
            .value(withdrawalFeeAmount)
            .notNull()
            .zeroOrPositiveAmount();
      }
    }

    if (this.fromApiJsonHelper.parameterExists(annualFeeAmountParamName, element)) {
      final BigDecimal annualFeeAmount =
          fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element);
      baseDataValidator
          .reset()
          .parameter(annualFeeAmountParamName)
          .value(annualFeeAmount)
          .zeroOrPositiveAmount();

      if (annualFeeAmount != null) {
        MonthDay monthDayOfAnnualFee =
            fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element);
        baseDataValidator
            .reset()
            .parameter(annualFeeOnMonthDayParamName)
            .value(monthDayOfAnnualFee)
            .notNull();
      }
    }

    if (this.fromApiJsonHelper.parameterExists(annualFeeOnMonthDayParamName, element)) {

      MonthDay monthDayOfAnnualFee =
          fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element);
      if (monthDayOfAnnualFee != null) {
        final BigDecimal annualFeeAmount =
            fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element);
        baseDataValidator
            .reset()
            .parameter(annualFeeAmountParamName)
            .value(annualFeeAmount)
            .notNull()
            .zeroOrPositiveAmount();
      }
    }

    // accounting related data validation
    final Integer accountingRuleType =
        fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault());
    baseDataValidator
        .reset()
        .parameter("accountingRule")
        .value(accountingRuleType)
        .notNull()
        .inMinMaxRange(1, 3);

    if (isCashBasedAccounting(accountingRuleType)) {

      final Long savingsControlAccountId =
          fromApiJsonHelper.extractLongNamed(
              SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element);
      baseDataValidator
          .reset()
          .parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue())
          .value(savingsControlAccountId)
          .notNull()
          .integerGreaterThanZero();

      final Long savingsReferenceAccountId =
          fromApiJsonHelper.extractLongNamed(
              SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element);
      baseDataValidator
          .reset()
          .parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue())
          .value(savingsReferenceAccountId)
          .notNull()
          .integerGreaterThanZero();

      final Long interestOnSavingsAccountId =
          fromApiJsonHelper.extractLongNamed(
              SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element);
      baseDataValidator
          .reset()
          .parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue())
          .value(interestOnSavingsAccountId)
          .notNull()
          .integerGreaterThanZero();

      final Long incomeFromFeeId =
          fromApiJsonHelper.extractLongNamed(
              SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element);
      baseDataValidator
          .reset()
          .parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue())
          .value(incomeFromFeeId)
          .notNull()
          .integerGreaterThanZero();

      validatePaymentChannelFundSourceMappings(baseDataValidator, element);
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForCreateGameEvent(String json) {

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

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final BigDecimal clientId =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("clientId", element);
    baseDataValidator
        .reset()
        .parameter("clientId")
        .value(clientId)
        .notBlank()
        .notExceedingLengthOf(50);

    /*final BigDecimal circle = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("circle", element);
    baseDataValidator.reset().parameter("circle").value(circle).notBlank().notExceedingLengthOf(50);*/

    final BigDecimal externalId =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("externalId", element);
    baseDataValidator
        .reset()
        .parameter("externalId")
        .value(externalId)
        .notBlank()
        .notExceedingLengthOf(50);

    /*final BigDecimal activityMonth = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("activityMonth",element);
    baseDataValidator.reset().parameter("activityMonth").value(activityMonth).notBlank().notExceedingLengthOf(50);*/

    final String activityMonth = fromApiJsonHelper.extractStringNamed("activityMonth", element);
    baseDataValidator.reset().parameter("activityMonth").value(activityMonth).notBlank();

    final BigDecimal businessLine =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("businessLine", element);
    baseDataValidator
        .reset()
        .parameter("businessLine")
        .value(businessLine)
        .notBlank()
        .notExceedingLengthOf(50);

    final BigDecimal mediaCategory =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("mediaCategory", element);
    baseDataValidator
        .reset()
        .parameter("mediaCategory")
        .value(mediaCategory)
        .notBlank()
        .notExceedingLengthOf(50);

    /*final BigDecimal chargeCode = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("chargeCode", element);
    baseDataValidator.reset().parameter("chargeCode").value(chargeCode).notBlank().notExceedingLengthOf(50);*/

    /*final LocalDate dataUploadedDate = fromApiJsonHelper.extractLocalDateNamed("dataUploadedDate", element);
    baseDataValidator.reset().parameter("dataUploadedDate").value(dataUploadedDate).notBlank();*/

    final JsonArray interactiveDataArray =
        fromApiJsonHelper.extractJsonArrayNamed("activeData", element);
    String[] interactiveDataArrayAttributes = null;
    interactiveDataArrayAttributes = new String[interactiveDataArray.size()];
    int interactiveDataSize = interactiveDataArray.size();
    baseDataValidator
        .reset()
        .parameter("interactiveDataArray")
        .value(interactiveDataSize)
        .integerGreaterThanZero();

    for (int i = 0; i < interactiveDataArray.size(); i++) {
      interactiveDataArrayAttributes[i] = interactiveDataArray.get(i).toString();
    }

    for (String singleinteractiveData : interactiveDataArrayAttributes) {

      final JsonElement elements = fromApiJsonHelper.parse(singleinteractiveData);

      final Long playSource = fromApiJsonHelper.extractLongNamed("playSource", elements);
      baseDataValidator.reset().parameter("playSource").value(playSource).notBlank();

      final String contentName = fromApiJsonHelper.extractStringNamed("contentName", elements);
      baseDataValidator.reset().parameter("contentName").value(contentName).notBlank();

      final Long contentProvider = fromApiJsonHelper.extractLongNamed("contentProvider", elements);
      baseDataValidator.reset().parameter("contentProvider").value(contentProvider).notBlank();

      final Long channelName = fromApiJsonHelper.extractLongNamed("channelName", elements);
      baseDataValidator.reset().parameter("channelName").value(channelName).notBlank();

      final Long serviceName = fromApiJsonHelper.extractLongNamed("serviceName", elements);
      baseDataValidator.reset().parameter("serviceName").value(serviceName).notBlank();

      final BigDecimal endUserPrice =
          fromApiJsonHelper.extractBigDecimalWithLocaleNamed("endUserPrice", elements);
      baseDataValidator.reset().parameter("endUserPrice").value(endUserPrice).notBlank();

      final BigDecimal grossRevenue =
          fromApiJsonHelper.extractBigDecimalWithLocaleNamed("grossRevenue", elements);
      baseDataValidator.reset().parameter("grossRevenue").value(grossRevenue).notBlank();

      final Integer downloads =
          fromApiJsonHelper.extractIntegerWithLocaleNamed("downloads", elements);
      baseDataValidator
          .reset()
          .parameter("downloads")
          .value(downloads)
          .notBlank()
          .integerGreaterThanZero();

      // final Long sequence = fromApiJsonHelper.extractLongNamed("sequence", elements);
      // baseDataValidator.reset().parameter("sequence").value(sequence).notBlank();

      throwExceptionIfValidationWarningsExist(dataValidationErrors);
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  public void validateForCreate(String json) {

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

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    // final LocalDate paymentDate = fromApiJsonHelper.extractLocalDateNamed("paymentDate",
    // element);
    final String paymentCode = fromApiJsonHelper.extractStringNamed("paymentCode", element);
    final BigDecimal amountPaid =
        fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amountPaid", element);
    // final String remarks = fromApiJsonHelper.extractStringNamed("remarks", element);

    /*String receiptNo = fromApiJsonHelper.extractStringNamed("receiptNo", element);
    baseDataValidator.reset().parameter("receiptNo").value(receiptNo).notBlank().notExceedingLengthOf(20);*/
    //	baseDataValidator.reset().parameter("paymentDate").value(paymentDate)
    // .notBlank().notExceedingLengthOf(100);
    baseDataValidator
        .reset()
        .parameter("paymentCode")
        .value(paymentCode)
        .notBlank()
        .notExceedingLengthOf(100);
    baseDataValidator
        .reset()
        .parameter("amountPaid")
        .value(amountPaid)
        .notBlank()
        .notExceedingLengthOf(100);
    // baseDataValidator.reset().parameter("remarks").value(remarks)
    // .notBlank().notExceedingLengthOf(100);
    if (fromApiJsonHelper.parameterExists("isChequeSelected", element)) {
      String isChequeSelected = fromApiJsonHelper.extractStringNamed("isChequeSelected", element);
      if (isChequeSelected.equalsIgnoreCase("yes")) {
        if (fromApiJsonHelper.parameterExists("chequeNo", element)) {
          String chequeNo = fromApiJsonHelper.extractStringNamed("chequeNo", element);
          baseDataValidator
              .reset()
              .parameter("chequeNo")
              .value(chequeNo)
              .notBlank()
              .notExceedingLengthOf(20);
        }
        if (fromApiJsonHelper.parameterExists("chequeDate", element)) {
          LocalDate chequeDate = fromApiJsonHelper.extractLocalDateNamed("chequeDate", element);
          baseDataValidator.reset().parameter("chequeDate").value(chequeDate).notBlank();
        }
        if (fromApiJsonHelper.parameterExists("bankName", element)) {
          String bankName = fromApiJsonHelper.extractStringNamed("bankName", element);
          baseDataValidator
              .reset()
              .parameter("bankName")
              .value(bankName)
              .notBlank()
              .notExceedingLengthOf(100);
        }
        if (fromApiJsonHelper.parameterExists("branchName", element)) {
          String branchName = fromApiJsonHelper.extractStringNamed("branchName", element);
          baseDataValidator
              .reset()
              .parameter("branchName")
              .value(branchName)
              .notBlank()
              .notExceedingLengthOf(100);
        }
      }
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
  }
  @Override
  public CommandProcessingResult createMediaAsset(JsonCommand command) {

    try {

      this.context.authenticatedUser();
      this.fromApiJsonDeserializer.validateForCreate(command.json());
      MediaAsset mediaAsset = MediaAsset.fromJson(command);
      final JsonArray mediaassetAttributesArray =
          command.arrayOfParameterNamed("mediaassetAttributes").getAsJsonArray();
      String[] mediaassetAttributes = null;
      mediaassetAttributes = new String[mediaassetAttributesArray.size()];
      for (int i = 0; i < mediaassetAttributesArray.size(); i++) {
        mediaassetAttributes[i] = mediaassetAttributesArray.get(i).toString();
        // JsonObject temp = mediaassetAttributesArray.getAsJsonObject();

      }
      // For Media Attributes
      for (String mediaassetAttribute : mediaassetAttributes) {

        final JsonElement element = fromApiJsonHelper.parse(mediaassetAttribute);
        final String mediaAttributeType =
            fromApiJsonHelper.extractStringNamed("attributeType", element);
        final String mediaattributeName =
            fromApiJsonHelper.extractStringNamed("attributeName", element);
        final String mediaattributeValue =
            fromApiJsonHelper.extractStringNamed("attributevalue", element);
        final String mediaattributeNickname =
            fromApiJsonHelper.extractStringNamed("attributeNickname", element);
        final String mediaattributeImage =
            fromApiJsonHelper.extractStringNamed("attributeImage", element);
        MediaassetAttributes attributes =
            new MediaassetAttributes(
                mediaAttributeType,
                mediaattributeName,
                mediaattributeValue,
                mediaattributeNickname,
                mediaattributeImage);
        mediaAsset.add(attributes);
      }

      final JsonArray mediaassetLocationsArray =
          command.arrayOfParameterNamed("mediaAssetLocations").getAsJsonArray();
      String[] mediaassetLocations = null;
      mediaassetLocations = new String[mediaassetLocationsArray.size()];
      for (int i = 0; i < mediaassetLocationsArray.size(); i++) {

        mediaassetLocations[i] = mediaassetLocationsArray.get(i).toString();
      }
      // For Media Attributes
      for (String mediaassetLocationData : mediaassetLocations) {

        final JsonElement element = fromApiJsonHelper.parse(mediaassetLocationData);
        final Long languageId = fromApiJsonHelper.extractLongNamed("languageId", element);
        final String formatType = fromApiJsonHelper.extractStringNamed("formatType", element);
        final String location = fromApiJsonHelper.extractStringNamed("location", element);
        MediaassetLocation mediaassetLocation =
            new MediaassetLocation(languageId, formatType, location);
        mediaAsset.addMediaLocations(mediaassetLocation);
      }

      this.assetRepository.save(mediaAsset);
      return new CommandProcessingResult(mediaAsset.getId());

    } catch (DataIntegrityViolationException dve) {
      handleCodeDataIntegrityIssues(command, dve);
      return new CommandProcessingResult(Long.valueOf(-1));
    }
  }
  @Override
  public CommandProcessingResult updateGameMediaAsset(JsonCommand command) {

    MediaAsset mediaAssetMaster = null;
    try {
      this.context.authenticatedUser();
      final Long mediaId = command.entityId();
      mediaAssetMaster = this.assetRepository.findOne(mediaId);

      if (mediaAssetMaster == null) {
        throw new NoMoviesFoundException(
            "error.media.assets.game.not.found", "No Game Asset Found");
      }

      final Map<String, Object> changes = mediaAssetMaster.updateForGame(command);
      if (!changes.isEmpty()) {
        assetRepository.save(mediaAssetMaster);
      }

      final JsonArray gameData = command.arrayOfParameterNamed("gameMediaData").getAsJsonArray();
      for (int i = 0; i < gameData.size(); i++) {
        String currentData = gameData.get(i).toString();
        final JsonElement element = fromApiJsonHelper.parse(currentData);

        final Long settlementId = fromApiJsonHelper.extractLongNamed("settlementId", element);
        if (settlementId == null) {

          final BigDecimal amount =
              fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element);
          final String category = fromApiJsonHelper.extractStringNamed("category", element);
          final String mediaContentProvider =
              fromApiJsonHelper.extractStringNamed("mediaContentProvider", element);
          final String mt = fromApiJsonHelper.extractStringNamed("mediaType", element);
          final Character mediaType = mt.equals("Flat") ? 'F' : 'P';
          final Long sequence = fromApiJsonHelper.extractLongNamed("sequence", element);
          final String source = fromApiJsonHelper.extractStringNamed("source", element);

          final Settlement settlement =
              Settlement.fromJson(
                  mediaId, amount, category, mediaContentProvider, mediaType, sequence, source);
          settlementJpaRepository.save(settlement);
        } else {
          final Settlement settlement = settlementJpaRepository.findOne(settlementId);
          if (settlement == null) {
            throw new SettlementNotFoundException();
          }

          final Map<String, Object> settlementChanges =
              settlement.update(element, fromApiJsonHelper, mediaId);

          if (!settlementChanges.isEmpty()) {
            settlementJpaRepository.save(settlement);
          }
        }
      }

    } catch (DataIntegrityViolationException dve) {
      handleCodeDataIntegrityIssues(command, dve);
      return new CommandProcessingResult(Long.valueOf(-1));
    }
    return new CommandProcessingResult(mediaAssetMaster.getId());
  }
  public void validateForCreateRevenue(String json) {

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final Long businessLine = fromApiJsonHelper.extractLongNamed("businessLine", element);
    baseDataValidator.reset().parameter("businessLine").value(businessLine).notBlank();

    final Long mediaCategory = fromApiJsonHelper.extractLongNamed("mediaCategory", element);
    baseDataValidator.reset().parameter("mediaCategory").value(mediaCategory).notBlank();

    final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element);
    baseDataValidator.reset().parameter("clientId").value(clientId).notBlank();

    final Long revenueShareType = fromApiJsonHelper.extractLongNamed("revenueShareType", element);
    baseDataValidator.reset().parameter("revenueShareType").value(revenueShareType).notBlank();

    final JsonArray percentageParamsDataArray =
        fromApiJsonHelper.extractJsonArrayNamed("percentageParams", element);

    if (percentageParamsDataArray != null && percentageParamsDataArray.size() > 0) {
      String[] percentageParamsDataArrayAttributes = null;
      percentageParamsDataArrayAttributes = new String[percentageParamsDataArray.size()];
      int interactiveDataSize = percentageParamsDataArray.size();
      baseDataValidator.reset().parameter(null).value(interactiveDataSize).integerGreaterThanZero();

      for (int i = 0; i < percentageParamsDataArray.size(); i++) {
        percentageParamsDataArrayAttributes[i] = percentageParamsDataArray.get(i).toString();
      }

      for (String singleinteractiveData : percentageParamsDataArrayAttributes) {

        final JsonElement elements = fromApiJsonHelper.parse(singleinteractiveData);

        final Long startValue = fromApiJsonHelper.extractLongNamed("startValue", elements);
        baseDataValidator.reset().parameter("startValue").value(startValue).notBlank();

        final Long endValue = fromApiJsonHelper.extractLongNamed("endValue", elements);
        baseDataValidator.reset().parameter("endValue").value(endValue).notBlank();

        final BigDecimal percentage =
            fromApiJsonHelper.extractBigDecimalWithLocaleNamed("percentage", elements);
        baseDataValidator.reset().parameter("percentage").value(percentage).notBlank();

        throwExceptionIfValidationWarningsExist(dataValidationErrors);
      }
    } else {
      final BigDecimal flat = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("flat", element);
      baseDataValidator.reset().parameter("flat").value(flat).notBlank();

      throwExceptionIfValidationWarningsExist(dataValidationErrors);
    }
  }
  // @SuppressWarnings("unused")
  @Override
  public CommandProcessingResult selfRegistrationProcess(JsonCommand command) {

    try {

      context.authenticatedUser();
      Configuration deviceStatusConfiguration =
          configurationRepository.findOneByName(
              ConfigurationConstants.CONFIR_PROPERTY_REGISTRATION_DEVICE);

      commandFromApiJsonDeserializer.validateForCreate(
          command.json(), deviceStatusConfiguration.isEnabled());
      Long id = new Long(1);
      CommandProcessingResult resultClient = null;
      CommandProcessingResult resultSale = null;
      CommandProcessingResult resultOrder = null;
      String device = null;
      String dateFormat = "dd MMMM yyyy";
      String activationDate = new SimpleDateFormat(dateFormat).format(DateUtils.getDateOfTenant());

      String fullname = command.stringValueOfParameterNamed("fullname");
      String firstName = command.stringValueOfParameterNamed("firstname");
      String city = command.stringValueOfParameterNamed("city");
      String address = command.stringValueOfParameterNamed("address");
      Long phone = command.longValueOfParameterNamed("phone");
      Long homePhoneNumber = command.longValueOfParameterNamed("homePhoneNumber");
      String email = command.stringValueOfParameterNamed("email");
      String nationalId = command.stringValueOfParameterNamed("nationalId");
      String deviceId = command.stringValueOfParameterNamed("device");
      String deviceAgreementType = command.stringValueOfParameterNamed("deviceAgreementType");
      String password = command.stringValueOfParameterNamed("password");
      String isMailCheck = command.stringValueOfParameterNamed("isMailCheck");
      String passport = command.stringValueOfParameterNamed("passport");
      SelfCareTemporary temporary = null;

      if (isMailCheck == null || isMailCheck.isEmpty()) {
        temporary = selfCareTemporaryRepository.findOneByEmailId(email);

        if (temporary == null) {
          throw new SelfCareTemporaryEmailIdNotFoundException(email);

        } else if (temporary.getStatus().equalsIgnoreCase("ACTIVE")) {
          throw new ClientAlreadyCreatedException();

        } else if (temporary.getStatus().equalsIgnoreCase("INACTIVE")) {
          throw new SelfCareNotVerifiedException(email);
        }
      }

      //	if (temporary.getStatus().equalsIgnoreCase("PENDING")){

      String zipCode = command.stringValueOfParameterNamed("zipCode");
      // client creation
      AddressData addressData = this.addressReadPlatformService.retrieveAdressBy(city);
      CodeValue codeValue = this.codeValueRepository.findOneByCodeValue("Normal");
      JSONObject clientcreation = new JSONObject();
      clientcreation.put("officeId", new Long(1));
      clientcreation.put("clientCategory", codeValue.getId());
      clientcreation.put("firstname", firstName);
      clientcreation.put("lastname", fullname);
      clientcreation.put("phone", phone);
      clientcreation.put("homePhoneNumber", homePhoneNumber);
      clientcreation.put("entryType", "IND"); // new Long(1));
      clientcreation.put("addressNo", address);
      clientcreation.put("city", addressData.getCity());
      clientcreation.put("state", addressData.getState());
      clientcreation.put("country", addressData.getCountry());
      clientcreation.put("email", email);
      clientcreation.put("locale", "en");
      clientcreation.put("active", true);
      clientcreation.put("dateFormat", dateFormat);
      clientcreation.put("activationDate", activationDate);
      clientcreation.put("flag", false);
      clientcreation.put("zipCode", zipCode);
      clientcreation.put("device", deviceId);
      clientcreation.put("password", password);

      if (nationalId != null && !nationalId.equalsIgnoreCase("")) {
        clientcreation.put("externalId", nationalId);
      }

      final JsonElement element = fromJsonHelper.parse(clientcreation.toString());
      JsonCommand clientCommand =
          new JsonCommand(
              null,
              clientcreation.toString(),
              element,
              fromJsonHelper,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null,
              null);
      resultClient = this.clientWritePlatformService.createClient(clientCommand);

      if (resultClient == null) {
        throw new PlatformDataIntegrityException(
            "error.msg.client.creation.failed", "Client Creation Failed", "Client Creation Failed");
      }

      if (passport != null && !passport.equalsIgnoreCase("")) {
        CodeValue passportcodeValue = this.codeValueRepository.findOneByCodeValue("Passport");
        JSONObject clientIdentifierJson = new JSONObject();
        clientIdentifierJson.put("documentTypeId", passportcodeValue.getId());
        clientIdentifierJson.put("documentKey", passport);
        final JsonElement idenfierJsonEement =
            fromJsonHelper.parse(clientIdentifierJson.toString());
        JsonCommand idenfierJsonCommand =
            new JsonCommand(
                null,
                clientIdentifierJson.toString(),
                idenfierJsonEement,
                fromJsonHelper,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);
        this.clientIdentifierWritePlatformService.addClientIdentifier(
            resultClient.getClientId(), idenfierJsonCommand);
      }

      if (temporary != null) {
        temporary.setStatus("ACTIVE");
        this.selfCareTemporaryRepository.saveAndFlush(temporary);
      }

      // book device
      if (deviceStatusConfiguration != null) {

        if (deviceStatusConfiguration.isEnabled()) {

          JSONObject bookDevice = new JSONObject();
          /*deviceStatusConfiguration = configurationRepository
          .findOneByName(ConfigurationConstants.CONFIG_PROPERTY_DEVICE_AGREMENT_TYPE);*/

          /*if (deviceStatusConfiguration != null&& deviceStatusConfiguration.isEnabled()
          && deviceStatusConfiguration.getValue().equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_SALE)) {*/
          if (deviceAgreementType.equalsIgnoreCase(ConfigurationConstants.CONFIR_PROPERTY_SALE)) {

            device = command.stringValueOfParameterNamed("device");
            ItemDetails detail = itemDetailsRepository.getInventoryItemDetailBySerialNum(device);

            if (detail == null) {
              throw new SerialNumberNotFoundException(device);
            }

            ItemMaster itemMaster = this.itemRepository.findOne(detail.getItemMasterId());

            if (itemMaster == null) {
              throw new ItemNotFoundException(deviceId);
            }

            if (detail != null && detail.getStatus().equalsIgnoreCase("Used")) {
              throw new SerialNumberAlreadyExistException(device);
            }

            JSONObject serialNumberObject = new JSONObject();
            serialNumberObject.put("serialNumber", device);
            serialNumberObject.put("clientId", resultClient.getClientId());
            serialNumberObject.put("status", "allocated");
            serialNumberObject.put("itemMasterId", detail.getItemMasterId());
            serialNumberObject.put("isNewHw", "Y");
            JSONArray serialNumber = new JSONArray();
            serialNumber.put(0, serialNumberObject);

            bookDevice.put("chargeCode", itemMaster.getChargeCode());
            bookDevice.put("unitPrice", itemMaster.getUnitPrice());
            bookDevice.put("itemId", itemMaster.getId());
            bookDevice.put("discountId", id);
            bookDevice.put("officeId", detail.getOfficeId());
            bookDevice.put("totalPrice", itemMaster.getUnitPrice());

            bookDevice.put("quantity", id);
            bookDevice.put("locale", "en");
            bookDevice.put("dateFormat", dateFormat);
            bookDevice.put("saleType", "NEWSALE");
            bookDevice.put("saleDate", activationDate);
            bookDevice.put("serialNumber", serialNumber);

            final JsonElement deviceElement = fromJsonHelper.parse(bookDevice.toString());
            JsonCommand comm =
                new JsonCommand(
                    null,
                    bookDevice.toString(),
                    deviceElement,
                    fromJsonHelper,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null);

            resultSale =
                this.oneTimeSaleWritePlatformService.createOneTimeSale(
                    comm, resultClient.getClientId());

            if (resultSale == null) {
              throw new PlatformDataIntegrityException(
                  "error.msg.client.device.assign.failed",
                  "Device Assign Failed for ClientId :" + resultClient.getClientId(),
                  "Device Assign Failed");
            }

          } else if (deviceAgreementType.equalsIgnoreCase(
              ConfigurationConstants.CONFIR_PROPERTY_OWN)) {

            List<ItemMaster> itemMaster = this.itemRepository.findAll();
            bookDevice.put("locale", "en");
            bookDevice.put("dateFormat", dateFormat);
            bookDevice.put("allocationDate", activationDate);
            bookDevice.put("provisioningSerialNumber", deviceId);
            bookDevice.put("itemType", itemMaster.get(0).getId());
            bookDevice.put("serialNumber", deviceId);
            bookDevice.put("status", "ACTIVE");
            CommandWrapper commandWrapper =
                new CommandWrapperBuilder()
                    .createOwnedHardware(resultClient.getClientId())
                    .withJson(bookDevice.toString())
                    .build();
            final CommandProcessingResult result =
                portfolioCommandSourceWritePlatformService.logCommandSource(commandWrapper);

            if (result == null) {
              throw new PlatformDataIntegrityException(
                  "error.msg.client.device.assign.failed",
                  "Device Assign Failed for ClientId :" + resultClient.getClientId(),
                  "Device Assign Failed");
            }
          } else {

          }
        }
      }

      // book order
      Configuration selfregistrationconfiguration =
          configurationRepository.findOneByName(
              ConfigurationConstants.CONFIR_PROPERTY_SELF_REGISTRATION);

      if (selfregistrationconfiguration != null && selfregistrationconfiguration.isEnabled()) {

        if (selfregistrationconfiguration.getValue() != null) {

          JSONObject ordeJson = new JSONObject(selfregistrationconfiguration.getValue());
          ordeJson.put("locale", "en");
          ordeJson.put("isNewplan", true);
          ordeJson.put("dateFormat", dateFormat);
          ordeJson.put("start_date", activationDate);

          CommandWrapper commandRequest =
              new CommandWrapperBuilder()
                  .createOrder(resultClient.getClientId())
                  .withJson(ordeJson.toString())
                  .build();
          resultOrder =
              this.portfolioCommandSourceWritePlatformService.logCommandSource(commandRequest);

          if (resultOrder == null) {
            throw new PlatformDataIntegrityException(
                "error.msg.client.order.creation",
                "Book Order Failed for ClientId:" + resultClient.getClientId(),
                "Book Order Failed");
          }

        } else {

          String paytermCode = command.stringValueOfParameterNamed("paytermCode");
          Long contractPeriod = command.longValueOfParameterNamed("contractPeriod");
          Long planCode = command.longValueOfParameterNamed("planCode");

          JSONObject ordeJson = new JSONObject();

          ordeJson.put("planCode", planCode);
          ordeJson.put("contractPeriod", contractPeriod);
          ordeJson.put("paytermCode", paytermCode);
          ordeJson.put("billAlign", false);
          ordeJson.put("locale", "en");
          ordeJson.put("isNewplan", true);
          ordeJson.put("dateFormat", dateFormat);
          ordeJson.put("start_date", activationDate);

          CommandWrapper commandRequest =
              new CommandWrapperBuilder()
                  .createOrder(resultClient.getClientId())
                  .withJson(ordeJson.toString())
                  .build();
          resultOrder =
              this.portfolioCommandSourceWritePlatformService.logCommandSource(commandRequest);

          if (resultOrder == null) {
            throw new PlatformDataIntegrityException(
                "error.msg.client.order.creation",
                "Book Order Failed for ClientId:" + resultClient.getClientId(),
                "Book Order Failed");
          }
        }
      }

      return resultClient;

      /*}  else {
      	return new CommandProcessingResult(Long.valueOf(-1));
      }*/

    } catch (DataIntegrityViolationException dve) {
      handleDataIntegrityIssues(command, dve);
      return new CommandProcessingResult(Long.valueOf(-1));
    } catch (JSONException e) {
      return new CommandProcessingResult(Long.valueOf(-1));
    }
  }
  public void validateForCreateInteractive(String json) {

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

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

    final JsonElement element = fromApiJsonHelper.parse(json);

    final JsonArray interactiveDataArray =
        fromApiJsonHelper.extractJsonArrayNamed("activeData", element);
    String[] interactiveDataArrayAttributes = null;
    interactiveDataArrayAttributes = new String[interactiveDataArray.size()];
    int interactiveDataSize = interactiveDataArray.size();
    baseDataValidator.reset().parameter(null).value(interactiveDataSize).integerGreaterThanZero();

    for (int i = 0; i < interactiveDataArray.size(); i++) {
      interactiveDataArrayAttributes[i] = interactiveDataArray.get(i).toString();
    }

    for (String singleinteractiveData : interactiveDataArrayAttributes) {

      final JsonElement elements = fromApiJsonHelper.parse(singleinteractiveData);

      final Long playSource = fromApiJsonHelper.extractLongNamed("playSource", elements);
      baseDataValidator.reset().parameter("playSource").value(playSource).notBlank();

      final String contentName = fromApiJsonHelper.extractStringNamed("contentName", elements);
      baseDataValidator.reset().parameter("contentName").value(contentName).notBlank();

      final Long contentProvider = fromApiJsonHelper.extractLongNamed("contentProvider", elements);
      baseDataValidator.reset().parameter("contentProvider").value(contentProvider).notBlank();

      final Long channelName = fromApiJsonHelper.extractLongNamed("channelName", elements);
      baseDataValidator.reset().parameter("channelName").value(channelName).notBlank();

      final Long serviceName = fromApiJsonHelper.extractLongNamed("serviceName", elements);
      baseDataValidator.reset().parameter("serviceName").value(serviceName).notBlank();

      final BigDecimal endUserPrice =
          fromApiJsonHelper.extractBigDecimalWithLocaleNamed("endUserPrice", elements);
      baseDataValidator.reset().parameter("endUserPrice").value(endUserPrice).notBlank();

      final BigDecimal grossRevenue =
          fromApiJsonHelper.extractBigDecimalWithLocaleNamed("grossRevenue", elements);
      baseDataValidator.reset().parameter("grossRevenue").value(grossRevenue).notBlank();

      final Long downloads = fromApiJsonHelper.extractLongNamed("downloads", elements);
      baseDataValidator.reset().parameter("downloads").value(downloads).notBlank();

      // final Long sequence = fromApiJsonHelper.extractLongNamed("sequence", elements);
      // baseDataValidator.reset().parameter("sequence").value(sequence).notBlank();

      throwExceptionIfValidationWarningsExist(dataValidationErrors);
    }
  }