From 9aa9b870f0975b522a0d4ec401392dc497dda9a5 Mon Sep 17 00:00:00 2001 From: Keith Woodlock Date: Wed, 21 Nov 2012 14:22:47 +0000 Subject: [PATCH] MIFOSX-97: refactor into command handling logic, prepare for sql based approach for change detection. --- .../api/infrastructure/ApiConstants.java | 8 +- ...GsonPortfolioApiJsonSerializerService.java | 1181 +++---- .../PortfolioApiDataConversionService.java | 85 +- ...PortfolioApiDataConversionServiceImpl.java | 2958 ++++++++--------- .../PortfolioApiJsonSerializerService.java | 147 +- .../service/ClientWritePlatformService.java | 58 +- ...WritePlatformServiceJpaRepositoryImpl.java | 584 ++-- .../UnsupportedCommandException.java | 19 + .../UnsupportedCommandExceptionMapper.java | 42 + .../makerchecker/domain/CommandSource.java | 175 +- .../service/ChangeDetectionService.java | 7 + .../service/ChangeDetectionServiceJdbc.java | 48 + .../service/ClientCommandHandler.java | 113 + .../service/CommandSourceHandler.java | 5 + .../CommandSourceHandlerDelegator.java | 48 + ...ortfolioCommandSourceWriteServiceImpl.java | 173 +- 16 files changed, 2731 insertions(+), 2920 deletions(-) create mode 100644 mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/errorhandling/UnsupportedCommandException.java create mode 100644 mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/errorhandling/UnsupportedCommandExceptionMapper.java create mode 100644 mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ChangeDetectionService.java create mode 100644 mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ChangeDetectionServiceJdbc.java create mode 100644 mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ClientCommandHandler.java create mode 100644 mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/CommandSourceHandler.java create mode 100644 mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/CommandSourceHandlerDelegator.java diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/ApiConstants.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/ApiConstants.java index e13f2b0a8..d5085d6d9 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/ApiConstants.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/ApiConstants.java @@ -2,9 +2,9 @@ package org.mifosng.platform.api.infrastructure; public class ApiConstants { - // TODO:Vishwas Need to move these settings to the Database - public static final Integer MAX_FILE_UPLOAD_SIZE_IN_MB = 5; + // TODO:Vishwas Need to move these settings to the Database + public static final Integer MAX_FILE_UPLOAD_SIZE_IN_MB = 5; - // TODO:Vishwas Need to move these settings to the Database - public static final Integer MAX_IMAGE_UPLOAD_SIZE_IN_MB = 1; + // TODO:Vishwas Need to move these settings to the Database + public static final Integer MAX_IMAGE_UPLOAD_SIZE_IN_MB = 1; } diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonPortfolioApiJsonSerializerService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonPortfolioApiJsonSerializerService.java index 1184ca1fa..b0dfbc2d4 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonPortfolioApiJsonSerializerService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/GoogleGsonPortfolioApiJsonSerializerService.java @@ -48,749 +48,540 @@ import org.springframework.stereotype.Service; import com.google.gson.Gson; /** - * Implementation of {@link PortfolioApiJsonSerializerService} that uses google-gson to - * serialize Java object representation into JSON. + * Implementation of {@link PortfolioApiJsonSerializerService} that uses + * google-gson to serialize Java object representation into JSON. */ @Service public class GoogleGsonPortfolioApiJsonSerializerService implements PortfolioApiJsonSerializerService { - 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 ROLE_PERMISSION_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "description", "permissionUsageData")); - 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", "officeId", "officeName", - "loanOfficerFlag","allowedOffices")); - 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 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 ROLE_PERMISSION_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "name", "description", + "permissionUsageData")); + 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", "officeId", "officeName", "loanOfficerFlag", "allowedOffices")); + 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("currencyOptions", "id", "createdOn", "lastModifedOn", - "locale", "name", "description","currencyCode", "digitsAfterDecimal","interstRate", "minInterestRate","maxInterestRate", - "savingsDepositAmount","savingProductType","tenureType","tenure", "frequency","interestType","interestCalculationMethod", - "minimumBalanceForWithdrawal","isPartialDepositAllowed","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType", - "currencyOptions", "savingsProductTypeOptions", "tenureTypeOptions", "savingFrequencyOptions", "savingsInterestTypeOptions", - "lockinPeriodTypeOptions", "interestCalculationOptions")); + private static final Set SAVINGS_PRODUCT_DATA_PARAMETERS = new HashSet(Arrays.asList("currencyOptions", "id", + "createdOn", "lastModifedOn", "locale", "name", "description", "currencyCode", "digitsAfterDecimal", "interstRate", + "minInterestRate", "maxInterestRate", "savingsDepositAmount", "savingProductType", "tenureType", "tenure", "frequency", + "interestType", "interestCalculationMethod", "minimumBalanceForWithdrawal", "isPartialDepositAllowed", "isLockinPeriodAllowed", + "lockinPeriod", "lockinPeriodType", "currencyOptions", "savingsProductTypeOptions", "tenureTypeOptions", + "savingFrequencyOptions", "savingsInterestTypeOptions", "lockinPeriodTypeOptions", "interestCalculationOptions")); - 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", "interestCompoundingAllowed", - "isLockinPeriodAllowed","lockinPeriod","lockinPeriodType")); + 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", "interestCompoundingAllowed", "isLockinPeriodAllowed", + "lockinPeriod", "lockinPeriodType")); - 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","transactions", - "permissions","isInterestWithdrawable","interestPaid","interestCompoundingAllowed", - "availableInterestForWithdrawal","availableWithdrawalAmount","todaysDate", - "isLockinPeriodAllowed","lockinPeriod","lockinPeriodType") - ); - - private static final Set CLIENT_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "officeId", "officeName", "externalId", - "firstname", "lastname", "joinedDate", "displayName", - "clientOrBusinessName", "allowedOffices", "imagePresent")); - - private static final Set CLIENT_IDENTIFIER_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "clientId", "documentTypeId", "documentKey", - "description", "documentTypeName" ,"allowedDocumentTypes")); - - private static final Set DOCUMENT_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "parentEntityType", "parentEntityId", "name", - "fileName", "type", "size", "description")); + 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", "transactions", "permissions", "isInterestWithdrawable", "interestPaid", + "interestCompoundingAllowed", "availableInterestForWithdrawal", "availableWithdrawalAmount", "todaysDate", + "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType")); - 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", - "withdrawnByClientDespositAccountsCount","withdrawnByClientDespositAccounts", - "closedDepositAccountsCount","closedDepositAccounts", - "rejectedDepositAccountsCount","rejectedDepositAccounts", - "preclosedDepositAccountsCount","preclosedDepositAccounts")); + private static final Set CLIENT_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "officeId", "officeName", + "externalId", "firstname", "lastname", "joinedDate", "displayName", "clientOrBusinessName", "allowedOffices", "imagePresent")); - private static final Set GROUP_ACCOUNTS_DATA_PARAMETERS = new HashSet( - Arrays.asList("pendingApprovalLoans", "awaitingDisbursalLoans", - "openLoans", "closedLoans", "anyLoanCount", - "pendingApprovalLoanCount", "awaitingDisbursalLoanCount", - "activeLoanCount", "closedLoanCount")); + private static final Set CLIENT_IDENTIFIER_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "clientId", + "documentTypeId", "documentKey", "description", "documentTypeName", "allowedDocumentTypes")); - private static final Set GROUP_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "officeId", "name", "externalId", "clientMembers", - "allowedClients", "allowedOffices")); + private static final Set DOCUMENT_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "parentEntityType", + "parentEntityId", "name", "fileName", "type", "size", "description")); - 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 CLIENT_ACCOUNTS_DATA_PARAMETERS = new HashSet(Arrays.asList("pendingApprovalLoans", + "awaitingDisbursalLoans", "openLoans", "closedLoans", "anyLoanCount", "pendingApprovalLoanCount", "awaitingDisbursalLoanCount", + "activeLoanCount", "closedLoanCount", "pendingApprovalDespositAccountsCount", "pendingApprovalDespositAccounts", + "approvedDespositAccountsCount", "approvedDespositAccounts", "withdrawnByClientDespositAccountsCount", + "withdrawnByClientDespositAccounts", "closedDepositAccountsCount", "closedDepositAccounts", "rejectedDepositAccountsCount", + "rejectedDepositAccounts", "preclosedDepositAccountsCount", "preclosedDepositAccounts")); - private static final Set LOAN_SCHEDULE_DATA_PARAMETERS = new HashSet( - Arrays.asList("periods", "cumulativePrincipalDisbursed")); - - private static final Set LOAN_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "externalId", "clientId","groupId", "clientName", "groupName", "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", "repaymentSchedule", - "transactions", "permissions", "convenienceData", "charges", - "productOptions", "amortizationTypeOptions", "interestTypeOptions", "interestCalculationPeriodTypeOptions", - "repaymentFrequencyTypeOptions", "interestRateFrequencyTypeOptions", "fundOptions", "repaymentStrategyOptions", "chargeOptions", - "loanOfficerId", "loanOfficerName", "loanOfficerOptions", "chargeTemplate")); + private static final Set GROUP_ACCOUNTS_DATA_PARAMETERS = new HashSet(Arrays.asList("pendingApprovalLoans", + "awaitingDisbursalLoans", "openLoans", "closedLoans", "anyLoanCount", "pendingApprovalLoanCount", "awaitingDisbursalLoanCount", + "activeLoanCount", "closedLoanCount")); - private static final Set LOAN_TRANSACTION_NEW_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "type", "date", "currency", "amount")); + private static final Set GROUP_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "officeId", "name", "externalId", + "clientMembers", "allowedClients", "allowedOffices")); - private static final Set LOAN_REASSIGNMENT_DATA_PARAMETERS = new HashSet( - Arrays.asList("officeId", "fromLoanOfficerId", "assignmentDate", - "officeOptions", "loanOfficerOptions", "accountSummaryCollection") - ); + 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 CHARGES_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "name", "amount", "currency", "penalty", "active", - "chargeAppliesTo", "chargeTimeType", - "chargeCalculationType", "chargeCalculationTypeOptions", - "chargeAppliesToOptions", "chargeTimeTypeOptions", "currencyOptions")); + private static final Set LOAN_SCHEDULE_DATA_PARAMETERS = new HashSet(Arrays.asList("periods", + "cumulativePrincipalDisbursed")); - private static final Set LOAN_CHARGES_DATA_PARAMETERS = new HashSet( - Arrays.asList("chargeOptions")); - - private static final Set CODE_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "codename")); - - private static final Set MAKER_CHECKER_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "taskName", "madeOnDate")); - - private static final Set SAVINGS_ACCOUNTS_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "status", "externalId", "clientId", "clientName", "productId", "productName", "productType", "currencyData", "savingsDepostiAmountPerPeriod", "savingsFrequencyType", - "totalDepositAmount", "reccuringInterestRate", "savingInterestRate", "interestType", "interestCalculationMethod", "tenure", "tenureType", "projectedCommencementDate", - "actualCommencementDate", "maturesOnDate", "projectedInterestAccuredOnMaturity", "actualInterestAccured", "projectedMaturityAmount", "actualMaturityAmount", "preClosureAllowed", - "preClosureInterestRate", "withdrawnonDate", "rejectedonDate", "closedonDate", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType")); + private static final Set LOAN_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "externalId", "clientId", "groupId", + "clientName", "groupName", "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", "repaymentSchedule", + "transactions", "permissions", "convenienceData", "charges", "productOptions", "amortizationTypeOptions", + "interestTypeOptions", "interestCalculationPeriodTypeOptions", "repaymentFrequencyTypeOptions", + "interestRateFrequencyTypeOptions", "fundOptions", "repaymentStrategyOptions", "chargeOptions", "loanOfficerId", + "loanOfficerName", "loanOfficerOptions", "chargeTemplate")); - // accounting - private static final Set CHART_OF_ACCOUNTS_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "name")); - - private final GoogleGsonSerializerHelper helper; + private static final Set LOAN_TRANSACTION_NEW_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "type", "date", + "currency", "amount")); - @Autowired - public GoogleGsonPortfolioApiJsonSerializerService( - final GoogleGsonSerializerHelper helper) { - this.helper = helper; - } + private static final Set LOAN_REASSIGNMENT_DATA_PARAMETERS = new HashSet(Arrays.asList("officeId", "fromLoanOfficerId", + "assignmentDate", "officeOptions", "loanOfficerOptions", "accountSummaryCollection")); - @Override - public String serializeAuthenticatedUserDataToJson( - final boolean prettyPrint, - final AuthenticatedUserData authenticatedUserData) { - final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); - return helper.serializedJsonFrom(gsonDeserializer, - authenticatedUserData); - } + private static final Set CHARGES_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "name", "amount", "currency", + "penalty", "active", "chargeAppliesTo", "chargeTimeType", "chargeCalculationType", "chargeCalculationTypeOptions", + "chargeAppliesToOptions", "chargeTimeTypeOptions", "currencyOptions")); - @Override - public String serializeGenericResultsetDataToJson( - final boolean prettyPrint, final GenericResultsetData resultsetData) { - final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); - return helper.serializedJsonFrom(gsonDeserializer, resultsetData); - } + private static final Set LOAN_CHARGES_DATA_PARAMETERS = new HashSet(Arrays.asList("chargeOptions")); - @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 serializeDatatableDataToJson( - final boolean prettyPrint, - final Collection datatables) { - final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); - return helper.serializedJsonFrom(gsonDeserializer, - datatables.toArray(new DatatableData[datatables.size()])); - } + private static final Set CODE_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "codename")); - @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()])); - } + private static final Set MAKER_CHECKER_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "taskName", "madeOnDate")); - @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()])); - } + private static final Set SAVINGS_ACCOUNTS_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "status", "externalId", + "clientId", "clientName", "productId", "productName", "productType", "currencyData", "savingsDepostiAmountPerPeriod", + "savingsFrequencyType", "totalDepositAmount", "reccuringInterestRate", "savingInterestRate", "interestType", + "interestCalculationMethod", "tenure", "tenureType", "projectedCommencementDate", "actualCommencementDate", "maturesOnDate", + "projectedInterestAccuredOnMaturity", "actualInterestAccured", "projectedMaturityAmount", "actualMaturityAmount", + "preClosureAllowed", "preClosureInterestRate", "withdrawnonDate", "rejectedonDate", "closedonDate", "isLockinPeriodAllowed", + "lockinPeriod", "lockinPeriodType")); - @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); - } + // accounting + private static final Set CHART_OF_ACCOUNTS_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "name")); - @Override - public String serializeRolePermissionDataToJson(final boolean prettyPrint, - final Set responseParameters, - final RolePermissionData rolePermissionData) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - ROLE_PERMISSION_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, rolePermissionData); - } + private final GoogleGsonSerializerHelper helper; - @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 serializeClientCommandToJson(final ClientCommand command) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy(new HashSet(), false, new HashSet()); - return helper.serializedJsonFrom(gsonDeserializer, command); - } - - @Override - public String serializeClientDataToJson(final ClientData client) { - return serializeClientDataToJson(false, new HashSet(), client); - } - - @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 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 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); - } + @Autowired + public GoogleGsonPortfolioApiJsonSerializerService(final GoogleGsonSerializerHelper helper) { + this.helper = helper; + } @Override - public String serializeGroupAccountSummaryCollectionDataToJson( - final boolean prettyPrint, final Set responseParameters, + 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 serializeDatatableDataToJson(final boolean prettyPrint, final Collection datatables) { + final Gson gsonDeserializer = helper.createGsonBuilder(prettyPrint); + return helper.serializedJsonFrom(gsonDeserializer, datatables.toArray(new DatatableData[datatables.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 serializeRolePermissionDataToJson(final boolean prettyPrint, final Set responseParameters, + final RolePermissionData rolePermissionData) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(ROLE_PERMISSION_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, rolePermissionData); + } + + @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 serializeClientCommandToJson(final ClientCommand command) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(new HashSet(), false, + new HashSet()); + return helper.serializedJsonFrom(gsonDeserializer, command); + } + + @Override + public String serializeClientDataToJson(final ClientData client) { + return serializeClientDataToJson(false, new HashSet(), client); + } + + @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 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 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 serializeGroupAccountSummaryCollectionDataToJson(final boolean prettyPrint, final Set responseParameters, final GroupAccountSummaryCollectionData groupAccount) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - GROUP_ACCOUNTS_DATA_PARAMETERS, prettyPrint, - responseParameters); + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(GROUP_ACCOUNTS_DATA_PARAMETERS, + prettyPrint, responseParameters); return helper.serializedJsonFrom(gsonDeserializer, groupAccount); } - @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 serializeLoanScheduleDataToJson(final boolean prettyPrint, final Set responseParameters, final LoanScheduleData loanSchedule) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy(LOAN_SCHEDULE_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, loanSchedule); - } - - @Override - public String serializeLoanAccountDataToJson(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_NEW_DATA_PARAMETERS, prettyPrint, - responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, transaction); - } + @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 serializeLoanReassignmentDataToJson(boolean prettyPrint, - Set responseParameters, - LoanReassignmentData loanReassignmentData) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - LOAN_REASSIGNMENT_DATA_PARAMETERS, prettyPrint, - responseParameters); + 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 serializeLoanScheduleDataToJson(final boolean prettyPrint, final Set responseParameters, + final LoanScheduleData loanSchedule) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(LOAN_SCHEDULE_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, loanSchedule); + } + + @Override + public String serializeLoanAccountDataToJson(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_NEW_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, transaction); + } + + @Override + public String serializeLoanReassignmentDataToJson(boolean prettyPrint, Set responseParameters, + LoanReassignmentData loanReassignmentData) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy( + LOAN_REASSIGNMENT_DATA_PARAMETERS, prettyPrint, responseParameters); return helper.serializedJsonFrom(gsonDeserializer, loanReassignmentData); - } - - @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 serializeLoanChargeDataToJson(boolean prettyPrint, Set responseParameters, LoanChargeData charge) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - LOAN_CHARGES_DATA_PARAMETERS, prettyPrint, - responseParameters); + 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); - } + public String serializeLoanChargeDataToJson(boolean prettyPrint, Set responseParameters, LoanChargeData charge) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(LOAN_CHARGES_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, charge); + } - @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()])); - } + @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 serializeEntityIdentifier(final EntityIdentifier identifier) { - final Set DATA_PARAMETERS = new HashSet(Arrays.asList("entityId")); - final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(DATA_PARAMETERS, false, DATA_PARAMETERS); - return helper.serializedJsonFrom(gsonDeserializer, identifier); - } + @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()])); + } - @Override - public String serializeClientIdentifierDataToJson(boolean prettyPrint, - Set responseParameters, - Collection clientIdentifiers) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CLIENT_IDENTIFIER_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - clientIdentifiers.toArray(new ClientIdentifierData[clientIdentifiers.size()])); - } + @Override + public String serializeEntityIdentifier(final EntityIdentifier identifier) { + final Set DATA_PARAMETERS = new HashSet(Arrays.asList("entityId")); + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(DATA_PARAMETERS, false, + DATA_PARAMETERS); + return helper.serializedJsonFrom(gsonDeserializer, identifier); + } - @Override - public String serializeClientIdentifierDataToJson(boolean prettyPrint, - Set responseParameters, - ClientIdentifierData clientIdentifierData) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CLIENT_IDENTIFIER_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, clientIdentifierData); - } - - @Override - public String serializeDocumentDataToJson(boolean prettyPrint, - Set responseParameters, - Collection documentDatas) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - DOCUMENT_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - documentDatas.toArray(new DocumentData[documentDatas.size()])); - } + @Override + public String serializeClientIdentifierDataToJson(boolean prettyPrint, Set responseParameters, + Collection clientIdentifiers) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy( + CLIENT_IDENTIFIER_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, clientIdentifiers.toArray(new ClientIdentifierData[clientIdentifiers.size()])); + } - @Override - public String serializeDocumentDataToJson(boolean prettyPrint, - Set responseParameters, - DocumentData documentData) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - DOCUMENT_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, documentData); - } + @Override + public String serializeClientIdentifierDataToJson(boolean prettyPrint, Set responseParameters, + ClientIdentifierData clientIdentifierData) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy( + CLIENT_IDENTIFIER_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, clientIdentifierData); + } - @Override - public String serializeCodeDataToJson( - final boolean prettyPrint, - final Set responseParameters, - final Collection codes) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CODE_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - codes.toArray(new CodeData[codes.size()])); - } + @Override + public String serializeDocumentDataToJson(boolean prettyPrint, Set responseParameters, Collection documentDatas) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(DOCUMENT_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, documentDatas.toArray(new DocumentData[documentDatas.size()])); + } - @Override - public String serializeCodeDataToJson( - final boolean prettyPrint, - final Set responseParameters, - final CodeData code) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CODE_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, code); - } - - @Override - public String serializeMakerCheckerDataToJson( - final boolean prettyPrint, - final Set responseParameters, - final Collection entries) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - MAKER_CHECKER_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - entries.toArray(new CommandSourceData[entries.size()])); - } - - @Override - public String serializeSavingAccountsDataToJson(boolean prettyPrint, - Set responseParameters, SavingAccountData account) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - SAVINGS_ACCOUNTS_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, account); - } + @Override + public String serializeDocumentDataToJson(boolean prettyPrint, Set responseParameters, DocumentData documentData) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(DOCUMENT_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, documentData); + } - @Override - public String serializeSavingAccountsDataToJson(boolean prettyPrint, - Set responseParameters, - Collection accounts) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - SAVINGS_ACCOUNTS_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, - accounts.toArray(new SavingAccountData[accounts.size()])); - } + @Override + public String serializeCodeDataToJson(final boolean prettyPrint, final Set responseParameters, final Collection codes) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(CODE_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, codes.toArray(new CodeData[codes.size()])); + } - @Override - public String serializeChartOfAccountDataToJson( - final boolean prettyPrint, - final Set responseParameters, - final ChartOfAccountsData chartOfAccounts) { - final Gson gsonDeserializer = helper - .createGsonBuilderWithParameterExclusionSerializationStrategy( - CHART_OF_ACCOUNTS_DATA_PARAMETERS, prettyPrint, responseParameters); - return helper.serializedJsonFrom(gsonDeserializer, chartOfAccounts); - } + @Override + public String serializeCodeDataToJson(final boolean prettyPrint, final Set responseParameters, final CodeData code) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(CODE_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, code); + } + + @Override + public String serializeMakerCheckerDataToJson(final boolean prettyPrint, final Set responseParameters, + final Collection entries) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(MAKER_CHECKER_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, entries.toArray(new CommandSourceData[entries.size()])); + } + + @Override + public String serializeSavingAccountsDataToJson(boolean prettyPrint, Set responseParameters, SavingAccountData account) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(SAVINGS_ACCOUNTS_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, account); + } + + @Override + public String serializeSavingAccountsDataToJson(boolean prettyPrint, Set responseParameters, + Collection accounts) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(SAVINGS_ACCOUNTS_DATA_PARAMETERS, + prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, accounts.toArray(new SavingAccountData[accounts.size()])); + } + + @Override + public String serializeChartOfAccountDataToJson(final boolean prettyPrint, final Set responseParameters, + final ChartOfAccountsData chartOfAccounts) { + final Gson gsonDeserializer = helper.createGsonBuilderWithParameterExclusionSerializationStrategy( + CHART_OF_ACCOUNTS_DATA_PARAMETERS, prettyPrint, responseParameters); + return helper.serializedJsonFrom(gsonDeserializer, chartOfAccounts); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java index 283d31e18..cf47e3770 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionService.java @@ -31,69 +31,68 @@ import org.mifosng.platform.api.commands.UserCommand; import org.mifosng.platform.api.data.ClientData; public interface PortfolioApiDataConversionService { - + ChargeCommand convertJsonToChargeCommand(Long resourceIdentifier, String json); - FundCommand convertJsonToFundCommand(Long resourceIdentifier, String json); - - OfficeCommand convertJsonToOfficeCommand(Long resourceIdentifier, String json); - - RoleCommand convertJsonToRoleCommand(Long resourceIdentifier, String json); + FundCommand convertJsonToFundCommand(Long resourceIdentifier, String json); - UserCommand convertJsonToUserCommand(Long resourceIdentifier, String json); + OfficeCommand convertJsonToOfficeCommand(Long resourceIdentifier, String json); - BranchMoneyTransferCommand convertJsonToBranchMoneyTransferCommand(String json); - - LoanProductCommand convertJsonToLoanProductCommand(Long resourceIdentifier, String json); - - SavingProductCommand convertJsonToSavingProductCommand(Long resourceIdentifier, String json); - - DepositProductCommand convertJsonToDepositProductCommand(Long resourceIdentifier, String json); + RoleCommand convertJsonToRoleCommand(Long resourceIdentifier, String json); - ClientCommand convertApiRequestJsonToClientCommand(Long resourceIdentifier, String json); - - ClientCommand convertInternalJsonFormatToClientCommand(Long resourceIdentifier, String json, boolean checkerApproved); - - ClientData convertInternalJsonFormatToClientDataChange(Long clientId, String json); - - ClientCommand detectChanges(Long resourceId, String baseJson, String workingJson); + UserCommand convertJsonToUserCommand(Long resourceIdentifier, String json); - GroupCommand convertJsonToGroupCommand(Long resourceIdentifier, String json); - - LoanApplicationCommand convertJsonToLoanApplicationCommand(Long resourceIdentifier, String json); + BranchMoneyTransferCommand convertJsonToBranchMoneyTransferCommand(String json); + + LoanProductCommand convertJsonToLoanProductCommand(Long resourceIdentifier, String json); + + SavingProductCommand convertJsonToSavingProductCommand(Long resourceIdentifier, String json); + + DepositProductCommand convertJsonToDepositProductCommand(Long resourceIdentifier, String json); + + ClientCommand convertApiRequestJsonToClientCommand(Long resourceIdentifier, String json); + + ClientCommand convertInternalJsonFormatToClientCommand(Long resourceIdentifier, String json, boolean checkerApproved); + + ClientData convertInternalJsonFormatToClientDataChange(Long clientId, String json); + + ClientCommand detectChanges(Long resourceId, String baseJson, String workingJson); + + GroupCommand convertJsonToGroupCommand(Long resourceIdentifier, String json); + + LoanApplicationCommand convertJsonToLoanApplicationCommand(Long resourceIdentifier, String json); LoanChargeCommand convertJsonToLoanChargeCommand(Long loanChargeId, Long loanId, String json); - LoanStateTransitionCommand convertJsonToLoanStateTransitionCommand(Long resourceIdentifier, String json); + LoanStateTransitionCommand convertJsonToLoanStateTransitionCommand(Long resourceIdentifier, String json); - LoanTransactionCommand convertJsonToLoanTransactionCommand(Long resourceIdentifier, String json); + LoanTransactionCommand convertJsonToLoanTransactionCommand(Long resourceIdentifier, String json); - AdjustLoanTransactionCommand convertJsonToAdjustLoanTransactionCommand( - Long loanId, Long transactionId, String json); + AdjustLoanTransactionCommand convertJsonToAdjustLoanTransactionCommand(Long loanId, Long transactionId, String json); - OrganisationCurrencyCommand convertJsonToOrganisationCurrencyCommand(String json); + OrganisationCurrencyCommand convertJsonToOrganisationCurrencyCommand(String json); - NoteCommand convertJsonToNoteCommand(Long resourceIdentifier, Long clientId, String json); + NoteCommand convertJsonToNoteCommand(Long resourceIdentifier, Long clientId, String json); - DepositAccountCommand convertJsonToDepositAccountCommand(Long resourceIdentifier, String json); - - DepositStateTransitionCommand convertJsonToDepositStateTransitionCommand(Long resourceIdentifier, String json); - - DepositStateTransitionApprovalCommand convertJsonToDepositStateTransitionApprovalCommand(Long resourceIdentifier, String json); + DepositAccountCommand convertJsonToDepositAccountCommand(Long resourceIdentifier, String json); - StaffCommand convertJsonToStaffCommand(Long resourceIdentifier, String json); + DepositStateTransitionCommand convertJsonToDepositStateTransitionCommand(Long resourceIdentifier, String json); + + DepositStateTransitionApprovalCommand convertJsonToDepositStateTransitionApprovalCommand(Long resourceIdentifier, String json); + + StaffCommand convertJsonToStaffCommand(Long resourceIdentifier, String json); LoanReassignmentCommand convertJsonToLoanReassignmentCommand(Long resourceIdentifier, String json); LoanReassignmentCommand convertJsonToBulkLoanReassignmentCommand(String json); - DepositAccountWithdrawalCommand convertJsonToDepositWithdrawalCommand(Long resourceIdentifier, String json); - - DepositAccountWithdrawInterestCommand convertJsonToDepositAccountWithdrawInterestCommand(Long resourceIdentifier, String json); - - ClientIdentifierCommand convertJsonToClientIdentifierCommand(Long resourceIdentifier, Long clientId, String json); + DepositAccountWithdrawalCommand convertJsonToDepositWithdrawalCommand(Long resourceIdentifier, String json); - CodeCommand convertJsonToCodeCommand(Long resourceIdentifier, String json); + DepositAccountWithdrawInterestCommand convertJsonToDepositAccountWithdrawInterestCommand(Long resourceIdentifier, String json); - SavingAccountCommand convertJsonToSavingAccountCommand(Long resourceIdentifier,String json); + ClientIdentifierCommand convertJsonToClientIdentifierCommand(Long resourceIdentifier, Long clientId, String json); + + CodeCommand convertJsonToCodeCommand(Long resourceIdentifier, String json); + + SavingAccountCommand convertJsonToSavingAccountCommand(Long resourceIdentifier, String json); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java index 3453970df..b7158dfeb 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiDataConversionServiceImpl.java @@ -64,26 +64,22 @@ import com.google.gson.reflect.TypeToken; @Service public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataConversionService { - private final Gson gsonConverter; - - public PortfolioApiDataConversionServiceImpl() { - gsonConverter = new Gson(); - } - + private final Gson gsonConverter; + + public PortfolioApiDataConversionServiceImpl() { + gsonConverter = new Gson(); + } + @Override public ChargeCommand convertJsonToChargeCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Type typeOfMap = new TypeToken>(){}.getType(); + final Type typeOfMap = new TypeToken>() {}.getType(); final Map requestMap = gsonConverter.fromJson(json, typeOfMap); - final Set supportedParams = new HashSet( - Arrays.asList("name", "amount", "locale", "currencyCode", - "currencyOptions", "chargeAppliesTo", "chargeTimeType", - "chargeCalculationType", "chargeCalculationTypeOptions", "penalty", "active" - )); + final Set supportedParams = new HashSet(Arrays.asList("name", "amount", "locale", "currencyCode", + "currencyOptions", "chargeAppliesTo", "chargeTimeType", "chargeCalculationType", "chargeCalculationTypeOptions", "penalty", + "active")); checkForUnsupportedParameters(requestMap, supportedParams); @@ -100,76 +96,62 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo final boolean penalty = extractBooleanParameter("penalty", requestMap, modifiedParameters); final boolean active = extractBooleanParameter("active", requestMap, modifiedParameters); - return new ChargeCommand(modifiedParameters, resourceIdentifier, name, amount, - currencyCode, chargeTimeType, chargeAppliesTo, chargeCalculationType, penalty, active); + return new ChargeCommand(modifiedParameters, resourceIdentifier, name, amount, currencyCode, chargeTimeType, chargeAppliesTo, + chargeCalculationType, penalty, active); } @Override - public FundCommand convertJsonToFundCommand(final Long resourceIdentifier, final String json) { + 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(); } - 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","officeId", "loanOfficerFlag") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String firstname = extractStringParameter("firstname", requestMap, modifiedParameters); - String lastname = extractStringParameter("lastname", requestMap, modifiedParameters); - Boolean isLoanOfficer = extractBooleanParameter("loanOfficerFlag", requestMap, modifiedParameters); - Long officeId = extractLongParameter("officeId", requestMap, modifiedParameters); - - return new StaffCommand(modifiedParameters, resourceIdentifier, officeId,firstname, lastname, isLoanOfficer); - } + 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", "officeId", "loanOfficerFlag")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String firstname = extractStringParameter("firstname", requestMap, modifiedParameters); + String lastname = extractStringParameter("lastname", requestMap, modifiedParameters); + Boolean isLoanOfficer = extractBooleanParameter("loanOfficerFlag", requestMap, modifiedParameters); + Long officeId = extractLongParameter("officeId", requestMap, modifiedParameters); + + return new StaffCommand(modifiedParameters, resourceIdentifier, officeId, firstname, lastname, isLoanOfficer); + } @Override public LoanReassignmentCommand convertJsonToLoanReassignmentCommand(Long resourceIdentifier, String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - Type typeOfMap = new TypeToken>(){}.getType(); + Type typeOfMap = new TypeToken>() {}.getType(); Map requestMap = gsonConverter.fromJson(json, typeOfMap); - Set supportedParams = new HashSet( - Arrays.asList("fromLoanOfficerId", "toLoanOfficerId", "assignmentDate", "locale", "dateFormat") - ); + Set supportedParams = new HashSet(Arrays.asList("fromLoanOfficerId", "toLoanOfficerId", "assignmentDate", "locale", + "dateFormat")); checkForUnsupportedParameters(requestMap, supportedParams); @@ -185,16 +167,13 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo @Override public LoanReassignmentCommand convertJsonToBulkLoanReassignmentCommand(final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - Type typeOfMap = new TypeToken>(){}.getType(); + Type typeOfMap = new TypeToken>() {}.getType(); Map requestMap = gsonConverter.fromJson(json, typeOfMap); - Set supportedParams = new HashSet( - Arrays.asList("fromLoanOfficerId", "toLoanOfficerId", "assignmentDate", "locale", "dateFormat", "loans") - ); + Set supportedParams = new HashSet(Arrays.asList("fromLoanOfficerId", "toLoanOfficerId", "assignmentDate", "locale", + "dateFormat", "loans")); checkForUnsupportedParameters(requestMap, supportedParams); @@ -215,7 +194,7 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo modifiedParameters.add("loans"); JsonArray array = object.get("loans").getAsJsonArray(); loans = new String[array.size()]; - for (int i=0; i>(){}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - Set supportedParams = new HashSet( - Arrays.asList("name", "externalId", "parentId", "openingDate", "locale", "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 detectChanges(final Long resourceIdentifier, final String baseJson, final String workingJson) { - - final Type typeOfMap = new TypeToken>(){}.getType(); - final Map workingVersion = gsonConverter.fromJson(workingJson, typeOfMap); - - final Set workingParameters = workingVersion.keySet(); - - final JsonParser parser = new JsonParser(); - final JsonElement baseElement = parser.parse(baseJson); - final JsonElement workingElement = parser.parse(workingJson); - - final JsonParserHelper helper = new JsonParserHelper(); - final Set ignoreParameters = new HashSet(); - final Set parametersPassedInRequest = new HashSet(); - - Long officeId = null; - String externalId = null; - String firstname = null; - String lastname = null; - String clientOrBusinessName = null; - LocalDate joiningDate = null; - - for (final String parameter : workingParameters) { - - final String officeIdParameterName = "officeId"; - if (officeIdParameterName.equalsIgnoreCase(parameter)) { - final Long baseOfficeId = helper.extractLongNamed(officeIdParameterName, baseElement, ignoreParameters); - final Long workingOfficeId = helper.extractLongNamed(officeIdParameterName, workingElement, ignoreParameters); - if (!workingOfficeId.equals(baseOfficeId)) { - officeId = workingOfficeId; - parametersPassedInRequest.add(officeIdParameterName); - } - } - - final String externalIdParamName = "externalId"; - if (externalIdParamName.equalsIgnoreCase(parameter)) { - final String baseExternalId = helper.extractStringNamed(externalIdParamName, baseElement, ignoreParameters); - final String workingExternalId = helper.extractStringNamed(externalIdParamName, workingElement, ignoreParameters); - if (!baseExternalId.equals(workingExternalId)) { - externalId = workingExternalId; - parametersPassedInRequest.add(externalIdParamName); - } - } - - final String firstnameParamName = "firstname"; - if (firstnameParamName.equalsIgnoreCase(parameter)) { - final String baseValue = helper.extractStringNamed(firstnameParamName, baseElement, ignoreParameters); - final String workingCopyValue = helper.extractStringNamed(firstnameParamName, workingElement, ignoreParameters); - if (!baseValue.equals(workingCopyValue)) { - firstname = workingCopyValue; - parametersPassedInRequest.add(firstnameParamName); - } - } - - final String lastnameParamName = "lastname"; - if (lastnameParamName.equalsIgnoreCase(parameter)) { - final String baseValue = helper.extractStringNamed(lastnameParamName, baseElement, ignoreParameters); - final String workingCopyValue = helper.extractStringNamed(lastnameParamName, workingElement, ignoreParameters); - if (!baseValue.equals(workingCopyValue)) { - lastname = workingCopyValue; - parametersPassedInRequest.add(lastnameParamName); - } - } - - final String clientOrBusinessNameParamName = "clientOrBusinessName"; - if (clientOrBusinessNameParamName.equalsIgnoreCase(parameter)) { - final String baseValue = helper.extractStringNamed(clientOrBusinessNameParamName, baseElement, ignoreParameters); - final String workingCopyValue = helper.extractStringNamed(clientOrBusinessNameParamName, workingElement, ignoreParameters); - if (!baseValue.equals(workingCopyValue)) { - clientOrBusinessName = workingCopyValue; - parametersPassedInRequest.add(clientOrBusinessNameParamName); - } - } + @Override + public OfficeCommand convertJsonToOfficeCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final String joinedDateParamName = "joinedDate"; - if (joinedDateParamName.equalsIgnoreCase(parameter)) { - final LocalDate baseValue = helper.extractLocalDateAsArrayNamed(joinedDateParamName, baseElement, ignoreParameters); - final LocalDate workingCopyValue = helper.extractLocalDateAsArrayNamed(joinedDateParamName, workingElement, ignoreParameters); - if (!baseValue.isEqual(workingCopyValue)) { - joiningDate = workingCopyValue; - parametersPassedInRequest.add(joinedDateParamName); - } - } - } - - return new ClientCommand(parametersPassedInRequest, resourceIdentifier, externalId, firstname, lastname, clientOrBusinessName, officeId, joiningDate, false); - } - - @Override - public ClientCommand convertApiRequestJsonToClientCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - final Type typeOfMap = new TypeToken>(){}.getType(); - final Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - final Set supportedParams = new HashSet( - Arrays.asList("id", "externalId", "firstname", "lastname", "clientOrBusinessName", "officeId", "joiningDate", "locale", "dateFormat") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - final JsonParser parser = new JsonParser(); - final JsonElement element = parser.parse(json); - final JsonParserHelper helper = new JsonParserHelper(); - final Set parametersPassedInRequest = new HashSet(); - - final Long officeId = helper.extractLongNamed("officeId", element, parametersPassedInRequest); - final String externalId = helper.extractStringNamed("externalId", element, parametersPassedInRequest); - final String firstname = helper.extractStringNamed("firstname", element, parametersPassedInRequest); - final String lastname = helper.extractStringNamed("lastname", element, parametersPassedInRequest); - final String clientOrBusinessName = helper.extractStringNamed("clientOrBusinessName", element, parametersPassedInRequest); - final LocalDate joiningDate = helper.extractLocalDateNamed("joiningDate", element, parametersPassedInRequest); + Type typeOfMap = new TypeToken>() {}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); - return new ClientCommand(parametersPassedInRequest, resourceIdentifier, externalId, firstname, lastname, clientOrBusinessName, officeId, joiningDate, false); - } - - @Override - public ClientCommand convertInternalJsonFormatToClientCommand(final Long resourceIdentifier, final String json, final boolean checkerApproved) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - final Type typeOfMap = new TypeToken>(){}.getType(); - final Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - final Set supportedParams = new HashSet( - Arrays.asList("id", "externalId", "firstname", "lastname", "clientOrBusinessName", "officeId", "joiningDate") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - final JsonParser parser = new JsonParser(); - final JsonElement element = parser.parse(json); - final JsonParserHelper helper = new JsonParserHelper(); - final Set parametersPassedInRequest = new HashSet(); - - final Long officeId = helper.extractLongNamed("officeId", element, parametersPassedInRequest); - final String externalId = helper.extractStringNamed("externalId", element, parametersPassedInRequest); - final String firstname = helper.extractStringNamed("firstname", element, parametersPassedInRequest); - final String lastname = helper.extractStringNamed("lastname", element, parametersPassedInRequest); - final String clientOrBusinessName = helper.extractStringNamed("clientOrBusinessName", element, parametersPassedInRequest); - final LocalDate joiningDate = helper.extractLocalDateAsArrayNamed("joiningDate", element, parametersPassedInRequest); - - return new ClientCommand(parametersPassedInRequest, resourceIdentifier, externalId, firstname, lastname, clientOrBusinessName, officeId, joiningDate, checkerApproved); - } - - @Override - public ClientData convertInternalJsonFormatToClientDataChange(final Long resourceIdentifier, final String json) { - - final ClientCommand command = convertInternalJsonFormatToClientCommand(resourceIdentifier, json, false); - - return ClientData.dataChangeInstance(resourceIdentifier, command.getOfficeId(), command.getExternalId(), - command.getFirstname(), command.getLastname(), command.getClientOrBusinessName(), command.getJoiningDate()); - } - - @Override - public GroupCommand convertJsonToGroupCommand(final Long resourceIdentifier, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); + Set supportedParams = new HashSet(Arrays.asList("name", "externalId", "parentId", "openingDate", "locale", + "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 < array.size(); i++) { + permissionIds[i] = array.get(i).getAsString(); + } + } } - - final Type typeOfMap = new TypeToken>(){}.getType(); + // + + String name = extractStringParameter("name", requestMap, modifiedParameters); + String description = extractStringParameter("description", requestMap, modifiedParameters); + + return new RoleCommand(modifiedParameters, resourceIdentifier, name, description, permissionIds); + } + + @Override + public UserCommand convertJsonToUserCommand(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("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 < array.size(); i++) { + notSelectedRoles[i] = array.get(i).getAsString(); + } + } + + if (object.has("roles")) { + modifiedParameters.add("roles"); + JsonArray array = object.get("roles").getAsJsonArray(); + roles = new String[array.size()]; + for (int i = 0; i < array.size(); i++) { + roles[i] = array.get(i).getAsString(); + } + } + } + // + + return new UserCommand(modifiedParameters, resourceIdentifier, username, firstname, lastname, password, repeatPassword, email, + officeId, notSelectedRoles, roles); + } + + @Override + public BranchMoneyTransferCommand convertJsonToBranchMoneyTransferCommand(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("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 detectChanges(final Long resourceIdentifier, final String baseJson, final String workingJson) { + + final Type typeOfMap = new TypeToken>() {}.getType(); + final Map workingVersion = gsonConverter.fromJson(workingJson, typeOfMap); + + final Set workingParameters = workingVersion.keySet(); + + final JsonParser parser = new JsonParser(); + final JsonElement baseElement = parser.parse(baseJson); + final JsonElement workingElement = parser.parse(workingJson); + + final JsonParserHelper helper = new JsonParserHelper(); + final Set ignoreParameters = new HashSet(); + final Set parametersPassedInRequest = new HashSet(); + + Long officeId = null; + String externalId = null; + String firstname = null; + String lastname = null; + String clientOrBusinessName = null; + LocalDate joiningDate = null; + + for (final String parameter : workingParameters) { + + final String officeIdParameterName = "officeId"; + if (officeIdParameterName.equalsIgnoreCase(parameter)) { + final Long baseOfficeId = helper.extractLongNamed(officeIdParameterName, baseElement, ignoreParameters); + final Long workingOfficeId = helper.extractLongNamed(officeIdParameterName, workingElement, ignoreParameters); + if (!workingOfficeId.equals(baseOfficeId)) { + officeId = workingOfficeId; + parametersPassedInRequest.add(officeIdParameterName); + } + } + + final String externalIdParamName = "externalId"; + if (externalIdParamName.equalsIgnoreCase(parameter)) { + final String baseExternalId = helper.extractStringNamed(externalIdParamName, baseElement, ignoreParameters); + final String workingExternalId = helper.extractStringNamed(externalIdParamName, workingElement, ignoreParameters); + if (!baseExternalId.equals(workingExternalId)) { + externalId = workingExternalId; + parametersPassedInRequest.add(externalIdParamName); + } + } + + final String firstnameParamName = "firstname"; + if (firstnameParamName.equalsIgnoreCase(parameter)) { + final String baseValue = helper.extractStringNamed(firstnameParamName, baseElement, ignoreParameters); + final String workingCopyValue = helper.extractStringNamed(firstnameParamName, workingElement, ignoreParameters); + if (!baseValue.equals(workingCopyValue)) { + firstname = workingCopyValue; + parametersPassedInRequest.add(firstnameParamName); + } + } + + final String lastnameParamName = "lastname"; + if (lastnameParamName.equalsIgnoreCase(parameter)) { + final String baseValue = helper.extractStringNamed(lastnameParamName, baseElement, ignoreParameters); + final String workingCopyValue = helper.extractStringNamed(lastnameParamName, workingElement, ignoreParameters); + if (!baseValue.equals(workingCopyValue)) { + lastname = workingCopyValue; + parametersPassedInRequest.add(lastnameParamName); + } + } + + final String clientOrBusinessNameParamName = "clientOrBusinessName"; + if (clientOrBusinessNameParamName.equalsIgnoreCase(parameter)) { + final String baseValue = helper.extractStringNamed(clientOrBusinessNameParamName, baseElement, ignoreParameters); + final String workingCopyValue = helper.extractStringNamed(clientOrBusinessNameParamName, workingElement, ignoreParameters); + if (!baseValue.equals(workingCopyValue)) { + clientOrBusinessName = workingCopyValue; + parametersPassedInRequest.add(clientOrBusinessNameParamName); + } + } + + final String joinedDateParamName = "joinedDate"; + if (joinedDateParamName.equalsIgnoreCase(parameter)) { + final LocalDate baseValue = helper.extractLocalDateAsArrayNamed(joinedDateParamName, baseElement, ignoreParameters); + final LocalDate workingCopyValue = helper.extractLocalDateAsArrayNamed(joinedDateParamName, workingElement, + ignoreParameters); + if (!baseValue.isEqual(workingCopyValue)) { + joiningDate = workingCopyValue; + parametersPassedInRequest.add(joinedDateParamName); + } + } + } + + return new ClientCommand(parametersPassedInRequest, resourceIdentifier, externalId, firstname, lastname, clientOrBusinessName, + officeId, joiningDate, false); + } + + @Override + public ClientCommand convertApiRequestJsonToClientCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); final Map requestMap = gsonConverter.fromJson(json, typeOfMap); - final Set supportedParams = new HashSet( - Arrays.asList("name", "officeId", "externalId", "clientMembers") - ); - + final Set supportedParams = new HashSet(Arrays.asList("id", "externalId", "firstname", "lastname", + "clientOrBusinessName", "officeId", "joiningDate", "locale", "dateFormat")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + final JsonParser parser = new JsonParser(); + final JsonElement element = parser.parse(json); + final JsonParserHelper helper = new JsonParserHelper(); + final Set parametersPassedInRequest = new HashSet(); + + final Long officeId = helper.extractLongNamed("officeId", element, parametersPassedInRequest); + final String externalId = helper.extractStringNamed("externalId", element, parametersPassedInRequest); + final String firstname = helper.extractStringNamed("firstname", element, parametersPassedInRequest); + final String lastname = helper.extractStringNamed("lastname", element, parametersPassedInRequest); + final String clientOrBusinessName = helper.extractStringNamed("clientOrBusinessName", element, parametersPassedInRequest); + final LocalDate joiningDate = helper.extractLocalDateNamed("joiningDate", element, parametersPassedInRequest); + + return new ClientCommand(parametersPassedInRequest, resourceIdentifier, externalId, firstname, lastname, clientOrBusinessName, + officeId, joiningDate, false); + } + + @Override + public ClientCommand convertInternalJsonFormatToClientCommand(final Long resourceIdentifier, final String json, + final boolean checkerApproved) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); + final Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + final Set supportedParams = new HashSet(Arrays.asList("id", "externalId", "firstname", "lastname", + "clientOrBusinessName", "officeId", "joiningDate")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + final JsonParser parser = new JsonParser(); + final JsonElement element = parser.parse(json); + final JsonParserHelper helper = new JsonParserHelper(); + final Set parametersPassedInRequest = new HashSet(); + + final Long officeId = helper.extractLongNamed("officeId", element, parametersPassedInRequest); + final String externalId = helper.extractStringNamed("externalId", element, parametersPassedInRequest); + final String firstname = helper.extractStringNamed("firstname", element, parametersPassedInRequest); + final String lastname = helper.extractStringNamed("lastname", element, parametersPassedInRequest); + final String clientOrBusinessName = helper.extractStringNamed("clientOrBusinessName", element, parametersPassedInRequest); + final LocalDate joiningDate = helper.extractLocalDateAsArrayNamed("joiningDate", element, parametersPassedInRequest); + + return new ClientCommand(parametersPassedInRequest, resourceIdentifier, externalId, firstname, lastname, clientOrBusinessName, + officeId, joiningDate, checkerApproved); + } + + @Override + public ClientData convertInternalJsonFormatToClientDataChange(final Long resourceIdentifier, final String json) { + + final ClientCommand command = convertInternalJsonFormatToClientCommand(resourceIdentifier, json, false); + + return ClientData.dataChangeInstance(resourceIdentifier, command.getOfficeId(), command.getExternalId(), command.getFirstname(), + command.getLastname(), command.getClientOrBusinessName(), command.getJoiningDate()); + } + + @Override + public GroupCommand convertJsonToGroupCommand(final Long resourceIdentifier, final String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); + final Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + final Set supportedParams = new HashSet(Arrays.asList("name", "officeId", "externalId", "clientMembers")); + checkForUnsupportedParameters(requestMap, supportedParams); final Set modifiedParameters = new HashSet(); @@ -557,7 +520,7 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo // check array final JsonParser parser = new JsonParser(); - + String[] clientMembers = null; JsonElement element = parser.parse(json); if (element.isJsonObject()) { @@ -566,70 +529,73 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo modifiedParameters.add("clientMembers"); JsonArray array = object.get("clientMembers").getAsJsonArray(); clientMembers = new String[array.size()]; - for (int i=0; i>(){}.getType(); - final Map requestMap = gsonConverter.fromJson(json, typeOfMap); - -// FIXME - A - LoanProduct - KW - Do we add support for "overpaidTolerance" parameter? - final 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); - - final JsonParser parser = new JsonParser(); - final JsonElement element = parser.parse(json); - final JsonParserHelper helper = new JsonParserHelper(); - - final Set modifiedParameters = new HashSet(); - final String name = helper.extractStringNamed("name", element, modifiedParameters); - final String description = helper.extractStringNamed("description", element, modifiedParameters); - final Long fundId = helper.extractLongNamed("fundId", element, modifiedParameters); - - final Long transactionProcessingStrategyId = helper.extractLongNamed("transactionProcessingStrategyId", element, modifiedParameters); - - final String currencyCode = helper.extractStringNamed("currencyCode", element, modifiedParameters); - final Integer digitsAfterDecimal = helper.extractIntegerNamed("digitsAfterDecimal", element, modifiedParameters); - - final BigDecimal principal = helper.extractBigDecimalNamed("principal", element, modifiedParameters); - final BigDecimal inArrearsTolerance = helper.extractBigDecimalNamed("inArrearsTolerance", element, modifiedParameters); - final BigDecimal interestRatePerPeriod = helper.extractBigDecimalNamed("interestRatePerPeriod", element, modifiedParameters); - final Integer repaymentEvery = helper.extractIntegerNamed("repaymentEvery", element, modifiedParameters); - final Integer numberOfRepayments = helper.extractIntegerNamed("numberOfRepayments", element, modifiedParameters); - final Integer repaymentFrequencyType = helper.extractIntegerNamed("repaymentFrequencyType", element, modifiedParameters); - -// FIXME - A - LoanProduct - KW - should loan term fields be part of product also as are basic part of 'loan terms' -// final Integer loanTermFrequency = helper.extractIntegerNamed("loanTermFrequency", element, modifiedParameters); -// final Integer loanTermFrequencyType = helper.extractIntegerNamed("loanTermFrequencyType", element, modifiedParameters); - final Integer interestRateFrequencyType = helper.extractIntegerNamed("interestRateFrequencyType", element, modifiedParameters); - final Integer amortizationType = helper.extractIntegerNamed("amortizationType", element, modifiedParameters); - final Integer interestType = helper.extractIntegerNamed("interestType", element, modifiedParameters); - final Integer interestCalculationPeriodType = helper.extractIntegerNamed("interestCalculationPeriodType", element, modifiedParameters); - - // FIXME - A - LoanProduct - KW - product charges at present dont allow for adding 'charge' to loan product and setting its 'amount', might this be needed? - // loan product charges + public LoanProductCommand convertJsonToLoanProductCommand(final Long resourceIdentifier, final String json) { + + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); + final Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + // FIXME - A - LoanProduct - KW - Do we add support for + // "overpaidTolerance" parameter? + final 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); + + final JsonParser parser = new JsonParser(); + final JsonElement element = parser.parse(json); + final JsonParserHelper helper = new JsonParserHelper(); + + final Set modifiedParameters = new HashSet(); + final String name = helper.extractStringNamed("name", element, modifiedParameters); + final String description = helper.extractStringNamed("description", element, modifiedParameters); + final Long fundId = helper.extractLongNamed("fundId", element, modifiedParameters); + + final Long transactionProcessingStrategyId = helper + .extractLongNamed("transactionProcessingStrategyId", element, modifiedParameters); + + final String currencyCode = helper.extractStringNamed("currencyCode", element, modifiedParameters); + final Integer digitsAfterDecimal = helper.extractIntegerNamed("digitsAfterDecimal", element, modifiedParameters); + + final BigDecimal principal = helper.extractBigDecimalNamed("principal", element, modifiedParameters); + final BigDecimal inArrearsTolerance = helper.extractBigDecimalNamed("inArrearsTolerance", element, modifiedParameters); + final BigDecimal interestRatePerPeriod = helper.extractBigDecimalNamed("interestRatePerPeriod", element, modifiedParameters); + final Integer repaymentEvery = helper.extractIntegerNamed("repaymentEvery", element, modifiedParameters); + final Integer numberOfRepayments = helper.extractIntegerNamed("numberOfRepayments", element, modifiedParameters); + final Integer repaymentFrequencyType = helper.extractIntegerNamed("repaymentFrequencyType", element, modifiedParameters); + + // FIXME - A - LoanProduct - KW - should loan term fields be part of + // product also as are basic part of 'loan terms' + // final Integer loanTermFrequency = + // helper.extractIntegerNamed("loanTermFrequency", element, + // modifiedParameters); + // final Integer loanTermFrequencyType = + // helper.extractIntegerNamed("loanTermFrequencyType", element, + // modifiedParameters); + final Integer interestRateFrequencyType = helper.extractIntegerNamed("interestRateFrequencyType", element, modifiedParameters); + final Integer amortizationType = helper.extractIntegerNamed("amortizationType", element, modifiedParameters); + final Integer interestType = helper.extractIntegerNamed("interestType", element, modifiedParameters); + final Integer interestCalculationPeriodType = helper.extractIntegerNamed("interestCalculationPeriodType", element, + modifiedParameters); + + // FIXME - A - LoanProduct - KW - product charges at present dont allow + // for adding 'charge' to loan product and setting its 'amount', might + // this be needed? + // loan product charges String[] charges = null; if (element.isJsonObject()) { JsonObject object = element.getAsJsonObject(); @@ -637,122 +603,123 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo modifiedParameters.add("charges"); JsonArray array = object.get("charges").getAsJsonArray(); charges = new String[array.size()]; - for (int i=0; i>(){}.getType(); - final Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - final Set supportedParams = new HashSet( - Arrays.asList("clientId", "groupId", "productId", "externalId", "fundId", "transactionProcessingStrategyId", - "principal", "inArrearsTolerance", "interestRatePerPeriod", "repaymentEvery", "numberOfRepayments", - "loanTermFrequency", "loanTermFrequencyType", "charges", - "repaymentFrequencyType", "interestRateFrequencyType", "amortizationType", "interestType", "interestCalculationPeriodType", - "expectedDisbursementDate", "repaymentsStartingFromDate", "interestChargedFromDate", "submittedOnDate", "submittedOnNote", - "locale", "dateFormat", "loanOfficerId", "id") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - final Set parametersPassedInCommand = new HashSet(); - - final JsonParser parser = new JsonParser(); - final JsonElement element = parser.parse(json); - final JsonParserHelper helper = new JsonParserHelper(); - - final Long clientId = helper.extractLongNamed("clientId", element, parametersPassedInCommand); - final Long groupId = helper.extractLongNamed("groupId", element, parametersPassedInCommand); - final Long productId = helper.extractLongNamed("productId", element, parametersPassedInCommand); - final Long fundId = helper.extractLongNamed("fundId", element, parametersPassedInCommand); - final Long loanOfficerId = helper.extractLongNamed("loanOfficerId", element, parametersPassedInCommand); - final Long transactionProcessingStrategyId = helper.extractLongNamed("transactionProcessingStrategyId", element, parametersPassedInCommand); - final String externalId = helper.extractStringNamed("externalId", element, parametersPassedInCommand); - final BigDecimal principal = helper.extractBigDecimalNamed("principal", element, parametersPassedInCommand); - final BigDecimal inArrearsToleranceValue = helper.extractBigDecimalNamed("inArrearsTolerance", element, parametersPassedInCommand); - final BigDecimal interestRatePerPeriod = helper.extractBigDecimalNamed("interestRatePerPeriod", element, parametersPassedInCommand); - - final Integer repaymentEvery = helper.extractIntegerNamed("repaymentEvery", element, parametersPassedInCommand); - final Integer numberOfRepayments = helper.extractIntegerNamed("numberOfRepayments", element, parametersPassedInCommand); - final Integer repaymentFrequencyType = helper.extractIntegerNamed("repaymentFrequencyType", element, parametersPassedInCommand); - final Integer loanTermFrequency = helper.extractIntegerNamed("loanTermFrequency", element, parametersPassedInCommand); - final Integer loanTermFrequencyType = helper.extractIntegerNamed("loanTermFrequencyType", element, parametersPassedInCommand); - final Integer interestRateFrequencyType = helper.extractIntegerNamed("interestRateFrequencyType", element, parametersPassedInCommand); - final Integer amortizationType = helper.extractIntegerNamed("amortizationType", element, parametersPassedInCommand); - final Integer interestType = helper.extractIntegerNamed("interestType", element, parametersPassedInCommand); - final Integer interestCalculationPeriodType = helper.extractIntegerNamed("interestCalculationPeriodType", element, parametersPassedInCommand); - - final LocalDate expectedDisbursementDate = helper.extractLocalDateNamed("expectedDisbursementDate", element, parametersPassedInCommand); - final LocalDate repaymentsStartingFromDate = helper.extractLocalDateNamed("repaymentsStartingFromDate", element, parametersPassedInCommand); - final LocalDate interestChargedFromDate = helper.extractLocalDateNamed("interestChargedFromDate", element, parametersPassedInCommand); - final LocalDate submittedOnDate = helper.extractLocalDateNamed("submittedOnDate", element, parametersPassedInCommand); - - final String submittedOnNote = helper.extractStringNamed("submittedOnNote", element, parametersPassedInCommand); - + return new LoanProductCommand(modifiedParameters, resourceIdentifier, name, description, fundId, transactionProcessingStrategyId, + currencyCode, digitsAfterDecimal, principal, inArrearsTolerance, numberOfRepayments, repaymentEvery, interestRatePerPeriod, + repaymentFrequencyType, interestRateFrequencyType, amortizationType, interestType, interestCalculationPeriodType, charges); + } + + @Override + public LoanApplicationCommand convertJsonToLoanApplicationCommand(final Long resourceIdentifier, final String json) { + + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + final Type typeOfMap = new TypeToken>() {}.getType(); + final Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + final Set supportedParams = new HashSet(Arrays.asList("clientId", "groupId", "productId", "externalId", "fundId", + "transactionProcessingStrategyId", "principal", "inArrearsTolerance", "interestRatePerPeriod", "repaymentEvery", + "numberOfRepayments", "loanTermFrequency", "loanTermFrequencyType", "charges", "repaymentFrequencyType", + "interestRateFrequencyType", "amortizationType", "interestType", "interestCalculationPeriodType", + "expectedDisbursementDate", "repaymentsStartingFromDate", "interestChargedFromDate", "submittedOnDate", "submittedOnNote", + "locale", "dateFormat", "loanOfficerId", "id")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + final Set parametersPassedInCommand = new HashSet(); + + final JsonParser parser = new JsonParser(); + final JsonElement element = parser.parse(json); + final JsonParserHelper helper = new JsonParserHelper(); + + final Long clientId = helper.extractLongNamed("clientId", element, parametersPassedInCommand); + final Long groupId = helper.extractLongNamed("groupId", element, parametersPassedInCommand); + final Long productId = helper.extractLongNamed("productId", element, parametersPassedInCommand); + final Long fundId = helper.extractLongNamed("fundId", element, parametersPassedInCommand); + final Long loanOfficerId = helper.extractLongNamed("loanOfficerId", element, parametersPassedInCommand); + final Long transactionProcessingStrategyId = helper.extractLongNamed("transactionProcessingStrategyId", element, + parametersPassedInCommand); + final String externalId = helper.extractStringNamed("externalId", element, parametersPassedInCommand); + final BigDecimal principal = helper.extractBigDecimalNamed("principal", element, parametersPassedInCommand); + final BigDecimal inArrearsToleranceValue = helper.extractBigDecimalNamed("inArrearsTolerance", element, parametersPassedInCommand); + final BigDecimal interestRatePerPeriod = helper.extractBigDecimalNamed("interestRatePerPeriod", element, parametersPassedInCommand); + + final Integer repaymentEvery = helper.extractIntegerNamed("repaymentEvery", element, parametersPassedInCommand); + final Integer numberOfRepayments = helper.extractIntegerNamed("numberOfRepayments", element, parametersPassedInCommand); + final Integer repaymentFrequencyType = helper.extractIntegerNamed("repaymentFrequencyType", element, parametersPassedInCommand); + final Integer loanTermFrequency = helper.extractIntegerNamed("loanTermFrequency", element, parametersPassedInCommand); + final Integer loanTermFrequencyType = helper.extractIntegerNamed("loanTermFrequencyType", element, parametersPassedInCommand); + final Integer interestRateFrequencyType = helper.extractIntegerNamed("interestRateFrequencyType", element, + parametersPassedInCommand); + final Integer amortizationType = helper.extractIntegerNamed("amortizationType", element, parametersPassedInCommand); + final Integer interestType = helper.extractIntegerNamed("interestType", element, parametersPassedInCommand); + final Integer interestCalculationPeriodType = helper.extractIntegerNamed("interestCalculationPeriodType", element, + parametersPassedInCommand); + + final LocalDate expectedDisbursementDate = helper.extractLocalDateNamed("expectedDisbursementDate", element, + parametersPassedInCommand); + final LocalDate repaymentsStartingFromDate = helper.extractLocalDateNamed("repaymentsStartingFromDate", element, + parametersPassedInCommand); + final LocalDate interestChargedFromDate = helper.extractLocalDateNamed("interestChargedFromDate", element, + parametersPassedInCommand); + final LocalDate submittedOnDate = helper.extractLocalDateNamed("submittedOnDate", element, parametersPassedInCommand); + + final String submittedOnNote = helper.extractStringNamed("submittedOnNote", element, parametersPassedInCommand); + LoanChargeCommand[] charges = null; if (element.isJsonObject()) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); final String dateFormat = helper.extractDateFormatParameter(topLevelJsonElement); final Locale locale = helper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.has("charges") && topLevelJsonElement.get("charges").isJsonArray()) { - - parametersPassedInCommand.add("charges"); + + parametersPassedInCommand.add("charges"); final JsonArray array = topLevelJsonElement.get("charges").getAsJsonArray(); charges = new LoanChargeCommand[array.size()]; - for (int i=0; i parametersPassedInForChargesCommand = new HashSet(); final Long id = helper.extractLongNamed("id", loanChargeElement, parametersPassedInForChargesCommand); final Long chargeId = helper.extractLongNamed("chargeId", loanChargeElement, parametersPassedInForChargesCommand); - final BigDecimal amount = helper.extractBigDecimalNamed("amount", loanChargeElement, locale, parametersPassedInForChargesCommand); - final Integer chargeTimeType = helper.extractIntegerNamed("chargeTimeType", loanChargeElement, locale, parametersPassedInForChargesCommand); - final Integer chargeCalculationType = helper.extractIntegerNamed("chargeCalculationType", loanChargeElement, locale, parametersPassedInForChargesCommand); - final LocalDate specifiedDueDate = helper.extractLocalDateNamed("specifiedDueDate", loanChargeElement, dateFormat, locale, parametersPassedInForChargesCommand); - - charges[i] = new LoanChargeCommand(parametersPassedInForChargesCommand, id, null, chargeId, amount, chargeTimeType, chargeCalculationType, specifiedDueDate); + final BigDecimal amount = helper.extractBigDecimalNamed("amount", loanChargeElement, locale, + parametersPassedInForChargesCommand); + final Integer chargeTimeType = helper.extractIntegerNamed("chargeTimeType", loanChargeElement, locale, + parametersPassedInForChargesCommand); + final Integer chargeCalculationType = helper.extractIntegerNamed("chargeCalculationType", loanChargeElement, locale, + parametersPassedInForChargesCommand); + final LocalDate specifiedDueDate = helper.extractLocalDateNamed("specifiedDueDate", loanChargeElement, dateFormat, + locale, parametersPassedInForChargesCommand); + + charges[i] = new LoanChargeCommand(parametersPassedInForChargesCommand, id, null, chargeId, amount, chargeTimeType, + chargeCalculationType, specifiedDueDate); } } } - return new LoanApplicationCommand(parametersPassedInCommand, - resourceIdentifier, clientId, groupId, productId, externalId, fundId, transactionProcessingStrategyId, - submittedOnDate, submittedOnNote, - expectedDisbursementDate, repaymentsStartingFromDate, interestChargedFromDate, - principal, interestRatePerPeriod, interestRateFrequencyType, interestType, interestCalculationPeriodType, - repaymentEvery, repaymentFrequencyType, numberOfRepayments, amortizationType, - loanTermFrequency, loanTermFrequencyType, - inArrearsToleranceValue, charges,loanOfficerId); - } + return new LoanApplicationCommand(parametersPassedInCommand, resourceIdentifier, clientId, groupId, productId, externalId, fundId, + transactionProcessingStrategyId, submittedOnDate, submittedOnNote, expectedDisbursementDate, repaymentsStartingFromDate, + interestChargedFromDate, principal, interestRatePerPeriod, interestRateFrequencyType, interestType, + interestCalculationPeriodType, repaymentEvery, repaymentFrequencyType, numberOfRepayments, amortizationType, + loanTermFrequency, loanTermFrequencyType, inArrearsToleranceValue, charges, loanOfficerId); + } - // FIXME - KW - charges + // FIXME - KW - charges @Override public LoanChargeCommand convertJsonToLoanChargeCommand(final Long loanChargeId, final Long loanId, final String json) { - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - Type typeOfMap = new TypeToken>(){}.getType(); + Type typeOfMap = new TypeToken>() {}.getType(); Map requestMap = gsonConverter.fromJson(json, typeOfMap); - final Set supportedParams = new HashSet( - Arrays.asList("chargeId", "amount", "chargeTimeType", "chargeCalculationType", "specifiedDueDate", "locale", "dateFormat") - ); + final Set supportedParams = new HashSet(Arrays.asList("chargeId", "amount", "chargeTimeType", + "chargeCalculationType", "specifiedDueDate", "locale", "dateFormat")); checkForUnsupportedParameters(requestMap, supportedParams); @@ -764,1018 +731,901 @@ public class PortfolioApiDataConversionServiceImpl implements PortfolioApiDataCo Integer chargeCalculationType = extractIntegerParameter("chargeCalculationType", requestMap, modifiedParameters); final LocalDate submittedOnDate = extractLocalDateParameter("specifiedDueDate", requestMap, modifiedParameters); - return new LoanChargeCommand(modifiedParameters, loanChargeId, loanId, chargeId, amount, - chargeTimeType, chargeCalculationType, submittedOnDate); + return new LoanChargeCommand(modifiedParameters, loanChargeId, loanId, chargeId, amount, chargeTimeType, chargeCalculationType, + submittedOnDate); } @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", "locale", "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"); - final Locale locale = new Locale((String) requestMap.get("locale")); - paramValue = convertFrom(valueAsString, paramName, dateFormat, locale); - } - 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, - final Locale clientApplicationLocale) { - - if (StringUtils.isBlank(dateFormat) || clientApplicationLocale == null) { - - List dataValidationErrors = new ArrayList(); - if (StringUtils.isBlank(dateFormat)) { - 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); - } - if (clientApplicationLocale == null) { - 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); - } - - LocalDate eventLocalDate = null; - if (StringUtils.isNotBlank(dateAsString)) { - try { - // Locale locale = LocaleContextHolder.getLocale(); - eventLocalDate = DateTimeFormat - .forPattern(dateFormat) - .withLocale(clientApplicationLocale) - .parseLocalDate( - dateAsString - .toLowerCase(clientApplicationLocale)); - } 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: '" - + dateFormat + "' and locale: '" - + clientApplicationLocale + "' provided:", - 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 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("locale", "name", "description","currencyCode", "digitsAfterDecimal","interestRate", "minInterestRate", - "maxInterestRate","savingsDepositAmount","savingProductType","tenureType","tenure", "frequency","interestType","interestCalculationMethod", - "minimumBalanceForWithdrawal","isPartialDepositAllowed","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType")); - - 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 minInterestRate = extractBigDecimalParameter("minInterestRate", requestMap, modifiedParameters); - BigDecimal maxInterestRate = extractBigDecimalParameter("maxInterestRate", requestMap, modifiedParameters); - BigDecimal savingsDepositAmount=extractBigDecimalParameter("savingsDepositAmount", requestMap, modifiedParameters); - Integer savingProductType = extractIntegerParameter("savingProductType", requestMap, modifiedParameters); - Integer tenureType = extractIntegerParameter("tenureType", requestMap, modifiedParameters); - Integer tenure = extractIntegerParameter("tenure", requestMap, modifiedParameters); - Integer frequency = extractIntegerParameter("frequency", requestMap, modifiedParameters); - Integer interestType = extractIntegerParameter("interestType", requestMap, modifiedParameters); - Integer interestCalculationMethod=extractIntegerParameter("interestCalculationMethod", requestMap, modifiedParameters); - BigDecimal minimumBalanceForWithdrawal=extractBigDecimalParameter("minimumBalanceForWithdrawal", requestMap, modifiedParameters); - boolean isPartialDepositAllowed = extractBooleanParameter("isPartialDepositAllowed", requestMap, modifiedParameters); - boolean isLockinPeriodAllowed = extractBooleanParameter("isLockinPeriodAllowed", requestMap, modifiedParameters); - Integer lockinPeriod = extractIntegerParameter("lockinPeriod", requestMap, modifiedParameters); - Integer lockinPeriodType = extractIntegerParameter("lockinPeriodType", requestMap, modifiedParameters); - - - return new SavingProductCommand(modifiedParameters, resourceIdentifier,name, description,currencyCode,digitsAfterDecimalValue,interestRate, minInterestRate, - maxInterestRate, savingsDepositAmount,savingProductType, tenureType,tenure,frequency,interestType,interestCalculationMethod,minimumBalanceForWithdrawal, - isPartialDepositAllowed, isLockinPeriodAllowed,lockinPeriod,lockinPeriodType); - } - - @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", "deposit", "maturityInterestRate", "preClosureInterestRate", - "tenureInMonths", "interestCompoundedEvery", "interestCompoundedEveryPeriodType", "commencementDate", - "renewalAllowed", "preClosureAllowed","interestCompoundingAllowed", - "locale", "dateFormat","isInterestWithdrawable","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType") - ); - 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 deposit=extractBigDecimalParameter("deposit", requestMap, modifiedParameters); - BigDecimal interestRate = extractBigDecimalParameter("maturityInterestRate", requestMap, modifiedParameters); - BigDecimal preClosureInterestRate = extractBigDecimalParameter("preClosureInterestRate", requestMap, modifiedParameters); - Integer tenureInMonths = extractIntegerParameter("tenureInMonths", requestMap, modifiedParameters); - - boolean isLockinPeriodAllowed = extractBooleanParameter("isLockinPeriodAllowed", requestMap, modifiedParameters); - Integer lockinPeriod = extractIntegerParameter("lockinPeriod", requestMap, modifiedParameters); - Integer lockinPeriodType = extractIntegerParameter("lockinPeriodType", 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); - boolean isInterestWithdrawable = extractBooleanParameter("isInterestWithdrawable", requestMap, modifiedParameters); - boolean interestCompoundingAllowed = extractBooleanParameter("interestCompoundingAllowed", requestMap, modifiedParameters); - - return new DepositAccountCommand(modifiedParameters, resourceIdentifier, clientId, productId, - externalId, deposit, interestRate, preClosureInterestRate, tenureInMonths, - interestCompoundedEvery, interestCompoundedEveryPeriodType, commencementDate, renewalAllowed, - preClosureAllowed, isInterestWithdrawable, interestCompoundingAllowed, - isLockinPeriodAllowed,lockinPeriod,lockinPeriodType); - } - - @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","interestCompoundingAllowed","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType") - ); - 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 interestCompoundingAllowed = extractBooleanParameter("interestCompoundingAllowed", requestMap, modifiedParameters); - - boolean canRenew = extractBooleanParameter("renewalAllowed", requestMap, modifiedParameters); - boolean canPreClose = extractBooleanParameter("preClosureAllowed", requestMap, modifiedParameters); - BigDecimal preClosureInterestRate = extractBigDecimalParameter("preClosureInterestRate", requestMap, modifiedParameters); - - boolean isLockinPeriodAllowed = extractBooleanParameter("isLockinPeriodAllowed", requestMap, modifiedParameters); - Integer lockinPeriod = extractIntegerParameter("lockinPeriod", requestMap, modifiedParameters); - Integer lockinPeriodType = extractIntegerParameter("lockinPeriodType", requestMap, modifiedParameters); - - - - return new DepositProductCommand(modifiedParameters, resourceIdentifier, externalId, - name, description, currencyCode, digitsAfterDecimalValue, minimumBalance,maximumBalance, - tenureMonths, maturityDefaultInterestRate, maturityMinInterestRate, maturityMaxInterestRate, - interestCompoundedEvery, interestCompoundedEveryPeriodType, - canRenew, canPreClose, preClosureInterestRate, interestCompoundingAllowed,isLockinPeriodAllowed,lockinPeriod,lockinPeriodType); - } - - @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", "locale", "dateFormat", "note")); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - LocalDate eventDate = extractLocalDateParameter("eventDate", requestMap, modifiedParameters); - String note =extractStringParameter("note", requestMap, modifiedParameters); - - return new DepositStateTransitionCommand(resourceIdentifier, eventDate, note); - } - - @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","commencementDate", "locale", "dateFormat", "tenureInMonths", "deposit", "interestCompoundedEveryPeriodType", "productId","interestCompoundedEvery","note","maturityInterestRate")); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - LocalDate commencementDate = extractLocalDateParameter("commencementDate", requestMap, modifiedParameters); - BigDecimal deposit=extractBigDecimalParameter("deposit", requestMap, modifiedParameters); - BigDecimal maturityInterestRate=extractBigDecimalParameter("maturityInterestRate", 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); - String note = extractStringParameter("note", requestMap, modifiedParameters); - - return new DepositStateTransitionApprovalCommand(resourceIdentifier, productId, commencementDate, tenureInMonths, deposit, interestCompoundedEveryPeriodType,interestCompoundedEvery, note,maturityInterestRate); - } - - @Override - public DepositAccountWithdrawalCommand convertJsonToDepositWithdrawalCommand(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("note","locale","maturesOnDate", "dateFormat")); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String note = extractStringParameter("note", requestMap, modifiedParameters); - LocalDate maturesOnDate = extractLocalDateParameter("maturesOnDate", requestMap, modifiedParameters); - - return new DepositAccountWithdrawalCommand(resourceIdentifier,note,maturesOnDate); - } - - @Override - public DepositAccountWithdrawInterestCommand convertJsonToDepositAccountWithdrawInterestCommand(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("amount", "note", "locale")); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - BigDecimal amount=extractBigDecimalParameter("amount", requestMap, modifiedParameters); - String note = extractStringParameter("note", requestMap, modifiedParameters); - - return new DepositAccountWithdrawInterestCommand(resourceIdentifier, amount, note); - } - - @Override - public ClientIdentifierCommand convertJsonToClientIdentifierCommand( - Long resourceIdentifier, Long clientId, 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("clientId", "documentTypeId", "documentKey", "description")); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - Long documentTypeId = extractLongParameter("documentTypeId", requestMap, modifiedParameters); - String documentKey = extractStringParameter("documentKey", requestMap, modifiedParameters); - String documentDescription = extractStringParameter("description", requestMap, modifiedParameters); - - return new ClientIdentifierCommand(modifiedParameters,resourceIdentifier,clientId,documentTypeId,documentKey,documentDescription); - } - - @Override - public CodeCommand convertJsonToCodeCommand(Long resourceIdentifier,String json) { - // TODO Auto-generated method stub - 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") - ); - - checkForUnsupportedParameters(requestMap, supportedParams); - - Set modifiedParameters = new HashSet(); - - String name = extractStringParameter("name", requestMap, modifiedParameters); - - return new CodeCommand(modifiedParameters, resourceIdentifier, name); - - - } - - - - @Override - public SavingAccountCommand convertJsonToSavingAccountCommand(Long resourceIdentifier, String json) { - - - if (StringUtils.isBlank(json)) { - throw new InvalidJsonException(); - } - - Type typeOfMap = new TypeToken>() {}.getType(); - Map requestMap = gsonConverter.fromJson(json, typeOfMap); - - // currencyCode, currencyDigits - Set supportedParams = new HashSet( - Arrays.asList("clientId", "productId", "externalId", "currencyCode", "digitsAfterDecimal", "savingsDepositAmountPerPeriod", "recurringInterestRate", "savingInterestRate", - "tenure", "commencementDate", "locale", "dateFormat","isLockinPeriodAllowed","lockinPeriod","lockinPeriodType", - "savingProductType","tenureType", "frequency","interestType","interestCalculationMethod", - "minimumBalanceForWithdrawal","isPartialDepositAllowed" ) - ); - 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); - String currencyCode=extractStringParameter("currencyCode", requestMap,modifiedParameters); - Integer digitsAfterDecimalValue = extractIntegerParameter("digitsAfterDecimal", requestMap, modifiedParameters); - BigDecimal savingsDepositAmount=extractBigDecimalParameter("savingsDepositAmountPerPeriod", requestMap, modifiedParameters); - BigDecimal recurringInterestRate = extractBigDecimalParameter("recurringInterestRate", requestMap, modifiedParameters); - BigDecimal savingInterestRate = extractBigDecimalParameter("savingInterestRate", requestMap, modifiedParameters); - Integer tenure = extractIntegerParameter("tenure", requestMap, modifiedParameters); - - boolean isLockinPeriodAllowed = extractBooleanParameter("isLockinPeriodAllowed", requestMap, modifiedParameters); - Integer lockinPeriod = extractIntegerParameter("lockinPeriod", requestMap, modifiedParameters); - Integer lockinPeriodType = extractIntegerParameter("lockinPeriodType", requestMap, modifiedParameters); - - LocalDate commencementDate = extractLocalDateParameter("commencementDate", requestMap, modifiedParameters); - Integer savingProductType = extractIntegerParameter("savingProductType", requestMap, modifiedParameters); - Integer tenureType = extractIntegerParameter("tenureType", requestMap, modifiedParameters); - Integer frequency = extractIntegerParameter("frequency", requestMap, modifiedParameters); - Integer interestType = extractIntegerParameter("interestType", requestMap, modifiedParameters); - Integer interestCalculationMethod=extractIntegerParameter("interestCalculationMethod", requestMap, modifiedParameters); - BigDecimal minimumBalanceForWithdrawal=extractBigDecimalParameter("minimumBalanceForWithdrawal", requestMap, modifiedParameters); - boolean isPartialDepositAllowed = extractBooleanParameter("isPartialDepositAllowed", requestMap, modifiedParameters); - - return new SavingAccountCommand(modifiedParameters, resourceIdentifier, clientId, productId, externalId, currencyCode, digitsAfterDecimalValue, - savingsDepositAmount, recurringInterestRate,savingInterestRate, tenure, commencementDate, savingProductType, tenureType, frequency, - interestType, minimumBalanceForWithdrawal, interestCalculationMethod, isLockinPeriodAllowed, isPartialDepositAllowed, lockinPeriod, lockinPeriodType); - } + 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", "locale", "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 < array.size(); i++) { + currencies[i] = array.get(i).getAsString(); + } + } + } + // + + return new OrganisationCurrencyCommand(currencies); + } + + private void checkForUnsupportedParameters(Map 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"); + final Locale locale = new Locale((String) requestMap.get("locale")); + paramValue = convertFrom(valueAsString, paramName, dateFormat, locale); + } + 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, + final Locale clientApplicationLocale) { + + if (StringUtils.isBlank(dateFormat) || clientApplicationLocale == null) { + + List dataValidationErrors = new ArrayList(); + if (StringUtils.isBlank(dateFormat)) { + 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); + } + if (clientApplicationLocale == null) { + 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); + } + + LocalDate eventLocalDate = null; + if (StringUtils.isNotBlank(dateAsString)) { + try { + // Locale locale = LocaleContextHolder.getLocale(); + eventLocalDate = DateTimeFormat.forPattern(dateFormat).withLocale(clientApplicationLocale) + .parseLocalDate(dateAsString.toLowerCase(clientApplicationLocale)); + } 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: '" + dateFormat + "' and locale: '" + + clientApplicationLocale + "' provided:", 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 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("locale", "name", "description", "currencyCode", + "digitsAfterDecimal", "interestRate", "minInterestRate", "maxInterestRate", "savingsDepositAmount", "savingProductType", + "tenureType", "tenure", "frequency", "interestType", "interestCalculationMethod", "minimumBalanceForWithdrawal", + "isPartialDepositAllowed", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType")); + + 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 minInterestRate = extractBigDecimalParameter("minInterestRate", requestMap, modifiedParameters); + BigDecimal maxInterestRate = extractBigDecimalParameter("maxInterestRate", requestMap, modifiedParameters); + BigDecimal savingsDepositAmount = extractBigDecimalParameter("savingsDepositAmount", requestMap, modifiedParameters); + Integer savingProductType = extractIntegerParameter("savingProductType", requestMap, modifiedParameters); + Integer tenureType = extractIntegerParameter("tenureType", requestMap, modifiedParameters); + Integer tenure = extractIntegerParameter("tenure", requestMap, modifiedParameters); + Integer frequency = extractIntegerParameter("frequency", requestMap, modifiedParameters); + Integer interestType = extractIntegerParameter("interestType", requestMap, modifiedParameters); + Integer interestCalculationMethod = extractIntegerParameter("interestCalculationMethod", requestMap, modifiedParameters); + BigDecimal minimumBalanceForWithdrawal = extractBigDecimalParameter("minimumBalanceForWithdrawal", requestMap, modifiedParameters); + boolean isPartialDepositAllowed = extractBooleanParameter("isPartialDepositAllowed", requestMap, modifiedParameters); + boolean isLockinPeriodAllowed = extractBooleanParameter("isLockinPeriodAllowed", requestMap, modifiedParameters); + Integer lockinPeriod = extractIntegerParameter("lockinPeriod", requestMap, modifiedParameters); + Integer lockinPeriodType = extractIntegerParameter("lockinPeriodType", requestMap, modifiedParameters); + + return new SavingProductCommand(modifiedParameters, resourceIdentifier, name, description, currencyCode, digitsAfterDecimalValue, + interestRate, minInterestRate, maxInterestRate, savingsDepositAmount, savingProductType, tenureType, tenure, frequency, + interestType, interestCalculationMethod, minimumBalanceForWithdrawal, isPartialDepositAllowed, isLockinPeriodAllowed, + lockinPeriod, lockinPeriodType); + } + + @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", "deposit", + "maturityInterestRate", "preClosureInterestRate", "tenureInMonths", "interestCompoundedEvery", + "interestCompoundedEveryPeriodType", "commencementDate", "renewalAllowed", "preClosureAllowed", + "interestCompoundingAllowed", "locale", "dateFormat", "isInterestWithdrawable", "isLockinPeriodAllowed", "lockinPeriod", + "lockinPeriodType")); + 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 deposit = extractBigDecimalParameter("deposit", requestMap, modifiedParameters); + BigDecimal interestRate = extractBigDecimalParameter("maturityInterestRate", requestMap, modifiedParameters); + BigDecimal preClosureInterestRate = extractBigDecimalParameter("preClosureInterestRate", requestMap, modifiedParameters); + Integer tenureInMonths = extractIntegerParameter("tenureInMonths", requestMap, modifiedParameters); + + boolean isLockinPeriodAllowed = extractBooleanParameter("isLockinPeriodAllowed", requestMap, modifiedParameters); + Integer lockinPeriod = extractIntegerParameter("lockinPeriod", requestMap, modifiedParameters); + Integer lockinPeriodType = extractIntegerParameter("lockinPeriodType", 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); + boolean isInterestWithdrawable = extractBooleanParameter("isInterestWithdrawable", requestMap, modifiedParameters); + boolean interestCompoundingAllowed = extractBooleanParameter("interestCompoundingAllowed", requestMap, modifiedParameters); + + return new DepositAccountCommand(modifiedParameters, resourceIdentifier, clientId, productId, externalId, deposit, interestRate, + preClosureInterestRate, tenureInMonths, interestCompoundedEvery, interestCompoundedEveryPeriodType, commencementDate, + renewalAllowed, preClosureAllowed, isInterestWithdrawable, interestCompoundingAllowed, isLockinPeriodAllowed, lockinPeriod, + lockinPeriodType); + } + + @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", "interestCompoundingAllowed", "isLockinPeriodAllowed", + "lockinPeriod", "lockinPeriodType")); + 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 interestCompoundingAllowed = extractBooleanParameter("interestCompoundingAllowed", requestMap, modifiedParameters); + + boolean canRenew = extractBooleanParameter("renewalAllowed", requestMap, modifiedParameters); + boolean canPreClose = extractBooleanParameter("preClosureAllowed", requestMap, modifiedParameters); + BigDecimal preClosureInterestRate = extractBigDecimalParameter("preClosureInterestRate", requestMap, modifiedParameters); + + boolean isLockinPeriodAllowed = extractBooleanParameter("isLockinPeriodAllowed", requestMap, modifiedParameters); + Integer lockinPeriod = extractIntegerParameter("lockinPeriod", requestMap, modifiedParameters); + Integer lockinPeriodType = extractIntegerParameter("lockinPeriodType", requestMap, modifiedParameters); + + return new DepositProductCommand(modifiedParameters, resourceIdentifier, externalId, name, description, currencyCode, + digitsAfterDecimalValue, minimumBalance, maximumBalance, tenureMonths, maturityDefaultInterestRate, + maturityMinInterestRate, maturityMaxInterestRate, interestCompoundedEvery, interestCompoundedEveryPeriodType, canRenew, + canPreClose, preClosureInterestRate, interestCompoundingAllowed, isLockinPeriodAllowed, lockinPeriod, lockinPeriodType); + } + + @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", "locale", "dateFormat", "note")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + LocalDate eventDate = extractLocalDateParameter("eventDate", requestMap, modifiedParameters); + String note = extractStringParameter("note", requestMap, modifiedParameters); + + return new DepositStateTransitionCommand(resourceIdentifier, eventDate, note); + } + + @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", "commencementDate", "locale", "dateFormat", + "tenureInMonths", "deposit", "interestCompoundedEveryPeriodType", "productId", "interestCompoundedEvery", "note", + "maturityInterestRate")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + LocalDate commencementDate = extractLocalDateParameter("commencementDate", requestMap, modifiedParameters); + BigDecimal deposit = extractBigDecimalParameter("deposit", requestMap, modifiedParameters); + BigDecimal maturityInterestRate = extractBigDecimalParameter("maturityInterestRate", 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); + String note = extractStringParameter("note", requestMap, modifiedParameters); + + return new DepositStateTransitionApprovalCommand(resourceIdentifier, productId, commencementDate, tenureInMonths, deposit, + interestCompoundedEveryPeriodType, interestCompoundedEvery, note, maturityInterestRate); + } + + @Override + public DepositAccountWithdrawalCommand convertJsonToDepositWithdrawalCommand(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("note", "locale", "maturesOnDate", "dateFormat")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String note = extractStringParameter("note", requestMap, modifiedParameters); + LocalDate maturesOnDate = extractLocalDateParameter("maturesOnDate", requestMap, modifiedParameters); + + return new DepositAccountWithdrawalCommand(resourceIdentifier, note, maturesOnDate); + } + + @Override + public DepositAccountWithdrawInterestCommand convertJsonToDepositAccountWithdrawInterestCommand(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("amount", "note", "locale")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + BigDecimal amount = extractBigDecimalParameter("amount", requestMap, modifiedParameters); + String note = extractStringParameter("note", requestMap, modifiedParameters); + + return new DepositAccountWithdrawInterestCommand(resourceIdentifier, amount, note); + } + + @Override + public ClientIdentifierCommand convertJsonToClientIdentifierCommand(Long resourceIdentifier, Long clientId, 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("clientId", "documentTypeId", "documentKey", "description")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + Long documentTypeId = extractLongParameter("documentTypeId", requestMap, modifiedParameters); + String documentKey = extractStringParameter("documentKey", requestMap, modifiedParameters); + String documentDescription = extractStringParameter("description", requestMap, modifiedParameters); + + return new ClientIdentifierCommand(modifiedParameters, resourceIdentifier, clientId, documentTypeId, documentKey, + documentDescription); + } + + @Override + public CodeCommand convertJsonToCodeCommand(Long resourceIdentifier, String json) { + // TODO Auto-generated method stub + 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")); + + checkForUnsupportedParameters(requestMap, supportedParams); + + Set modifiedParameters = new HashSet(); + + String name = extractStringParameter("name", requestMap, modifiedParameters); + + return new CodeCommand(modifiedParameters, resourceIdentifier, name); + + } + + @Override + public SavingAccountCommand convertJsonToSavingAccountCommand(Long resourceIdentifier, String json) { + + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } + + Type typeOfMap = new TypeToken>() {}.getType(); + Map requestMap = gsonConverter.fromJson(json, typeOfMap); + + // currencyCode, currencyDigits + Set supportedParams = new HashSet(Arrays.asList("clientId", "productId", "externalId", "currencyCode", + "digitsAfterDecimal", "savingsDepositAmountPerPeriod", "recurringInterestRate", "savingInterestRate", "tenure", + "commencementDate", "locale", "dateFormat", "isLockinPeriodAllowed", "lockinPeriod", "lockinPeriodType", + "savingProductType", "tenureType", "frequency", "interestType", "interestCalculationMethod", "minimumBalanceForWithdrawal", + "isPartialDepositAllowed")); + 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); + String currencyCode = extractStringParameter("currencyCode", requestMap, modifiedParameters); + Integer digitsAfterDecimalValue = extractIntegerParameter("digitsAfterDecimal", requestMap, modifiedParameters); + BigDecimal savingsDepositAmount = extractBigDecimalParameter("savingsDepositAmountPerPeriod", requestMap, modifiedParameters); + BigDecimal recurringInterestRate = extractBigDecimalParameter("recurringInterestRate", requestMap, modifiedParameters); + BigDecimal savingInterestRate = extractBigDecimalParameter("savingInterestRate", requestMap, modifiedParameters); + Integer tenure = extractIntegerParameter("tenure", requestMap, modifiedParameters); + + boolean isLockinPeriodAllowed = extractBooleanParameter("isLockinPeriodAllowed", requestMap, modifiedParameters); + Integer lockinPeriod = extractIntegerParameter("lockinPeriod", requestMap, modifiedParameters); + Integer lockinPeriodType = extractIntegerParameter("lockinPeriodType", requestMap, modifiedParameters); + + LocalDate commencementDate = extractLocalDateParameter("commencementDate", requestMap, modifiedParameters); + Integer savingProductType = extractIntegerParameter("savingProductType", requestMap, modifiedParameters); + Integer tenureType = extractIntegerParameter("tenureType", requestMap, modifiedParameters); + Integer frequency = extractIntegerParameter("frequency", requestMap, modifiedParameters); + Integer interestType = extractIntegerParameter("interestType", requestMap, modifiedParameters); + Integer interestCalculationMethod = extractIntegerParameter("interestCalculationMethod", requestMap, modifiedParameters); + BigDecimal minimumBalanceForWithdrawal = extractBigDecimalParameter("minimumBalanceForWithdrawal", requestMap, modifiedParameters); + boolean isPartialDepositAllowed = extractBooleanParameter("isPartialDepositAllowed", requestMap, modifiedParameters); + + return new SavingAccountCommand(modifiedParameters, resourceIdentifier, clientId, productId, externalId, currencyCode, + digitsAfterDecimalValue, savingsDepositAmount, recurringInterestRate, savingInterestRate, tenure, commencementDate, + savingProductType, tenureType, frequency, interestType, minimumBalanceForWithdrawal, interestCalculationMethod, + isLockinPeriodAllowed, isPartialDepositAllowed, lockinPeriod, lockinPeriodType); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiJsonSerializerService.java b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiJsonSerializerService.java index 2411ec511..b3bcdd7f2 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiJsonSerializerService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/api/infrastructure/PortfolioApiJsonSerializerService.java @@ -42,114 +42,121 @@ import org.mifosng.platform.api.data.StaffData; public interface PortfolioApiJsonSerializerService { - String serializeAuthenticatedUserDataToJson(boolean prettyPrint, AuthenticatedUserData authenticatedUserData); - - String serializeGenericResultsetDataToJson(boolean prettyPrint, GenericResultsetData result); + String serializeAuthenticatedUserDataToJson(boolean prettyPrint, AuthenticatedUserData authenticatedUserData); - String serializeAdditionalFieldsSetDataToJson(boolean prettyPrint, Collection result); - - String serializeDatatableDataToJson(boolean prettyPrint, Collection result); - - String serializePermissionDataToJson(boolean prettyPrint, Set responseParameters, Collection permissions); + String serializeGenericResultsetDataToJson(boolean prettyPrint, GenericResultsetData result); - String serializeRoleDataToJson(boolean prettyPrint, Set responseParameters, Collection roles); + String serializeAdditionalFieldsSetDataToJson(boolean prettyPrint, Collection result); - String serializeRoleDataToJson(boolean prettyPrint, Set responseParameters, RoleData role); - - String serializeRolePermissionDataToJson(boolean prettyPrint, Set responseParameters, RolePermissionData rolePermissionData); + String serializeDatatableDataToJson(boolean prettyPrint, Collection result); - String serializeAppUserDataToJson(boolean prettyPrint, Set responseParameters, Collection users); + String serializePermissionDataToJson(boolean prettyPrint, Set responseParameters, Collection permissions); - String serializeAppUserDataToJson(boolean prettyPrint, Set responseParameters, AppUserData user); + String serializeRoleDataToJson(boolean prettyPrint, Set responseParameters, Collection roles); - String serializeOfficeDataToJson(boolean prettyPrint, Set responseParameters, Collection offices); + String serializeRoleDataToJson(boolean prettyPrint, Set responseParameters, RoleData role); - String serializeOfficeDataToJson(boolean prettyPrint, Set responseParameters, OfficeData office); + String serializeRolePermissionDataToJson(boolean prettyPrint, Set responseParameters, RolePermissionData rolePermissionData); - String serializeOfficeTransactionDataToJson(boolean prettyPrint, Set responseParameters, Collection officeTransactions); - - String serializeOfficeTransactionDataToJson(boolean prettyPrint, Set responseParameters, OfficeTransactionData officeTransaction); + String serializeAppUserDataToJson(boolean prettyPrint, Set responseParameters, Collection users); - String serializeConfigurationDataToJson(boolean prettyPrint, Set responseParameters, ConfigurationData configuration); + String serializeAppUserDataToJson(boolean prettyPrint, Set responseParameters, AppUserData user); - String serializeFundDataToJson(boolean prettyPrint, Set responseParameters, Collection funds); + String serializeOfficeDataToJson(boolean prettyPrint, Set responseParameters, Collection offices); - String serializeFundDataToJson(boolean prettyPrint, Set responseParameters, FundData fund); + String serializeOfficeDataToJson(boolean prettyPrint, Set responseParameters, OfficeData office); - String serializeLoanProductDataToJson(boolean prettyPrint, Set responseParameters, Collection products); - - String serializeLoanProductDataToJson(boolean prettyPrint, Set responseParameters, LoanProductData loanProduct); + String serializeOfficeTransactionDataToJson(boolean prettyPrint, Set responseParameters, + Collection officeTransactions); - String serializeSavingProductDataToJson(boolean prettyPrint, Set responseParameters, Collection products); + String serializeOfficeTransactionDataToJson(boolean prettyPrint, Set responseParameters, OfficeTransactionData officeTransaction); - String serializeSavingProductDataToJson(boolean prettyPrint, Set responseParameters, SavingProductData savingProduct); + String serializeConfigurationDataToJson(boolean prettyPrint, Set responseParameters, ConfigurationData configuration); - String serializeDepositProductDataToJson(boolean prettyPrint, Set responseParameters, Collection products); + String serializeFundDataToJson(boolean prettyPrint, Set responseParameters, Collection funds); - String serializeDepositProductDataToJson(boolean prettyPrint, Set responseParameters, DepositProductData depositProduct); + String serializeFundDataToJson(boolean prettyPrint, Set responseParameters, FundData fund); - String serializeDepositAccountDataToJson(boolean prettyPrint, Set responseParameters, Collection accounts); + String serializeLoanProductDataToJson(boolean prettyPrint, Set responseParameters, Collection products); - String serializeDepositAccountDataToJson(boolean prettyPrint, Set responseParameters, DepositAccountData account); + String serializeLoanProductDataToJson(boolean prettyPrint, Set responseParameters, LoanProductData loanProduct); - String serializeClientCommandToJson(ClientCommand command); - - String serializeClientDataToJson(ClientData clientData); - - String serializeClientDataToJson(boolean prettyPrint, Set responseParameters, ClientData clientData); - - String serializeClientDataToJson(boolean prettyPrint, Set responseParameters, Collection clients); - - String serializeClientAccountSummaryCollectionDataToJson(boolean prettyPrint, Set responseParameters, ClientAccountSummaryCollectionData clientAccount); + String serializeSavingProductDataToJson(boolean prettyPrint, Set responseParameters, Collection products); - String serializeGroupAccountSummaryCollectionDataToJson(boolean prettyPrint, Set responseParameters, GroupAccountSummaryCollectionData groupAccount); + String serializeSavingProductDataToJson(boolean prettyPrint, Set responseParameters, SavingProductData savingProduct); - String serializeGroupDataToJson(boolean prettyPrint, Set responseParameters, Collection groups); + String serializeDepositProductDataToJson(boolean prettyPrint, Set responseParameters, Collection products); - String serializeGroupDataToJson(boolean prettyPrint, Set responseParameters, GroupData group); + String serializeDepositProductDataToJson(boolean prettyPrint, Set responseParameters, DepositProductData depositProduct); - String serializeNoteDataToJson(boolean prettyPrint, Set responseParameters, Collection notes); + String serializeDepositAccountDataToJson(boolean prettyPrint, Set responseParameters, Collection accounts); - String serializeNoteDataToJson(boolean prettyPrint, Set responseParameters, NoteData note); - - String serializeLoanScheduleDataToJson(boolean prettyPrint, Set responseParameters, LoanScheduleData loanSchedule); + String serializeDepositAccountDataToJson(boolean prettyPrint, Set responseParameters, DepositAccountData account); - String serializeLoanAccountDataToJson(boolean prettyPrint, Set responseParameters, LoanAccountData loanAccount); + String serializeClientCommandToJson(ClientCommand command); - String serializeLoanTransactionDataToJson(boolean prettyPrint, Set responseParameters, LoanTransactionData newTransactionData); + String serializeClientDataToJson(ClientData clientData); - String serializeLoanReassignmentDataToJson(boolean prettyPrint, Set responseParameters, LoanReassignmentData loanReassignmentData); + String serializeClientDataToJson(boolean prettyPrint, Set responseParameters, ClientData clientData); - String serializeChargeDataToJson(boolean prettyPrint, Set responseParameters, Collection charges); + String serializeClientDataToJson(boolean prettyPrint, Set responseParameters, Collection clients); - String serializeChargeDataToJson(boolean prettyPrint, Set responseParameters, ChargeData charge); + String serializeClientAccountSummaryCollectionDataToJson(boolean prettyPrint, Set responseParameters, + ClientAccountSummaryCollectionData clientAccount); + + String serializeGroupAccountSummaryCollectionDataToJson(boolean prettyPrint, Set responseParameters, + GroupAccountSummaryCollectionData groupAccount); + + String serializeGroupDataToJson(boolean prettyPrint, Set responseParameters, Collection groups); + + String serializeGroupDataToJson(boolean prettyPrint, Set responseParameters, GroupData group); + + String serializeNoteDataToJson(boolean prettyPrint, Set responseParameters, Collection notes); + + String serializeNoteDataToJson(boolean prettyPrint, Set responseParameters, NoteData note); + + String serializeLoanScheduleDataToJson(boolean prettyPrint, Set responseParameters, LoanScheduleData loanSchedule); + + String serializeLoanAccountDataToJson(boolean prettyPrint, Set responseParameters, LoanAccountData loanAccount); + + String serializeLoanTransactionDataToJson(boolean prettyPrint, Set responseParameters, LoanTransactionData newTransactionData); + + String serializeLoanReassignmentDataToJson(boolean prettyPrint, Set responseParameters, + LoanReassignmentData loanReassignmentData); + + String serializeChargeDataToJson(boolean prettyPrint, Set responseParameters, Collection charges); + + String serializeChargeDataToJson(boolean prettyPrint, Set responseParameters, ChargeData charge); String serializeLoanChargeDataToJson(boolean prettyPrint, Set responseParameters, LoanChargeData charge); - String serializeStaffDataToJson(boolean prettyPrint, Set responseParameters, StaffData staff); - - String serializeStaffDataToJson(boolean prettyPrint, Set responseParameters, Collection staff); + String serializeStaffDataToJson(boolean prettyPrint, Set responseParameters, StaffData staff); - String serializeEntityIdentifier(EntityIdentifier identifier); - - String serializeClientIdentifierDataToJson(boolean prettyPrint, Set responseParameters, Collection clientIdentifiers); + String serializeStaffDataToJson(boolean prettyPrint, Set responseParameters, Collection staff); - String serializeClientIdentifierDataToJson(boolean prettyPrint, Set responseParameters, ClientIdentifierData clientIdentifierData); - - String serializeDocumentDataToJson(boolean prettyPrint, Set responseParameters, Collection documentDatas); + String serializeEntityIdentifier(EntityIdentifier identifier); - String serializeDocumentDataToJson(boolean prettyPrint, Set responseParameters, DocumentData documentData); + String serializeClientIdentifierDataToJson(boolean prettyPrint, Set responseParameters, + Collection clientIdentifiers); - String serializeCodeDataToJson(boolean prettyPrint,Set responseParameters, Collection codes); + String serializeClientIdentifierDataToJson(boolean prettyPrint, Set responseParameters, + ClientIdentifierData clientIdentifierData); - String serializeCodeDataToJson(boolean prettyPrint,Set responseParameters, CodeData code); - - String serializeMakerCheckerDataToJson(boolean prettyPrint,Set responseParameters, Collection entries); + String serializeDocumentDataToJson(boolean prettyPrint, Set responseParameters, Collection documentDatas); - String serializeSavingAccountsDataToJson(boolean prettyPrint, Set responseParameters, SavingAccountData account); + String serializeDocumentDataToJson(boolean prettyPrint, Set responseParameters, DocumentData documentData); - String serializeSavingAccountsDataToJson(boolean prettyPrint, Set responseParameters, Collection accounts); + String serializeCodeDataToJson(boolean prettyPrint, Set responseParameters, Collection codes); - // TODO - KW - might devide serialize up into portfolio and account to reduce interface - String serializeChartOfAccountDataToJson(boolean prettyPrint, Set responseParameters, ChartOfAccountsData chartOfAccounts); + String serializeCodeDataToJson(boolean prettyPrint, Set responseParameters, CodeData code); + + String serializeMakerCheckerDataToJson(boolean prettyPrint, Set responseParameters, Collection entries); + + String serializeSavingAccountsDataToJson(boolean prettyPrint, Set responseParameters, SavingAccountData account); + + String serializeSavingAccountsDataToJson(boolean prettyPrint, Set responseParameters, Collection accounts); + + // TODO - KW - might devide serialize up into portfolio and account to + // reduce interface + String serializeChartOfAccountDataToJson(boolean prettyPrint, Set responseParameters, ChartOfAccountsData chartOfAccounts); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformService.java index 7716d00b9..7f975e2ff 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformService.java @@ -11,36 +11,36 @@ import org.springframework.security.access.prepost.PreAuthorize; public interface ClientWritePlatformService { - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENT')") - Long createClient(ClientCommand command); - - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_CLIENT')") - EntityIdentifier updateClientDetails(ClientCommand command); - - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_CLIENT')") - EntityIdentifier deleteClient(ClientCommand command); - - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIMAGE')") - EntityIdentifier saveOrUpdateClientImage(Long clientId, String imageName, InputStream inputStream); - - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIMAGE')") - EntityIdentifier saveOrUpdateClientImage(Long clientId, Base64EncodedImage encodedImage); - - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_CLIENTIMAGE')") - EntityIdentifier deleteClientImage(Long clientId); + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENT')") + Long createClient(ClientCommand command); - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTNOTE')") - EntityIdentifier addClientNote(NoteCommand command); + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_CLIENT')") + EntityIdentifier updateClientDetails(ClientCommand command); - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_CLIENTNOTE')") - EntityIdentifier updateNote(NoteCommand command); + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_CLIENT')") + EntityIdentifier deleteClient(ClientCommand command); - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIDENTIFIER')") - Long addClientIdentifier(ClientIdentifierCommand clientIdentifierCommand); - - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_CLIENTIDENTIFIER')") - EntityIdentifier updateClientIdentifier(ClientIdentifierCommand clientIdentifierCommand); - - @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_CLIENTIDENTIFIER')") - EntityIdentifier deleteClientIdentifier(Long clientIdentifierId); + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIMAGE')") + EntityIdentifier saveOrUpdateClientImage(Long clientId, String imageName, InputStream inputStream); + + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIMAGE')") + EntityIdentifier saveOrUpdateClientImage(Long clientId, Base64EncodedImage encodedImage); + + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_CLIENTIMAGE')") + EntityIdentifier deleteClientImage(Long clientId); + + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTNOTE')") + EntityIdentifier addClientNote(NoteCommand command); + + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_CLIENTNOTE')") + EntityIdentifier updateNote(NoteCommand command); + + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'CREATE_CLIENTIDENTIFIER')") + Long addClientIdentifier(ClientIdentifierCommand clientIdentifierCommand); + + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'UPDATE_CLIENTIDENTIFIER')") + EntityIdentifier updateClientIdentifier(ClientIdentifierCommand clientIdentifierCommand); + + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'PORTFOLIO_MANAGEMENT_SUPER_USER', 'DELETE_CLIENTIDENTIFIER')") + EntityIdentifier deleteClientIdentifier(Long clientIdentifierId); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java index 5106d3c4b..76530006f 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java @@ -40,382 +40,332 @@ import org.springframework.transaction.annotation.Transactional; @Service public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWritePlatformService { - private final static Logger logger = LoggerFactory.getLogger(ClientWritePlatformServiceJpaRepositoryImpl.class); + private final static Logger logger = LoggerFactory.getLogger(ClientWritePlatformServiceJpaRepositoryImpl.class); - private final PlatformSecurityContext context; - private final ClientRepository clientRepository; - private final ClientIdentifierRepository clientIdentifierRepository; - private final OfficeRepository officeRepository; - private final NoteRepository noteRepository; - private final CodeValueRepository codeValueRepository; + private final PlatformSecurityContext context; + private final ClientRepository clientRepository; + private final ClientIdentifierRepository clientIdentifierRepository; + private final OfficeRepository officeRepository; + private final NoteRepository noteRepository; + private final CodeValueRepository codeValueRepository; - // FIXME - kw - this value is hardcoded for now but will be retrieved from configuration - private boolean makerCheckerEnabledForTask = false; + // FIXME - kw - this value is hardcoded for now but will be retrieved from + // configuration + private boolean makerCheckerEnabledForTask = false; - @Autowired - public ClientWritePlatformServiceJpaRepositoryImpl( - final PlatformSecurityContext context, - final ClientRepository clientRepository, - final ClientIdentifierRepository clientIdentifierRepository, - final OfficeRepository officeRepository, - NoteRepository noteRepository, - final CodeValueRepository codeValueRepository) { - this.context = context; - this.clientRepository = clientRepository; - this.clientIdentifierRepository = clientIdentifierRepository; - this.officeRepository = officeRepository; - this.noteRepository = noteRepository; - this.codeValueRepository = codeValueRepository; - } + @Autowired + public ClientWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final ClientRepository clientRepository, + final ClientIdentifierRepository clientIdentifierRepository, final OfficeRepository officeRepository, + NoteRepository noteRepository, final CodeValueRepository codeValueRepository) { + this.context = context; + this.clientRepository = clientRepository; + this.clientIdentifierRepository = clientIdentifierRepository; + this.officeRepository = officeRepository; + this.noteRepository = noteRepository; + this.codeValueRepository = codeValueRepository; + } - @Transactional - @Override - public EntityIdentifier deleteClient(final ClientCommand command) { + @Transactional + @Override + public EntityIdentifier deleteClient(final ClientCommand command) { - final Long clientId = command.getId(); - final Client client = this.clientRepository.findOne(clientId); - if (client == null || client.isDeleted()) { - throw new ClientNotFoundException(clientId); - } + final Long clientId = command.getId(); + final Client client = this.clientRepository.findOne(clientId); + if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); } - client.delete(); - this.clientRepository.save(client); - - if (this.makerCheckerEnabledForTask && !command.isApprovedByChecker()) { - throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); - } + client.delete(); + this.clientRepository.save(client); - return new EntityIdentifier(client.getId()); - } + if (this.makerCheckerEnabledForTask && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - /* - * Guaranteed to throw an exception no matter what the data integrity issue - * is. - */ - private void handleDataIntegrityIssues(final ClientCommand command, - final DataIntegrityViolationException dve) { + return new EntityIdentifier(client.getId()); + } - Throwable realCause = dve.getMostSpecificCause(); - if (realCause.getMessage().contains("external_id")) { - throw new PlatformDataIntegrityException( - "error.msg.client.duplicate.externalId", - "Client with externalId `" + command.getExternalId() - + "` already exists", "externalId", - command.getExternalId()); - } + /* + * Guaranteed to throw an exception no matter what the data integrity issue + * is. + */ + private void handleDataIntegrityIssues(final ClientCommand command, final DataIntegrityViolationException dve) { - logger.error(dve.getMessage(), dve); - throw new PlatformDataIntegrityException( - "error.msg.client.unknown.data.integrity.issue", - "Unknown data integrity issue with resource."); - } + Throwable realCause = dve.getMostSpecificCause(); + if (realCause.getMessage().contains("external_id")) { throw new PlatformDataIntegrityException( + "error.msg.client.duplicate.externalId", "Client with externalId `" + command.getExternalId() + "` already exists", + "externalId", command.getExternalId()); } - @Transactional - @Override - public Long createClient(final ClientCommand command) { + logger.error(dve.getMessage(), dve); + throw new PlatformDataIntegrityException("error.msg.client.unknown.data.integrity.issue", + "Unknown data integrity issue with resource."); + } - try { - context.authenticatedUser(); + @Transactional + @Override + public Long createClient(final ClientCommand command) { - final ClientCommandValidator validator = new ClientCommandValidator(command); - validator.validateForCreate(); + try { + context.authenticatedUser(); - final Office clientOffice = this.officeRepository.findOne(command.getOfficeId()); - if (clientOffice == null) { - throw new OfficeNotFoundException(command.getOfficeId()); - } + final ClientCommandValidator validator = new ClientCommandValidator(command); + validator.validateForCreate(); - String firstname = command.getFirstname(); - String lastname = command.getLastname(); - if (StringUtils.isNotBlank(command.getClientOrBusinessName())) { - lastname = command.getClientOrBusinessName(); - firstname = null; - } + final Office clientOffice = this.officeRepository.findOne(command.getOfficeId()); + if (clientOffice == null) { throw new OfficeNotFoundException(command.getOfficeId()); } - final Client newClient = Client - .newClient(clientOffice, firstname, lastname, - command.getJoiningDate(), command.getExternalId()); + String firstname = command.getFirstname(); + String lastname = command.getLastname(); + if (StringUtils.isNotBlank(command.getClientOrBusinessName())) { + lastname = command.getClientOrBusinessName(); + firstname = null; + } - this.clientRepository.save(newClient); + final Client newClient = Client.newClient(clientOffice, firstname, lastname, command.getJoiningDate(), command.getExternalId()); - if (this.makerCheckerEnabledForTask && !command.isApprovedByChecker()) { - throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); - } - - return newClient.getId(); - } catch (DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve); - return Long.valueOf(-1); - } - } + this.clientRepository.save(newClient); - @Transactional - @Override - public EntityIdentifier updateClientDetails(final ClientCommand command) { + if (this.makerCheckerEnabledForTask && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - try { - context.authenticatedUser(); + return newClient.getId(); + } catch (DataIntegrityViolationException dve) { + handleDataIntegrityIssues(command, dve); + return Long.valueOf(-1); + } + } - final ClientCommandValidator validator = new ClientCommandValidator(command); - validator.validateForUpdate(); + @Transactional + @Override + public EntityIdentifier updateClientDetails(final ClientCommand command) { - Office clientOffice = null; - Long officeId = command.getOfficeId(); - if (command.isOfficeChanged() && officeId != null) { - clientOffice = this.officeRepository.findOne(officeId); - if (clientOffice == null) { - throw new OfficeNotFoundException(command.getOfficeId()); - } - } + try { + context.authenticatedUser(); - final Client clientForUpdate = this.clientRepository.findOne(command.getId()); - if (clientForUpdate == null || clientForUpdate.isDeleted()) { - throw new ClientNotFoundException(command.getId()); - } - clientForUpdate.update(clientOffice, command); + final ClientCommandValidator validator = new ClientCommandValidator(command); + validator.validateForUpdate(); - this.clientRepository.saveAndFlush(clientForUpdate); - - if (this.makerCheckerEnabledForTask && !command.isApprovedByChecker()) { - throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); - } + Office clientOffice = null; + Long officeId = command.getOfficeId(); + if (command.isOfficeChanged() && officeId != null) { + clientOffice = this.officeRepository.findOne(officeId); + if (clientOffice == null) { throw new OfficeNotFoundException(command.getOfficeId()); } + } - return new EntityIdentifier(clientForUpdate.getId()); - } catch (DataIntegrityViolationException dve) { - handleDataIntegrityIssues(command, dve); - return new EntityIdentifier(Long.valueOf(-1)); - } - } + final Client clientForUpdate = this.clientRepository.findOne(command.getId()); + if (clientForUpdate == null || clientForUpdate.isDeleted()) { throw new ClientNotFoundException(command.getId()); } + clientForUpdate.update(clientOffice, command); - @Transactional - @Override - public EntityIdentifier addClientNote(final NoteCommand command) { + this.clientRepository.saveAndFlush(clientForUpdate); - context.authenticatedUser(); + if (this.makerCheckerEnabledForTask && !command.isApprovedByChecker()) { throw new RollbackTransactionAsCommandIsNotApprovedByCheckerException(); } - final Client clientForUpdate = this.clientRepository.findOne(command.getClientId()); - if (clientForUpdate == null) { - throw new ClientNotFoundException(command.getClientId()); - } + return new EntityIdentifier(clientForUpdate.getId()); + } catch (DataIntegrityViolationException dve) { + handleDataIntegrityIssues(command, dve); + return new EntityIdentifier(Long.valueOf(-1)); + } + } - final Note note = Note.clientNote(clientForUpdate, command.getNote()); + @Transactional + @Override + public EntityIdentifier addClientNote(final NoteCommand command) { - this.noteRepository.save(note); + context.authenticatedUser(); - return new EntityIdentifier(note.getId()); - } + final Client clientForUpdate = this.clientRepository.findOne(command.getClientId()); + if (clientForUpdate == null) { throw new ClientNotFoundException(command.getClientId()); } - @Transactional - @Override - public EntityIdentifier updateNote(final NoteCommand command) { + final Note note = Note.clientNote(clientForUpdate, command.getNote()); - context.authenticatedUser(); + this.noteRepository.save(note); - final Note noteForUpdate = this.noteRepository.findOne(command.getId()); - if (noteForUpdate == null - || noteForUpdate.isNotAgainstClientWithIdOf(command.getClientId())) { - throw new NoteNotFoundException(command.getId(),command.getClientId(), "client"); - } + return new EntityIdentifier(note.getId()); + } - noteForUpdate.update(command.getNote()); + @Transactional + @Override + public EntityIdentifier updateNote(final NoteCommand command) { - return new EntityIdentifier(noteForUpdate.getId()); - } + context.authenticatedUser(); - @Transactional - @Override - public Long addClientIdentifier(final ClientIdentifierCommand command) { - - String documentTypeLabel = null; - Long documentTypeId = null; - final String documentKey = command.getDocumentKey(); - - try { - context.authenticatedUser(); + final Note noteForUpdate = this.noteRepository.findOne(command.getId()); + if (noteForUpdate == null || noteForUpdate.isNotAgainstClientWithIdOf(command.getClientId())) { throw new NoteNotFoundException( + command.getId(), command.getClientId(), "client"); } - final ClientIdentifierCommandValidator validator = new ClientIdentifierCommandValidator(command); - validator.validateForCreate(); + noteForUpdate.update(command.getNote()); - final Client client = this.clientRepository.findOne(command.getClientId()); - if (client == null || client.isDeleted()) { - throw new ClientNotFoundException(command.getClientId()); - } + return new EntityIdentifier(noteForUpdate.getId()); + } - final CodeValue documentType = this.codeValueRepository.findOne(command.getDocumentTypeId()); - if (documentType == null) { - throw new CodeValueNotFoundException(command.getDocumentTypeId()); - } - documentTypeId = documentType.getId(); - documentTypeLabel = documentType.getLabel(); + @Transactional + @Override + public Long addClientIdentifier(final ClientIdentifierCommand command) { - final ClientIdentifier clientIdentifier = ClientIdentifier.createNew(client, documentType, documentKey, command.getDescription()); + String documentTypeLabel = null; + Long documentTypeId = null; + final String documentKey = command.getDocumentKey(); - this.clientIdentifierRepository.save(clientIdentifier); + try { + context.authenticatedUser(); - return clientIdentifier.getId(); - } catch (DataIntegrityViolationException dve) { - handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve); - return Long.valueOf(-1); - } - } - - @Transactional - @Override - public EntityIdentifier updateClientIdentifier(final ClientIdentifierCommand command) { - - String documentTypeLabel = null; - Long documentTypeId = null; - String documentKey = command.getDocumentKey(); - - try { - context.authenticatedUser(); + final ClientIdentifierCommandValidator validator = new ClientIdentifierCommandValidator(command); + validator.validateForCreate(); - final ClientIdentifierCommandValidator validator = new ClientIdentifierCommandValidator(command); - validator.validateForUpdate(); + final Client client = this.clientRepository.findOne(command.getClientId()); + if (client == null || client.isDeleted()) { throw new ClientNotFoundException(command.getClientId()); } - CodeValue documentType = null; - documentTypeId = command.getDocumentTypeId(); - if (command.isDocumentTypeChanged() && documentTypeId != null) { - documentType = this.codeValueRepository.findOne(documentTypeId); - if (documentType == null) { - throw new CodeValueNotFoundException(command.getDocumentTypeId()); - } - documentTypeId = documentType.getId(); - documentTypeLabel = documentType.getLabel(); - } + final CodeValue documentType = this.codeValueRepository.findOne(command.getDocumentTypeId()); + if (documentType == null) { throw new CodeValueNotFoundException(command.getDocumentTypeId()); } + documentTypeId = documentType.getId(); + documentTypeLabel = documentType.getLabel(); - final ClientIdentifier clientIdentifierForUpdate = this.clientIdentifierRepository.findOne(command.getId()); - if (clientIdentifierForUpdate == null) { - throw new ClientIdentifierNotFoundException(command.getId()); - } - - // TODO - KW - why need to check what changed when integrity violation occurs? - if (command.isDocumentTypeChanged() && command.isDocumentKeyChanged()) { - documentTypeId = command.getDocumentTypeId(); - documentKey = command.getDocumentKey(); - } else if (command.isDocumentTypeChanged() && !command.isDocumentKeyChanged()) { - documentTypeId = command.getDocumentTypeId(); - documentKey = clientIdentifierForUpdate.getDocumentKey(); - } else if (!command.isDocumentTypeChanged() && command.isDocumentKeyChanged()) { - documentTypeId = clientIdentifierForUpdate.getDocumentType().getId(); - documentKey = clientIdentifierForUpdate.getDocumentKey(); - } - - clientIdentifierForUpdate.update(command, documentType); + final ClientIdentifier clientIdentifier = ClientIdentifier.createNew(client, documentType, documentKey, + command.getDescription()); - this.clientIdentifierRepository.saveAndFlush(clientIdentifierForUpdate); + this.clientIdentifierRepository.save(clientIdentifier); - return new EntityIdentifier(clientIdentifierForUpdate.getId()); - } catch (DataIntegrityViolationException dve) { - handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve); - return new EntityIdentifier(Long.valueOf(-1)); - } - } + return clientIdentifier.getId(); + } catch (DataIntegrityViolationException dve) { + handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve); + return Long.valueOf(-1); + } + } - private void handleClientIdentifierDataIntegrityViolation( - final String documentTypeLabel, - final Long documentTypeId, - final String documentKey, - final DataIntegrityViolationException dve) { - - if (dve.getMostSpecificCause().getMessage().contains("unique_client_identifier")) { - throw new DuplicateClientIdentifierException(documentTypeLabel); - } else if (dve.getMostSpecificCause().getMessage().contains("unique_identifier_key")) { - throw new DuplicateClientIdentifierException(documentTypeId, documentTypeLabel, documentKey); - } - - // only log as error if unexpected data integrity violation. - logger.error(dve.getMessage(), dve); - throw new PlatformDataIntegrityException( - "error.msg.clientIdentifier.unknown.data.integrity.issue", - "Unknown data integrity issue with resource."); - } + @Transactional + @Override + public EntityIdentifier updateClientIdentifier(final ClientIdentifierCommand command) { - @Transactional - @Override - public EntityIdentifier deleteClientIdentifier(final Long clientIdentifierId) { - final ClientIdentifier clientIdentifier = this.clientIdentifierRepository.findOne(clientIdentifierId); - if (clientIdentifier == null) { - throw new ClientIdentifierNotFoundException(clientIdentifierId); - } - this.clientIdentifierRepository.delete(clientIdentifier); + String documentTypeLabel = null; + Long documentTypeId = null; + String documentKey = command.getDocumentKey(); - return new EntityIdentifier(clientIdentifierId); - } + try { + context.authenticatedUser(); - @Transactional - @Override - public EntityIdentifier saveOrUpdateClientImage(Long clientId, - String imageName, InputStream inputStream) { - try { - final Client client = this.clientRepository.findOne(clientId); - String imageUploadLocation = setupForClientImageUpdate(clientId, - client); + final ClientIdentifierCommandValidator validator = new ClientIdentifierCommandValidator(command); + validator.validateForUpdate(); - String imageLocation = FileUtils.saveToFileSystem(inputStream, - imageUploadLocation, imageName); + CodeValue documentType = null; + documentTypeId = command.getDocumentTypeId(); + if (command.isDocumentTypeChanged() && documentTypeId != null) { + documentType = this.codeValueRepository.findOne(documentTypeId); + if (documentType == null) { throw new CodeValueNotFoundException(command.getDocumentTypeId()); } + documentTypeId = documentType.getId(); + documentTypeLabel = documentType.getLabel(); + } - - return updateClientImage(clientId, client, imageLocation); - } catch (IOException ioe) { - logger.error(ioe.getMessage(), ioe); - throw new DocumentManagementException(imageName); - } - } + final ClientIdentifier clientIdentifierForUpdate = this.clientIdentifierRepository.findOne(command.getId()); + if (clientIdentifierForUpdate == null) { throw new ClientIdentifierNotFoundException(command.getId()); } - @Transactional - @Override - public EntityIdentifier deleteClientImage(final Long clientId) { - - final Client client = this.clientRepository.findOne(clientId); - if (client == null || client.isDeleted()) { - throw new ClientNotFoundException(clientId); - } - - // delete image from the file system - if (StringUtils.isNotEmpty(client.getImageKey())) { - FileUtils.deleteClientImage(clientId, client.getImageKey()); - } - return updateClientImage(clientId, client, null); - } + // TODO - KW - why need to check what changed when integrity + // violation occurs? + if (command.isDocumentTypeChanged() && command.isDocumentKeyChanged()) { + documentTypeId = command.getDocumentTypeId(); + documentKey = command.getDocumentKey(); + } else if (command.isDocumentTypeChanged() && !command.isDocumentKeyChanged()) { + documentTypeId = command.getDocumentTypeId(); + documentKey = clientIdentifierForUpdate.getDocumentKey(); + } else if (!command.isDocumentTypeChanged() && command.isDocumentKeyChanged()) { + documentTypeId = clientIdentifierForUpdate.getDocumentType().getId(); + documentKey = clientIdentifierForUpdate.getDocumentKey(); + } - @Override - public EntityIdentifier saveOrUpdateClientImage(final Long clientId, final Base64EncodedImage encodedImage) { - try { - final Client client = this.clientRepository.findOne(clientId); - final String imageUploadLocation = setupForClientImageUpdate(clientId, client); + clientIdentifierForUpdate.update(command, documentType); - final String imageLocation = FileUtils.saveToFileSystem(encodedImage, imageUploadLocation, "image"); - - return updateClientImage(clientId, client, imageLocation); - } catch (IOException ioe) { - logger.error(ioe.getMessage(), ioe); - throw new DocumentManagementException("image"); - } - } + this.clientIdentifierRepository.saveAndFlush(clientIdentifierForUpdate); - private String setupForClientImageUpdate(final Long clientId, final Client client) { - if (client == null || client.isDeleted()) { - throw new ClientNotFoundException(clientId); - } + return new EntityIdentifier(clientIdentifierForUpdate.getId()); + } catch (DataIntegrityViolationException dve) { + handleClientIdentifierDataIntegrityViolation(documentTypeLabel, documentTypeId, documentKey, dve); + return new EntityIdentifier(Long.valueOf(-1)); + } + } - final String imageUploadLocation = FileUtils.generateClientImageParentDirectory(clientId); - // delete previous image from the file system - if (StringUtils.isNotEmpty(client.getImageKey())) { - FileUtils.deleteClientImage(clientId, client.getImageKey()); - } + private void handleClientIdentifierDataIntegrityViolation(final String documentTypeLabel, final Long documentTypeId, + final String documentKey, final DataIntegrityViolationException dve) { - /** Recursively create the directory if it does not exist **/ - if (!new File(imageUploadLocation).isDirectory()) { - new File(imageUploadLocation).mkdirs(); - } - return imageUploadLocation; - } - - private EntityIdentifier updateClientImage(final Long clientId, final Client client, final String imageLocation) { - client.setImageKey(imageLocation); - this.clientRepository.save(client); + if (dve.getMostSpecificCause().getMessage().contains("unique_client_identifier")) { + throw new DuplicateClientIdentifierException(documentTypeLabel); + } else if (dve.getMostSpecificCause().getMessage().contains("unique_identifier_key")) { throw new DuplicateClientIdentifierException( + documentTypeId, documentTypeLabel, documentKey); } - return new EntityIdentifier(clientId); - } + // only log as error if unexpected data integrity violation. + logger.error(dve.getMessage(), dve); + throw new PlatformDataIntegrityException("error.msg.clientIdentifier.unknown.data.integrity.issue", + "Unknown data integrity issue with resource."); + } + + @Transactional + @Override + public EntityIdentifier deleteClientIdentifier(final Long clientIdentifierId) { + final ClientIdentifier clientIdentifier = this.clientIdentifierRepository.findOne(clientIdentifierId); + if (clientIdentifier == null) { throw new ClientIdentifierNotFoundException(clientIdentifierId); } + this.clientIdentifierRepository.delete(clientIdentifier); + + return new EntityIdentifier(clientIdentifierId); + } + + @Transactional + @Override + public EntityIdentifier saveOrUpdateClientImage(Long clientId, String imageName, InputStream inputStream) { + try { + final Client client = this.clientRepository.findOne(clientId); + String imageUploadLocation = setupForClientImageUpdate(clientId, client); + + String imageLocation = FileUtils.saveToFileSystem(inputStream, imageUploadLocation, imageName); + + return updateClientImage(clientId, client, imageLocation); + } catch (IOException ioe) { + logger.error(ioe.getMessage(), ioe); + throw new DocumentManagementException(imageName); + } + } + + @Transactional + @Override + public EntityIdentifier deleteClientImage(final Long clientId) { + + final Client client = this.clientRepository.findOne(clientId); + if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); } + + // delete image from the file system + if (StringUtils.isNotEmpty(client.getImageKey())) { + FileUtils.deleteClientImage(clientId, client.getImageKey()); + } + return updateClientImage(clientId, client, null); + } + + @Override + public EntityIdentifier saveOrUpdateClientImage(final Long clientId, final Base64EncodedImage encodedImage) { + try { + final Client client = this.clientRepository.findOne(clientId); + final String imageUploadLocation = setupForClientImageUpdate(clientId, client); + + final String imageLocation = FileUtils.saveToFileSystem(encodedImage, imageUploadLocation, "image"); + + return updateClientImage(clientId, client, imageLocation); + } catch (IOException ioe) { + logger.error(ioe.getMessage(), ioe); + throw new DocumentManagementException("image"); + } + } + + private String setupForClientImageUpdate(final Long clientId, final Client client) { + if (client == null || client.isDeleted()) { throw new ClientNotFoundException(clientId); } + + final String imageUploadLocation = FileUtils.generateClientImageParentDirectory(clientId); + // delete previous image from the file system + if (StringUtils.isNotEmpty(client.getImageKey())) { + FileUtils.deleteClientImage(clientId, client.getImageKey()); + } + + /** Recursively create the directory if it does not exist **/ + if (!new File(imageUploadLocation).isDirectory()) { + new File(imageUploadLocation).mkdirs(); + } + return imageUploadLocation; + } + + private EntityIdentifier updateClientImage(final Long clientId, final Client client, final String imageLocation) { + client.setImageKey(imageLocation); + this.clientRepository.save(client); + + return new EntityIdentifier(clientId); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/errorhandling/UnsupportedCommandException.java b/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/errorhandling/UnsupportedCommandException.java new file mode 100644 index 000000000..cee06fe0a --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/errorhandling/UnsupportedCommandException.java @@ -0,0 +1,19 @@ +package org.mifosng.platform.infrastructure.errorhandling; + + +/** + * A {@link RuntimeException} that is thrown in the case where an invalid or unknown + * command is attempted to be processed by platform. + */ +public class UnsupportedCommandException extends RuntimeException { + + private final String unsupportedCommandName; + + public UnsupportedCommandException(final String unsupportedCommandName) { + this.unsupportedCommandName = unsupportedCommandName; + } + + public String getUnsupportedCommandName() { + return unsupportedCommandName; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/errorhandling/UnsupportedCommandExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/errorhandling/UnsupportedCommandExceptionMapper.java new file mode 100644 index 000000000..0554d1ca2 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/infrastructure/errorhandling/UnsupportedCommandExceptionMapper.java @@ -0,0 +1,42 @@ +package org.mifosng.platform.infrastructure.errorhandling; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.mifosng.platform.api.data.ApiGlobalErrorResponse; +import org.mifosng.platform.api.data.ApiParameterError; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +/** + * An {@link ExceptionMapper} to map {@link UnsupportedCommandException} thrown by platform into a HTTP API friendly format. + */ +@Provider +@Component +@Scope("singleton") +public class UnsupportedCommandExceptionMapper implements ExceptionMapper { + + @Override + public Response toResponse(final UnsupportedCommandException exception) { + + List errors = new ArrayList(); + + StringBuilder validationErrorCode = new StringBuilder("error.msg.command.unsupported"); + StringBuilder defaultEnglishMessage = new StringBuilder("The command ").append(exception.getUnsupportedCommandName()).append(" is not supported."); + ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), exception.getUnsupportedCommandName(), exception.getUnsupportedCommandName()); + + errors.add(error); + + ApiGlobalErrorResponse invalidParameterError = ApiGlobalErrorResponse.badClientRequest( + "validation.msg.validation.errors.exist", + "Validation errors exist.", errors); + + return Response.status(Status.BAD_REQUEST).entity(invalidParameterError).type(MediaType.APPLICATION_JSON).build(); + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/domain/CommandSource.java b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/domain/CommandSource.java index 15ddc902b..5f02e55c1 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/domain/CommandSource.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/domain/CommandSource.java @@ -19,99 +19,108 @@ import org.springframework.data.jpa.domain.AbstractPersistable; @Table(name = "m_portfolio_command_source") public class CommandSource extends AbstractPersistable { - @Column(name = "api_operation", length = 20) - private String apiOperation; - - @Column(name = "api_resource", length = 20) - private String resource; - - @Column(name = "resource_id") - private Long resourceId; - - @Column(name = "command_as_json", length = 1000) - private String commandAsJson; + @Column(name = "api_operation", length = 20) + private String apiOperation; - // should maker and checker be a staff member as opposed to just any application user? - @SuppressWarnings("unused") - @ManyToOne - @JoinColumn(name = "maker_id", nullable = false) - private AppUser maker; - - @SuppressWarnings("unused") - @Column(name = "made_on_date", nullable = false) + @Column(name = "api_resource", length = 20) + private String resource; + + @Column(name = "resource_id") + private Long resourceId; + + @Column(name = "command_as_json", length = 1000) + private String commandAsJson; + + @ManyToOne + @JoinColumn(name = "maker_id", nullable = false) + private AppUser maker; + + @Column(name = "made_on_date", nullable = false) @Temporal(TemporalType.DATE) - private Date madeOnDate; - - @SuppressWarnings("unused") - @ManyToOne - @JoinColumn(name = "checker_id", nullable = true) - private AppUser checker; - - @SuppressWarnings("unused") - @Column(name = "checked_on_date", nullable = false) + private Date madeOnDate; + + @SuppressWarnings("unused") + @ManyToOne + @JoinColumn(name = "checker_id", nullable = true) + private AppUser checker; + + @SuppressWarnings("unused") + @Column(name = "checked_on_date", nullable = false) @Temporal(TemporalType.DATE) - private Date checkedOnDate; + private Date checkedOnDate; - public static CommandSource createdBy( - final String apiOperation, - final String resource, - final Long resourceId, - final AppUser maker, - final LocalDate madeOnDate) { - return new CommandSource(apiOperation, resource, resourceId, maker, madeOnDate); - } + public static CommandSource createdBy(final String apiOperation, final String resource, final Long resourceId, final AppUser maker, + final LocalDate madeOnDate) { + return new CommandSource(apiOperation, resource, resourceId, maker, madeOnDate); + } - protected CommandSource() { - // - } + protected CommandSource() { + // + } - private CommandSource( - final String apiOperation, - final String resource, - final Long resourceId, - final AppUser maker, - final LocalDate madeOnDate) { - this.apiOperation = StringUtils.defaultIfEmpty(apiOperation, null); - this.resource = StringUtils.defaultIfEmpty(resource, null); - this.resourceId = resourceId; - this.maker = maker; - this.madeOnDate = madeOnDate.toDate(); - } + private CommandSource(final String apiOperation, final String resource, final Long resourceId, final AppUser maker, + final LocalDate madeOnDate) { + this.apiOperation = StringUtils.defaultIfEmpty(apiOperation, null); + this.resource = StringUtils.defaultIfEmpty(resource, null); + this.resourceId = resourceId; + this.maker = maker; + this.madeOnDate = madeOnDate.toDate(); + } - public void markAsChecked(final AppUser checker, final LocalDate checkedOnDate) { - this.checker = checker; - this.checkedOnDate = checkedOnDate.toDate(); - } - - public void updateResourceId(final Long resourceId) { - this.resourceId = resourceId; - } - - public void updateJsonTo(final String json) { - this.commandAsJson = json; - } - - public Long resourceId() { - return this.resourceId; - } + public CommandSource copy() { + LocalDate madeOnLocalDate = null; + if (this.madeOnDate != null) { + madeOnLocalDate = new LocalDate(this.madeOnDate); + } + return new CommandSource(this.apiOperation, this.resource, this.resourceId, this.maker, madeOnLocalDate); + } - public String json() { - return this.commandAsJson; - } + public void markAsChecked(final AppUser checker, final LocalDate checkedOnDate) { + this.checker = checker; + this.checkedOnDate = checkedOnDate.toDate(); + } - public boolean isClientResource() { - return this.resource.equalsIgnoreCase("CLIENTS"); - } + public void updateResourceId(final Long resourceId) { + this.resourceId = resourceId; + } - public boolean isCreate() { - return this.apiOperation.equalsIgnoreCase("CREATE"); - } + public void updateJsonTo(final String json) { + this.commandAsJson = json; + } - public boolean isUpdate() { - return this.apiOperation.equalsIgnoreCase("UPDATE") && this.resourceId != null; - } + public Long resourceId() { + return this.resourceId; + } - public boolean isDelete() { - return this.apiOperation.equalsIgnoreCase("DELETE") && this.resourceId != null; - } + public String json() { + return this.commandAsJson; + } + + public String commandName() { + return this.apiOperation + '-' + this.resource; + } + + public String resourceName() { + return this.resource; + } + + public String operation() { + return this.apiOperation; + } + + public boolean isClientResource() { + return this.resource.equalsIgnoreCase("CLIENTS"); + } + + public boolean isCreate() { + return this.apiOperation.equalsIgnoreCase("CREATE"); + } + + public boolean isUpdate() { + return this.apiOperation.equalsIgnoreCase("UPDATE") && this.resourceId != null; + } + + public boolean isDelete() { + return this.apiOperation.equalsIgnoreCase("DELETE") && this.resourceId != null; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ChangeDetectionService.java b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ChangeDetectionService.java new file mode 100644 index 000000000..9d6258eda --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ChangeDetectionService.java @@ -0,0 +1,7 @@ +package org.mifosng.platform.makerchecker.service; + +public interface ChangeDetectionService { + + String detectChanges(String operation, String resourceName, Long resourceId, String commandSerializedAsJson); + +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ChangeDetectionServiceJdbc.java b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ChangeDetectionServiceJdbc.java new file mode 100644 index 000000000..b7c62fcdd --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ChangeDetectionServiceJdbc.java @@ -0,0 +1,48 @@ +package org.mifosng.platform.makerchecker.service; + +import org.mifosng.platform.api.commands.ClientCommand; +import org.mifosng.platform.api.data.ClientData; +import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; +import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService; +import org.mifosng.platform.client.service.ClientReadPlatformService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ChangeDetectionServiceJdbc implements ChangeDetectionService { + + private final PortfolioApiDataConversionService apiDataConversionService; + private final PortfolioApiJsonSerializerService apiJsonSerializerService; + private final ClientReadPlatformService clientReadPlatformService; + + @Autowired + public ChangeDetectionServiceJdbc(final PortfolioApiDataConversionService apiDataConversionService, + final PortfolioApiJsonSerializerService apiJsonSerializerService, final ClientReadPlatformService clientReadPlatformService) { + this.apiDataConversionService = apiDataConversionService; + this.apiJsonSerializerService = apiJsonSerializerService; + this.clientReadPlatformService = clientReadPlatformService; + } + + @Override + public String detectChanges(final String operation, final String resourceName, final Long resourceId, + final String commandSerializedAsJson) { + + String changesOnlyJson = ""; + + // FIXME - KW/JW - this change detection code for update of clients + // using ClientCommand can re placed when more suitable sql version is + // implemented. + final ClientData originalClient = this.clientReadPlatformService.retrieveIndividualClient(resourceId); + final ClientData changedClient = this.apiDataConversionService.convertInternalJsonFormatToClientDataChange(resourceId, + commandSerializedAsJson); + + final String baseJson = this.apiJsonSerializerService.serializeClientDataToJson(originalClient); + final String workingJson = this.apiJsonSerializerService.serializeClientDataToJson(changedClient); + final ClientCommand changesOnly = this.apiDataConversionService.detectChanges(resourceId, baseJson, workingJson); + + changesOnlyJson = this.apiJsonSerializerService.serializeClientCommandToJson(changesOnly); + + return changesOnlyJson; + } + +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ClientCommandHandler.java b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ClientCommandHandler.java new file mode 100644 index 000000000..ec4180d32 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/ClientCommandHandler.java @@ -0,0 +1,113 @@ +package org.mifosng.platform.makerchecker.service; + +import org.joda.time.LocalDate; +import org.mifosng.platform.api.commands.ClientCommand; +import org.mifosng.platform.api.data.EntityIdentifier; +import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; +import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService; +import org.mifosng.platform.client.service.ClientWritePlatformService; +import org.mifosng.platform.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException; +import org.mifosng.platform.makerchecker.domain.CommandSource; +import org.mifosng.platform.security.PlatformSecurityContext; +import org.mifosng.platform.user.domain.AppUser; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ClientCommandHandler implements CommandSourceHandler { + + private final PlatformSecurityContext context; + private final ChangeDetectionService changeDetectionService; + private final PortfolioApiDataConversionService apiDataConversionService; + private final PortfolioApiJsonSerializerService apiJsonSerializerService; + private final ClientWritePlatformService clientWritePlatformService; + + @Autowired + public ClientCommandHandler(final PlatformSecurityContext context, final ChangeDetectionService changeDetectionService, + final PortfolioApiDataConversionService apiDataConversionService, + final PortfolioApiJsonSerializerService apiJsonSerializerService, final ClientWritePlatformService clientWritePlatformService) { + this.context = context; + this.changeDetectionService = changeDetectionService; + this.apiDataConversionService = apiDataConversionService; + this.apiJsonSerializerService = apiJsonSerializerService; + this.clientWritePlatformService = clientWritePlatformService; + } + + public CommandSource handle(final CommandSource commandSource, final String apiRequestBodyInJson) { + + final AppUser maker = context.authenticatedUser(); + final LocalDate asToday = new LocalDate(); + + CommandSource commandSourceResult = commandSource.copy(); + + final Long resourceId = commandSource.resourceId(); + Long newResourceId = null; + + final ClientCommand command = this.apiDataConversionService.convertApiRequestJsonToClientCommand(resourceId, apiRequestBodyInJson); + final String commandSerializedAsJson = this.apiJsonSerializerService.serializeClientCommandToJson(command); + commandSourceResult.updateJsonTo(commandSerializedAsJson); + + if (commandSource.isCreate()) { + try { + newResourceId = this.clientWritePlatformService.createClient(command); + commandSourceResult.markAsChecked(maker, asToday); + commandSourceResult.updateResourceId(newResourceId); + } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { + // swallow this rollback transaction by design + } + } else if (commandSource.isUpdate()) { + try { + final String jsonOfChangesOnly = this.changeDetectionService.detectChanges(commandSource.operation(), + commandSource.resourceName(), commandSource.resourceId(), commandSerializedAsJson); + commandSourceResult.updateJsonTo(jsonOfChangesOnly); + + final ClientCommand changesOnly = this.apiDataConversionService.convertInternalJsonFormatToClientCommand( + commandSource.resourceId(), jsonOfChangesOnly, false); + + EntityIdentifier result = this.clientWritePlatformService.updateClientDetails(changesOnly); + newResourceId = result.getEntityId(); + + commandSourceResult.markAsChecked(maker, asToday); + } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { + // swallow this rollback transaction by design + } + } else if (commandSource.isDelete()) { + try { + EntityIdentifier result = this.clientWritePlatformService.deleteClient(command); + newResourceId = result.getEntityId(); + commandSourceResult.markAsChecked(maker, asToday); + } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { + // swallow this rollback transaction by design + } + } + + return commandSourceResult; + } + + public CommandSource handle(final CommandSource commandSourceResult) { + + Long resourceId = null; + if (commandSourceResult.isClientResource()) { + final ClientCommand command = this.apiDataConversionService.convertInternalJsonFormatToClientCommand( + commandSourceResult.resourceId(), commandSourceResult.json(), true); + + if (commandSourceResult.isCreate()) { + resourceId = this.clientWritePlatformService.createClient(command); + } else if (commandSourceResult.isUpdate()) { + + // TODO - is there a case for doing change detection at this + // point also? + + EntityIdentifier result = this.clientWritePlatformService.updateClientDetails(command); + resourceId = result.getEntityId(); + } else if (commandSourceResult.isDelete()) { + EntityIdentifier result = this.clientWritePlatformService.deleteClient(command); + resourceId = result.getEntityId(); + } + } + + commandSourceResult.updateResourceId(resourceId); + + return commandSourceResult; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/CommandSourceHandler.java b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/CommandSourceHandler.java new file mode 100644 index 000000000..2aad99075 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/CommandSourceHandler.java @@ -0,0 +1,5 @@ +package org.mifosng.platform.makerchecker.service; + +public interface CommandSourceHandler { + +} diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/CommandSourceHandlerDelegator.java b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/CommandSourceHandlerDelegator.java new file mode 100644 index 000000000..7d15e6cc1 --- /dev/null +++ b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/CommandSourceHandlerDelegator.java @@ -0,0 +1,48 @@ +package org.mifosng.platform.makerchecker.service; + +import org.mifosng.platform.infrastructure.errorhandling.UnsupportedCommandException; +import org.mifosng.platform.makerchecker.domain.CommandSource; +import org.mifosng.platform.security.PlatformSecurityContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * A class to delegate handling of commands to appropriate handler. + */ +@Service +public class CommandSourceHandlerDelegator { + + private final PlatformSecurityContext context; + private final ClientCommandHandler clientCommandHandler; + + @Autowired + public CommandSourceHandlerDelegator(final PlatformSecurityContext context, final ClientCommandHandler clientCommandHandler) { + this.context = context; + this.clientCommandHandler = clientCommandHandler; + } + + public CommandSource handle(final CommandSource commandSource, final String apiRequestBodyInJson) { + + context.authenticatedUser(); + CommandSource commandSourceResult = null; + if (commandSource.isClientResource()) { + commandSourceResult = clientCommandHandler.handle(commandSource, apiRequestBodyInJson); + } else { + throw new UnsupportedCommandException(commandSource.commandName()); + } + + return commandSourceResult; + } + + public CommandSource handleExistingCommand(final CommandSource commandSource) { + + CommandSource commandSourceResult = null; + if (commandSource.isClientResource()) { + commandSourceResult = clientCommandHandler.handle(commandSource); + } else { + throw new UnsupportedCommandException(commandSource.commandName()); + } + + return commandSourceResult; + } +} \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/PortfolioCommandSourceWriteServiceImpl.java b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/PortfolioCommandSourceWriteServiceImpl.java index 691a9d8a9..4e0ac2fef 100644 --- a/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/PortfolioCommandSourceWriteServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosng/platform/makerchecker/service/PortfolioCommandSourceWriteServiceImpl.java @@ -1,14 +1,7 @@ package org.mifosng.platform.makerchecker.service; import org.joda.time.LocalDate; -import org.mifosng.platform.api.commands.ClientCommand; -import org.mifosng.platform.api.data.ClientData; import org.mifosng.platform.api.data.EntityIdentifier; -import org.mifosng.platform.api.infrastructure.PortfolioApiDataConversionService; -import org.mifosng.platform.api.infrastructure.PortfolioApiJsonSerializerService; -import org.mifosng.platform.client.service.ClientReadPlatformService; -import org.mifosng.platform.client.service.ClientWritePlatformService; -import org.mifosng.platform.client.service.RollbackTransactionAsCommandIsNotApprovedByCheckerException; import org.mifosng.platform.makerchecker.domain.CommandSource; import org.mifosng.platform.makerchecker.domain.CommandSourceRepository; import org.mifosng.platform.security.PlatformSecurityContext; @@ -20,128 +13,58 @@ import org.springframework.transaction.annotation.Transactional; @Service public class PortfolioCommandSourceWriteServiceImpl implements PortfolioCommandSourceWritePlatformService { - private final PlatformSecurityContext context; - private final CommandSourceRepository commandSourceRepository; - private final PortfolioApiDataConversionService apiDataConversionService; - private final PortfolioApiJsonSerializerService apiJsonSerializerService; - private final ClientWritePlatformService clientWritePlatformService; - private final ClientReadPlatformService clientReadPlatformService; + private final PlatformSecurityContext context; + private final CommandSourceRepository commandSourceRepository; + private final CommandSourceHandlerDelegator commandSourceHandlerDelegator; - @Autowired - public PortfolioCommandSourceWriteServiceImpl(final PlatformSecurityContext context, final CommandSourceRepository makerCheckerRepository, - final PortfolioApiDataConversionService apiDataConversionService, - final PortfolioApiJsonSerializerService apiJsonSerializerService, - final ClientWritePlatformService clientWritePlatformService, - final ClientReadPlatformService clientReadPlatformService) { - this.context = context; - this.commandSourceRepository = makerCheckerRepository; - this.apiDataConversionService = apiDataConversionService; - this.apiJsonSerializerService = apiJsonSerializerService; - this.clientWritePlatformService = clientWritePlatformService; - this.clientReadPlatformService = clientReadPlatformService; - } + @Autowired + public PortfolioCommandSourceWriteServiceImpl(final PlatformSecurityContext context, + final CommandSourceRepository makerCheckerRepository, + final CommandSourceHandlerDelegator commandSourceHandlerDelegator) { + this.context = context; + this.commandSourceRepository = makerCheckerRepository; + this.commandSourceHandlerDelegator = commandSourceHandlerDelegator; + } - // NOT TRANSACTIONAL BY DESIGN FOR NOW - @Override - public EntityIdentifier logCommandSource(final String apiOperation, final String resource, final Long resourceId, final String jsonRequestBody) { - - final AppUser maker = context.authenticatedUser(); - - final LocalDate asToday = new LocalDate(); - - final CommandSource commandSource = CommandSource.createdBy(apiOperation, resource, resourceId, maker, asToday); - - Long newResourceId = null; - if (commandSource.isClientResource()) { - - // translate incoming api request json into java object catering for local and dateFormat parts of api - final ClientCommand command = this.apiDataConversionService.convertApiRequestJsonToClientCommand(resourceId, jsonRequestBody); - // produce serialized json of internal java object representation for persistence. - final String internalCommandSerializedAsJson = this.apiJsonSerializerService.serializeClientCommandToJson(command); - commandSource.updateJsonTo(internalCommandSerializedAsJson); - - if (commandSource.isCreate()) { - try { - newResourceId = this.clientWritePlatformService.createClient(command); - commandSource.markAsChecked(maker, asToday); - commandSource.updateResourceId(newResourceId); - } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { - // swallow this rollback transaction by design - } - } else if (commandSource.isUpdate()) { - try { - // useful to employ change detection on update scenario to only store what details have changed - final ClientData originalClient = this.clientReadPlatformService.retrieveIndividualClient(resourceId); - final ClientData changedClient = this.apiDataConversionService.convertInternalJsonFormatToClientDataChange(resourceId, internalCommandSerializedAsJson); + // NOT TRANSACTIONAL BY DESIGN FOR NOW + @Override + public EntityIdentifier logCommandSource(final String apiOperation, final String resource, final Long resourceId, + final String apiRequestBodyInJson) { - final String baseJson = this.apiJsonSerializerService.serializeClientDataToJson(originalClient); - final String workingJson = this.apiJsonSerializerService.serializeClientDataToJson(changedClient); - final ClientCommand changesOnly = this.apiDataConversionService.detectChanges(resourceId, baseJson, workingJson); + final AppUser maker = context.authenticatedUser(); + final LocalDate asToday = new LocalDate(); - final String changesOnlyJson = this.apiJsonSerializerService.serializeClientCommandToJson(changesOnly); - commandSource.updateJsonTo(changesOnlyJson); - - EntityIdentifier result = this.clientWritePlatformService.updateClientDetails(changesOnly); - newResourceId = result.getEntityId(); - - commandSource.markAsChecked(maker, asToday); - } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { - // swallow this rollback transaction by design - } - } else if (commandSource.isDelete()) { - try { - EntityIdentifier result = this.clientWritePlatformService.deleteClient(command); - newResourceId = result.getEntityId(); - commandSource.markAsChecked(maker, asToday); - } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { - // swallow this rollback transaction by design - } - } - } - - commandSourceRepository.save(commandSource); - - return EntityIdentifier.makerChecker(newResourceId, commandSource.getId()); - } + final CommandSource commandSourceInput = CommandSource.createdBy(apiOperation, resource, resourceId, maker, asToday); + final CommandSource commandSourceResult = this.commandSourceHandlerDelegator.handle(commandSourceInput, apiRequestBodyInJson); + commandSourceRepository.save(commandSourceResult); - @Transactional - @Override - public EntityIdentifier approveEntry(final Long id) { - - final AppUser checker = context.authenticatedUser(); - - final CommandSource entity = this.commandSourceRepository.findOne(id); - entity.markAsChecked(checker, new LocalDate()); - - Long resourceId = null; - if (entity.isClientResource()) { - final ClientCommand command = this.apiDataConversionService.convertInternalJsonFormatToClientCommand(entity.resourceId(), entity.json(), true); - if (entity.isCreate()) { - resourceId = this.clientWritePlatformService.createClient(command); - } else if (entity.isUpdate()) { - EntityIdentifier result = this.clientWritePlatformService.updateClientDetails(command); - resourceId = result.getEntityId(); - } else if (entity.isDelete()) { - EntityIdentifier result = this.clientWritePlatformService.deleteClient(command); - resourceId = result.getEntityId(); - } - } - - entity.updateResourceId(resourceId); - - commandSourceRepository.save(entity); - - return EntityIdentifier.makerChecker(resourceId, entity.getId()); - } + return EntityIdentifier.makerChecker(commandSourceResult.resourceId(), commandSourceResult.getId()); + } - @Transactional - @Override - public Long deleteEntry(final Long makerCheckerId) { - - context.authenticatedUser(); - - this.commandSourceRepository.delete(makerCheckerId); - - return makerCheckerId; - } + @Transactional + @Override + public EntityIdentifier approveEntry(final Long id) { + + final AppUser checker = context.authenticatedUser(); + + final CommandSource commandSourceInput = this.commandSourceRepository.findOne(id); + commandSourceInput.markAsChecked(checker, new LocalDate()); + + final CommandSource commandSourceResult = this.commandSourceHandlerDelegator.handleExistingCommand(commandSourceInput); + + commandSourceRepository.save(commandSourceResult); + + return EntityIdentifier.makerChecker(commandSourceResult.resourceId(), commandSourceResult.getId()); + } + + @Transactional + @Override + public Long deleteEntry(final Long makerCheckerId) { + + context.authenticatedUser(); + + this.commandSourceRepository.delete(makerCheckerId); + + return makerCheckerId; + } } \ No newline at end of file