From 04fc9357eba7a1e12559c524ababca8bcafcaf6d Mon Sep 17 00:00:00 2001 From: John Woodlock Date: Thu, 6 Sep 2012 09:16:19 +1000 Subject: [PATCH] test commit --- .../ApiDataConversionServiceImpl.java | 2278 ++++++++--------- .../GoogleGsonApiJsonSerializerService.java | 1122 ++++---- 2 files changed, 1700 insertions(+), 1700 deletions(-) diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/ApiDataConversionServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/ApiDataConversionServiceImpl.java index c4e0957b6..44fbcc2af 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/ApiDataConversionServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/ApiDataConversionServiceImpl.java @@ -1,1140 +1,1140 @@ -package org.mifosng.platform.api.infrastructure; - -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.NumberFormat; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.lang.StringUtils; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormat; -import org.mifosng.platform.api.commands.AdjustLoanTransactionCommand; -import org.mifosng.platform.api.commands.BranchMoneyTransferCommand; -import org.mifosng.platform.api.commands.ChargeCommand; -import org.mifosng.platform.api.commands.ClientCommand; -import org.mifosng.platform.api.commands.DepositAccountCommand; -import org.mifosng.platform.api.commands.DepositProductCommand; -import org.mifosng.platform.api.commands.DepositStateTransitionApprovalCommand; -import org.mifosng.platform.api.commands.DepositStateTransitionCommand; -import org.mifosng.platform.api.commands.FundCommand; -import org.mifosng.platform.api.commands.GroupCommand; -import org.mifosng.platform.api.commands.LoanChargeCommand; -import org.mifosng.platform.api.commands.LoanProductCommand; -import org.mifosng.platform.api.commands.LoanStateTransitionCommand; -import org.mifosng.platform.api.commands.LoanTransactionCommand; -import org.mifosng.platform.api.commands.NoteCommand; -import org.mifosng.platform.api.commands.OfficeCommand; -import org.mifosng.platform.api.commands.OrganisationCurrencyCommand; -import org.mifosng.platform.api.commands.RoleCommand; -import org.mifosng.platform.api.commands.SavingProductCommand; -import org.mifosng.platform.api.commands.StaffCommand; -import org.mifosng.platform.api.commands.SubmitLoanApplicationCommand; -import org.mifosng.platform.api.commands.UserCommand; -import org.mifosng.platform.api.data.ApiParameterError; -import org.mifosng.platform.api.errorhandling.InvalidJsonException; -import org.mifosng.platform.api.errorhandling.UnsupportedParameterException; -import org.mifosng.platform.exceptions.PlatformApiDataValidationException; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.format.number.NumberFormatter; -import org.springframework.stereotype.Service; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; - -@Service -public class ApiDataConversionServiceImpl implements ApiDataConversionService { - - private final Gson gsonConverter; - - public ApiDataConversionServiceImpl() { - gsonConverter = new Gson(); - } - - @Override - public ChargeCommand convertJsonToChargeCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - - Set supportedParams = new HashSet(Arrays.asList("name", "amount", "locale", "currencyCode", - "currencyOptions", "chargeAppliesTo", "chargeTimeType", - "chargeCalculationType", "chargeCalculationTypeOptions", "active" - )); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String name = extractStringParameter("name", requestMap, modifiedParameters); - BigDecimal amount = extractBigDecimalParameter("amount", requestMap, modifiedParameters); - String currencyCode = extractStringParameter("currencyCode", requestMap, modifiedParameters); - - Integer chargeTimeType = extractIntegerParameter("chargeTimeType", requestMap, modifiedParameters); - Integer chargeAppliesTo = extractIntegerParameter("chargeAppliesTo", requestMap, modifiedParameters); - Integer chargeCalculationType = extractIntegerParameter("chargeCalculationType", requestMap, modifiedParameters); - - boolean active = extractBooleanParameter("active", requestMap, modifiedParameters); - - return new ChargeCommand(modifiedParameters, resourceIdentifier, name, amount, - currencyCode, chargeTimeType, chargeAppliesTo, chargeCalculationType, active); - } - - @Override - public FundCommand convertJsonToFundCommand(final Long resourceIdentifier, final String json) { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - - Set supportedParams = new HashSet( - Arrays.asList("name", "externalId") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String name = extractStringParameter("name", requestMap, modifiedParameters); - String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); - - return new FundCommand(modifiedParameters, resourceIdentifier, name, externalId); - } - - @Override - public StaffCommand convertJsonToStaffCommand(Long resourceIdentifier, - String json) { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - - Set supportedParams = new HashSet( - Arrays.asList("firstname", "lastname") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String firstname = extractStringParameter("firstname", requestMap, modifiedParameters); - String lastname = extractStringParameter("lastname", requestMap, modifiedParameters); - - return new StaffCommand(modifiedParameters, resourceIdentifier, firstname, lastname); - } - - @Override - public OfficeCommand convertJsonToOfficeCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("name", "externalId", "parentId", "openingDate", "dateFormat") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String name = extractStringParameter("name", requestMap, modifiedParameters); - String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); - Long parentId = extractLongParameter("parentId", requestMap, modifiedParameters); - LocalDate openingLocalDate = extractLocalDateParameter("openingDate", requestMap, modifiedParameters); - - return new OfficeCommand(modifiedParameters, resourceIdentifier, name, externalId, parentId, openingLocalDate); - } - - @Override - public RoleCommand convertJsonToRoleCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("name", "description", "permissions") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - // check array - JsonParser parser = new JsonParser(); - - String[] permissionIds = null; - JsonElement element = parser.parse(json); - if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); - if (object.has("permissions")) { - modifiedParameters.add("permissions"); - JsonArray array = object.get("permissions").getAsJsonArray(); - permissionIds = new String[array.size()]; - for (int i=0; i>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("username", "firstname", "lastname", "password", "repeatPassword", "email", "officeId", "notSelectedRoles", "roles") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String username = extractStringParameter("username", requestMap, modifiedParameters); - String firstname = extractStringParameter("firstname", requestMap, modifiedParameters); - String lastname = extractStringParameter("lastname", requestMap, modifiedParameters); - String password = extractStringParameter("password", requestMap, modifiedParameters); - String repeatPassword = extractStringParameter("repeatPassword", requestMap, modifiedParameters); - String email = extractStringParameter("email", requestMap, modifiedParameters); - Long officeId = extractLongParameter("officeId", requestMap, modifiedParameters); - - // check array - JsonParser parser = new JsonParser(); - - String[] notSelectedRoles = null; - String[] roles = null; - JsonElement element = parser.parse(json); - if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); - if (object.has("notSelectedRoles")) { - modifiedParameters.add("notSelectedRoles"); - JsonArray array = object.get("notSelectedRoles").getAsJsonArray(); - notSelectedRoles = new String[array.size()]; - for (int i=0; i>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("fromOfficeId", "toOfficeId", "transactionDate", "currencyCode", "transactionAmount", "description", "locale", "dateFormat") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - Long fromOfficeId = extractLongParameter("fromOfficeId", requestMap, modifiedParameters); - Long toOfficeId = extractLongParameter("toOfficeId", requestMap, modifiedParameters); - LocalDate transactionLocalDate = extractLocalDateParameter("transactionDate", requestMap, modifiedParameters); - String currencyCode = extractStringParameter("currencyCode", requestMap, modifiedParameters); - BigDecimal transactionAmountValue = extractBigDecimalParameter("transactionAmount", requestMap, modifiedParameters); - String description = extractStringParameter("description", requestMap, modifiedParameters); - - return new BranchMoneyTransferCommand(modifiedParameters, fromOfficeId, toOfficeId, transactionLocalDate, currencyCode, transactionAmountValue, description); - } - - @Override - public ClientCommand convertJsonToClientCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("externalId", "firstname", "lastname", "clientOrBusinessName", "officeId", "joiningDate", "dateFormat") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); - Long officeId = extractLongParameter("officeId", requestMap, modifiedParameters); - LocalDate joiningDate = extractLocalDateParameter("joiningDate", requestMap, modifiedParameters); - String firstname = extractStringParameter("firstname", requestMap, modifiedParameters); - String lastname = extractStringParameter("lastname", requestMap, modifiedParameters); - String clientOrBusinessName = extractStringParameter("clientOrBusinessName", requestMap, modifiedParameters); - - return new ClientCommand(modifiedParameters, resourceIdentifier, externalId, firstname, lastname, clientOrBusinessName, officeId, joiningDate); - } - - @Override - public GroupCommand convertJsonToGroupCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("name", "externalId", "clientMembers") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); - String name = extractStringParameter("name", requestMap, modifiedParameters); - - // check array - JsonParser parser = new JsonParser(); - - String[] clientMembers = null; - JsonElement element = parser.parse(json); - if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); - if (object.has("clientMembers")) { - modifiedParameters.add("clientMembers"); - JsonArray array = object.get("clientMembers").getAsJsonArray(); - clientMembers = new String[array.size()]; - for (int i=0; i>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("name", "description", "fundId", "transactionProcessingStrategyId", "currencyCode", "digitsAfterDecimal", - "principal", "inArrearsTolerance", "interestRatePerPeriod", "repaymentEvery", "numberOfRepayments", - "repaymentFrequencyType", "interestRateFrequencyType", "amortizationType", "interestType", "interestCalculationPeriodType", - "charges", "locale") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String name = extractStringParameter("name", requestMap, modifiedParameters); - String description = extractStringParameter("description", requestMap, modifiedParameters); - Long fundId = extractLongParameter("fundId", requestMap, modifiedParameters); - Long transactionProcessingStrategyId = extractLongParameter("transactionProcessingStrategyId", requestMap, modifiedParameters); - String currencyCode = extractStringParameter("currencyCode", requestMap, modifiedParameters); - Integer digitsAfterDecimalValue = extractIntegerParameter("digitsAfterDecimal", requestMap, modifiedParameters); - BigDecimal principalValue = extractBigDecimalParameter("principal", requestMap, modifiedParameters); - BigDecimal inArrearsToleranceValue = extractBigDecimalParameter("inArrearsTolerance", requestMap, modifiedParameters); - BigDecimal interestRatePerPeriodValue = extractBigDecimalParameter("interestRatePerPeriod", requestMap, modifiedParameters); - - Integer repaymentEveryValue = extractIntegerParameter("repaymentEvery", requestMap, modifiedParameters); - Integer numberOfRepaymentsValue = extractIntegerParameter("numberOfRepayments", requestMap, modifiedParameters); - Integer repaymentFrequencyTypeValue = extractIntegerParameter("repaymentFrequencyType", requestMap, modifiedParameters); - - Integer interestRateFrequencyTypeValue = extractIntegerParameter("interestRateFrequencyType", requestMap, modifiedParameters); - Integer amortizationTypeValue = extractIntegerParameter("amortizationType", requestMap, modifiedParameters); - Integer interestTypeValue = extractIntegerParameter("interestType", requestMap, modifiedParameters); - Integer interestCalculationPeriodTypeValue = extractIntegerParameter("interestCalculationPeriodType", requestMap, modifiedParameters); - - // check array - JsonParser parser = new JsonParser(); - - String[] charges = null; - JsonElement element = parser.parse(json); - if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); - if (object.has("charges")) { - modifiedParameters.add("charges"); - JsonArray array = object.get("charges").getAsJsonArray(); - charges = new String[array.size()]; - for (int i=0; i>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("clientId", "productId", "externalId", "fundId", "transactionProcessingStrategyId", - "principal", "inArrearsTolerance", "interestRatePerPeriod", "repaymentEvery", "numberOfRepayments", - "loanTermFrequency", "loanTermFrequencyType", "charges", - "repaymentFrequencyType", "interestRateFrequencyType", "amortizationType", "interestType", "interestCalculationPeriodType", - "expectedDisbursementDate", "repaymentsStartingFromDate", "interestChargedFromDate", "submittedOnDate", "submittedOnNote", - "locale", "dateFormat") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - Long clientId = extractLongParameter("clientId", requestMap, modifiedParameters); - Long productId = extractLongParameter("productId", requestMap, modifiedParameters); - Long fundId = extractLongParameter("fundId", requestMap, modifiedParameters); - Long transactionProcessingStrategyId = extractLongParameter("transactionProcessingStrategyId", requestMap, modifiedParameters); - String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); - - BigDecimal principal = extractBigDecimalParameter("principal", requestMap, modifiedParameters); - BigDecimal inArrearsToleranceValue = extractBigDecimalParameter("inArrearsTolerance", requestMap, modifiedParameters); - BigDecimal interestRatePerPeriod = extractBigDecimalParameter("interestRatePerPeriod", requestMap, modifiedParameters); - - Integer repaymentEvery = extractIntegerParameter("repaymentEvery", requestMap, modifiedParameters); - Integer numberOfRepayments = extractIntegerParameter("numberOfRepayments", requestMap, modifiedParameters); - Integer repaymentFrequencyType = extractIntegerParameter("repaymentFrequencyType", requestMap, modifiedParameters); - - Integer loanTermFrequency = extractIntegerParameter("loanTermFrequency", requestMap, modifiedParameters); - Integer loanTermFrequencyType = extractIntegerParameter("loanTermFrequencyType", requestMap, modifiedParameters); - - Integer interestRateFrequencyTypeValue = extractIntegerParameter("interestRateFrequencyType", requestMap, modifiedParameters); - Integer amortizationTypeValue = extractIntegerParameter("amortizationType", requestMap, modifiedParameters); - Integer interestTypeValue = extractIntegerParameter("interestType", requestMap, modifiedParameters); - Integer interestCalculationPeriodTypeValue = extractIntegerParameter("interestCalculationPeriodType", requestMap, modifiedParameters); - - LocalDate expectedDisbursementDate = extractLocalDateParameter("expectedDisbursementDate", requestMap, modifiedParameters); - LocalDate repaymentsStartingFromDate = extractLocalDateParameter("repaymentsStartingFromDate", requestMap, modifiedParameters); - LocalDate interestChargedFromDate = extractLocalDateParameter("interestChargedFromDate", requestMap, modifiedParameters); - LocalDate submittedOnDate = extractLocalDateParameter("submittedOnDate", requestMap, modifiedParameters); - - String submittedOnNote = extractStringParameter("submittedOnNote", requestMap, modifiedParameters); - - JsonParser parser = new JsonParser(); - - LoanChargeCommand[] charges = null; - JsonElement element = parser.parse(json); - if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); - if (object.has("charges") && object.get("charges").isJsonArray()) { - modifiedParameters.add("charges"); - JsonArray array = object.get("charges").getAsJsonArray(); - charges = new LoanChargeCommand[array.size()]; - for (int i=0; i chargeModifiedParameters = new HashSet(); - Long id = loanCharge.get("id").getAsLong(); - BigDecimal amount = null; - Integer chargeTimeType = null; - Integer chargeCalculationType = null; - - if (loanCharge.has("amount")){ - chargeModifiedParameters.add("amount"); - amount = loanCharge.get("amount").getAsBigDecimal(); - } - if (loanCharge.has("chargeTimeType")){ - chargeModifiedParameters.add("chargeTimeType"); - chargeTimeType = loanCharge.get("chargeTimeType").getAsInt(); - } - if (loanCharge.has("chargeCalculationType")){ - chargeModifiedParameters.add("chargeCalculationType"); - chargeCalculationType = loanCharge.get("chargeCalculationType").getAsInt(); - } - charges[i] = new LoanChargeCommand(chargeModifiedParameters, id, amount, chargeTimeType, chargeCalculationType); - } - } - } - - return new SubmitLoanApplicationCommand(clientId, productId, externalId, fundId, transactionProcessingStrategyId, - submittedOnDate, submittedOnNote, - expectedDisbursementDate, repaymentsStartingFromDate, interestChargedFromDate, - principal, interestRatePerPeriod, interestRateFrequencyTypeValue, interestTypeValue, interestCalculationPeriodTypeValue, - repaymentEvery, repaymentFrequencyType, numberOfRepayments, amortizationTypeValue, - loanTermFrequency, loanTermFrequencyType, - inArrearsToleranceValue, charges); - } - - @Override - public LoanStateTransitionCommand convertJsonToLoanStateTransitionCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("eventDate", "note", "dateFormat") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - LocalDate eventDate = extractLocalDateParameter("eventDate", requestMap, modifiedParameters); - String note = extractStringParameter("note", requestMap, modifiedParameters); - - return new LoanStateTransitionCommand(resourceIdentifier, eventDate, note); - } - - @Override - public LoanTransactionCommand convertJsonToLoanTransactionCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("transactionDate", "transactionAmount", "note", "dateFormat", "locale") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - LocalDate transactionDate = extractLocalDateParameter("transactionDate", requestMap, modifiedParameters); - BigDecimal transactionAmount = extractBigDecimalParameter("transactionAmount", requestMap, modifiedParameters); - String note = extractStringParameter("note", requestMap, modifiedParameters); - - return new LoanTransactionCommand(resourceIdentifier, transactionDate, transactionAmount, note); - } - - @Override - public AdjustLoanTransactionCommand convertJsonToAdjustLoanTransactionCommand( - final Long loanId, final Long transactionId, final String json) { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("transactionDate", "transactionAmount", "note", "dateFormat", "locale") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - LocalDate transactionDate = extractLocalDateParameter("transactionDate", requestMap, modifiedParameters); - BigDecimal transactionAmount = extractBigDecimalParameter("transactionAmount", requestMap, modifiedParameters); - String note = extractStringParameter("note", requestMap, modifiedParameters); - - return new AdjustLoanTransactionCommand(loanId, transactionId, transactionDate, note, transactionAmount); - } - - @Override - public NoteCommand convertJsonToNoteCommand(final Long noteId, final Long clientId, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("note") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String note = extractStringParameter("note", requestMap, modifiedParameters); - - return new NoteCommand(noteId, clientId, note); - } - - @Override - public OrganisationCurrencyCommand convertJsonToOrganisationCurrencyCommand(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("currencies") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - // check array - JsonParser parser = new JsonParser(); - - String[] currencies = null; - JsonElement element = parser.parse(json); - if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); - if (object.has("currencies")) { - modifiedParameters.add("currencies"); - JsonArray array = object.get("currencies").getAsJsonArray(); - currencies = new String[array.size()]; - for (int i=0; i requestMap, Set supportedParams) { - List unsupportedParameterList = new ArrayList(); - for (String providedParameter : requestMap.keySet()) { - if (!supportedParams.contains(providedParameter)) { - unsupportedParameterList.add(providedParameter); - } - } - - if (!unsupportedParameterList.isEmpty()) { - throw new UnsupportedParameterException(unsupportedParameterList); - } - } - - private String extractStringParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { - String paramValue = null; - if (requestMap.containsKey(paramName)) { - paramValue = (String) requestMap.get(paramName); - modifiedParameters.add(paramName); - } - - if (paramValue != null) { - paramValue = paramValue.trim(); - } - - return paramValue; - } - - private Integer extractIntegerParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { - Integer paramValue = null; - if (requestMap.containsKey(paramName)) { - String valueAsString = (String) requestMap.get(paramName); - paramValue = convertToInteger(valueAsString, paramName, extractLocaleValue(requestMap)); - modifiedParameters.add(paramName); - } - return paramValue; - } - - private BigDecimal extractBigDecimalParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { - BigDecimal paramValue = null; - if (requestMap.containsKey(paramName)) { - String valueAsString = (String) requestMap.get(paramName); - paramValue = convertFrom(valueAsString, paramName, extractLocaleValue(requestMap)); - modifiedParameters.add(paramName); - } - return paramValue; - } - - private boolean extractBooleanParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { - boolean paramValue = false; - String paramValueAsString = null; - if (requestMap.containsKey(paramName)) { - paramValueAsString = (String) requestMap.get(paramName); - - if (paramValueAsString != null) { - paramValueAsString = paramValueAsString.trim(); - } - - paramValue = Boolean.valueOf(paramValueAsString); - modifiedParameters.add(paramName); - } - return paramValue; - } - - private Long extractLongParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { - Long paramValue = null; - if (requestMap.containsKey(paramName)) { - String valueAsString = (String) requestMap.get(paramName); - if (StringUtils.isNotBlank(valueAsString)) { - paramValue = Long.valueOf(Double.valueOf(valueAsString).longValue()); - } - modifiedParameters.add(paramName); - } - return paramValue; - } - - private LocalDate extractLocalDateParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { - LocalDate paramValue = null; - if (requestMap.containsKey(paramName)) { - String valueAsString = (String) requestMap.get(paramName); - if (StringUtils.isNotBlank(valueAsString)) { - final String dateFormat = (String) requestMap.get("dateFormat"); - paramValue = convertFrom(valueAsString, paramName, dateFormat); - } - modifiedParameters.add(paramName); - } - return paramValue; - } - - private Locale extractLocaleValue(Map requestMap) { - Locale clientApplicationLocale = null; - String locale = null; - if (requestMap.containsKey("locale")) { - locale = (String) requestMap.get("locale"); - clientApplicationLocale = localeFromString(locale); - } - return clientApplicationLocale; - } - - private LocalDate convertFrom(final String dateAsString, final String parameterName, final String dateFormat) { - - if (StringUtils.isBlank(dateFormat)) { - - List dataValidationErrors = new ArrayList(); - String defaultMessage = new StringBuilder("The parameter '" + parameterName + "' requires a 'dateFormat' parameter to be passed with it.").toString(); - ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.dateFormat.parameter", defaultMessage, parameterName); - dataValidationErrors.add(error); - - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - - LocalDate eventLocalDate = null; - if (StringUtils.isNotBlank(dateAsString)) { - try { - Locale locale = LocaleContextHolder.getLocale(); - eventLocalDate = DateTimeFormat.forPattern(dateFormat) - .withLocale(locale) - .parseLocalDate(dateAsString.toLowerCase(locale)); - } catch (IllegalArgumentException e) { - List dataValidationErrors = new ArrayList(); - ApiParameterError error = ApiParameterError - .parameterError( - "validation.msg.invalid.date.format", - "The parameter " - + parameterName - + " is invalid based on the dateFormat provided:" - + dateFormat, parameterName, - dateAsString, dateFormat); - dataValidationErrors.add(error); - - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - } - - return eventLocalDate; - } - - private Integer convertToInteger(final String numericalValueFormatted, final String parameterName, final Locale clientApplicationLocale) { - - if (clientApplicationLocale == null) { - - List dataValidationErrors = new ArrayList(); - String defaultMessage = new StringBuilder("The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.").toString(); - ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); - dataValidationErrors.add(error); - - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - - try { - Integer number = null; - - if (StringUtils.isNotBlank(numericalValueFormatted)) { - - String source = numericalValueFormatted.trim(); - - NumberFormat format = NumberFormat.getInstance(clientApplicationLocale); - DecimalFormat df = (DecimalFormat) format; - DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); - df.setParseBigDecimal(true); - - // http://bugs.sun.com/view_bug.do?bug_id=4510618 - char groupingSeparator = symbols.getGroupingSeparator(); - if (groupingSeparator == '\u00a0') { - source = source.replaceAll(" ", Character.toString('\u00a0')); - } - - Number parsedNumber = df.parse(source); - - double parsedNumberDouble = parsedNumber.doubleValue(); - int parsedNumberInteger = parsedNumber.intValue(); - - if (source.contains(Character.toString(symbols.getDecimalSeparator()))) { - throw new ParseException(source, 0); - } - - if (!Double.valueOf(parsedNumberDouble).equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) { - throw new ParseException(source, 0); - } - - number = parsedNumber.intValue(); - } - - return number; - } catch (ParseException e) { - - List dataValidationErrors = new ArrayList(); - ApiParameterError error = ApiParameterError.parameterError( - "validation.msg.invalid.integer.format", "The parameter " - + parameterName + " has value: " + numericalValueFormatted + " which is invalid integer value for provided locale of [" - + clientApplicationLocale.toString() + "].", - parameterName, numericalValueFormatted, - clientApplicationLocale); - dataValidationErrors.add(error); - - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - } - - private BigDecimal convertFrom(final String numericalValueFormatted, final String parameterName, final Locale clientApplicationLocale) { - - if (clientApplicationLocale == null) { - - List dataValidationErrors = new ArrayList(); - String defaultMessage = new StringBuilder("The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.").toString(); - ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); - dataValidationErrors.add(error); - - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - - try { - BigDecimal number = null; - - if (StringUtils.isNotBlank(numericalValueFormatted)) { - - String source = numericalValueFormatted.trim(); - - NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale); - DecimalFormat df = (DecimalFormat) format; - DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); - // http://bugs.sun.com/view_bug.do?bug_id=4510618 - char groupingSeparator = symbols.getGroupingSeparator(); - if (groupingSeparator == '\u00a0') { - source = source.replaceAll(" ", Character.toString('\u00a0')); - } - - NumberFormatter numberFormatter = new NumberFormatter(); - Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale); - number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue())); - } - - return number; - } catch (ParseException e) { - - List dataValidationErrors = new ArrayList(); - ApiParameterError error = ApiParameterError.parameterError( - "validation.msg.invalid.decimal.format", "The parameter " - + parameterName + " has value: " + numericalValueFormatted + " which is invalid decimal value for provided locale of [" - + clientApplicationLocale.toString() + "].", - parameterName, numericalValueFormatted, - clientApplicationLocale); - dataValidationErrors.add(error); - - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - } - - private Locale localeFromString(final String localeAsString) { - - if (StringUtils.isBlank(localeAsString)) { - List dataValidationErrors = new ArrayList(); - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", "The parameter locale is invalid. It cannot be blank.", "locale"); - dataValidationErrors.add(error); - - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - - String languageCode = ""; - String courntryCode = ""; - String variantCode = ""; - - String[] localeParts = localeAsString.split("_"); - - if (localeParts != null && localeParts.length == 1) { - languageCode = localeParts[0]; - } - - if (localeParts != null && localeParts.length == 2) { - languageCode = localeParts[0]; - courntryCode = localeParts[1]; - } - - if (localeParts != null && localeParts.length == 3) { - languageCode = localeParts[0]; - courntryCode = localeParts[1]; - variantCode = localeParts[2]; - } - - return localeFrom(languageCode, courntryCode, variantCode); - } - - private Locale localeFrom(final String languageCode, final String courntryCode, final String variantCode) { - - List dataValidationErrors = new ArrayList(); - - List allowedLanguages = Arrays.asList(Locale.getISOLanguages()); - if (!allowedLanguages.contains(languageCode.toLowerCase())) { - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", "The parameter locale has an invalid language value " + languageCode + " .", "locale", languageCode); - dataValidationErrors.add(error); - } - - if (StringUtils.isNotBlank(courntryCode.toUpperCase())) { - List allowedCountries = Arrays.asList(Locale.getISOCountries()); - if (!allowedCountries.contains(courntryCode)) { - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", "The parameter locale has an invalid country value " + courntryCode + " .", "locale", courntryCode); - dataValidationErrors.add(error); - } - } - - if (!dataValidationErrors.isEmpty()) { - throw new PlatformApiDataValidationException( - "validation.msg.validation.errors.exist", - "Validation errors exist.", dataValidationErrors); - } - - return new Locale(languageCode.toLowerCase(), courntryCode.toUpperCase(), variantCode); - } - - @Override - public SavingProductCommand convertJsonToSavingProductCommand(final Long resourceIdentifier, final String json) { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - Type typeOfMap = new TypeToken>() {}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet(Arrays.asList("name","description","currencyCode", "digitsAfterDecimal","interestRate","locale","minimumBalance","maximumBalance")); - checkForUnsupportedParameters(requestMap, supportedParams); - Set modifiedParameters = new HashSet(); - String name = extractStringParameter("name", requestMap,modifiedParameters); - String description = extractStringParameter("description", requestMap,modifiedParameters); - String currencyCode=extractStringParameter("currencyCode", requestMap,modifiedParameters); - Integer digitsAfterDecimalValue = extractIntegerParameter("digitsAfterDecimal", requestMap, modifiedParameters); - BigDecimal interestRate = extractBigDecimalParameter("interestRate", requestMap, modifiedParameters); - BigDecimal minimumBalance=extractBigDecimalParameter("minimumBalance", requestMap, modifiedParameters); - BigDecimal maximumBalance=extractBigDecimalParameter("maximumBalance", requestMap, modifiedParameters); - - - return new SavingProductCommand(modifiedParameters, resourceIdentifier,name, description,currencyCode,digitsAfterDecimalValue,interestRate,minimumBalance,maximumBalance); - } - - @Override - public DepositAccountCommand convertJsonToDepositAccountCommand(final Long resourceIdentifier, final String json) { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>() {}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - // preClosureInterestRate - Set supportedParams = new HashSet( - Arrays.asList("clientId", "productId", "externalId", "depositAmount", "maturityInterestRate", - "tenureInMonths", "interestCompoundedEvery", "interestCompoundedEveryPeriodType", "commencementDate", - "renewalAllowed", "preClosureAllowed", - "locale", "dateFormat") - ); - checkForUnsupportedParameters(requestMap, supportedParams); - Set modifiedParameters = new HashSet(); - - Long clientId = extractLongParameter("clientId", requestMap, modifiedParameters); - Long productId = extractLongParameter("productId", requestMap, modifiedParameters); - String externalId = extractStringParameter("externalId", requestMap,modifiedParameters); - BigDecimal depositAmount=extractBigDecimalParameter("depositAmount", requestMap, modifiedParameters); - BigDecimal interestRate = extractBigDecimalParameter("maturityInterestRate", requestMap, modifiedParameters); - Integer tenureInMonths = extractIntegerParameter("tenureInMonths", requestMap, modifiedParameters); - - Integer interestCompoundedEvery = extractIntegerParameter("interestCompoundedEvery", requestMap, modifiedParameters); - Integer interestCompoundedEveryPeriodType = extractIntegerParameter("interestCompoundedEveryPeriodType", requestMap, modifiedParameters); - LocalDate commencementDate = extractLocalDateParameter("commencementDate", requestMap, modifiedParameters); - - boolean renewalAllowed = extractBooleanParameter("renewalAllowed", requestMap, modifiedParameters); - boolean preClosureAllowed = extractBooleanParameter("preClosureAllowed", requestMap, modifiedParameters); - - return new DepositAccountCommand(modifiedParameters, resourceIdentifier, clientId, productId, - externalId, depositAmount, interestRate, tenureInMonths, - interestCompoundedEvery, interestCompoundedEveryPeriodType, commencementDate, renewalAllowed, preClosureAllowed); - } - - @Override - public DepositProductCommand convertJsonToDepositProductCommand(final Long resourceIdentifier, final String json) { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>() {}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("locale", "name", "externalId", "description","currencyCode", "digitsAfterDecimal","minimumBalance","maximumBalance","tenureInMonths", - "maturityDefaultInterestRate","maturityMinInterestRate","maturityMaxInterestRate", - "interestCompoundedEvery", "interestCompoundedEveryPeriodType", - "renewalAllowed","preClosureAllowed","preClosureInterestRate") - ); - checkForUnsupportedParameters(requestMap, supportedParams); - Set modifiedParameters = new HashSet(); - String name = extractStringParameter("name", requestMap,modifiedParameters); - String externalId = extractStringParameter("externalId", requestMap,modifiedParameters); - - String description = extractStringParameter("description", requestMap,modifiedParameters); - String currencyCode=extractStringParameter("currencyCode", requestMap,modifiedParameters); - Integer digitsAfterDecimalValue = extractIntegerParameter("digitsAfterDecimal", requestMap, modifiedParameters); - BigDecimal minimumBalance=extractBigDecimalParameter("minimumBalance", requestMap, modifiedParameters); - BigDecimal maximumBalance=extractBigDecimalParameter("maximumBalance", requestMap, modifiedParameters); - - Integer tenureMonths = extractIntegerParameter("tenureInMonths", requestMap, modifiedParameters); - BigDecimal maturityDefaultInterestRate = extractBigDecimalParameter("maturityDefaultInterestRate", requestMap, modifiedParameters); - BigDecimal maturityMinInterestRate = extractBigDecimalParameter("maturityMinInterestRate", requestMap, modifiedParameters); - BigDecimal maturityMaxInterestRate = extractBigDecimalParameter("maturityMaxInterestRate", requestMap, modifiedParameters); - - Integer interestCompoundedEvery = extractIntegerParameter("interestCompoundedEvery", requestMap, modifiedParameters); - Integer interestCompoundedEveryPeriodType = extractIntegerParameter("interestCompoundedEveryPeriodType", requestMap, modifiedParameters); - - boolean canRenew = extractBooleanParameter("renewalAllowed", requestMap, modifiedParameters); - boolean canPreClose = extractBooleanParameter("preClosureAllowed", requestMap, modifiedParameters); - BigDecimal preClosureInterestRate = extractBigDecimalParameter("preClosureInterestRate", requestMap, modifiedParameters); - - return new DepositProductCommand(modifiedParameters, resourceIdentifier, externalId, - name, description, currencyCode, digitsAfterDecimalValue, minimumBalance,maximumBalance, - tenureMonths, maturityDefaultInterestRate, maturityMinInterestRate, maturityMaxInterestRate, - interestCompoundedEvery, interestCompoundedEveryPeriodType, - canRenew, canPreClose, preClosureInterestRate); - } - - @Override - public DepositStateTransitionCommand convertJsonToDepositStateTransitionCommand( - Long resourceIdentifier, String json) { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( Arrays.asList("eventDate", "dateFormat")); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - LocalDate eventDate = extractLocalDateParameter("eventDate", requestMap, modifiedParameters); - - return new DepositStateTransitionCommand(resourceIdentifier, eventDate); - } - - @Override - public DepositStateTransitionApprovalCommand convertJsonToDepositStateTransitionApprovalCommand( - final Long resourceIdentifier, final String json) { - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet(Arrays.asList("locale","eventDate", "dateFormat", "tenureInMonths", "depositAmount", "interestCompoundedEveryPeriodType", "productId","interestCompoundedEvery")); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - LocalDate eventDate = extractLocalDateParameter("eventDate", requestMap, modifiedParameters); - BigDecimal depositAmount=extractBigDecimalParameter("depositAmount", requestMap, modifiedParameters); - Integer tenureInMonths = extractIntegerParameter("tenureInMonths", requestMap, modifiedParameters); - Integer interestCompoundedEveryPeriodType = extractIntegerParameter("interestCompoundedEveryPeriodType", requestMap, modifiedParameters); - Integer interestCompoundedEvery = extractIntegerParameter("interestCompoundedEvery", requestMap, modifiedParameters); - Long productId = extractLongParameter("productId", requestMap, modifiedParameters); - - return new DepositStateTransitionApprovalCommand(resourceIdentifier, productId, eventDate, tenureInMonths, depositAmount, interestCompoundedEveryPeriodType,interestCompoundedEvery); - } +package org.mifosng.platform.api.infrastructure; + +import java.lang.reflect.Type; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.StringUtils; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormat; +import org.mifosng.platform.api.commands.AdjustLoanTransactionCommand; +import org.mifosng.platform.api.commands.BranchMoneyTransferCommand; +import org.mifosng.platform.api.commands.ChargeCommand; +import org.mifosng.platform.api.commands.ClientCommand; +import org.mifosng.platform.api.commands.DepositAccountCommand; +import org.mifosng.platform.api.commands.DepositProductCommand; +import org.mifosng.platform.api.commands.DepositStateTransitionApprovalCommand; +import org.mifosng.platform.api.commands.DepositStateTransitionCommand; +import org.mifosng.platform.api.commands.FundCommand; +import org.mifosng.platform.api.commands.GroupCommand; +import org.mifosng.platform.api.commands.LoanChargeCommand; +import org.mifosng.platform.api.commands.LoanProductCommand; +import org.mifosng.platform.api.commands.LoanStateTransitionCommand; +import org.mifosng.platform.api.commands.LoanTransactionCommand; +import org.mifosng.platform.api.commands.NoteCommand; +import org.mifosng.platform.api.commands.OfficeCommand; +import org.mifosng.platform.api.commands.OrganisationCurrencyCommand; +import org.mifosng.platform.api.commands.RoleCommand; +import org.mifosng.platform.api.commands.SavingProductCommand; +import org.mifosng.platform.api.commands.StaffCommand; +import org.mifosng.platform.api.commands.SubmitLoanApplicationCommand; +import org.mifosng.platform.api.commands.UserCommand; +import org.mifosng.platform.api.data.ApiParameterError; +import org.mifosng.platform.api.errorhandling.InvalidJsonException; +import org.mifosng.platform.api.errorhandling.UnsupportedParameterException; +import org.mifosng.platform.exceptions.PlatformApiDataValidationException; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.format.number.NumberFormatter; +import org.springframework.stereotype.Service; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +@Service +public class ApiDataConversionServiceImpl implements ApiDataConversionService { + + private final Gson gsonConverter; + + public ApiDataConversionServiceImpl() { + gsonConverter = new Gson(); + } + + @Override + public ChargeCommand convertJsonToChargeCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + + Set supportedParams = new HashSet(Arrays.asList("name", "amount", "locale", "currencyCode", + "currencyOptions", "chargeAppliesTo", "chargeTimeType", + "chargeCalculationType", "chargeCalculationTypeOptions", "active" + )); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String name = extractStringParameter("name", requestMap, modifiedParameters); + BigDecimal amount = extractBigDecimalParameter("amount", requestMap, modifiedParameters); + String currencyCode = extractStringParameter("currencyCode", requestMap, modifiedParameters); + + Integer chargeTimeType = extractIntegerParameter("chargeTimeType", requestMap, modifiedParameters); + Integer chargeAppliesTo = extractIntegerParameter("chargeAppliesTo", requestMap, modifiedParameters); + Integer chargeCalculationType = extractIntegerParameter("chargeCalculationType", requestMap, modifiedParameters); + + boolean active = extractBooleanParameter("active", requestMap, modifiedParameters); + + return new ChargeCommand(modifiedParameters, resourceIdentifier, name, amount, + currencyCode, chargeTimeType, chargeAppliesTo, chargeCalculationType, active); + } + + @Override + public FundCommand convertJsonToFundCommand(final Long resourceIdentifier, final String json) { + + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + + Set supportedParams = new HashSet( + Arrays.asList("name", "externalId") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String name = extractStringParameter("name", requestMap, modifiedParameters); + String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); + + return new FundCommand(modifiedParameters, resourceIdentifier, name, externalId); + } + + @Override + public StaffCommand convertJsonToStaffCommand(Long resourceIdentifier, + String json) { + + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + + Set supportedParams = new HashSet( + Arrays.asList("firstname", "lastname") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String firstname = extractStringParameter("firstname", requestMap, modifiedParameters); + String lastname = extractStringParameter("lastname", requestMap, modifiedParameters); + + return new StaffCommand(modifiedParameters, resourceIdentifier, firstname, lastname); + } + + @Override + public OfficeCommand convertJsonToOfficeCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("name", "externalId", "parentId", "openingDate", "dateFormat") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String name = extractStringParameter("name", requestMap, modifiedParameters); + String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); + Long parentId = extractLongParameter("parentId", requestMap, modifiedParameters); + LocalDate openingLocalDate = extractLocalDateParameter("openingDate", requestMap, modifiedParameters); + + return new OfficeCommand(modifiedParameters, resourceIdentifier, name, externalId, parentId, openingLocalDate); + } + + @Override + public RoleCommand convertJsonToRoleCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("name", "description", "permissions") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + // check array + JsonParser parser = new JsonParser(); + + String[] permissionIds = null; + JsonElement element = parser.parse(json); + if (element.isJsonObject()) { + JsonObject object = element.getAsJsonObject(); + if (object.has("permissions")) { + modifiedParameters.add("permissions"); + JsonArray array = object.get("permissions").getAsJsonArray(); + permissionIds = new String[array.size()]; + for (int i=0; i>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("username", "firstname", "lastname", "password", "repeatPassword", "email", "officeId", "notSelectedRoles", "roles") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String username = extractStringParameter("username", requestMap, modifiedParameters); + String firstname = extractStringParameter("firstname", requestMap, modifiedParameters); + String lastname = extractStringParameter("lastname", requestMap, modifiedParameters); + String password = extractStringParameter("password", requestMap, modifiedParameters); + String repeatPassword = extractStringParameter("repeatPassword", requestMap, modifiedParameters); + String email = extractStringParameter("email", requestMap, modifiedParameters); + Long officeId = extractLongParameter("officeId", requestMap, modifiedParameters); + + // check array + JsonParser parser = new JsonParser(); + + String[] notSelectedRoles = null; + String[] roles = null; + JsonElement element = parser.parse(json); + if (element.isJsonObject()) { + JsonObject object = element.getAsJsonObject(); + if (object.has("notSelectedRoles")) { + modifiedParameters.add("notSelectedRoles"); + JsonArray array = object.get("notSelectedRoles").getAsJsonArray(); + notSelectedRoles = new String[array.size()]; + for (int i=0; i>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("fromOfficeId", "toOfficeId", "transactionDate", "currencyCode", "transactionAmount", "description", "locale", "dateFormat") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + Long fromOfficeId = extractLongParameter("fromOfficeId", requestMap, modifiedParameters); + Long toOfficeId = extractLongParameter("toOfficeId", requestMap, modifiedParameters); + LocalDate transactionLocalDate = extractLocalDateParameter("transactionDate", requestMap, modifiedParameters); + String currencyCode = extractStringParameter("currencyCode", requestMap, modifiedParameters); + BigDecimal transactionAmountValue = extractBigDecimalParameter("transactionAmount", requestMap, modifiedParameters); + String description = extractStringParameter("description", requestMap, modifiedParameters); + + return new BranchMoneyTransferCommand(modifiedParameters, fromOfficeId, toOfficeId, transactionLocalDate, currencyCode, transactionAmountValue, description); + } + + @Override + public ClientCommand convertJsonToClientCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("externalId", "firstname", "lastname", "clientOrBusinessName", "officeId", "joiningDate", "dateFormat") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); + Long officeId = extractLongParameter("officeId", requestMap, modifiedParameters); + LocalDate joiningDate = extractLocalDateParameter("joiningDate", requestMap, modifiedParameters); + String firstname = extractStringParameter("firstname", requestMap, modifiedParameters); + String lastname = extractStringParameter("lastname", requestMap, modifiedParameters); + String clientOrBusinessName = extractStringParameter("clientOrBusinessName", requestMap, modifiedParameters); + + return new ClientCommand(modifiedParameters, resourceIdentifier, externalId, firstname, lastname, clientOrBusinessName, officeId, joiningDate); + } + + @Override + public GroupCommand convertJsonToGroupCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("name", "externalId", "clientMembers") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); + String name = extractStringParameter("name", requestMap, modifiedParameters); + + // check array + JsonParser parser = new JsonParser(); + + String[] clientMembers = null; + JsonElement element = parser.parse(json); + if (element.isJsonObject()) { + JsonObject object = element.getAsJsonObject(); + if (object.has("clientMembers")) { + modifiedParameters.add("clientMembers"); + JsonArray array = object.get("clientMembers").getAsJsonArray(); + clientMembers = new String[array.size()]; + for (int i=0; i>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("name", "description", "fundId", "transactionProcessingStrategyId", "currencyCode", "digitsAfterDecimal", + "principal", "inArrearsTolerance", "interestRatePerPeriod", "repaymentEvery", "numberOfRepayments", + "repaymentFrequencyType", "interestRateFrequencyType", "amortizationType", "interestType", "interestCalculationPeriodType", + "charges", "locale") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String name = extractStringParameter("name", requestMap, modifiedParameters); + String description = extractStringParameter("description", requestMap, modifiedParameters); + Long fundId = extractLongParameter("fundId", requestMap, modifiedParameters); + Long transactionProcessingStrategyId = extractLongParameter("transactionProcessingStrategyId", requestMap, modifiedParameters); + String currencyCode = extractStringParameter("currencyCode", requestMap, modifiedParameters); + Integer digitsAfterDecimalValue = extractIntegerParameter("digitsAfterDecimal", requestMap, modifiedParameters); + BigDecimal principalValue = extractBigDecimalParameter("principal", requestMap, modifiedParameters); + BigDecimal inArrearsToleranceValue = extractBigDecimalParameter("inArrearsTolerance", requestMap, modifiedParameters); + BigDecimal interestRatePerPeriodValue = extractBigDecimalParameter("interestRatePerPeriod", requestMap, modifiedParameters); + + Integer repaymentEveryValue = extractIntegerParameter("repaymentEvery", requestMap, modifiedParameters); + Integer numberOfRepaymentsValue = extractIntegerParameter("numberOfRepayments", requestMap, modifiedParameters); + Integer repaymentFrequencyTypeValue = extractIntegerParameter("repaymentFrequencyType", requestMap, modifiedParameters); + + Integer interestRateFrequencyTypeValue = extractIntegerParameter("interestRateFrequencyType", requestMap, modifiedParameters); + Integer amortizationTypeValue = extractIntegerParameter("amortizationType", requestMap, modifiedParameters); + Integer interestTypeValue = extractIntegerParameter("interestType", requestMap, modifiedParameters); + Integer interestCalculationPeriodTypeValue = extractIntegerParameter("interestCalculationPeriodType", requestMap, modifiedParameters); + + // check array + JsonParser parser = new JsonParser(); + + String[] charges = null; + JsonElement element = parser.parse(json); + if (element.isJsonObject()) { + JsonObject object = element.getAsJsonObject(); + if (object.has("charges")) { + modifiedParameters.add("charges"); + JsonArray array = object.get("charges").getAsJsonArray(); + charges = new String[array.size()]; + for (int i=0; i>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("clientId", "productId", "externalId", "fundId", "transactionProcessingStrategyId", + "principal", "inArrearsTolerance", "interestRatePerPeriod", "repaymentEvery", "numberOfRepayments", + "loanTermFrequency", "loanTermFrequencyType", "charges", + "repaymentFrequencyType", "interestRateFrequencyType", "amortizationType", "interestType", "interestCalculationPeriodType", + "expectedDisbursementDate", "repaymentsStartingFromDate", "interestChargedFromDate", "submittedOnDate", "submittedOnNote", + "locale", "dateFormat") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + Long clientId = extractLongParameter("clientId", requestMap, modifiedParameters); + Long productId = extractLongParameter("productId", requestMap, modifiedParameters); + Long fundId = extractLongParameter("fundId", requestMap, modifiedParameters); + Long transactionProcessingStrategyId = extractLongParameter("transactionProcessingStrategyId", requestMap, modifiedParameters); + String externalId = extractStringParameter("externalId", requestMap, modifiedParameters); + + BigDecimal principal = extractBigDecimalParameter("principal", requestMap, modifiedParameters); + BigDecimal inArrearsToleranceValue = extractBigDecimalParameter("inArrearsTolerance", requestMap, modifiedParameters); + BigDecimal interestRatePerPeriod = extractBigDecimalParameter("interestRatePerPeriod", requestMap, modifiedParameters); + + Integer repaymentEvery = extractIntegerParameter("repaymentEvery", requestMap, modifiedParameters); + Integer numberOfRepayments = extractIntegerParameter("numberOfRepayments", requestMap, modifiedParameters); + Integer repaymentFrequencyType = extractIntegerParameter("repaymentFrequencyType", requestMap, modifiedParameters); + + Integer loanTermFrequency = extractIntegerParameter("loanTermFrequency", requestMap, modifiedParameters); + Integer loanTermFrequencyType = extractIntegerParameter("loanTermFrequencyType", requestMap, modifiedParameters); + + Integer interestRateFrequencyTypeValue = extractIntegerParameter("interestRateFrequencyType", requestMap, modifiedParameters); + Integer amortizationTypeValue = extractIntegerParameter("amortizationType", requestMap, modifiedParameters); + Integer interestTypeValue = extractIntegerParameter("interestType", requestMap, modifiedParameters); + Integer interestCalculationPeriodTypeValue = extractIntegerParameter("interestCalculationPeriodType", requestMap, modifiedParameters); + + LocalDate expectedDisbursementDate = extractLocalDateParameter("expectedDisbursementDate", requestMap, modifiedParameters); + LocalDate repaymentsStartingFromDate = extractLocalDateParameter("repaymentsStartingFromDate", requestMap, modifiedParameters); + LocalDate interestChargedFromDate = extractLocalDateParameter("interestChargedFromDate", requestMap, modifiedParameters); + LocalDate submittedOnDate = extractLocalDateParameter("submittedOnDate", requestMap, modifiedParameters); + + String submittedOnNote = extractStringParameter("submittedOnNote", requestMap, modifiedParameters); + + JsonParser parser = new JsonParser(); + + LoanChargeCommand[] charges = null; + JsonElement element = parser.parse(json); + if (element.isJsonObject()) { + JsonObject object = element.getAsJsonObject(); + if (object.has("charges") && object.get("charges").isJsonArray()) { + modifiedParameters.add("charges"); + JsonArray array = object.get("charges").getAsJsonArray(); + charges = new LoanChargeCommand[array.size()]; + for (int i=0; i chargeModifiedParameters = new HashSet(); + Long id = loanCharge.get("id").getAsLong(); + BigDecimal amount = null; + Integer chargeTimeType = null; + Integer chargeCalculationType = null; + + if (loanCharge.has("amount")){ + chargeModifiedParameters.add("amount"); + amount = loanCharge.get("amount").getAsBigDecimal(); + } + if (loanCharge.has("chargeTimeType")){ + chargeModifiedParameters.add("chargeTimeType"); + chargeTimeType = loanCharge.get("chargeTimeType").getAsInt(); + } + if (loanCharge.has("chargeCalculationType")){ + chargeModifiedParameters.add("chargeCalculationType"); + chargeCalculationType = loanCharge.get("chargeCalculationType").getAsInt(); + } + charges[i] = new LoanChargeCommand(chargeModifiedParameters, id, amount, chargeTimeType, chargeCalculationType); + } + } + } + + return new SubmitLoanApplicationCommand(clientId, productId, externalId, fundId, transactionProcessingStrategyId, + submittedOnDate, submittedOnNote, + expectedDisbursementDate, repaymentsStartingFromDate, interestChargedFromDate, + principal, interestRatePerPeriod, interestRateFrequencyTypeValue, interestTypeValue, interestCalculationPeriodTypeValue, + repaymentEvery, repaymentFrequencyType, numberOfRepayments, amortizationTypeValue, + loanTermFrequency, loanTermFrequencyType, + inArrearsToleranceValue, charges); + } + + @Override + public LoanStateTransitionCommand convertJsonToLoanStateTransitionCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("eventDate", "note", "dateFormat") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + LocalDate eventDate = extractLocalDateParameter("eventDate", requestMap, modifiedParameters); + String note = extractStringParameter("note", requestMap, modifiedParameters); + + return new LoanStateTransitionCommand(resourceIdentifier, eventDate, note); + } + + @Override + public LoanTransactionCommand convertJsonToLoanTransactionCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("transactionDate", "transactionAmount", "note", "dateFormat", "locale") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + LocalDate transactionDate = extractLocalDateParameter("transactionDate", requestMap, modifiedParameters); + BigDecimal transactionAmount = extractBigDecimalParameter("transactionAmount", requestMap, modifiedParameters); + String note = extractStringParameter("note", requestMap, modifiedParameters); + + return new LoanTransactionCommand(resourceIdentifier, transactionDate, transactionAmount, note); + } + + @Override + public AdjustLoanTransactionCommand convertJsonToAdjustLoanTransactionCommand( + final Long loanId, final Long transactionId, final String json) { + + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("transactionDate", "transactionAmount", "note", "dateFormat", "locale") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + LocalDate transactionDate = extractLocalDateParameter("transactionDate", requestMap, modifiedParameters); + BigDecimal transactionAmount = extractBigDecimalParameter("transactionAmount", requestMap, modifiedParameters); + String note = extractStringParameter("note", requestMap, modifiedParameters); + + return new AdjustLoanTransactionCommand(loanId, transactionId, transactionDate, note, transactionAmount); + } + + @Override + public NoteCommand convertJsonToNoteCommand(final Long noteId, final Long clientId, final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("note") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String note = extractStringParameter("note", requestMap, modifiedParameters); + + return new NoteCommand(noteId, clientId, note); + } + + @Override + public OrganisationCurrencyCommand convertJsonToOrganisationCurrencyCommand(final String json) { + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("currencies") + ); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + // check array + JsonParser parser = new JsonParser(); + + String[] currencies = null; + JsonElement element = parser.parse(json); + if (element.isJsonObject()) { + JsonObject object = element.getAsJsonObject(); + if (object.has("currencies")) { + modifiedParameters.add("currencies"); + JsonArray array = object.get("currencies").getAsJsonArray(); + currencies = new String[array.size()]; + for (int i=0; i requestMap, Set supportedParams) { + List unsupportedParameterList = new ArrayList(); + for (String providedParameter : requestMap.keySet()) { + if (!supportedParams.contains(providedParameter)) { + unsupportedParameterList.add(providedParameter); + } + } + + if (!unsupportedParameterList.isEmpty()) { + throw new UnsupportedParameterException(unsupportedParameterList); + } + } + + private String extractStringParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { + String paramValue = null; + if (requestMap.containsKey(paramName)) { + paramValue = (String) requestMap.get(paramName); + modifiedParameters.add(paramName); + } + + if (paramValue != null) { + paramValue = paramValue.trim(); + } + + return paramValue; + } + + private Integer extractIntegerParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { + Integer paramValue = null; + if (requestMap.containsKey(paramName)) { + String valueAsString = (String) requestMap.get(paramName); + paramValue = convertToInteger(valueAsString, paramName, extractLocaleValue(requestMap)); + modifiedParameters.add(paramName); + } + return paramValue; + } + + private BigDecimal extractBigDecimalParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { + BigDecimal paramValue = null; + if (requestMap.containsKey(paramName)) { + String valueAsString = (String) requestMap.get(paramName); + paramValue = convertFrom(valueAsString, paramName, extractLocaleValue(requestMap)); + modifiedParameters.add(paramName); + } + return paramValue; + } + + private boolean extractBooleanParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { + boolean paramValue = false; + String paramValueAsString = null; + if (requestMap.containsKey(paramName)) { + paramValueAsString = (String) requestMap.get(paramName); + + if (paramValueAsString != null) { + paramValueAsString = paramValueAsString.trim(); + } + + paramValue = Boolean.valueOf(paramValueAsString); + modifiedParameters.add(paramName); + } + return paramValue; + } + + private Long extractLongParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { + Long paramValue = null; + if (requestMap.containsKey(paramName)) { + String valueAsString = (String) requestMap.get(paramName); + if (StringUtils.isNotBlank(valueAsString)) { + paramValue = Long.valueOf(Double.valueOf(valueAsString).longValue()); + } + modifiedParameters.add(paramName); + } + return paramValue; + } + + private LocalDate extractLocalDateParameter(final String paramName, final Map requestMap, final Set modifiedParameters) { + LocalDate paramValue = null; + if (requestMap.containsKey(paramName)) { + String valueAsString = (String) requestMap.get(paramName); + if (StringUtils.isNotBlank(valueAsString)) { + final String dateFormat = (String) requestMap.get("dateFormat"); + paramValue = convertFrom(valueAsString, paramName, dateFormat); + } + modifiedParameters.add(paramName); + } + return paramValue; + } + + private Locale extractLocaleValue(Map requestMap) { + Locale clientApplicationLocale = null; + String locale = null; + if (requestMap.containsKey("locale")) { + locale = (String) requestMap.get("locale"); + clientApplicationLocale = localeFromString(locale); + } + return clientApplicationLocale; + } + + private LocalDate convertFrom(final String dateAsString, final String parameterName, final String dateFormat) { + + if (StringUtils.isBlank(dateFormat)) { + + List dataValidationErrors = new ArrayList(); + String defaultMessage = new StringBuilder("The parameter '" + parameterName + "' requires a 'dateFormat' parameter to be passed with it.").toString(); + ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.dateFormat.parameter", defaultMessage, parameterName); + dataValidationErrors.add(error); + + throw new PlatformApiDataValidationException( + "validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); + } + + LocalDate eventLocalDate = null; + if (StringUtils.isNotBlank(dateAsString)) { + try { + Locale locale = LocaleContextHolder.getLocale(); + eventLocalDate = DateTimeFormat.forPattern(dateFormat) + .withLocale(locale) + .parseLocalDate(dateAsString.toLowerCase(locale)); + } catch (IllegalArgumentException e) { + List dataValidationErrors = new ArrayList(); + ApiParameterError error = ApiParameterError + .parameterError( + "validation.msg.invalid.date.format", + "The parameter " + + parameterName + + " is invalid based on the dateFormat provided:" + + dateFormat, parameterName, + dateAsString, dateFormat); + dataValidationErrors.add(error); + + throw new PlatformApiDataValidationException( + "validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); + } + } + + return eventLocalDate; + } + + private Integer convertToInteger(final String numericalValueFormatted, final String parameterName, final Locale clientApplicationLocale) { + + if (clientApplicationLocale == null) { + + List dataValidationErrors = new ArrayList(); + String defaultMessage = new StringBuilder("The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.").toString(); + ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); + dataValidationErrors.add(error); + + throw new PlatformApiDataValidationException( + "validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); + } + + try { + Integer number = null; + + if (StringUtils.isNotBlank(numericalValueFormatted)) { + + String source = numericalValueFormatted.trim(); + + NumberFormat format = NumberFormat.getInstance(clientApplicationLocale); + DecimalFormat df = (DecimalFormat) format; + DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); + df.setParseBigDecimal(true); + + // http://bugs.sun.com/view_bug.do?bug_id=4510618 + char groupingSeparator = symbols.getGroupingSeparator(); + if (groupingSeparator == '\u00a0') { + source = source.replaceAll(" ", Character.toString('\u00a0')); + } + + Number parsedNumber = df.parse(source); + + double parsedNumberDouble = parsedNumber.doubleValue(); + int parsedNumberInteger = parsedNumber.intValue(); + + if (source.contains(Character.toString(symbols.getDecimalSeparator()))) { + throw new ParseException(source, 0); + } + + if (!Double.valueOf(parsedNumberDouble).equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) { + throw new ParseException(source, 0); + } + + number = parsedNumber.intValue(); + } + + return number; + } catch (ParseException e) { + + List dataValidationErrors = new ArrayList(); + ApiParameterError error = ApiParameterError.parameterError( + "validation.msg.invalid.integer.format", "The parameter " + + parameterName + " has value: " + numericalValueFormatted + " which is invalid integer value for provided locale of [" + + clientApplicationLocale.toString() + "].", + parameterName, numericalValueFormatted, + clientApplicationLocale); + dataValidationErrors.add(error); + + throw new PlatformApiDataValidationException( + "validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); + } + } + + private BigDecimal convertFrom(final String numericalValueFormatted, final String parameterName, final Locale clientApplicationLocale) { + + if (clientApplicationLocale == null) { + + List dataValidationErrors = new ArrayList(); + String defaultMessage = new StringBuilder("The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.").toString(); + ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); + dataValidationErrors.add(error); + + throw new PlatformApiDataValidationException( + "validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); + } + + try { + BigDecimal number = null; + + if (StringUtils.isNotBlank(numericalValueFormatted)) { + + String source = numericalValueFormatted.trim(); + + NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale); + DecimalFormat df = (DecimalFormat) format; + DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); + // http://bugs.sun.com/view_bug.do?bug_id=4510618 + char groupingSeparator = symbols.getGroupingSeparator(); + if (groupingSeparator == '\u00a0') { + source = source.replaceAll(" ", Character.toString('\u00a0')); + } + + NumberFormatter numberFormatter = new NumberFormatter(); + Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale); + number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue())); + } + + return number; + } catch (ParseException e) { + + List dataValidationErrors = new ArrayList(); + ApiParameterError error = ApiParameterError.parameterError( + "validation.msg.invalid.decimal.format", "The parameter " + + parameterName + " has value: " + numericalValueFormatted + " which is invalid decimal value for provided locale of [" + + clientApplicationLocale.toString() + "].", + parameterName, numericalValueFormatted, + clientApplicationLocale); + dataValidationErrors.add(error); + + throw new PlatformApiDataValidationException( + "validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); + } + } + + private Locale localeFromString(final String localeAsString) { + + if (StringUtils.isBlank(localeAsString)) { + List dataValidationErrors = new ArrayList(); + ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", "The parameter locale is invalid. It cannot be blank.", "locale"); + dataValidationErrors.add(error); + + throw new PlatformApiDataValidationException( + "validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); + } + + String languageCode = ""; + String courntryCode = ""; + String variantCode = ""; + + String[] localeParts = localeAsString.split("_"); + + if (localeParts != null && localeParts.length == 1) { + languageCode = localeParts[0]; + } + + if (localeParts != null && localeParts.length == 2) { + languageCode = localeParts[0]; + courntryCode = localeParts[1]; + } + + if (localeParts != null && localeParts.length == 3) { + languageCode = localeParts[0]; + courntryCode = localeParts[1]; + variantCode = localeParts[2]; + } + + return localeFrom(languageCode, courntryCode, variantCode); + } + + private Locale localeFrom(final String languageCode, final String courntryCode, final String variantCode) { + + List dataValidationErrors = new ArrayList(); + + List allowedLanguages = Arrays.asList(Locale.getISOLanguages()); + if (!allowedLanguages.contains(languageCode.toLowerCase())) { + ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", "The parameter locale has an invalid language value " + languageCode + " .", "locale", languageCode); + dataValidationErrors.add(error); + } + + if (StringUtils.isNotBlank(courntryCode.toUpperCase())) { + List allowedCountries = Arrays.asList(Locale.getISOCountries()); + if (!allowedCountries.contains(courntryCode)) { + ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", "The parameter locale has an invalid country value " + courntryCode + " .", "locale", courntryCode); + dataValidationErrors.add(error); + } + } + + if (!dataValidationErrors.isEmpty()) { + throw new PlatformApiDataValidationException( + "validation.msg.validation.errors.exist", + "Validation errors exist.", dataValidationErrors); + } + + return new Locale(languageCode.toLowerCase(), courntryCode.toUpperCase(), variantCode); + } + + @Override + public SavingProductCommand convertJsonToSavingProductCommand(final Long resourceIdentifier, final String json) { + + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + Type typeOfMap = new TypeToken>() {}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet(Arrays.asList("name","description","currencyCode", "digitsAfterDecimal","interestRate","locale","minimumBalance","maximumBalance")); + checkForUnsupportedParameters(requestMap, supportedParams); + Set modifiedParameters = new HashSet(); + String name = extractStringParameter("name", requestMap,modifiedParameters); + String description = extractStringParameter("description", requestMap,modifiedParameters); + String currencyCode=extractStringParameter("currencyCode", requestMap,modifiedParameters); + Integer digitsAfterDecimalValue = extractIntegerParameter("digitsAfterDecimal", requestMap, modifiedParameters); + BigDecimal interestRate = extractBigDecimalParameter("interestRate", requestMap, modifiedParameters); + BigDecimal minimumBalance=extractBigDecimalParameter("minimumBalance", requestMap, modifiedParameters); + BigDecimal maximumBalance=extractBigDecimalParameter("maximumBalance", requestMap, modifiedParameters); + + + return new SavingProductCommand(modifiedParameters, resourceIdentifier,name, description,currencyCode,digitsAfterDecimalValue,interestRate,minimumBalance,maximumBalance); + } + + @Override + public DepositAccountCommand convertJsonToDepositAccountCommand(final Long resourceIdentifier, final String json) { + + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>() {}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + // preClosureInterestRate + Set supportedParams = new HashSet( + Arrays.asList("clientId", "productId", "externalId", "depositAmount", "maturityInterestRate", + "tenureInMonths", "interestCompoundedEvery", "interestCompoundedEveryPeriodType", "commencementDate", + "renewalAllowed", "preClosureAllowed", + "locale", "dateFormat") + ); + checkForUnsupportedParameters(requestMap, supportedParams); + Set modifiedParameters = new HashSet(); + + Long clientId = extractLongParameter("clientId", requestMap, modifiedParameters); + Long productId = extractLongParameter("productId", requestMap, modifiedParameters); + String externalId = extractStringParameter("externalId", requestMap,modifiedParameters); + BigDecimal depositAmount=extractBigDecimalParameter("depositAmount", requestMap, modifiedParameters); + BigDecimal interestRate = extractBigDecimalParameter("maturityInterestRate", requestMap, modifiedParameters); + Integer tenureInMonths = extractIntegerParameter("tenureInMonths", requestMap, modifiedParameters); + + Integer interestCompoundedEvery = extractIntegerParameter("interestCompoundedEvery", requestMap, modifiedParameters); + Integer interestCompoundedEveryPeriodType = extractIntegerParameter("interestCompoundedEveryPeriodType", requestMap, modifiedParameters); + LocalDate commencementDate = extractLocalDateParameter("commencementDate", requestMap, modifiedParameters); + + boolean renewalAllowed = extractBooleanParameter("renewalAllowed", requestMap, modifiedParameters); + boolean preClosureAllowed = extractBooleanParameter("preClosureAllowed", requestMap, modifiedParameters); + + return new DepositAccountCommand(modifiedParameters, resourceIdentifier, clientId, productId, + externalId, depositAmount, interestRate, tenureInMonths, + interestCompoundedEvery, interestCompoundedEveryPeriodType, commencementDate, renewalAllowed, preClosureAllowed); + } + + @Override + public DepositProductCommand convertJsonToDepositProductCommand(final Long resourceIdentifier, final String json) { + + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>() {}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( + Arrays.asList("locale", "name", "externalId", "description","currencyCode", "digitsAfterDecimal","minimumBalance","maximumBalance","tenureInMonths", + "maturityDefaultInterestRate","maturityMinInterestRate","maturityMaxInterestRate", + "interestCompoundedEvery", "interestCompoundedEveryPeriodType", + "renewalAllowed","preClosureAllowed","preClosureInterestRate") + ); + checkForUnsupportedParameters(requestMap, supportedParams); + Set modifiedParameters = new HashSet(); + String name = extractStringParameter("name", requestMap,modifiedParameters); + String externalId = extractStringParameter("externalId", requestMap,modifiedParameters); + + String description = extractStringParameter("description", requestMap,modifiedParameters); + String currencyCode=extractStringParameter("currencyCode", requestMap,modifiedParameters); + Integer digitsAfterDecimalValue = extractIntegerParameter("digitsAfterDecimal", requestMap, modifiedParameters); + BigDecimal minimumBalance=extractBigDecimalParameter("minimumBalance", requestMap, modifiedParameters); + BigDecimal maximumBalance=extractBigDecimalParameter("maximumBalance", requestMap, modifiedParameters); + + Integer tenureMonths = extractIntegerParameter("tenureInMonths", requestMap, modifiedParameters); + BigDecimal maturityDefaultInterestRate = extractBigDecimalParameter("maturityDefaultInterestRate", requestMap, modifiedParameters); + BigDecimal maturityMinInterestRate = extractBigDecimalParameter("maturityMinInterestRate", requestMap, modifiedParameters); + BigDecimal maturityMaxInterestRate = extractBigDecimalParameter("maturityMaxInterestRate", requestMap, modifiedParameters); + + Integer interestCompoundedEvery = extractIntegerParameter("interestCompoundedEvery", requestMap, modifiedParameters); + Integer interestCompoundedEveryPeriodType = extractIntegerParameter("interestCompoundedEveryPeriodType", requestMap, modifiedParameters); + + boolean canRenew = extractBooleanParameter("renewalAllowed", requestMap, modifiedParameters); + boolean canPreClose = extractBooleanParameter("preClosureAllowed", requestMap, modifiedParameters); + BigDecimal preClosureInterestRate = extractBigDecimalParameter("preClosureInterestRate", requestMap, modifiedParameters); + + return new DepositProductCommand(modifiedParameters, resourceIdentifier, externalId, + name, description, currencyCode, digitsAfterDecimalValue, minimumBalance,maximumBalance, + tenureMonths, maturityDefaultInterestRate, maturityMinInterestRate, maturityMaxInterestRate, + interestCompoundedEvery, interestCompoundedEveryPeriodType, + canRenew, canPreClose, preClosureInterestRate); + } + + @Override + public DepositStateTransitionCommand convertJsonToDepositStateTransitionCommand( + Long resourceIdentifier, String json) { + + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet( Arrays.asList("eventDate", "dateFormat")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + LocalDate eventDate = extractLocalDateParameter("eventDate", requestMap, modifiedParameters); + + return new DepositStateTransitionCommand(resourceIdentifier, eventDate); + } + + @Override + public DepositStateTransitionApprovalCommand convertJsonToDepositStateTransitionApprovalCommand( + final Long resourceIdentifier, final String json) { + + if (StringUtils.isBlank(json)) { + throw new InvalidJsonException(); + } + + Type typeOfMap = new TypeToken>(){}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + Set supportedParams = new HashSet(Arrays.asList("locale","eventDate", "dateFormat", "tenureInMonths", "depositAmount", "interestCompoundedEveryPeriodType", "productId","interestCompoundedEvery")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + LocalDate eventDate = extractLocalDateParameter("eventDate", requestMap, modifiedParameters); + BigDecimal depositAmount=extractBigDecimalParameter("depositAmount", requestMap, modifiedParameters); + Integer tenureInMonths = extractIntegerParameter("tenureInMonths", requestMap, modifiedParameters); + Integer interestCompoundedEveryPeriodType = extractIntegerParameter("interestCompoundedEveryPeriodType", requestMap, modifiedParameters); + Integer interestCompoundedEvery = extractIntegerParameter("interestCompoundedEvery", requestMap, modifiedParameters); + Long productId = extractLongParameter("productId", requestMap, modifiedParameters); + + return new DepositStateTransitionApprovalCommand(resourceIdentifier, productId, eventDate, tenureInMonths, depositAmount, interestCompoundedEveryPeriodType,interestCompoundedEvery); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonApiJsonSerializerService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonApiJsonSerializerService.java index f7da8a9d3..2abfe8e7e 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonApiJsonSerializerService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonApiJsonSerializerService.java @@ -1,562 +1,562 @@ -package org.mifosng.platform.api.infrastructure; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import org.mifosng.platform.api.data.AdditionalFieldsSetData; -import org.mifosng.platform.api.data.AppUserData; -import org.mifosng.platform.api.data.AuthenticatedUserData; -import org.mifosng.platform.api.data.ChargeData; -import org.mifosng.platform.api.data.ClientData; -import org.mifosng.platform.api.data.ClientAccountSummaryCollectionData; -import org.mifosng.platform.api.data.ConfigurationData; -import org.mifosng.platform.api.data.DepositAccountData; -import org.mifosng.platform.api.data.DepositProductData; -import org.mifosng.platform.api.data.FundData; -import org.mifosng.platform.api.data.GenericResultsetData; -import org.mifosng.platform.api.data.GroupData; -import org.mifosng.platform.api.data.LoanAccountData; -import org.mifosng.platform.api.data.LoanProductData; -import org.mifosng.platform.api.data.LoanTransactionData; -import org.mifosng.platform.api.data.NewLoanData; -import org.mifosng.platform.api.data.NoteData; -import org.mifosng.platform.api.data.OfficeData; -import org.mifosng.platform.api.data.OfficeTransactionData; -import org.mifosng.platform.api.data.PermissionData; -import org.mifosng.platform.api.data.RoleData; -import org.mifosng.platform.api.data.SavingProductData; -import org.mifosng.platform.api.data.StaffData; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.google.gson.Gson; - -/** - * Implementation of {@link ApiJsonSerializerService} that uses google-gson to - * serialize Java object representation into JSON. - */ -@Service -public class GoogleGsonApiJsonSerializerService implements - ApiJsonSerializerService { - - private static final Set PERMISSION_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "description", "code")); - private static final Set ROLE_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "description", "availablePermissions", - "selectedPermissions")); - private static final Set APP_USER_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "officeId", "officeName", "username", - "firstname", "lastname", "email", "allowedOffices", - "availableRoles", "selectedRoles")); - private static final Set OFFICE_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "nameDecorated", "externalId", - "openingDate", "hierarchy", "parentId", "parentName", - "allowedParents")); - private static final Set OFFICE_TRANSACTIONS_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "transactionDate", "fromOfficeId", - "fromOfficeName", "toOfficeId", "toOfficeIdName", - "currencyCode", "digitsAfterDecimal", "transactionAmount", - "description", "allowedOffices", "currencyOptions")); - private static final Set CONFIGURATION_DATA_PARAMETERS = new HashSet( - Arrays.asList("selectedCurrencyOptions", "currencyOptions")); - private static final Set FUND_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "externalId")); - private static final Set STAFF_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "firstname", "lastname","displayName")); - private static final Set LOAN_PRODUCT_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "description", "fundId", "fundName", - "transactionProcessingStrategyId", - "transactionProcessingStrategyName", "principal", - "inArrearsTolerance", "numberOfRepayments", - "repaymentEvery", "interestRatePerPeriod", - "annualInterestRate", "repaymentFrequencyType", - "interestRateFrequencyType", "amortizationType", - "interestType", "interestCalculationPeriodType", - "charges", - "createdOn", "lastModifedOn", "currencyOptions", - "amortizationTypeOptions", "interestTypeOptions", - "interestCalculationPeriodTypeOptions", - "repaymentFrequencyTypeOptions", - "interestRateFrequencyTypeOptions", "fundOptions", - "transactionProcessingStrategyOptions", "chargeOptions")); - - private static final Set SAVINGS_PRODUCT_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "description", "createdOn", - "lastModifedOn", "interestRate", "currencyCode", - "digitsAfterDecimal", "currencyOptions", "minimumBalance", - "maximumBalance")); - - private static final Set SAVINGS_DEPOSIT_PRODUCT_DATA_PARAMETERS = new HashSet( - Arrays.asList("currencyOptions", - "interestCompoundedEveryPeriodTypeOptions", "id", - "externalId", "name", "description", "createdOn", - "lastModifedOn", "currencyCode", "digitsAfterDecimal", - "minimumBalance", "maximumBalance", "tenureInMonths", - "maturityDefaultInterestRate", "maturityMinInterestRate", - "maturityMaxInterestRate", "interestCompoundedEvery", - "interestCompoundedEveryPeriodType", "renewalAllowed", - "preClosureAllowed", "preClosureInterestRate")); - - private static final Set SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS = new HashSet( - Arrays.asList("productOptions", "interestCompoundedEveryPeriodTypeOptions", - "id", "externalId", "clientId", "clientName", "productId", "productName", "status", - "currency", "deposit", "maturityInterestRate", "tenureInMonths", - "interestCompoundedEvery", "interestCompoundedEveryPeriodType", - "renewalAllowed","preClosureAllowed","preClosureInterestRate", - "withdrawnonDate","rejectedonDate","closedonDate" - ) - ); - - private static final Set CLIENT_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "officeId", "officeName", "externalId", - "firstname", "lastname", "joinedDate", "displayName", - "clientOrBusinessName", "allowedOffices")); - - private static final Set CLIENT_ACCOUNTS_DATA_PARAMETERS = new HashSet( - Arrays.asList("pendingApprovalLoans", "awaitingDisbursalLoans", - "openLoans", "closedLoans", "anyLoanCount", - "pendingApprovalLoanCount", "awaitingDisbursalLoanCount", - "activeLoanCount", "closedLoanCount", - "pendingApprovalDespositAccountsCount", - "pendingApprovalDespositAccounts", - "approvedDespositAccountsCount", "approvedDespositAccounts")); - - private static final Set GROUP_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "externalId", "clientMembers", - "allowedClients")); - - private static final Set NOTE_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "clientId", "loanId", "loanTransactionId", - "noteType", "note", "createdById", "createdByUsername", - "createdOn", "updatedById", "updatedByUsername", - "updatedOn")); - - private static final Set NEW_LOAN_DATA_PARAMETERS = new HashSet( - Arrays.asList("clientId", "clientName", "productId", "productName", - "selectedProduct", "expectedDisbursementDate", - "allowedProducts")); - - private static final Set LOAN_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "externalId", "clientId", "clientName", "fundId", "fundName", - "loanProductId", "loanProductName", "loanProductDescription", - "currency", "principal", - "inArrearsTolerance", "numberOfRepayments", - "repaymentEvery", "interestRatePerPeriod", - "annualInterestRate", "repaymentFrequencyType", - "interestRateFrequencyType", "amortizationType", - "interestType", "interestCalculationPeriodType", - "submittedOnDate", "approvedOnDate", - "expectedDisbursementDate", "actualDisbursementDate", - "expectedFirstRepaymentOnDate", "interestChargedFromDate", - "closedOnDate", "expectedMaturityDate", - "status", - "lifeCycleStatusDate", "summary", "repaymentSchedule", - "loanRepayments", "permissions", "convenienceData", "charges", - "productOptions", "amortizationTypeOptions", "interestTypeOptions", "interestCalculationPeriodTypeOptions", - "repaymentFrequencyTypeOptions", "interestRateFrequencyTypeOptions", "fundOptions", "transactionProcessingStrategyOptions", "chargeOptions")); - - private static final Set LOAN_TRANSACTION_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "transactionType", "date", "principal", - "interest", "total", "totalWaived", "overpaid")); - - private static final Set CHARGES_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "amount", "currency", "active", - "chargeAppliesTo", "chargeTimeType", - "chargeCalculationType", "chargeCalculationTypeOptions", - "chargeAppliesToOptions", "chargeTimeTypeOptions", "currencyOptions")); - - private final GoogleGsonSerializerHelper helper; - - @Autowired - public GoogleGsonApiJsonSerializerService( - final GoogleGsonSerializerHelper helper) { - this.helper = helper; - } - - @Override - public String serializeAuthenticatedUserDataToJson( - final boolean prettyPrint, - final AuthenticatedUserData authenticatedUserData) { - final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); - return helper.serializedJsonFrom(gsonDeserializer, - authenticatedUserData); - } - - @Override - public String serializeGenericResultsetDataToJson( - final boolean prettyPrint, final GenericResultsetData resultsetData) { - final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); - return helper.serializedJsonFrom(gsonDeserializer, resultsetData); - } - - @Override - public String serializeAdditionalFieldsSetDataToJson( - final boolean prettyPrint, - final Collection datasets) { - final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); - return helper.serializedJsonFrom(gsonDeserializer, - datasets.toArray(new AdditionalFieldsSetData[datasets.size()])); - } - - @Override - public String serializePermissionDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection permissions) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - PERMISSION_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - permissions.toArray(new PermissionData[permissions.size()])); - } - - @Override - public String serializeRoleDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection roles) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - ROLE_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - roles.toArray(new RoleData[roles.size()])); - } - - @Override - public String serializeRoleDataToJson(final boolean prettyPrint, - final Set responseParameters, final RoleData role) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - ROLE_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, role); - } - - @Override - public String serializeAppUserDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection users) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - APP_USER_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - users.toArray(new AppUserData[users.size()])); - } - - @Override - public String serializeAppUserDataToJson(final boolean prettyPrint, - final Set responseParameters, final AppUserData user) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - APP_USER_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, user); - } - - @Override - public String serializeOfficeDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection offices) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - OFFICE_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - offices.toArray(new OfficeData[offices.size()])); - } - - @Override - public String serializeOfficeDataToJson(final boolean prettyPrint, - final Set responseParameters, final OfficeData office) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - OFFICE_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, office); - } - - @Override - public String serializeOfficeTransactionDataToJson( - final boolean prettyPrint, final Set responseParameters, - final Collection officeTransactions) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - OFFICE_TRANSACTIONS_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, officeTransactions); - } - - @Override - public String serializeOfficeTransactionDataToJson( - final boolean prettyPrint, final Set responseParameters, - final OfficeTransactionData officeTransaction) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - OFFICE_TRANSACTIONS_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, officeTransaction); - } - - @Override - public String serializeConfigurationDataToJson(final boolean prettyPrint, - final Set responseParameters, - final ConfigurationData configuration) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CONFIGURATION_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, configuration); - } - - @Override - public String serializeFundDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection funds) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - FUND_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - funds.toArray(new FundData[funds.size()])); - } - - @Override - public String serializeFundDataToJson(final boolean prettyPrint, - final Set responseParameters, final FundData fund) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - FUND_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, fund); - } - - @Override - public String serializeLoanProductDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection products) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - LOAN_PRODUCT_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - products.toArray(new LoanProductData[products.size()])); - } - - @Override - public String serializeLoanProductDataToJson(final boolean prettyPrint, - final Set responseParameters, final LoanProductData product) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - LOAN_PRODUCT_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, product); - } - - @Override - public String serializeSavingProductDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection products) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - SAVINGS_PRODUCT_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - products.toArray(new SavingProductData[products.size()])); - } - - @Override - public String serializeSavingProductDataToJson(final boolean prettyPrint, - final Set responseParameters, - final SavingProductData savingProduct) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - SAVINGS_PRODUCT_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, savingProduct); - } - - @Override - public String serializeDepositProductDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection products) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - SAVINGS_DEPOSIT_PRODUCT_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - products.toArray(new DepositProductData[products.size()])); - } - - @Override - public String serializeDepositProductDataToJson(final boolean prettyPrint, - final Set responseParameters, - final DepositProductData depositProduct) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - SAVINGS_DEPOSIT_PRODUCT_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, depositProduct); - } - - @Override - public String serializeDepositAccountDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection accounts) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - accounts.toArray(new DepositAccountData[accounts.size()])); - } - - @Override - public String serializeDepositAccountDataToJson(final boolean prettyPrint, - final Set responseParameters, - final DepositAccountData account) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, account); - } - - @Override - public String serializeClientDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection clients) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CLIENT_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - clients.toArray(new ClientData[clients.size()])); - } - - @Override - public String serializeClientDataToJson(final boolean prettyPrint, - final Set responseParameters, final ClientData client) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CLIENT_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, client); - } - - @Override - public String serializeClientAccountSummaryCollectionDataToJson( - final boolean prettyPrint, final Set responseParameters, - final ClientAccountSummaryCollectionData clientAccount) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CLIENT_ACCOUNTS_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, clientAccount); - } - - @Override - public String serializeGroupDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection groups) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - GROUP_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - groups.toArray(new GroupData[groups.size()])); - } - - @Override - public String serializeGroupDataToJson(final boolean prettyPrint, - final Set responseParameters, final GroupData group) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - GROUP_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, group); - } - - @Override - public String serializeNoteDataToJson(boolean prettyPrint, - Set responseParameters, Collection notes) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - NOTE_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - notes.toArray(new NoteData[notes.size()])); - } - - @Override - public String serializeNoteDataToJson(final boolean prettyPrint, - final Set responseParameters, final NoteData note) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - NOTE_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, note); - } - - @Override - public String serializeNewLoanDataToJson(final boolean prettyPrint, - final Set responseParameters, final NewLoanData newLoan) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - NEW_LOAN_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, newLoan); - } - - @Override - public String serialzieLoanAccountDataToJson(final boolean prettyPrint, - final Set responseParameters, - final LoanAccountData loanAccount) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - LOAN_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, loanAccount); - } - - @Override - public String serializeLoanTransactionDataToJson(final boolean prettyPrint, - final Set responseParameters, - final LoanTransactionData transaction) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - LOAN_TRANSACTION_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, transaction); - } - - @Override - public String serializeChargeDataToJson(final boolean prettyPrint, - final Set responseParameters, - final Collection charges) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CHARGES_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - charges.toArray(new ChargeData[charges.size()])); - } - - @Override - public String serializeChargeDataToJson(final boolean prettyPrint, - final Set responseParameters, final ChargeData charge) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CHARGES_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, charge); - } - - @Override - public String serializeStaffDataToJson(boolean prettyPrint, - Set responseParameters, StaffData staff) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - STAFF_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, staff); - } - - @Override - public String serializeStaffDataToJson(boolean prettyPrint, - Set responseParameters, Collection staff) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - STAFF_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - staff.toArray(new StaffData[staff.size()])); - } +package org.mifosng.platform.api.infrastructure; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.mifosng.platform.api.data.AdditionalFieldsSetData; +import org.mifosng.platform.api.data.AppUserData; +import org.mifosng.platform.api.data.AuthenticatedUserData; +import org.mifosng.platform.api.data.ChargeData; +import org.mifosng.platform.api.data.ClientData; +import org.mifosng.platform.api.data.ClientAccountSummaryCollectionData; +import org.mifosng.platform.api.data.ConfigurationData; +import org.mifosng.platform.api.data.DepositAccountData; +import org.mifosng.platform.api.data.DepositProductData; +import org.mifosng.platform.api.data.FundData; +import org.mifosng.platform.api.data.GenericResultsetData; +import org.mifosng.platform.api.data.GroupData; +import org.mifosng.platform.api.data.LoanAccountData; +import org.mifosng.platform.api.data.LoanProductData; +import org.mifosng.platform.api.data.LoanTransactionData; +import org.mifosng.platform.api.data.NewLoanData; +import org.mifosng.platform.api.data.NoteData; +import org.mifosng.platform.api.data.OfficeData; +import org.mifosng.platform.api.data.OfficeTransactionData; +import org.mifosng.platform.api.data.PermissionData; +import org.mifosng.platform.api.data.RoleData; +import org.mifosng.platform.api.data.SavingProductData; +import org.mifosng.platform.api.data.StaffData; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.google.gson.Gson; + +/** + * Implementation of {@link ApiJsonSerializerService} that uses google-gson to + * serialize Java object representation into JSON. + */ +@Service +public class GoogleGsonApiJsonSerializerService implements + ApiJsonSerializerService { + + private static final Set PERMISSION_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "name", "description", "code")); + private static final Set ROLE_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "name", "description", "availablePermissions", + "selectedPermissions")); + private static final Set APP_USER_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "officeId", "officeName", "username", + "firstname", "lastname", "email", "allowedOffices", + "availableRoles", "selectedRoles")); + private static final Set OFFICE_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "name", "nameDecorated", "externalId", + "openingDate", "hierarchy", "parentId", "parentName", + "allowedParents")); + private static final Set OFFICE_TRANSACTIONS_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "transactionDate", "fromOfficeId", + "fromOfficeName", "toOfficeId", "toOfficeIdName", + "currencyCode", "digitsAfterDecimal", "transactionAmount", + "description", "allowedOffices", "currencyOptions")); + private static final Set CONFIGURATION_DATA_PARAMETERS = new HashSet( + Arrays.asList("selectedCurrencyOptions", "currencyOptions")); + private static final Set FUND_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "name", "externalId")); + private static final Set STAFF_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "firstname", "lastname","displayName")); + private static final Set LOAN_PRODUCT_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "name", "description", "fundId", "fundName", + "transactionProcessingStrategyId", + "transactionProcessingStrategyName", "principal", + "inArrearsTolerance", "numberOfRepayments", + "repaymentEvery", "interestRatePerPeriod", + "annualInterestRate", "repaymentFrequencyType", + "interestRateFrequencyType", "amortizationType", + "interestType", "interestCalculationPeriodType", + "charges", + "createdOn", "lastModifedOn", "currencyOptions", + "amortizationTypeOptions", "interestTypeOptions", + "interestCalculationPeriodTypeOptions", + "repaymentFrequencyTypeOptions", + "interestRateFrequencyTypeOptions", "fundOptions", + "transactionProcessingStrategyOptions", "chargeOptions")); + + private static final Set SAVINGS_PRODUCT_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "name", "description", "createdOn", + "lastModifedOn", "interestRate", "currencyCode", + "digitsAfterDecimal", "currencyOptions", "minimumBalance", + "maximumBalance")); + + private static final Set SAVINGS_DEPOSIT_PRODUCT_DATA_PARAMETERS = new HashSet( + Arrays.asList("currencyOptions", + "interestCompoundedEveryPeriodTypeOptions", "id", + "externalId", "name", "description", "createdOn", + "lastModifedOn", "currencyCode", "digitsAfterDecimal", + "minimumBalance", "maximumBalance", "tenureInMonths", + "maturityDefaultInterestRate", "maturityMinInterestRate", + "maturityMaxInterestRate", "interestCompoundedEvery", + "interestCompoundedEveryPeriodType", "renewalAllowed", + "preClosureAllowed", "preClosureInterestRate")); + + private static final Set SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS = new HashSet( + Arrays.asList("productOptions", "interestCompoundedEveryPeriodTypeOptions", + "id", "externalId", "clientId", "clientName", "productId", "productName", "status", + "currency", "deposit", "maturityInterestRate", "tenureInMonths", + "interestCompoundedEvery", "interestCompoundedEveryPeriodType", + "renewalAllowed","preClosureAllowed","preClosureInterestRate", + "withdrawnonDate","rejectedonDate","closedonDate" + ) + ); + + private static final Set CLIENT_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "officeId", "officeName", "externalId", + "firstname", "lastname", "joinedDate", "displayName", + "clientOrBusinessName", "allowedOffices")); + + private static final Set CLIENT_ACCOUNTS_DATA_PARAMETERS = new HashSet( + Arrays.asList("pendingApprovalLoans", "awaitingDisbursalLoans", + "openLoans", "closedLoans", "anyLoanCount", + "pendingApprovalLoanCount", "awaitingDisbursalLoanCount", + "activeLoanCount", "closedLoanCount", + "pendingApprovalDespositAccountsCount", + "pendingApprovalDespositAccounts", + "approvedDespositAccountsCount", "approvedDespositAccounts")); + + private static final Set GROUP_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "name", "externalId", "clientMembers", + "allowedClients")); + + private static final Set NOTE_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "clientId", "loanId", "loanTransactionId", + "noteType", "note", "createdById", "createdByUsername", + "createdOn", "updatedById", "updatedByUsername", + "updatedOn")); + + private static final Set NEW_LOAN_DATA_PARAMETERS = new HashSet( + Arrays.asList("clientId", "clientName", "productId", "productName", + "selectedProduct", "expectedDisbursementDate", + "allowedProducts")); + + private static final Set LOAN_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "externalId", "clientId", "clientName", "fundId", "fundName", + "loanProductId", "loanProductName", "loanProductDescription", + "currency", "principal", + "inArrearsTolerance", "numberOfRepayments", + "repaymentEvery", "interestRatePerPeriod", + "annualInterestRate", "repaymentFrequencyType", + "interestRateFrequencyType", "amortizationType", + "interestType", "interestCalculationPeriodType", + "submittedOnDate", "approvedOnDate", + "expectedDisbursementDate", "actualDisbursementDate", + "expectedFirstRepaymentOnDate", "interestChargedFromDate", + "closedOnDate", "expectedMaturityDate", + "status", + "lifeCycleStatusDate", "summary", "repaymentSchedule", + "loanRepayments", "permissions", "convenienceData", "charges", + "productOptions", "amortizationTypeOptions", "interestTypeOptions", "interestCalculationPeriodTypeOptions", + "repaymentFrequencyTypeOptions", "interestRateFrequencyTypeOptions", "fundOptions", "transactionProcessingStrategyOptions", "chargeOptions")); + + private static final Set LOAN_TRANSACTION_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "transactionType", "date", "principal", + "interest", "total", "totalWaived", "overpaid")); + + private static final Set CHARGES_DATA_PARAMETERS = new HashSet( + Arrays.asList("id", "name", "amount", "currency", "active", + "chargeAppliesTo", "chargeTimeType", + "chargeCalculationType", "chargeCalculationTypeOptions", + "chargeAppliesToOptions", "chargeTimeTypeOptions", "currencyOptions")); + + private final GoogleGsonSerializerHelper helper; + + @Autowired + public GoogleGsonApiJsonSerializerService( + final GoogleGsonSerializerHelper helper) { + this.helper = helper; + } + + @Override + public String serializeAuthenticatedUserDataToJson( + final boolean prettyPrint, + final AuthenticatedUserData authenticatedUserData) { + final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); + return helper.serializedJsonFrom(gsonDeserializer, + authenticatedUserData); + } + + @Override + public String serializeGenericResultsetDataToJson( + final boolean prettyPrint, final GenericResultsetData resultsetData) { + final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); + return helper.serializedJsonFrom(gsonDeserializer, resultsetData); + } + + @Override + public String serializeAdditionalFieldsSetDataToJson( + final boolean prettyPrint, + final Collection datasets) { + final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); + return helper.serializedJsonFrom(gsonDeserializer, + datasets.toArray(new AdditionalFieldsSetData[datasets.size()])); + } + + @Override + public String serializePermissionDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection permissions) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + PERMISSION_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + permissions.toArray(new PermissionData[permissions.size()])); + } + + @Override + public String serializeRoleDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection roles) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + ROLE_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + roles.toArray(new RoleData[roles.size()])); + } + + @Override + public String serializeRoleDataToJson(final boolean prettyPrint, + final Set responseParameters, final RoleData role) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + ROLE_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, role); + } + + @Override + public String serializeAppUserDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection users) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + APP_USER_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + users.toArray(new AppUserData[users.size()])); + } + + @Override + public String serializeAppUserDataToJson(final boolean prettyPrint, + final Set responseParameters, final AppUserData user) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + APP_USER_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, user); + } + + @Override + public String serializeOfficeDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection offices) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + OFFICE_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + offices.toArray(new OfficeData[offices.size()])); + } + + @Override + public String serializeOfficeDataToJson(final boolean prettyPrint, + final Set responseParameters, final OfficeData office) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + OFFICE_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, office); + } + + @Override + public String serializeOfficeTransactionDataToJson( + final boolean prettyPrint, final Set responseParameters, + final Collection officeTransactions) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + OFFICE_TRANSACTIONS_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, officeTransactions); + } + + @Override + public String serializeOfficeTransactionDataToJson( + final boolean prettyPrint, final Set responseParameters, + final OfficeTransactionData officeTransaction) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + OFFICE_TRANSACTIONS_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, officeTransaction); + } + + @Override + public String serializeConfigurationDataToJson(final boolean prettyPrint, + final Set responseParameters, + final ConfigurationData configuration) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + CONFIGURATION_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, configuration); + } + + @Override + public String serializeFundDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection funds) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + FUND_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + funds.toArray(new FundData[funds.size()])); + } + + @Override + public String serializeFundDataToJson(final boolean prettyPrint, + final Set responseParameters, final FundData fund) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + FUND_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, fund); + } + + @Override + public String serializeLoanProductDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection products) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + LOAN_PRODUCT_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + products.toArray(new LoanProductData[products.size()])); + } + + @Override + public String serializeLoanProductDataToJson(final boolean prettyPrint, + final Set responseParameters, final LoanProductData product) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + LOAN_PRODUCT_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, product); + } + + @Override + public String serializeSavingProductDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection products) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + SAVINGS_PRODUCT_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + products.toArray(new SavingProductData[products.size()])); + } + + @Override + public String serializeSavingProductDataToJson(final boolean prettyPrint, + final Set responseParameters, + final SavingProductData savingProduct) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + SAVINGS_PRODUCT_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, savingProduct); + } + + @Override + public String serializeDepositProductDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection products) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + SAVINGS_DEPOSIT_PRODUCT_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + products.toArray(new DepositProductData[products.size()])); + } + + @Override + public String serializeDepositProductDataToJson(final boolean prettyPrint, + final Set responseParameters, + final DepositProductData depositProduct) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + SAVINGS_DEPOSIT_PRODUCT_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, depositProduct); + } + + @Override + public String serializeDepositAccountDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection accounts) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + accounts.toArray(new DepositAccountData[accounts.size()])); + } + + @Override + public String serializeDepositAccountDataToJson(final boolean prettyPrint, + final Set responseParameters, + final DepositAccountData account) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + SAVINGS_DEPOSIT_ACCOUNT_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, account); + } + + @Override + public String serializeClientDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection clients) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + CLIENT_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + clients.toArray(new ClientData[clients.size()])); + } + + @Override + public String serializeClientDataToJson(final boolean prettyPrint, + final Set responseParameters, final ClientData client) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + CLIENT_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, client); + } + + @Override + public String serializeClientAccountSummaryCollectionDataToJson( + final boolean prettyPrint, final Set responseParameters, + final ClientAccountSummaryCollectionData clientAccount) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + CLIENT_ACCOUNTS_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, clientAccount); + } + + @Override + public String serializeGroupDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection groups) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + GROUP_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + groups.toArray(new GroupData[groups.size()])); + } + + @Override + public String serializeGroupDataToJson(final boolean prettyPrint, + final Set responseParameters, final GroupData group) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + GROUP_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, group); + } + + @Override + public String serializeNoteDataToJson(boolean prettyPrint, + Set responseParameters, Collection notes) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + NOTE_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + notes.toArray(new NoteData[notes.size()])); + } + + @Override + public String serializeNoteDataToJson(final boolean prettyPrint, + final Set responseParameters, final NoteData note) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + NOTE_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, note); + } + + @Override + public String serializeNewLoanDataToJson(final boolean prettyPrint, + final Set responseParameters, final NewLoanData newLoan) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + NEW_LOAN_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, newLoan); + } + + @Override + public String serialzieLoanAccountDataToJson(final boolean prettyPrint, + final Set responseParameters, + final LoanAccountData loanAccount) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + LOAN_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, loanAccount); + } + + @Override + public String serializeLoanTransactionDataToJson(final boolean prettyPrint, + final Set responseParameters, + final LoanTransactionData transaction) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + LOAN_TRANSACTION_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, transaction); + } + + @Override + public String serializeChargeDataToJson(final boolean prettyPrint, + final Set responseParameters, + final Collection charges) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + CHARGES_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + charges.toArray(new ChargeData[charges.size()])); + } + + @Override + public String serializeChargeDataToJson(final boolean prettyPrint, + final Set responseParameters, final ChargeData charge) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + CHARGES_DATA_PARAMETERS, prettyPrint, + responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, charge); + } + + @Override + public String serializeStaffDataToJson(boolean prettyPrint, + Set responseParameters, StaffData staff) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + STAFF_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, staff); + } + + @Override + public String serializeStaffDataToJson(boolean prettyPrint, + Set responseParameters, Collection staff) { + final Gson gsonDeserializer = helper + .createGsonBuilderWithParameterExclusionSerializationStrategy( + STAFF_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, + staff.toArray(new StaffData[staff.size()])); + } } \ No newline at end of file