From 1474ea9179c7d0ec72d84598c421502153ce3385 Mon Sep 17 00:00:00 2001 From: Keith Woodlock Date: Fri, 20 Sep 2013 09:41:38 +0100 Subject: [PATCH 1/8] update version numbers for release. --- api-docs/apiLive.htm | 2 +- mifosng-provider/gradle.properties | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/api-docs/apiLive.htm b/api-docs/apiLive.htm index b9fda5f0e..fb7fc2522 100644 --- a/api-docs/apiLive.htm +++ b/api-docs/apiLive.htm @@ -90,7 +90,7 @@
- +

Overview

diff --git a/mifosng-provider/gradle.properties b/mifosng-provider/gradle.properties index fa2e5fbb8..02ffe6690 100644 --- a/mifosng-provider/gradle.properties +++ b/mifosng-provider/gradle.properties @@ -1,2 +1,2 @@ -releaseVersion=1.10.0.RELEASE +releaseVersion=1.10.1.RELEASE From 5463e27b2c79c63b1a43eb7dd8a2c00dab9a8524 Mon Sep 17 00:00:00 2001 From: ashok-conflux Date: Fri, 20 Sep 2013 14:30:09 +0530 Subject: [PATCH 2/8] Added missing charges columns to Savings account table --- .../migrations/core_db/V119__savings_charge_patch_update.sql | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 mifosng-db/migrations/core_db/V119__savings_charge_patch_update.sql diff --git a/mifosng-db/migrations/core_db/V119__savings_charge_patch_update.sql b/mifosng-db/migrations/core_db/V119__savings_charge_patch_update.sql new file mode 100644 index 000000000..01502cb4b --- /dev/null +++ b/mifosng-db/migrations/core_db/V119__savings_charge_patch_update.sql @@ -0,0 +1,3 @@ +ALTER TABLE `m_savings_account` + ADD COLUMN `total_fees_charge_derived` DECIMAL(19,6) NULL DEFAULT NULL AFTER `total_withdrawal_fees_derived`, + ADD COLUMN `total_penalty_charge_derived` DECIMAL(19,6) NULL DEFAULT NULL AFTER `total_fees_charge_derived`; \ No newline at end of file From f991ba64da4d601c39b829022a862eaf114be83f Mon Sep 17 00:00:00 2001 From: Keith Woodlock Date: Fri, 20 Sep 2013 10:10:35 +0100 Subject: [PATCH 3/8] fix eclipse warnings around unused imports and fields in Data objects. --- .../account/data/AccountAssociationsData.java | 2 + ...ntAssociationsReadPlatformServiceImpl.java | 27 +++--- .../loanaccount/data/LoanChargeData.java | 25 ++--- ...WritePlatformServiceJpaRepositoryImpl.java | 67 +++++++------- .../loanaccount/service/LoanAssembler.java | 7 +- ...WritePlatformServiceJpaRepositoryImpl.java | 70 +++++++------- .../savings/data/SavingsAccountData.java | 9 +- .../domain/SavingsProductAssembler.java | 27 +++--- ...WritePlatformServiceJpaRepositoryImpl.java | 92 +++++++++---------- ...WritePlatformServiceJpaRepositoryImpl.java | 5 +- ...SavingsProductReadPlatformServiceImpl.java | 43 +++++---- 11 files changed, 182 insertions(+), 192 deletions(-) diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountAssociationsData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountAssociationsData.java index 0ea13a06e..c873f442a 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountAssociationsData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountAssociationsData.java @@ -2,7 +2,9 @@ package org.mifosplatform.portfolio.account.data; public class AccountAssociationsData { + @SuppressWarnings("unused") private final Long id; + @SuppressWarnings("unused") private final PortfolioAccountData account; private final PortfolioAccountData linkedAccount; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java index b0b228cb4..886191dd2 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java @@ -31,14 +31,14 @@ public class AccountAssociationsReadPlatformServiceImpl implements AccountAssoci @Override public PortfolioAccountData retriveLoanAssociation(final Long loanId) { PortfolioAccountData linkedAccount = null; - AccountAssociationsMapper mapper = new AccountAssociationsMapper(); - String sql = "select " + mapper.schema() + " where aa.loan_account_id = ? "; + final AccountAssociationsMapper mapper = new AccountAssociationsMapper(); + final String sql = "select " + mapper.schema() + " where aa.loan_account_id = ? "; try { - AccountAssociationsData accountAssociationsData = jdbcTemplate.queryForObject(sql, mapper, loanId); + final AccountAssociationsData accountAssociationsData = this.jdbcTemplate.queryForObject(sql, mapper, loanId); if (accountAssociationsData != null) { linkedAccount = accountAssociationsData.linkedAccount(); } - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { logger.debug("Linking account is not configured"); } return linkedAccount; @@ -47,13 +47,13 @@ public class AccountAssociationsReadPlatformServiceImpl implements AccountAssoci @Override public boolean isLinkedWithAnyActiveLoan(final Long savingsId) { boolean hasActiveLoan = false; - String sql = "select loanAccount.loan_status_id as status from m_portfolio_account_associations aa " + + final String sql = "select loanAccount.loan_status_id as status from m_portfolio_account_associations aa " + "left join m_loan loanAccount on loanAccount.id = aa.loan_account_id " + "where aa.linked_savings_account_id = ?"; - - List statusList= this.jdbcTemplate.queryForList(sql,Integer.class, savingsId); - for(Integer status:statusList){ - LoanStatus loanStatus= LoanStatus.fromInt(status); + + final List statusList= this.jdbcTemplate.queryForList(sql,Integer.class, savingsId); + for(final Integer status:statusList){ + final LoanStatus loanStatus= LoanStatus.fromInt(status); if(loanStatus.isActiveOrAwaitingApprovalOrDisbursal() || loanStatus.isUnderTransfer()){ hasActiveLoan = true; break; @@ -67,7 +67,7 @@ public class AccountAssociationsReadPlatformServiceImpl implements AccountAssoci private final String schemaSql; public AccountAssociationsMapper() { - StringBuilder sqlBuilder = new StringBuilder(); + final StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("aa.id as id,"); // sqlBuilder.append("savingsAccount.id as savingsAccountId, savingsAccount.account_no as savingsAccountNo,"); sqlBuilder.append("loanAccount.id as loanAccountId, loanAccount.account_no as loanAccountNo,"); @@ -86,7 +86,7 @@ public class AccountAssociationsReadPlatformServiceImpl implements AccountAssoci } @Override - public AccountAssociationsData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { + public AccountAssociationsData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); // final Long savingsAccountId = JdbcSupport.getLong(rs, @@ -94,8 +94,7 @@ public class AccountAssociationsReadPlatformServiceImpl implements AccountAssoci // final String savingsAccountNo = rs.getString("savingsAccountNo"); final Long loanAccountId = JdbcSupport.getLong(rs, "loanAccountId"); final String loanAccountNo = rs.getString("loanAccountNo"); - PortfolioAccountData account = PortfolioAccountData.lookup(loanAccountId, loanAccountNo); - ; + final PortfolioAccountData account = PortfolioAccountData.lookup(loanAccountId, loanAccountNo); /* * if (savingsAccountId != null) { account = * PortfolioAccountData.lookup(savingsAccountId, savingsAccountNo); @@ -108,7 +107,7 @@ public class AccountAssociationsReadPlatformServiceImpl implements AccountAssoci // "linkLoanAccountId"); // final String linkLoanAccountNo = // rs.getString("linkLoanAccountNo"); - PortfolioAccountData linkedAccount = PortfolioAccountData.lookup(linkSavingsAccountId, linkSavingsAccountNo); + final PortfolioAccountData linkedAccount = PortfolioAccountData.lookup(linkSavingsAccountId, linkSavingsAccountNo); /* * if (linkSavingsAccountId != null) { linkedAccount = * PortfolioAccountData.lookup(linkSavingsAccountId, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanChargeData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanChargeData.java index e42f7d775..5d8f88576 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanChargeData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanChargeData.java @@ -19,19 +19,14 @@ import org.mifosplatform.portfolio.charge.domain.ChargePaymentMode; */ public class LoanChargeData { - @SuppressWarnings("unused") private final Long id; - @SuppressWarnings("unused") private final Long chargeId; - @SuppressWarnings("unused") private final String name; - @SuppressWarnings("unused") private final EnumOptionData chargeTimeType; - @SuppressWarnings("unused") private final LocalDate dueDate; @SuppressWarnings("unused") @@ -55,7 +50,6 @@ public class LoanChargeData { @SuppressWarnings("unused") private final BigDecimal amountWrittenOff; - @SuppressWarnings("unused") private final BigDecimal amountOutstanding; @SuppressWarnings("unused") @@ -72,9 +66,10 @@ public class LoanChargeData { private final boolean paid; private final boolean waived; - + + @SuppressWarnings("unused") private final boolean chargePayable; - + private final Long loanId; public static LoanChargeData template(final Collection chargeOptions) { @@ -96,7 +91,7 @@ public class LoanChargeData { final BigDecimal amountPaid, final BigDecimal amountWaived, final BigDecimal amountWrittenOff, final BigDecimal amountOutstanding, final EnumOptionData chargeTimeType, final LocalDate dueDate, final EnumOptionData chargeCalculationType, final BigDecimal percentage, final BigDecimal amountPercentageAppliedTo, - final boolean penalty, EnumOptionData chargePaymentMode, boolean paid, boolean waived, Long loanId) { + final boolean penalty, final EnumOptionData chargePaymentMode, final boolean paid, final boolean waived, final Long loanId) { this.id = id; this.chargeId = chargeId; this.name = name; @@ -129,8 +124,8 @@ public class LoanChargeData { private LoanChargeData(final Long id, final Long chargeId, final String name, final CurrencyData currency, final BigDecimal amount, final BigDecimal pecentage, final EnumOptionData chargeTimeType, final EnumOptionData chargeCalculationType, - final Collection chargeOptions, final boolean penalty, EnumOptionData chargePaymentMode, boolean paid, - boolean waived, Long loanId) { + final Collection chargeOptions, final boolean penalty, final EnumOptionData chargePaymentMode, final boolean paid, + final boolean waived, final Long loanId) { this.id = id; this.chargeId = chargeId; this.name = name; @@ -193,20 +188,20 @@ public class LoanChargeData { } return isAccountTransfer && !this.paid && !this.waived; } - + public Long getId() { return this.id; } - + public LocalDate getDueDate() { return this.dueDate; } - + public Long getLoanId() { return this.loanId; } - + public BigDecimal getAmountOutstanding() { return this.amountOutstanding; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java index 571ae4ded..343bdd345 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java @@ -33,7 +33,6 @@ import org.mifosplatform.portfolio.calendar.domain.CalendarInstance; import org.mifosplatform.portfolio.calendar.domain.CalendarInstanceRepository; import org.mifosplatform.portfolio.calendar.domain.CalendarRepository; import org.mifosplatform.portfolio.calendar.exception.CalendarNotFoundException; -import org.mifosplatform.portfolio.charge.domain.ChargePaymentMode; import org.mifosplatform.portfolio.client.domain.AccountNumberGenerator; import org.mifosplatform.portfolio.client.domain.AccountNumberGeneratorFactory; import org.mifosplatform.portfolio.client.domain.Client; @@ -149,7 +148,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa } private LoanLifecycleStateMachine defaultLoanLifecycleStateMachine() { - List allowedLoanStatuses = Arrays.asList(LoanStatus.values()); + final List allowedLoanStatuses = Arrays.asList(LoanStatus.values()); return new DefaultLoanLifecycleStateMachine(allowedLoanStatuses); } @@ -158,14 +157,14 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa public CommandProcessingResult submitApplication(final JsonCommand command) { try { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan"); - final Long productId = fromJsonHelper.extractLongNamed("productId", command.parsedJson()); + final Long productId = this.fromJsonHelper.extractLongNamed("productId", command.parsedJson()); final LoanProduct loanProduct = this.loanProductRepository.findOne(productId); if (loanProduct == null) { throw new LoanProductNotFoundException(productId); } @@ -173,7 +172,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - final Loan newLoanApplication = loanAssembler.assembleFrom(command, currentUser); + final Loan newLoanApplication = this.loanAssembler.assembleFrom(command, currentUser); validateSubmittedOnDate(newLoanApplication); @@ -193,7 +192,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa final String submittedOnNote = command.stringValueOfParameterNamed("submittedOnNote"); if (StringUtils.isNotBlank(submittedOnNote)) { - Note note = Note.loanNote(newLoanApplication, submittedOnNote); + final Note note = Note.loanNote(newLoanApplication, submittedOnNote); this.noteRepository.save(note); } @@ -205,7 +204,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa calendar = this.calendarRepository.findOne(calendarId); if (calendar == null) { throw new CalendarNotFoundException(calendarId); } - CalendarInstance calendarInstance = new CalendarInstance(calendar, newLoanApplication.getId(), + final CalendarInstance calendarInstance = new CalendarInstance(calendar, newLoanApplication.getId(), CalendarEntityType.LOANS.getValue()); this.calendarInstanceRepository.save(calendarInstance); } @@ -213,9 +212,9 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa // Save linked account information final Long savingsAccountId = command.longValueOfParameterNamed("linkAccountId"); if (savingsAccountId != null) { - SavingsAccount savingsAccount = this.savingsAccountAssembler.assembleFrom(savingsAccountId); + final SavingsAccount savingsAccount = this.savingsAccountAssembler.assembleFrom(savingsAccountId); this.fromApiJsonDeserializer.validatelinkedSavingsAccount(savingsAccount, newLoanApplication); - AccountAssociations accountAssociations = AccountAssociations.associateSavingsAccount(newLoanApplication, savingsAccount); + final AccountAssociations accountAssociations = AccountAssociations.associateSavingsAccount(newLoanApplication, savingsAccount); this.accountAssociationsRepository.save(accountAssociations); } @@ -227,7 +226,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa .withGroupId(newLoanApplication.getGroupId()) // .withLoanId(newLoanApplication.getId()) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -238,7 +237,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa public CommandProcessingResult modifyApplication(final Long loanId, final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForModify(command.json()); @@ -351,7 +350,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa final String submittedOnNote = command.stringValueOfParameterNamed("submittedOnNote"); if (StringUtils.isNotBlank(submittedOnNote)) { - Note note = Note.loanNote(existingLoanApplication, submittedOnNote); + final Note note = Note.loanNote(existingLoanApplication, submittedOnNote); this.noteRepository.save(note); } @@ -362,27 +361,27 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa if (calendar == null) { throw new CalendarNotFoundException(calendarId); } } - List ciList = (List) this.calendarInstanceRepository.findByEntityIdAndEntityTypeId(loanId, + final List ciList = (List) this.calendarInstanceRepository.findByEntityIdAndEntityTypeId(loanId, CalendarEntityType.LOANS.getValue()); if (calendar != null) { // For loans, allow to attach only one calendar instance per // loan if (ciList != null && !ciList.isEmpty()) { - CalendarInstance calendarInstance = ciList.get(0); + final CalendarInstance calendarInstance = ciList.get(0); if (calendarInstance.getCalendar().getId() != calendar.getId()) { calendarInstance.updateCalendar(calendar); this.calendarInstanceRepository.saveAndFlush(calendarInstance); } } else { // attaching new calendar - CalendarInstance calendarInstance = new CalendarInstance(calendar, existingLoanApplication.getId(), + final CalendarInstance calendarInstance = new CalendarInstance(calendar, existingLoanApplication.getId(), CalendarEntityType.LOANS.getValue()); this.calendarInstanceRepository.save(calendarInstance); } } else if (ciList != null && !ciList.isEmpty()) { - CalendarInstance calendarInstance = ciList.get(0); + final CalendarInstance calendarInstance = ciList.get(0); this.calendarInstanceRepository.delete(calendarInstance); } @@ -406,13 +405,13 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa if (accountAssociations == null) { isModified = true; } else { - SavingsAccount savingsAccount = accountAssociations.linkedSavingsAccount(); + final SavingsAccount savingsAccount = accountAssociations.linkedSavingsAccount(); if (savingsAccount == null || savingsAccount.getId() != savingsAccountId) { isModified = true; } } if (isModified) { - SavingsAccount savingsAccount = this.savingsAccountAssembler.assembleFrom(savingsAccountId); + final SavingsAccount savingsAccount = this.savingsAccountAssembler.assembleFrom(savingsAccountId); this.fromApiJsonDeserializer.validatelinkedSavingsAccount(savingsAccount, existingLoanApplication); if (accountAssociations == null) { accountAssociations = AccountAssociations.associateSavingsAccount(existingLoanApplication, savingsAccount); @@ -426,7 +425,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa if (!isLinkedAccPresent) { final Set charges = existingLoanApplication.charges(); - for (LoanCharge loanCharge : charges) { + for (final LoanCharge loanCharge : charges) { if (loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) { final String errorMessage = "one of the charges requires linked savings account for payment"; throw new LinkedAccountRequiredException("loanCharge", errorMessage); @@ -441,7 +440,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa .withGroupId(existingLoanApplication.getGroupId()) // .withLoanId(existingLoanApplication.getId()) // .with(changes).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -453,7 +452,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa */ private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("loan_account_no_UNIQUE")) { final String accountNo = command.stringValueOfParameterNamed("accountNo"); @@ -478,14 +477,14 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa @Override public CommandProcessingResult deleteApplication(final Long loanId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final Loan loan = retrieveLoanBy(loanId); checkClientOrGroupActive(loan); if (loan.isNotSubmittedAndPendingApproval()) { throw new LoanApplicationNotInSubmittedAndPendingApprovalStateCannotBeDeleted(loanId); } - List relatedNotes = this.noteRepository.findByLoanId(loan.getId()); + final List relatedNotes = this.noteRepository.findByLoanId(loan.getId()); this.noteRepository.deleteInBatch(relatedNotes); this.loanRepository.delete(loanId); @@ -503,7 +502,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa @Override public CommandProcessingResult approveApplication(final Long loanId, final JsonCommand command) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); this.loanApplicationTransitionApiJsonValidator.validateApproval(command.json()); @@ -516,7 +515,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { - Note note = Note.loanNote(loan, noteText); + final Note note = Note.loanNote(loan, noteText); changes.put("note", noteText); this.noteRepository.save(note); } @@ -537,7 +536,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa @Override public CommandProcessingResult undoApplicationApproval(final Long loanId, final JsonCommand command) { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUndo(command.json()); @@ -548,9 +547,9 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa if (!changes.isEmpty()) { this.loanRepository.save(loan); - String noteText = command.stringValueOfParameterNamed("note"); + final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { - Note note = Note.loanNote(loan, noteText); + final Note note = Note.loanNote(loan, noteText); this.noteRepository.save(note); } } @@ -570,7 +569,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa @Override public CommandProcessingResult rejectApplication(final Long loanId, final JsonCommand command) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); this.loanApplicationTransitionApiJsonValidator.validateRejection(command.json()); @@ -581,9 +580,9 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa if (!changes.isEmpty()) { this.loanRepository.save(loan); - String noteText = command.stringValueOfParameterNamed("note"); + final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { - Note note = Note.loanNote(loan, noteText); + final Note note = Note.loanNote(loan, noteText); this.noteRepository.save(note); } } @@ -603,7 +602,7 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa @Override public CommandProcessingResult applicantWithdrawsFromApplication(final Long loanId, final JsonCommand command) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); this.loanApplicationTransitionApiJsonValidator.validateApplicantWithdrawal(command.json()); @@ -615,9 +614,9 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa if (!changes.isEmpty()) { this.loanRepository.save(loan); - String noteText = command.stringValueOfParameterNamed("note"); + final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { - Note note = Note.loanNote(loan, noteText); + final Note note = Note.loanNote(loan, noteText); this.noteRepository.save(note); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanAssembler.java index 232d1b8d6..2a05f8354 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanAssembler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanAssembler.java @@ -25,7 +25,6 @@ import org.mifosplatform.organisation.staff.exception.StaffRoleException; import org.mifosplatform.organisation.workingdays.domain.WorkingDays; import org.mifosplatform.organisation.workingdays.domain.WorkingDaysRepositoryWrapper; import org.mifosplatform.portfolio.accountdetails.service.AccountEnumerations; -import org.mifosplatform.portfolio.charge.domain.ChargePaymentMode; import org.mifosplatform.portfolio.client.domain.Client; import org.mifosplatform.portfolio.client.domain.ClientRepositoryWrapper; import org.mifosplatform.portfolio.client.exception.ClientNotActiveException; @@ -56,8 +55,8 @@ import org.mifosplatform.portfolio.loanproduct.domain.LoanProduct; import org.mifosplatform.portfolio.loanproduct.domain.LoanProductRelatedDetail; import org.mifosplatform.portfolio.loanproduct.domain.LoanProductRepository; import org.mifosplatform.portfolio.loanproduct.domain.LoanTransactionProcessingStrategy; -import org.mifosplatform.portfolio.loanproduct.exception.LinkedAccountRequiredException; import org.mifosplatform.portfolio.loanproduct.exception.InvalidCurrencyException; +import org.mifosplatform.portfolio.loanproduct.exception.LinkedAccountRequiredException; import org.mifosplatform.portfolio.loanproduct.exception.LoanProductNotFoundException; import org.mifosplatform.useradministration.domain.AppUser; import org.springframework.beans.factory.annotation.Autowired; @@ -160,9 +159,9 @@ public class LoanAssembler { final String errorMessage = "Charge and Loan must have the same currency."; throw new InvalidCurrencyException("loanCharge", "attach.to.loan", errorMessage); } - if(loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()){ + if (loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) { final Long savingsAccountId = this.fromApiJsonHelper.extractLongNamed("linkAccountId", element); - if(savingsAccountId == null){ + if (savingsAccountId == null) { final String errorMessage = "one of the charges requires linked savings account for payment"; throw new LinkedAccountRequiredException("loanCharge", errorMessage); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java index 02435d792..a668a3ba3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java @@ -10,7 +10,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; -import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; @@ -246,22 +245,21 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf postJournalEntries(loan, existingTransactionIds, existingReversedTransactionIds); } - Set loanCharges = loan.charges(); - Map disBuLoanCharges = new HashMap(); - for (LoanCharge loanCharge : loanCharges) { + final Set loanCharges = loan.charges(); + final Map disBuLoanCharges = new HashMap(); + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueAtDisbursement() && loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) { disBuLoanCharges.put(loanCharge.getId(), loanCharge.amount()); } } final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); - for (Map.Entry entrySet: disBuLoanCharges.entrySet()) { - PortfolioAccountData savingAccountData = this.accountAssociationsReadPlatformService.retriveLoanAssociation(loanId); - AccountTransferDTO accountTransferDTO = new AccountTransferDTO(actualDisbursementDate, entrySet.getValue(), - PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN, savingAccountData.accountId(), loanId, - "Loan Charge Payment", locale, fmt, null, null, LoanTransactionType.REPAYMENT_AT_DISBURSEMENT.getValue(), - entrySet.getKey()); - accountTransfersWritePlatformService.transferFunds(accountTransferDTO); + for (final Map.Entry entrySet : disBuLoanCharges.entrySet()) { + final PortfolioAccountData savingAccountData = this.accountAssociationsReadPlatformService.retriveLoanAssociation(loanId); + final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(actualDisbursementDate, entrySet.getValue(), + PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN, savingAccountData.accountId(), loanId, "Loan Charge Payment", + locale, fmt, null, null, LoanTransactionType.REPAYMENT_AT_DISBURSEMENT.getValue(), entrySet.getKey()); + this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); } return new CommandProcessingResultBuilder() // @@ -475,7 +473,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final LoanTransaction transactionToAdjust = this.loanTransactionRepository.findOne(transactionId); if (transactionToAdjust == null) { throw new LoanTransactionNotFoundException(transactionId); } - if (accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.LOAN)) { throw new PlatformServiceUnavailableException( + if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.LOAN)) { throw new PlatformServiceUnavailableException( "error.msg.loan.transfer.transaction.update.not.allowed", "Loan transaction:" + transactionId + " update not allowed as it involves in account transfer", transactionId); } @@ -793,12 +791,12 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final String errorMessage = "Charge and Loan must have the same currency."; throw new InvalidCurrencyException("loanCharge", "attach.to.loan", errorMessage); } - if(loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()){ - PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService.retriveLoanAssociation(loanId); - if(portfolioAccountData == null){ - final String errorMessage = loanCharge.name()+"Charge requires linked savings account for payment"; - throw new LinkedAccountRequiredException("loanCharge.add", errorMessage,loanCharge.name()); - } + if (loanCharge.getChargePaymentMode().isPaymentModeAccountTransfer()) { + final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService.retriveLoanAssociation(loanId); + if (portfolioAccountData == null) { + final String errorMessage = loanCharge.name() + "Charge requires linked savings account for payment"; + throw new LinkedAccountRequiredException("loanCharge.add", errorMessage, loanCharge.name()); + } } final List existingTransactionIds = new ArrayList(); @@ -949,7 +947,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf @Override @Transactional public CommandProcessingResult payLoanCharge(final Long loanId, Long loanChargeId, final JsonCommand command, - boolean isChargeIdIncludedInJson) { + final boolean isChargeIdIncludedInJson) { this.loanEventApiJsonValidator.validateChargePaymentTransaction(command.json(), isChargeIdIncludedInJson); if (isChargeIdIncludedInJson) { @@ -978,15 +976,15 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); - PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService.retriveLoanAssociation(loanId); - if(portfolioAccountData == null){ - final String errorMessage = "Charge with id:"+loanChargeId+" requires linked savings account for payment"; - throw new LinkedAccountRequiredException("loanCharge.pay", errorMessage,loanChargeId); + final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService.retriveLoanAssociation(loanId); + if (portfolioAccountData == null) { + final String errorMessage = "Charge with id:" + loanChargeId + " requires linked savings account for payment"; + throw new LinkedAccountRequiredException("loanCharge.pay", errorMessage, loanChargeId); } - AccountTransferDTO accountTransferDTO = new AccountTransferDTO(transactionDate, loanCharge.amountOutstanding(), + final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(transactionDate, loanCharge.amountOutstanding(), PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN, portfolioAccountData.accountId(), loanId, "Loan Charge Payment", locale, fmt, null, null, LoanTransactionType.CHARGE_PAYMENT.getValue(), loanChargeId); - accountTransfersWritePlatformService.transferFunds(accountTransferDTO); + this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -1001,24 +999,24 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf @Override @CronTarget(jobName = JobName.TRANSFER_FEE_CHARGE_FOR_LOANS) public void transferFeeCharges() throws JobExecutionException { - Collection chargeDatas = this.LoanChargeReadPlatformService.retrieveLoanChargesForFeePayment( + final Collection chargeDatas = this.LoanChargeReadPlatformService.retrieveLoanChargesForFeePayment( ChargePaymentMode.ACCOUNT_TRANSFER.getValue(), LoanStatus.ACTIVE.getValue()); - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); if (chargeDatas != null) { - for (LoanChargeData chargeData : chargeDatas) { - if (chargeData.getDueDate()!=null && !chargeData.getDueDate().isAfter(new LocalDate())) { - PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService + for (final LoanChargeData chargeData : chargeDatas) { + if (chargeData.getDueDate() != null && !chargeData.getDueDate().isAfter(new LocalDate())) { + final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService .retriveLoanAssociation(chargeData.getLoanId()); - AccountTransferDTO accountTransferDTO = new AccountTransferDTO(new LocalDate(), chargeData.getAmountOutstanding(), + final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(new LocalDate(), chargeData.getAmountOutstanding(), PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN, portfolioAccountData.accountId(), chargeData.getLoanId(), "Loan Charge Payment", null, null, null, null, LoanTransactionType.CHARGE_PAYMENT.getValue(), chargeData.getId()); try { - accountTransfersWritePlatformService.transferFunds(accountTransferDTO); - } catch (PlatformApiDataValidationException e) { + this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); + } catch (final PlatformApiDataValidationException e) { sb.append("Validation exception while paying charge ").append(chargeData.getId()).append(" for loan id:") .append(chargeData.getLoanId()).append("--------"); - } catch (InsufficientAccountBalanceException e) { + } catch (final InsufficientAccountBalanceException e) { sb.append("InsufficientAccountBalance Exception while paying charge ").append(chargeData.getId()) .append("for loan id:").append(chargeData.getLoanId()).append("--------"); @@ -1086,7 +1084,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf @Transactional @Override - public LoanTransaction withdrawLoanTransfer(Long accountId, LocalDate transferDate) { + public LoanTransaction withdrawLoanTransfer(final Long accountId, final LocalDate transferDate) { final Loan loan = this.loanAssembler.assembleFrom(accountId); final List existingTransactionIds = new ArrayList(loan.findExistingTransactionIds()); @@ -1106,7 +1104,7 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf @Transactional @Override - public void rejectLoanTransfer(Long accountId) { + public void rejectLoanTransfer(final Long accountId) { final Loan loan = this.loanAssembler.assembleFrom(accountId); loan.setLoanStatus(LoanStatus.TRANSFER_ON_HOLD.getValue()); this.loanRepository.save(loan); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java index e08d966b3..1fcb80ac0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java @@ -55,6 +55,7 @@ public class SavingsAccountData { private final SavingsAccountSummaryData summary; @SuppressWarnings("unused") private final Collection transactions; + @SuppressWarnings("unused") private final Collection charges; // template @@ -76,7 +77,7 @@ public class SavingsAccountData { final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, final BigDecimal withdrawalFeeAmount, final EnumOptionData withdrawalFeeType, - boolean withdrawalFeeForTransfers, final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay, + final boolean withdrawalFeeForTransfers, final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay, final LocalDate annualFeeNextDueDate, final SavingsAccountSummaryData summary) { final Collection productOptions = null; @@ -217,7 +218,7 @@ public class SavingsAccountData { final Collection charges = null; final Collection chargeOptions = null; - + return new SavingsAccountData(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, status, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, @@ -282,7 +283,7 @@ public class SavingsAccountData { this.interestCalculationDaysInYearTypeOptions = interestCalculationDaysInYearTypeOptions; this.lockinPeriodFrequencyTypeOptions = lockinPeriodFrequencyTypeOptions; this.withdrawalFeeTypeOptions = withdrawalFeeTypeOptions; - + this.charges = charges;//charges associated with Savings account this.chargeOptions = chargeOptions;//charges available for adding to Savings account } @@ -313,7 +314,7 @@ public class SavingsAccountData { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } - SavingsAccountData rhs = (SavingsAccountData) obj; + final SavingsAccountData rhs = (SavingsAccountData) obj; return new EqualsBuilder().append(this.id, rhs.id).append(this.accountNo, rhs.accountNo).isEquals(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java index 1df895a36..6594a1d9c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java @@ -7,12 +7,11 @@ package org.mifosplatform.portfolio.savings.domain; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.annualFeeAmountParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.annualFeeOnMonthDayParamName; -import static org.mifosplatform.portfolio.savings.SavingsApiConstants.idParamName; -import static org.mifosplatform.portfolio.savings.SavingsApiConstants.chargeIdParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.chargesParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.currencyCodeParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.descriptionParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.digitsAfterDecimalParamName; +import static org.mifosplatform.portfolio.savings.SavingsApiConstants.idParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.inMultiplesOfParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.interestCalculationDaysInYearTypeParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.interestCalculationTypeParamName; @@ -55,7 +54,7 @@ import com.google.gson.JsonObject; public class SavingsProductAssembler { private final ChargeRepositoryWrapper chargeRepository; - + @Autowired public SavingsProductAssembler(final ChargeRepositoryWrapper chargeRepository) { this.chargeRepository = chargeRepository; @@ -69,7 +68,7 @@ public class SavingsProductAssembler { final String currencyCode = command.stringValueOfParameterNamed(currencyCodeParamName); final Integer digitsAfterDecimal = command.integerValueOfParameterNamed(digitsAfterDecimalParamName); final Integer inMultiplesOf = command.integerValueOfParameterNamed(inMultiplesOfParamName); - MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal,inMultiplesOf); + final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal,inMultiplesOf); final BigDecimal interestRate = command.bigDecimalValueOfParameterNamed(nominalAnnualInterestRateParamName); @@ -114,7 +113,7 @@ public class SavingsProductAssembler { if (withdrawalFeeTypeValue != null) { withdrawalFeeType = SavingsWithdrawalFeesType.fromInt(withdrawalFeeTypeValue); } - + boolean iswithdrawalFeeApplicableForTransfer = false; if(command.parameterExists(withdrawalFeeForTransfersParamName)){ iswithdrawalFeeApplicableForTransfer = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); @@ -123,10 +122,10 @@ public class SavingsProductAssembler { final BigDecimal annualFeeAmount = command.bigDecimalValueOfParameterNamedDefaultToNullIfZero(annualFeeAmountParamName); final MonthDay monthDayOfAnnualFee = command.extractMonthDayNamed(annualFeeOnMonthDayParamName); final AccountingRuleType accountingRuleType = AccountingRuleType.fromInt(command.integerValueOfParameterNamed("accountingRule")); - + //Savings product charges - final Set charges = this.assembleListOfSavingsProductCharges(command, currencyCode); - + final Set charges = assembleListOfSavingsProductCharges(command, currencyCode); + return SavingsProduct.createNew(name, description, currency, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, iswithdrawalFeeApplicableForTransfer, @@ -136,9 +135,9 @@ public class SavingsProductAssembler { public Set assembleListOfSavingsProductCharges(final JsonCommand command, final String savingsProductCurrencyCode) { final Set charges = new HashSet(); - + if (command.parameterExists(chargesParamName)) { - JsonArray chargesArray = command.arrayOfParameterNamed(chargesParamName); + final JsonArray chargesArray = command.arrayOfParameterNamed(chargesParamName); if (chargesArray != null) { for (int i = 0; i < chargesArray.size(); i++) { @@ -149,12 +148,12 @@ public class SavingsProductAssembler { final Charge charge = this.chargeRepository.findOneWithNotFoundDetection(id); if(!charge.isSavingsCharge()){ - String errorMessage = "Charge with identifier " + charge.getId() + " cannot be applied to Savings product."; - throw new ChargeCannotBeAppliedToException("savings.product", errorMessage, charge.getId()); + final String errorMessage = "Charge with identifier " + charge.getId() + " cannot be applied to Savings product."; + throw new ChargeCannotBeAppliedToException("savings.product", errorMessage, charge.getId()); } - + if (!savingsProductCurrencyCode.equals(charge.getCurrencyCode())) { - String errorMessage = "Charge and Savings Product must have the same currency."; + final String errorMessage = "Charge and Savings Product must have the same currency."; throw new InvalidCurrencyException("charge", "attach.to.savings.product", errorMessage); } charges.add(charge); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java index c5928cbd7..e23a1e2fe 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java @@ -173,7 +173,7 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi final BigDecimal transactionAmount = command.bigDecimalValueOfParameterNamed("transactionAmount"); final Map changes = new LinkedHashMap(); - PaymentDetail paymentDetail = paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes); + final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes); final SavingsAccountTransaction deposit = this.savingsAccountDomainService.handleDeposit(account, fmt, transactionDate, transactionAmount, paymentDetail); @@ -206,12 +206,12 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final Map changes = new LinkedHashMap(); - PaymentDetail paymentDetail = paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes); + final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes); final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId); checkClientOrGroupActive(account); - SavingsAccountTransaction withdrawal = this.savingsAccountDomainService.handleWithdrawal(account, fmt, transactionDate, + final SavingsAccountTransaction withdrawal = this.savingsAccountDomainService.handleWithdrawal(account, fmt, transactionDate, transactionAmount, paymentDetail, true); return new CommandProcessingResultBuilder() // @@ -319,16 +319,16 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi } @Override - public CommandProcessingResult undoTransaction(final Long savingsId, final Long transactionId, boolean allowAccountTransferModification) { + public CommandProcessingResult undoTransaction(final Long savingsId, final Long transactionId, final boolean allowAccountTransferModification) { final List newTransactionIds = new ArrayList(); final List reversedTransactionIds = new ArrayList(); - SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository.findOneByIdAndSavingsAccountId( + final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository.findOneByIdAndSavingsAccountId( transactionId, savingsId); if (savingsAccountTransaction == null) { throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId); } - - if(!allowAccountTransferModification && accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)){ + + if(!allowAccountTransferModification && this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)){ throw new PlatformServiceUnavailableException("error.msg.saving.account.transfer.transaction.update.not.allowed","Savings account transaction:"+transactionId+" update not allowed as it involves in account transfer",transactionId); } @@ -363,14 +363,14 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi @Override public CommandProcessingResult adjustSavingsTransaction(final Long savingsId, final Long transactionId, final JsonCommand command) { - SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository.findOneByIdAndSavingsAccountId( + final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository.findOneByIdAndSavingsAccountId( transactionId, savingsId); if (savingsAccountTransaction == null) { throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId); } if (!(savingsAccountTransaction.isDeposit() || savingsAccountTransaction.isWithdrawal()) || savingsAccountTransaction.isReversed()) { throw new TransactionUpdateNotAllowedException( savingsId, transactionId); } - - if(accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)){ + + if(this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)){ throw new PlatformServiceUnavailableException("error.msg.saving.account.transfer.transaction.update.not.allowed","Savings account transaction:"+transactionId+" update not allowed as it involves in account transfer",transactionId); } this.savingsAccountTransactionDataValidator.validate(command); @@ -389,13 +389,13 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi final List existingTransactionIds = new ArrayList(); final List existingReversedTransactionIds = new ArrayList(); final Map changes = new LinkedHashMap(); - PaymentDetail paymentDetail = paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes); + final PaymentDetail paymentDetail = this.paymentDetailWritePlatformService.createAndPersistPaymentDetail(command, changes); final MathContext mc = new MathContext(10, RoundingMode.HALF_EVEN); account.undoTransaction(transactionId, existingReversedTransactionIds); // for undo withdrawal fee - SavingsAccountTransaction nextSavingsAccountTransaction = this.savingsAccountTransactionRepository.findOneByIdAndSavingsAccountId( + final SavingsAccountTransaction nextSavingsAccountTransaction = this.savingsAccountTransactionRepository.findOneByIdAndSavingsAccountId( transactionId+1, savingsId); if(nextSavingsAccountTransaction!=null && nextSavingsAccountTransaction.isWithdrawalFeeAndNotReversed()){ account.undoTransaction(transactionId+1, existingReversedTransactionIds); @@ -403,11 +403,11 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi SavingsAccountTransaction transaction = null; if (savingsAccountTransaction.isDeposit()) { - SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, + final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, existingTransactionIds, existingReversedTransactionIds, paymentDetail); transaction = account.deposit(transactionDTO); } else { - SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, + final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, existingTransactionIds, existingReversedTransactionIds, paymentDetail); transaction = account.withdraw(transactionDTO, true); } @@ -433,9 +433,9 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi } /** - * + * */ - private void throwValidationForActiveStatus(String actionName) { + private void throwValidationForActiveStatus(final String actionName) { final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_ACCOUNT_RESOURCE_NAME + actionName); @@ -451,7 +451,7 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi final Map accountingBridgeData = savingsAccount.deriveAccountingBridgeData(applicationCurrency.toData(), existingTransactionIds, existingReversedTransactionIds); - journalEntryWritePlatformService.createJournalEntriesForSavings(accountingBridgeData); + this.journalEntryWritePlatformService.createJournalEntriesForSavings(accountingBridgeData); } private void checkClientOrGroupActive(final SavingsAccount account) { @@ -466,17 +466,17 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi } @Override - public CommandProcessingResult close(Long savingsId, JsonCommand command) { + public CommandProcessingResult close(final Long savingsId, final JsonCommand command) { final AppUser user = this.context.authenticatedUser(); this.savingsAccountTransactionDataValidator.validateClosing(command); final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId); - final boolean isLinkedWithAnyActiveLoan = accountAssociationsReadPlatformService.isLinkedWithAnyActiveLoan(savingsId); + final boolean isLinkedWithAnyActiveLoan = this.accountAssociationsReadPlatformService.isLinkedWithAnyActiveLoan(savingsId); if(isLinkedWithAnyActiveLoan){ - String defaultUserMessage = "Closing savings account with id:"+savingsId+" is not allowed, since it is linked with one of the active loans"; + final String defaultUserMessage = "Closing savings account with id:"+savingsId+" is not allowed, since it is linked with one of the active loans"; throw new SavingsAccountClosingNotAllowedException("linked", defaultUserMessage, savingsId); } - + final Map changes = account.close(user, command, DateUtils.getLocalDateOfTenant()); if (!changes.isEmpty()) { this.savingAccountRepository.save(account); @@ -499,7 +499,7 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi } @Override - public SavingsAccountTransaction initiateSavingsTransfer(Long accountId, LocalDate transferDate) { + public SavingsAccountTransaction initiateSavingsTransfer(final Long accountId, final LocalDate transferDate) { final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(accountId); final List existingTransactionIds = new ArrayList(savingsAccount.findExistingTransactionIds()); @@ -519,7 +519,7 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi } @Override - public SavingsAccountTransaction withdrawSavingsTransfer(Long accountId, LocalDate transferDate) { + public SavingsAccountTransaction withdrawSavingsTransfer(final Long accountId, final LocalDate transferDate) { final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(accountId); final List existingTransactionIds = new ArrayList(savingsAccount.findExistingTransactionIds()); @@ -539,15 +539,15 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi } @Override - public void rejectSavingsTransfer(Long accountId) { + public void rejectSavingsTransfer(final Long accountId) { final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(accountId); savingsAccount.setStatus(SavingsAccountStatusType.TRANSFER_ON_HOLD.getValue()); this.savingAccountRepository.save(savingsAccount); } @Override - public SavingsAccountTransaction acceptSavingsTransfer(Long accountId, LocalDate transferDate, Office acceptedInOffice, - Staff fieldOfficer) { + public SavingsAccountTransaction acceptSavingsTransfer(final Long accountId, final LocalDate transferDate, final Office acceptedInOffice, + final Staff fieldOfficer) { final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(accountId); final List existingTransactionIds = new ArrayList(savingsAccount.findExistingTransactionIds()); @@ -568,7 +568,7 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi return acceptTransferTransaction; } - + @Transactional @Override public CommandProcessingResult addSavingsAccountCharge(final JsonCommand command) { @@ -581,14 +581,14 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi checkClientOrGroupActive(savingsAccount); final DateTimeFormatter fmt = DateTimeFormat.forPattern("dd MM yyyy"); - + final Long chargeDefinitionId = command.longValueOfParameterNamed(chargeIdParamName); final Charge chargeDefinition = this.chargeRepository.findOneWithNotFoundDetection(chargeDefinitionId); final SavingsAccountCharge savingsAccountCharge = SavingsAccountCharge.createNewFromJson(savingsAccount, chargeDefinition, command); savingsAccount.addCharge(fmt, savingsAccountCharge, chargeDefinition); - + this.savingAccountRepository.saveAndFlush(savingsAccount); return new CommandProcessingResultBuilder() // @@ -603,16 +603,16 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi @Transactional @Override - public CommandProcessingResult updateSavingsAccountCharge(JsonCommand command) { + public CommandProcessingResult updateSavingsAccountCharge(final JsonCommand command) { this.context.authenticatedUser(); this.savingsAccountChargeDataValidator.validateUpdate(command.json()); final Long savingsAccountId = command.getSavingsId(); final Long savingsChargeId = command.entityId();//SavingsAccount Charge entity - + final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(savingsAccountId); checkClientOrGroupActive(savingsAccount); - + final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection(savingsChargeId, savingsAccountId); final Map changes = savingsAccountCharge.update(command); this.savingsAccountChargeRepository.saveAndFlush(savingsAccountCharge); @@ -634,24 +634,24 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi .with(changes) // .build(); } - - + + @Transactional @Override - public CommandProcessingResult waiveCharge(Long savingsAccountId, Long savingsAccountChargeId, JsonCommand command) { - + public CommandProcessingResult waiveCharge(final Long savingsAccountId, final Long savingsAccountChargeId, final JsonCommand command) { + this.context.authenticatedUser(); - + final List existingTransactionIds = new ArrayList(); final List existingReversedTransactionIds = new ArrayList(); - + final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(savingsAccountId); checkClientOrGroupActive(savingsAccount); savingsAccount.waiveCharge(savingsAccountChargeId, existingTransactionIds, existingReversedTransactionIds); - + this.savingAccountRepository.saveAndFlush(savingsAccount); - + return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(savingsAccountChargeId) // @@ -664,18 +664,18 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi @Transactional @Override - public CommandProcessingResult deleteSavingsAccountCharge(Long savingsAccountId, Long savingsAccountChargeId, JsonCommand command) { + public CommandProcessingResult deleteSavingsAccountCharge(final Long savingsAccountId, final Long savingsAccountChargeId, @SuppressWarnings("unused") final JsonCommand command) { this.context.authenticatedUser(); - + final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(savingsAccountId); checkClientOrGroupActive(savingsAccount); final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection(savingsAccountChargeId, savingsAccountId); //TODO AA: validate before deleting a charge - + savingsAccount.removeCharge(savingsAccountCharge); this.savingAccountRepository.saveAndFlush(savingsAccount); - + return new CommandProcessingResultBuilder() // .withEntityId(savingsAccountChargeId) // .withOfficeId(savingsAccount.officeId()) // @@ -687,7 +687,7 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi @Transactional @Override - public CommandProcessingResult payCharge(Long savingsAccountId, Long savingsAccountChargeId, JsonCommand command) { + public CommandProcessingResult payCharge(final Long savingsAccountId, final Long savingsAccountChargeId, final JsonCommand command) { this.context.authenticatedUser(); final List existingTransactionIds = new ArrayList(); @@ -711,5 +711,5 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi .build(); } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java index b7431eff0..12e28f6b3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java @@ -29,7 +29,6 @@ import org.mifosplatform.organisation.monetary.domain.ApplicationCurrencyReposit import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; import org.mifosplatform.organisation.staff.domain.Staff; import org.mifosplatform.organisation.staff.domain.StaffRepositoryWrapper; -import org.mifosplatform.portfolio.charge.domain.Charge; import org.mifosplatform.portfolio.client.domain.AccountNumberGenerator; import org.mifosplatform.portfolio.client.domain.AccountNumberGeneratorFactory; import org.mifosplatform.portfolio.client.domain.Client; @@ -232,11 +231,11 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } account.update(fieldOfficer); } - + if (changes.containsKey("charges")) { //final Set savingsProductCharges = this.savi.assembleListOfSavingsProductCharges(command, product.currency().getCode()); final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(command.parsedJson()); - boolean updated = account.update(charges); + final boolean updated = account.update(charges); if (!updated) { changes.remove("charges"); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java index a273c7cdd..9111e6b03 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductReadPlatformServiceImpl.java @@ -17,7 +17,6 @@ import org.mifosplatform.infrastructure.core.domain.JdbcSupport; import org.mifosplatform.infrastructure.core.service.RoutingDataSource; import org.mifosplatform.infrastructure.security.service.PlatformSecurityContext; import org.mifosplatform.organisation.monetary.data.CurrencyData; -import org.mifosplatform.portfolio.charge.data.ChargeData; import org.mifosplatform.portfolio.savings.data.SavingsProductData; import org.mifosplatform.portfolio.savings.exception.SavingsProductNotFoundException; import org.springframework.beans.factory.annotation.Autowired; @@ -37,7 +36,7 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead @Autowired public SavingsProductReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; - jdbcTemplate = new JdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override @@ -45,26 +44,26 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead this.context.authenticatedUser(); - final String sql = "select " + savingsProductRowMapper.schema(); + final String sql = "select " + this.savingsProductRowMapper.schema(); - return this.jdbcTemplate.query(sql, savingsProductRowMapper); + return this.jdbcTemplate.query(sql, this.savingsProductRowMapper); } @Override public Collection retrieveAllForLookup() { - final String sql = "select " + savingsProductLookupsRowMapper.schema(); + final String sql = "select " + this.savingsProductLookupsRowMapper.schema(); - return this.jdbcTemplate.query(sql, savingsProductLookupsRowMapper); + return this.jdbcTemplate.query(sql, this.savingsProductLookupsRowMapper); } @Override public SavingsProductData retrieveOne(final Long savingProductId) { try { this.context.authenticatedUser(); - final String sql = "select " + savingsProductRowMapper.schema() + " where sp.id = ?"; - return this.jdbcTemplate.queryForObject(sql, savingsProductRowMapper, new Object[] { savingProductId }); - } catch (EmptyResultDataAccessException e) { + final String sql = "select " + this.savingsProductRowMapper.schema() + " where sp.id = ?"; + return this.jdbcTemplate.queryForObject(sql, this.savingsProductRowMapper, new Object[] { savingProductId }); + } catch (final EmptyResultDataAccessException e) { throw new SavingsProductNotFoundException(savingProductId); } } @@ -108,29 +107,29 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead @Override public SavingsProductData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - Long id = rs.getLong("id"); - String name = rs.getString("name"); - String description = rs.getString("description"); + final Long id = rs.getLong("id"); + final String name = rs.getString("name"); + final String description = rs.getString("description"); - String currencyCode = rs.getString("currencyCode"); - String currencyName = rs.getString("currencyName"); - String currencyNameCode = rs.getString("currencyNameCode"); - String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); - Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); + final String currencyCode = rs.getString("currencyCode"); + final String currencyName = rs.getString("currencyName"); + final String currencyNameCode = rs.getString("currencyNameCode"); + final String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); + final Integer currencyDigits = JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs, "inMultiplesOf"); final CurrencyData currency = new CurrencyData(currencyCode, currencyName, currencyDigits, inMultiplesOf, currencyDisplaySymbol, currencyNameCode); final BigDecimal nominalAnnualInterestRate = rs.getBigDecimal("nominalAnnualInterestRate"); final Integer compoundingInterestPeriodTypeValue = JdbcSupport.getInteger(rs, "compoundingInterestPeriodType"); - EnumOptionData compoundingInterestPeriodType = SavingsEnumerations + final EnumOptionData compoundingInterestPeriodType = SavingsEnumerations .compoundingInterestPeriodType(compoundingInterestPeriodTypeValue); final Integer interestPostingPeriodTypeValue = JdbcSupport.getInteger(rs, "interestPostingPeriodType"); - EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType(interestPostingPeriodTypeValue); + final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType(interestPostingPeriodTypeValue); final Integer interestCalculationTypeValue = JdbcSupport.getInteger(rs, "interestCalculationType"); - EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(interestCalculationTypeValue); + final EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(interestCalculationTypeValue); EnumOptionData interestCalculationDaysInYearType = null; final Integer interestCalculationDaysInYearTypeValue = JdbcSupport.getInteger(rs, "interestCalculationDaysInYearType"); @@ -144,7 +143,7 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead final BigDecimal minRequiredOpeningBalance = rs.getBigDecimal("minRequiredOpeningBalance"); - Integer lockinPeriodFrequency = JdbcSupport.getInteger(rs, "lockinPeriodFrequency"); + final Integer lockinPeriodFrequency = JdbcSupport.getInteger(rs, "lockinPeriodFrequency"); EnumOptionData lockinPeriodFrequencyType = null; final Integer lockinPeriodFrequencyTypeValue = JdbcSupport.getInteger(rs, "lockinPeriodFrequencyType"); if (lockinPeriodFrequencyTypeValue != null) { @@ -158,7 +157,7 @@ public class SavingsProductReadPlatformServiceImpl implements SavingsProductRead if (withdrawalFeeTypeValue != null) { withdrawalFeeType = SavingsEnumerations.withdrawalFeeType(withdrawalFeeTypeValue); } - + final boolean withdrawalFeeForTransfers = rs.getBoolean("withdrawalFeeForTransfers"); final BigDecimal annualFeeAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "annualFeeAmount"); From 59e8fe838ed4f7d488f40d9615fd39f52892d1f8 Mon Sep 17 00:00:00 2001 From: Keith Woodlock Date: Fri, 20 Sep 2013 10:17:08 +0100 Subject: [PATCH 4/8] make patch follow _x naming convention for bug release. --- ...e_patch_update.sql => V118_1__savings_charge_patch_update.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename mifosng-db/migrations/core_db/{V119__savings_charge_patch_update.sql => V118_1__savings_charge_patch_update.sql} (100%) diff --git a/mifosng-db/migrations/core_db/V119__savings_charge_patch_update.sql b/mifosng-db/migrations/core_db/V118_1__savings_charge_patch_update.sql similarity index 100% rename from mifosng-db/migrations/core_db/V119__savings_charge_patch_update.sql rename to mifosng-db/migrations/core_db/V118_1__savings_charge_patch_update.sql From 07d36695496141f31282dfa62d58f76cdaf45209 Mon Sep 17 00:00:00 2001 From: Vishwas Babu A J Date: Fri, 20 Sep 2013 22:46:08 +0530 Subject: [PATCH 5/8] fix for multiple product mappings --- ..._mapping_delete_duplicate_fund_source_to_account_mappings.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 mifosng-db/migrations/core_db/V118_2__product_mapping_delete_duplicate_fund_source_to_account_mappings.sql diff --git a/mifosng-db/migrations/core_db/V118_2__product_mapping_delete_duplicate_fund_source_to_account_mappings.sql b/mifosng-db/migrations/core_db/V118_2__product_mapping_delete_duplicate_fund_source_to_account_mappings.sql new file mode 100644 index 000000000..fad8ea69d --- /dev/null +++ b/mifosng-db/migrations/core_db/V118_2__product_mapping_delete_duplicate_fund_source_to_account_mappings.sql @@ -0,0 +1 @@ +delete from acc_product_mapping where financial_account_type=10 and payment_type is not null; \ No newline at end of file From 749565dd1ca7d0656129111bac59fab051ae1b43 Mon Sep 17 00:00:00 2001 From: Vishwas Babu A J Date: Fri, 20 Sep 2013 23:11:38 +0530 Subject: [PATCH 6/8] formatting and cleaning up the entire project --- .../AccountingScenarioIntegrationTest.java | 188 +++--- .../ClientLoanIntegrationTest.java | 27 +- .../GroupLoanIntegrationTest.java | 35 +- .../integrationtests/GroupTest.java | 36 +- ...iveInterestAndWriteOffIntegrationTest.java | 103 +-- ...anWithdrawnByApplicantIntegrationTest.java | 24 +- .../integrationtests/XBRLIntegrationTest.java | 14 +- .../integrationtests/common/ClientHelper.java | 8 +- .../integrationtests/common/GroupHelper.java | 50 +- .../integrationtests/common/Utils.java | 66 +- .../common/accounting/Account.java | 18 +- .../common/accounting/AccountHelper.java | 38 +- .../common/accounting/GLAccountBuilder.java | 14 +- .../common/accounting/JournalEntry.java | 15 +- .../common/accounting/JournalEntryHelper.java | 6 +- .../loans/LoanApplicationTestBuilder.java | 37 +- .../common/loans/LoanProductTestBuilder.java | 223 ++++--- .../common/loans/LoanStatusChecker.java | 7 +- .../common/loans/LoanTransactionHelper.java | 80 ++- .../xbrl/XBRLIntegrationTestHelper.java | 6 +- .../closure/api/GLClosuresApiResource.java | 2 +- ...untingDropdownReadPlatformServiceImpl.java | 13 +- .../common/AccountingEnumerations.java | 2 +- .../accounting/common/AccountingRuleType.java | 4 +- .../glaccount/command/GLAccountCommand.java | 8 +- .../glaccount/domain/GLAccount.java | 12 +- ...AccountCommandFromApiJsonDeserializer.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 6 +- .../journalentry/api/DateParam.java | 6 +- .../api/JournalEntriesApiResource.java | 4 +- .../journalentry/data/ChargePaymentDTO.java | 2 +- .../journalentry/data/JournalEntryData.java | 3 +- .../accounting/journalentry/data/LoanDTO.java | 2 +- .../journalentry/data/SavingsDTO.java | 14 +- .../JournalEntryInvalidException.java | 3 +- .../AccountingProcessorForLoanFactory.java | 10 +- .../AccountingProcessorForSavingsFactory.java | 6 +- .../service/AccountingProcessorHelper.java | 52 +- ...ccrualBasedAccountingProcessorForLoan.java | 37 +- .../CashBasedAccountingProcessorForLoan.java | 32 +- ...ashBasedAccountingProcessorForSavings.java | 28 +- .../JournalEntryReadPlatformServiceImpl.java | 4 +- ...WritePlatformServiceJpaRepositoryImpl.java | 5 +- .../data/ChargeToGLAccountMapper.java | 2 +- .../data/PaymentTypeToGLAccountMapper.java | 2 +- .../domain/ProductToGLAccountMapping.java | 4 +- ...AccountMappingFromApiJsonDeserializer.java | 12 +- .../ProductToGLAccountMappingHelper.java | 70 +- ...AccountMappingReadPlatformServiceImpl.java | 22 +- ...ccountMappingWritePlatformServiceImpl.java | 85 +-- ...avingsProductToGLAccountMappingHelper.java | 10 +- .../rule/api/AccountingRuleApiResource.java | 28 +- .../rule/data/AccountingTagRuleData.java | 2 +- .../AccountingRuleDuplicateException.java | 4 +- ...AccountingRuleReadPlatformServiceImpl.java | 3 +- ...WritePlatformServiceJpaRepositoryImpl.java | 2 +- .../commands/api/AuditsApiResource.java | 16 +- .../api/MakercheckersApiResource.java | 6 +- .../domain/CommandProcessingResultType.java | 4 +- .../commands/domain/CommandSource.java | 253 ++++---- .../commands/domain/CommandWrapper.java | 12 +- .../UnsupportedCommandException.java | 2 +- .../service/AuditReadPlatformServiceImpl.java | 69 +- .../service/CommandWrapperBuilder.java | 15 +- ...CommandSourceWritePlatformServiceImpl.java | 12 +- .../SynchronousCommandProcessingService.java | 13 +- .../cache/CacheEnumerations.java | 6 +- ...WritePlatformServiceJpaRepositoryImpl.java | 2 +- .../RuntimeDelegatingCacheManager.java | 2 +- .../infrastructure/codes/CodeConstants.java | 5 +- .../codes/api/CodeValuesApiResource.java | 5 +- .../codes/api/CodesApiResource.java | 10 +- .../infrastructure/codes/data/CodeData.java | 4 +- .../codes/data/CodeValueData.java | 4 +- .../infrastructure/codes/domain/Code.java | 2 +- .../codes/domain/CodeValue.java | 116 ++-- ...emDefinedCodeCannotBeChangedException.java | 3 +- .../CodeCommandFromApiJsonDeserializer.java | 14 +- ...deValueCommandFromApiJsonDeserializer.java | 10 +- .../service/CodeReadPlatformService.java | 2 +- .../service/CodeReadPlatformServiceImpl.java | 12 +- .../CodeValueReadPlatformServiceImpl.java | 10 +- ...WritePlatformServiceJpaRepositoryImpl.java | 8 +- ...WritePlatformServiceJpaRepositoryImpl.java | 14 +- .../api/GlobalConfigurationApiResource.java | 10 +- .../data/GlobalConfigurationPropertyData.java | 4 +- .../configuration/data/S3CredentialsData.java | 2 +- .../domain/ConfigurationDomainService.java | 8 + .../domain/ConfigurationDomainServiceJpa.java | 20 +- .../domain/GlobalConfigurationProperty.java | 2 +- ...urationCommandFromApiJsonDeserializer.java | 4 +- .../ConfigurationReadPlatformServiceImpl.java | 6 +- ...ternalServicesReadPlatformServiceImpl.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 27 +- .../core/api/ApiParameterHelper.java | 32 +- .../core/api/ApiRequestParameterHelper.java | 2 +- .../infrastructure/core/api/JsonCommand.java | 5 +- .../infrastructure/core/api/JsonQuery.java | 26 +- .../api/ParameterListExclusionStrategy.java | 6 +- .../core/data/ApiErrorMessageArg.java | 43 +- .../core/data/ApiGlobalErrorResponse.java | 42 +- .../core/data/ApiParameterError.java | 38 +- .../data/CommandProcessingResultBuilder.java | 6 +- .../core/data/DataValidatorBuilder.java | 598 +++++++++--------- .../core/data/EnumOptionData.java | 4 +- .../core/domain/AbstractAuditableCustom.java | 35 +- .../core/domain/AuditorAwareImpl.java | 8 +- .../core/domain/Base64EncodedImage.java | 6 +- .../core/domain/EmailDetail.java | 44 +- .../core/domain/JdbcSupport.java | 4 +- .../infrastructure/core/domain/Tenant.java | 27 +- .../AbstractPlatformDomainRuleException.java | 9 +- ...ractPlatformResourceNotFoundException.java | 6 +- ...ctPlatformServiceUnavailableException.java | 6 +- .../PlatformApiDataValidationException.java | 6 +- .../PlatformDataIntegrityException.java | 8 +- .../PlatformInternalServerException.java | 9 +- .../PlatformServiceUnavailableException.java | 5 +- .../UnrecognizedQueryParamException.java | 4 +- .../UnsupportedParameterException.java | 4 +- .../BadCredentialsExceptionMapper.java | 2 +- .../InvalidJsonExceptionMapper.java | 6 +- .../JsonSyntaxExceptionMapper.java | 6 +- .../MalformedJsonExceptionMapper.java | 6 +- ...tformApiDataValidationExceptionMapper.java | 4 +- .../PlatformDataIntegrityExceptionMapper.java | 7 +- .../PlatformDomainRuleExceptionMapper.java | 6 +- ...PlatformInternalServerExceptionMapper.java | 4 +- ...atformResourceNotFoundExceptionMapper.java | 4 +- ...formServiceUnavailableExceptionMapper.java | 4 +- .../UnAuthenticatedUserExceptionMapper.java | 2 +- .../UnsupportedCommandExceptionMapper.java | 12 +- .../UnsupportedParameterExceptionMapper.java | 17 +- .../core/filters/ResponseCorsFilter.java | 6 +- ...CommandProcessingResultJsonSerializer.java | 13 +- .../core/serialization/CommandSerializer.java | 1 - .../CommandSerializerDefaultToJson.java | 11 +- ...tatableCommandFromApiJsonDeserializer.java | 271 ++++---- .../DefaultToApiJsonSerializer.java | 24 +- ...tyPrintingOffJsonSerializerGoogleGson.java | 13 +- ...ttyPrintingOnJsonSerializerGoogleGson.java | 13 +- .../FromCommandJsonDeserializer.java | 2 +- .../core/serialization/FromJsonHelper.java | 75 +-- .../core/serialization/JsonParserHelper.java | 151 ++--- .../serialization/ToApiJsonSerializer.java | 6 +- .../core/service/DateUtils.java | 10 +- .../GmailBackedPlatformEmailService.java | 21 +- .../infrastructure/core/service/Page.java | 2 +- .../core/service/PlatformEmailService.java | 1 - .../core/service/RoutingDataSource.java | 2 +- .../RoutingDataSourceServiceFactory.java | 2 +- .../service/TenantDatabaseUpgradeService.java | 6 +- .../TomcatJdbcDataSourcePerTenantService.java | 6 +- .../api/DatatablesApiResource.java | 45 +- .../dataqueries/api/ReportsApiResource.java | 181 +++--- .../api/RunreportsApiResource.java | 47 +- .../dataqueries/data/DatatableData.java | 6 +- .../data/GenericResultsetData.java | 6 +- .../dataqueries/data/ReportData.java | 144 ++--- .../dataqueries/data/ReportParameterData.java | 29 +- .../data/ReportParameterJoinData.java | 143 ++--- .../data/ResultsetColumnHeaderData.java | 14 +- .../dataqueries/data/ResultsetRowData.java | 2 +- .../dataqueries/domain/Report.java | 40 +- .../domain/ReportParameterUsage.java | 6 +- .../exception/ReportNotFoundException.java | 1 + .../CreateDatatableEntryCommandHandler.java | 2 +- .../DeleteDatatableCommandHandler.java | 13 +- ...OneToManyDatatableEntryCommandHandler.java | 2 +- ...eOneToOneDatatableEntryCommandHandler.java | 2 +- .../UpdateDatatableCommandHandler.java | 11 +- .../ReportCommandFromApiJsonDeserializer.java | 2 +- .../service/GenericDataServiceImpl.java | 52 +- .../service/ReadReportingServiceImpl.java | 176 +++--- .../service/ReadWriteNonCoreDataService.java | 6 +- .../ReadWriteNonCoreDataServiceImpl.java | 325 +++++----- .../ReportWritePlatformServiceImpl.java | 14 +- .../api/ImagesApiResource.java | 8 +- .../command/DocumentCommand.java | 2 +- .../ContentRepositoryFactory.java | 10 +- .../ContentRepositoryUtils.java | 26 +- .../FileSystemContentRepository.java | 50 +- .../S3ContentRepository.java | 74 +-- .../documentmanagement/data/DocumentData.java | 4 +- .../documentmanagement/data/FileData.java | 14 +- .../documentmanagement/data/ImageData.java | 20 +- .../documentmanagement/domain/Image.java | 6 +- .../domain/StorageType.java | 4 +- .../DocumentReadPlatformServiceImpl.java | 6 +- ...WritePlatformServiceJpaRepositoryImpl.java | 10 +- .../service/ImageReadPlatformServiceImpl.java | 12 +- ...WritePlatformServiceJpaRepositoryImpl.java | 18 +- .../jobs/annotation/CronMethodParser.java | 28 +- .../jobs/api/SchedulerApiResource.java | 10 +- .../jobs/api/SchedulerJobApiResource.java | 9 +- .../jobs/data/JobDetailData.java | 4 +- .../domain/ScheduledJobDetailRepository.java | 8 +- .../jobs/domain/SchedulerDetail.java | 6 +- .../jobs/exception/JobExecutionException.java | 5 +- .../jobs/exception/JobInProcessExecution.java | 5 +- .../UpdateJobDetailCommandhandler.java | 2 +- .../infrastructure/jobs/service/JobName.java | 2 +- .../jobs/service/JobRegisterService.java | 1 - .../jobs/service/JobRegisterServiceImpl.java | 148 ++--- ...WritePlatformServiceJpaRepositoryImpl.java | 18 +- .../jobs/service/SchedulerJobListener.java | 30 +- .../SchedulerJobRunnerReadServiceImpl.java | 99 +-- .../service/SchedulerServiceConstants.java | 2 +- .../jobs/service/SchedulerStopListener.java | 4 +- .../service/SchedulerTriggerListener.java | 22 +- .../api/AuthenticationApiResource.java | 23 +- .../security/data/PlatformRequestLog.java | 10 +- .../domain/PlatformUserRepository.java | 1 - .../TenantAwareBasicAuthenticationFilter.java | 13 +- .../CustomAuthenticationFailureHandler.java | 78 +-- .../service/JdbcTenantDetailsService.java | 4 +- .../service/PlatformSecurityContext.java | 2 +- .../service/PlatformUserDetailsService.java | 2 +- .../service/RandomPasswordGenerator.java | 2 +- ...SpringSecurityPlatformSecurityContext.java | 5 +- ...antAwareJpaPlatformUserDetailsService.java | 5 +- .../api/MixTaxonomyMappingApiResource.java | 15 +- .../mix/data/MixTaxonomyData.java | 3 +- .../XBRLMappingInvalidException.java | 2 +- .../UpdateTaxonomyMappingCommandHandler.java | 4 +- .../mix/service/XBRLBuilder.java | 103 +-- .../mix/service/XBRLResultServiceImpl.java | 4 +- .../holiday/api/HolidayApiConstants.java | 14 +- .../holiday/api/HolidaysApiResource.java | 17 +- .../holiday/data/HolidayData.java | 7 +- .../holiday/data/HolidayDataValidator.java | 9 +- .../organisation/holiday/domain/Holiday.java | 22 +- .../holiday/domain/HolidayRepository.java | 7 +- .../exception/HolidayDateException.java | 3 +- .../handler/CreateHolidayCommandHandler.java | 10 +- .../service/HolidayReadPlatformService.java | 1 - .../HolidayReadPlatformServiceImpl.java | 24 +- .../holiday/service/HolidayUtil.java | 13 +- .../service/HolidayWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 33 +- .../monetary/api/CurrenciesApiResource.java | 6 +- .../ApplicationCurrencyConfigurationData.java | 3 +- .../monetary/data/CurrencyData.java | 17 +- .../monetary/domain/ApplicationCurrency.java | 6 +- .../ApplicationCurrencyRepositoryWrapper.java | 2 +- .../monetary/domain/MonetaryCurrency.java | 12 +- .../organisation/monetary/domain/Money.java | 58 +- .../exception/CurrencyNotFoundException.java | 6 +- ...urrencyCommandFromApiJsonDeserializer.java | 6 +- .../CurrencyReadPlatformServiceImpl.java | 10 +- ...WritePlatformServiceJpaRepositoryImpl.java | 2 +- .../api/OfficeTransactionsApiResource.java | 14 +- .../office/data/OfficeTransactionData.java | 2 +- .../organisation/office/domain/Office.java | 14 +- .../office/domain/OfficeRepository.java | 3 +- .../domain/OfficeTransactionRepository.java | 6 +- .../exception/InvalidOfficeException.java | 8 +- .../OfficeTransactionNotFoundException.java | 3 +- .../OfficeCommandFromApiJsonDeserializer.java | 36 +- ...sactionCommandFromApiJsonDeserializer.java | 16 +- .../OfficeReadPlatformServiceImpl.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 19 +- .../staff/api/StaffApiResource.java | 14 +- .../StaffAccountSummaryCollectionData.java | 10 +- .../organisation/staff/domain/Staff.java | 16 +- .../domain/StaffOrganisationalRoleType.java | 4 +- .../staff/domain/StaffRepository.java | 7 +- .../staff/domain/StaffRepositoryWrapper.java | 6 +- .../exception/StaffNotFoundException.java | 10 +- .../staff/exception/StaffRoleException.java | 25 +- .../StaffCommandFromApiJsonDeserializer.java | 43 +- .../service/StaffReadPlatformServiceImpl.java | 6 +- ...WritePlatformServiceJpaRepositoryImpl.java | 13 +- .../domain/RepaymentRescheduleType.java | 9 +- .../workingdays/domain/WorkingDays.java | 12 +- .../workingdays/service/WorkingDaysUtil.java | 10 +- .../account/PortfolioAccountType.java | 4 +- .../api/AccountTransfersApiResource.java | 16 +- .../account/data/AccountTransferDTO.java | 27 +- .../account/data/AccountTransferData.java | 6 +- .../data/AccountTransfersDataValidator.java | 27 +- .../account/data/PortfolioAccountData.java | 4 +- .../account/domain/AccountAssociations.java | 2 +- .../domain/AccountAssociationsRepository.java | 2 +- .../account/domain/AccountTransfer.java | 11 +- .../domain/AccountTransferRepository.java | 2 +- .../CreateAccountTransferCommandHandler.java | 2 +- ...ccountAssociationsReadPlatformService.java | 1 - ...ntAssociationsReadPlatformServiceImpl.java | 19 +- .../service/AccountTransferEnumerations.java | 6 +- .../AccountTransfersReadPlatformService.java | 4 +- ...countTransfersReadPlatformServiceImpl.java | 16 +- ...ountTransfersWritePlatformServiceImpl.java | 10 +- ...rtfolioAccountReadPlatformServiceImpl.java | 11 +- .../data/AccountSummaryCollectionData.java | 2 +- .../accountdetails/domain/AccountType.java | 32 +- .../AccountDetailsReadPlatformService.java | 5 +- ...sReadPlatformServiceJpaRepositoryImpl.java | 56 +- .../service/AccountEnumerations.java | 7 +- .../portfolio/calendar/CalendarConstants.java | 4 +- .../portfolio/calendar/data/CalendarData.java | 10 +- .../portfolio/calendar/domain/Calendar.java | 53 +- .../calendar/domain/CalendarEntityType.java | 8 +- .../calendar/domain/CalendarInstance.java | 16 +- .../CalendarInstanceRepositoryWrapper.java | 7 +- .../domain/CalendarRepositoryWrapper.java | 6 +- .../exception/CalendarDateException.java | 4 +- .../CalendarInstanceNotFoundException.java | 5 +- ...rParameterUpdateNotSupportedException.java | 3 +- .../MeetingFrequencyMismatchException.java | 2 +- .../NotValidRecurringDateException.java | 2 +- ...alendarCommandFromApiJsonDeserializer.java | 25 +- .../CalendarReadPlatformServiceImpl.java | 72 ++- .../calendar/service/CalendarUtils.java | 295 ++++----- .../service/CalendarWritePlatformService.java | 4 +- ...WritePlatformServiceJpaRepositoryImpl.java | 44 +- .../charge/api/ChargesApiResource.java | 20 +- .../portfolio/charge/data/ChargeData.java | 62 +- .../portfolio/charge/domain/Charge.java | 103 +-- .../charge/domain/ChargeAppliesTo.java | 27 +- .../charge/domain/ChargeCalculationType.java | 18 +- .../charge/domain/ChargePaymentMode.java | 10 +- .../charge/domain/ChargeTimeType.java | 41 +- .../ChargeCannotBeAppliedToException.java | 7 +- .../ChargeCannotBeDeletedException.java | 8 +- ...eParameterUpdateNotSupportedException.java | 3 +- .../LoanChargeCannotBeAddedException.java | 8 +- .../LoanChargeCannotBePayedException.java | 16 +- ...nChargeWithoutMandatoryFieldException.java | 8 +- ...SavingsAccountChargeNotFoundException.java | 8 +- ...tChargeWithoutMandatoryFieldException.java | 8 +- ...initionCommandFromApiJsonDeserializer.java | 83 +-- .../ChargeDropdownReadPlatformService.java | 2 +- ...ChargeDropdownReadPlatformServiceImpl.java | 25 +- .../charge/service/ChargeEnumerations.java | 12 +- .../service/ChargeReadPlatformService.java | 2 +- .../ChargeReadPlatformServiceImpl.java | 26 +- ...WritePlatformServiceJpaRepositoryImpl.java | 25 +- .../client/api/ClientsApiResource.java | 18 +- .../command/ClientIdentifierCommand.java | 14 +- .../client/command/ClientNoteCommand.java | 4 +- .../portfolio/client/data/ClientData.java | 6 +- .../client/data/ClientDataValidator.java | 9 +- .../client/data/ClientIdentifierData.java | 62 +- .../client/domain/AccountNumberGenerator.java | 3 +- .../portfolio/client/domain/Client.java | 14 +- .../client/domain/ClientIdentifier.java | 124 ++-- .../domain/ClientRepositoryWrapper.java | 2 +- .../portfolio/client/domain/ClientStatus.java | 6 +- .../ZeroPaddedAccountNumberGenerator.java | 4 +- .../DuplicateClientIdentifierException.java | 8 +- ...InvalidClientStateTransitionException.java | 6 +- .../AssignClientStaffCommandHandler.java | 6 +- ...ntifierCommandFromApiJsonDeserializer.java | 4 +- .../service/ClientReadPlatformService.java | 2 +- .../ClientReadPlatformServiceImpl.java | 38 +- .../service/ClientWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 16 +- .../client/service/LoanStatusMapper.java | 14 +- .../api/CollateralApiConstants.java | 2 +- .../api/CollateralsApiResource.java | 14 +- .../collateral/command/CollateralCommand.java | 8 +- .../collateral/data/CollateralData.java | 4 +- .../CollateralNotFoundException.java | 2 +- ...lateralCommandFromApiJsonDeserializer.java | 18 +- .../service/CollateralAssembler.java | 10 +- .../CollateralReadPlatformServiceImpl.java | 10 +- ...WritePlatformServiceJpaRepositoryImpl.java | 2 +- .../CollectionSheetBulkDisbursalCommand.java | 8 +- .../CollectionSheetBulkRepaymentCommand.java | 7 +- .../command/SingleDisbursalCommand.java | 12 +- .../command/SingleRepaymentCommand.java | 12 +- ...llectionSheetTransactionDataValidator.java | 14 +- .../collectionsheet/data/JLGClientData.java | 6 +- .../data/JLGCollectionSheetData.java | 2 +- .../data/JLGCollectionSheetFlatData.java | 8 +- .../collectionsheet/data/JLGGroupData.java | 3 +- .../collectionsheet/data/LoanDueData.java | 10 +- ...sbursalCommandFromApiJsonDeserializer.java | 14 +- ...paymentCommandFromApiJsonDeserializer.java | 19 +- ...enerateCommandFromApiJsonDeserializer.java | 10 +- .../CollectionSheetReadPlatformService.java | 4 +- ...ollectionSheetReadPlatformServiceImpl.java | 10 +- .../CollectionSheetWritePlatformService.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 40 +- .../portfolio/fund/api/FundsApiResource.java | 12 +- .../portfolio/fund/data/FundData.java | 6 +- .../portfolio/fund/domain/FundRepository.java | 2 +- .../FundCommandFromApiJsonDeserializer.java | 20 +- .../service/FundReadPlatformServiceImpl.java | 6 +- ...WritePlatformServiceJpaRepositoryImpl.java | 12 +- .../group/api/CentersApiResource.java | 18 +- .../group/api/GroupingTypesApiConstants.java | 26 +- .../group/api/GroupsApiResource.java | 5 +- .../group/api/GroupsLevelApiResource.java | 4 +- .../portfolio/group/data/CenterData.java | 8 +- .../group/data/GroupGeneralData.java | 26 +- .../portfolio/group/domain/Group.java | 56 +- .../group/domain/GroupRepository.java | 1 + .../domain/GroupingTypeEnumerations.java | 8 +- .../group/domain/GroupingTypeStatus.java | 6 +- .../ClientExistInGroupException.java | 4 +- .../exception/ClientNotInGroupException.java | 11 +- .../GroupAccountExistsException.java | 3 +- .../InvalidGroupStateTransitionException.java | 1 - .../AssignGroupStaffCommandHandler.java | 6 +- .../handler/CloseCenterCommandHandler.java | 6 +- .../handler/CloseGroupCommandHandler.java | 6 +- .../handler/UnassignRoleCommandHandler.java | 8 +- .../UpdateGroupRoleCommandHandler.java | 6 +- .../GroupRolesDataValidator.java | 2 +- .../GroupingTypesDataValidator.java | 102 +-- .../service/CenterReadPlatformService.java | 4 +- .../CenterReadPlatformServiceImpl.java | 34 +- .../GroupLevelReadPlatformServiceImpl.java | 9 +- .../service/GroupReadPlatformService.java | 2 +- .../service/GroupReadPlatformServiceImpl.java | 8 +- .../GroupRolesWritePlatformService.java | 3 +- ...WritePlatformServiceJpaRepositoryImpl.java | 4 +- .../group/service/GroupTypeEnumerations.java | 2 +- .../GroupingTypesWritePlatformService.java | 12 +- ...WritePlatformServiceJpaRepositoryImpl.java | 87 +-- .../group/service/SearchParameters.java | 13 +- .../loanaccount/api/BulkLoansApiResource.java | 6 +- .../api/LoanChargesApiResource.java | 18 +- .../api/LoanTransactionsApiResource.java | 21 +- .../loanaccount/api/LoansApiResource.java | 59 +- .../command/LoanUpdateCommand.java | 4 +- .../command/UndoStateTransitionCommand.java | 2 +- .../loanaccount/data/DisbursementData.java | 4 +- .../loanaccount/data/LoanAccountData.java | 231 +++---- .../loanaccount/data/LoanChargeData.java | 5 +- .../loanaccount/data/LoanConvenienceData.java | 80 ++- .../loanaccount/data/LoanTransactionData.java | 11 +- .../data/LoanTransactionEnumData.java | 2 - .../RepaymentScheduleRelatedLoanData.java | 4 +- .../domain/ChangedTransactionDetail.java | 4 +- .../DefaultLoanLifecycleStateMachine.java | 52 +- .../portfolio/loanaccount/domain/Loan.java | 100 +-- .../domain/LoanAccountDomainService.java | 4 +- .../domain/LoanAccountDomainServiceJpa.java | 19 +- .../loanaccount/domain/LoanCharge.java | 45 +- .../loanaccount/domain/LoanChargePaidBy.java | 8 +- .../loanaccount/domain/LoanEvent.java | 27 +- .../domain/LoanOfficerAssignmentHistory.java | 13 +- .../domain/LoanRepaymentDataComparator.java | 2 +- .../LoanRepaymentScheduleInstallment.java | 12 +- ...oanRepaymentScheduleProcessingWrapper.java | 14 +- .../loanaccount/domain/LoanRepository.java | 2 +- .../loanaccount/domain/LoanStatus.java | 4 +- .../loanaccount/domain/LoanSummary.java | 8 +- .../domain/LoanSummaryWrapper.java | 38 +- .../loanaccount/domain/LoanTransaction.java | 62 +- ...ansactionProcessingStrategyRepository.java | 4 +- .../domain/LoanTransactionRepository.java | 5 +- .../domain/LoanTransactionType.java | 13 +- .../domain/TransactionProccessingResult.java | 24 +- ...RepaymentScheduleTransactionProcessor.java | 80 +-- ...RepaymentScheduleTransactionProcessor.java | 4 +- ...RepaymentScheduleTransactionProcessor.java | 10 +- ...RepaymentScheduleTransactionProcessor.java | 18 +- ...RepaymentScheduleTransactionProcessor.java | 8 +- ...RepaymentScheduleTransactionProcessor.java | 8 +- ...RepaymentScheduleTransactionProcessor.java | 8 +- ...RepaymentScheduleTransactionProcessor.java | 38 +- .../InvalidLoanStateTransitionException.java | 10 +- .../InvalidLoanTransactionTypeException.java | 10 +- .../LoanApplicationDateException.java | 3 +- .../LoanOfficerAssignmentDateException.java | 3 +- .../LoanOfficerUnassignmentDateException.java | 4 +- .../LoanOfficerUnassignmentException.java | 4 +- .../LoanTemplateTypeRequiredException.java | 9 +- .../LoanTransactionNotFoundException.java | 13 +- ...onProcessingStrategyNotFoundException.java | 10 +- ...NotSupportedLoanTemplateTypeException.java | 9 +- .../guarantor/GuarantorConstants.java | 2 +- .../guarantor/api/GuarantorsApiResource.java | 18 +- .../guarantor/command/GuarantorCommand.java | 22 +- .../guarantor/data/GuarantorData.java | 13 +- .../guarantor/domain/Guarantor.java | 49 +- .../guarantor/domain/GuarantorRepository.java | 1 + .../guarantor/domain/GuarantorType.java | 8 +- .../DuplicateGuarantorException.java | 4 +- .../exception/GuarantorNotFoundException.java | 4 +- .../exception/InvalidGuarantorException.java | 2 +- ...arantorCommandFromApiJsonDeserializer.java | 42 +- .../service/GuarantorEnumerations.java | 8 +- .../GuarantorReadPlatformServiceImpl.java | 65 +- ...ritePlatformServiceJpaRepositoryIImpl.java | 32 +- .../loanschedule/data/LoanScheduleData.java | 2 +- .../data/LoanSchedulePeriodData.java | 4 +- .../domain/AbstractLoanScheduleGenerator.java | 19 +- ...gBalanceInterestLoanScheduleGenerator.java | 12 +- ...aultPaymentPeriodsInOneYearCalculator.java | 6 +- .../domain/DefaultScheduledDateGenerator.java | 19 +- .../domain/FinanicalFunctions.java | 2 +- .../FlatInterestLoanScheduleGenerator.java | 12 +- .../domain/LoanApplicationTerms.java | 25 +- .../domain/LoanScheduleModel.java | 14 +- .../LoanScheduleModelRepaymentPeriod.java | 2 +- .../domain/ScheduledDateGenerator.java | 3 +- .../service/LoanScheduleAssembler.java | 96 +-- ...cheduleCalculationPlatformServiceImpl.java | 2 +- ...ateLoanScheduleQueryFromApiJsonHelper.java | 101 +-- ...anApplicationCommandFromApiJsonHelper.java | 385 +++++------ ...ApplicationTransitionApiJsonValidator.java | 27 +- .../LoanEventApiJsonValidator.java | 94 +-- .../service/BulkLoansReadPlatformService.java | 1 - .../BulkLoansReadPlatformServiceImpl.java | 16 +- ...WritePlatformServiceJpaRepositoryImpl.java | 7 +- .../service/LoanChargeAssembler.java | 25 +- .../LoanChargeReadPlatformServiceImpl.java | 3 +- .../service/LoanReadPlatformService.java | 12 +- .../service/LoanReadPlatformServiceImpl.java | 110 ++-- .../service/LoanWritePlatformService.java | 1 - ...WritePlatformServiceJpaRepositoryImpl.java | 6 +- .../api/LoanProductsApiResource.java | 73 ++- .../loanproduct/data/LoanProductData.java | 58 +- .../domain/AmortizationMethod.java | 2 +- .../InterestCalculationPeriodMethod.java | 2 +- .../loanproduct/domain/InterestMethod.java | 2 +- .../loanproduct/domain/LendingStrategy.java | 13 +- .../loanproduct/domain/LoanProduct.java | 73 +-- .../domain/LoanProductMinMaxConstraints.java | 8 +- .../domain/LoanProductRelatedDetail.java | 28 +- .../LoanTransactionProcessingStrategy.java | 2 +- .../domain/PeriodFrequencyType.java | 2 +- .../exception/InvalidCurrencyException.java | 3 +- .../exception/InvalidLendingStrategy.java | 9 +- .../LinkedAccountRequiredException.java | 3 +- .../exception/LoanProductDateException.java | 3 +- .../exception/NotInMinMaxRangeException.java | 6 +- .../productmix/data/ProductMixData.java | 8 +- .../productmix/domain/ProductMix.java | 2 +- .../ProductMixDataValidator.java | 5 +- .../ProductMixReadPlatformService.java | 3 +- .../ProductMixReadPlatformServiceImpl.java | 14 +- ...WritePlatformServiceJpaRepositoryImpl.java | 9 +- .../LoanProductDataValidator.java | 355 ++++++----- .../service/LendingStrategyEnumerations.java | 2 +- .../LoanDropdownReadPlatformServiceImpl.java | 18 +- .../LoanProductReadPlatformService.java | 2 +- .../LoanProductReadPlatformServiceImpl.java | 2 +- ...WritePlatformServiceJpaRepositoryImpl.java | 42 +- .../meeting/api/MeetingsApiResource.java | 23 +- .../meeting/attendance/AttendanceType.java | 2 +- .../attendance/data/ClientAttendanceData.java | 11 +- .../attendance/domain/ClientAttendance.java | 2 +- ...AttendanceDropdownReadPlatformService.java | 1 + .../service/AttendanceEnumerations.java | 6 +- .../ClientAttendanceReadPlatformService.java | 1 + ...ientAttendanceReadPlatformServiceImpl.java | 6 +- .../portfolio/meeting/data/MeetingData.java | 2 +- .../meeting/data/MeetingDataValidator.java | 74 ++- .../portfolio/meeting/domain/Meeting.java | 16 +- .../meeting/domain/MeetingRepository.java | 1 + .../domain/MeetingRepositoryWrapper.java | 6 +- .../MeetingNotSupportedResourceException.java | 9 +- .../MeetingReadPlatformServiceImpl.java | 16 +- .../service/MeetingWritePlatformService.java | 4 +- ...WritePlatformServiceJpaRepositoryImpl.java | 14 +- .../portfolio/note/domain/Note.java | 2 +- .../NoteCommandFromApiJsonDeserializer.java | 3 +- .../service/NoteReadPlatformServiceImpl.java | 11 +- .../paymentdetail/data/PaymentDetailData.java | 4 +- .../paymentdetail/domain/PaymentDetail.java | 5 +- ...WritePlatformServiceJpaRepositoryImpl.java | 14 +- .../SavingsAccountTransactionType.java | 11 +- .../savings/SavingsApiConstants.java | 19 +- .../SavingsCompoundingInterestPeriodType.java | 21 +- ...ingsInterestCalculationDaysInYearType.java | 6 +- .../SavingsInterestCalculationType.java | 6 +- .../savings/SavingsPeriodFrequencyType.java | 2 +- .../SavingsPostingInterestPeriodType.java | 6 +- .../savings/SavingsWithdrawalFeesType.java | 6 +- .../api/SavingsAccountChargesApiResource.java | 16 +- ...SavingsAccountTransactionsApiResource.java | 12 +- .../api/SavingsAccountsApiResource.java | 23 +- .../api/SavingsProductsApiResource.java | 36 +- .../data/SavingsAccountChargeData.java | 23 +- .../SavingsAccountChargeDataValidator.java | 32 +- .../savings/data/SavingsAccountData.java | 40 +- .../data/SavingsAccountDataValidator.java | 183 +++--- .../data/SavingsAccountTransactionDTO.java | 12 +- ...avingsAccountTransactionDataValidator.java | 27 +- .../savings/data/SavingsProductData.java | 62 +- .../data/SavingsProductDataValidator.java | 144 +++-- .../savings/domain/SavingsAccount.java | 38 +- .../domain/SavingsAccountAssembler.java | 32 +- .../savings/domain/SavingsAccountCharge.java | 56 +- .../domain/SavingsAccountChargeAssembler.java | 40 +- .../domain/SavingsAccountChargePaidBy.java | 30 +- .../SavingsAccountChargeRepository.java | 4 +- ...SavingsAccountChargeRepositoryWrapper.java | 8 +- .../SavingsAccountDomainServiceJpa.java | 13 +- .../domain/SavingsAccountRepository.java | 2 +- .../domain/SavingsAccountStatusType.java | 2 +- .../savings/domain/SavingsAccountSummary.java | 7 +- .../domain/SavingsAccountTransaction.java | 34 +- ...vingsAccountTransactionSummaryWrapper.java | 20 +- .../savings/domain/SavingsHelper.java | 6 +- .../savings/domain/SavingsProduct.java | 40 +- .../domain/SavingsProductAssembler.java | 15 +- .../domain/SavingsProductChargeAssembler.java | 29 +- .../interest/CompoundInterestHelper.java | 6 +- .../interest/DailyCompoundingPeriod.java | 15 +- .../domain/interest/EndOfDayBalance.java | 32 +- .../interest/MonthlyCompoundingPeriod.java | 27 +- .../domain/interest/PostingPeriod.java | 18 +- ...ingsAccountClosingNotAllowedException.java | 4 +- ...ctivityPriorToClientTransferException.java | 2 +- ...erTransactionsCannotBeUndoneException.java | 2 +- ...AnnualFeeSavingsAccountCommandHandler.java | 2 +- ...eInterestSavingsAccountCommandHandler.java | 3 +- .../CloseSavingsAccountCommandHandler.java | 2 +- ...ountApplicationDeletionCommandHandler.java | 3 +- ...ApplicationModificationCommandHandler.java | 3 +- ...untApplicationSubmittalCommandHandler.java | 3 +- ...ApplicationTransitionApiJsonValidator.java | 32 +- ...sAccountChargeReadPlatformServiceImpl.java | 12 +- ...SavingsAccountReadPlatformServiceImpl.java | 78 +-- .../SavingsAccountWritePlatformService.java | 4 +- ...WritePlatformServiceJpaRepositoryImpl.java | 105 +-- ...WritePlatformServiceJpaRepositoryImpl.java | 114 ++-- ...avingsDropdownReadPlatformServiceImpl.java | 30 +- ...WritePlatformServiceJpaRepositoryImpl.java | 21 +- .../portfolio/search/SearchConstants.java | 8 +- .../search/api/SearchApiResource.java | 4 +- .../search/data/SearchConditions.java | 35 +- .../portfolio/search/data/SearchData.java | 21 +- .../SearchReadPlatformServiceImpl.java | 38 +- .../transfer/data/TransfersDataValidator.java | 8 +- .../transfer/service/TransferEventType.java | 1 - ...WritePlatformServiceJpaRepositoryImpl.java | 38 +- .../ScheduledJobRunnerServiceImpl.java | 33 +- .../api/PermissionsApiResource.java | 6 +- .../api/RolesApiResource.java | 18 +- .../useradministration/data/AppUserData.java | 4 +- .../useradministration/data/RoleData.java | 2 +- .../useradministration/domain/AppUser.java | 5 +- .../domain/AppUserRepository.java | 2 +- .../domain/JpaUserDomainService.java | 2 +- .../useradministration/domain/Permission.java | 83 ++- .../domain/UserDomainService.java | 2 +- .../PasswordMustBeDifferentException.java | 2 +- ...issionCantBeMakerCheckerableException.java | 3 +- .../exception/RoleNotFoundException.java | 2 +- .../exception/UserNotFoundException.java | 2 +- .../UsernameMustBeDifferentException.java | 2 +- ...issionsCommandFromApiJsonDeserializer.java | 4 +- .../AppUserReadPlatformServiceImpl.java | 32 +- ...WritePlatformServiceJpaRepositoryImpl.java | 23 +- .../PermissionReadPlatformService.java | 2 +- .../PermissionReadPlatformServiceImpl.java | 4 +- ...WritePlatformServiceJpaRepositoryImpl.java | 13 +- .../service/RoleDataValidator.java | 20 +- .../service/RoleReadPlatformServiceImpl.java | 6 +- ...WritePlatformServiceJpaRepositoryImpl.java | 18 +- .../service/UserDataValidator.java | 79 ++- .../mix/report/service/XBRLBuilderTest.java | 19 +- ...ymentScheduleTransactionProcessorTest.java | 319 ++++++---- ...ymentScheduleTransactionProcessorTest.java | 12 +- .../LoanProductRelatedDetailTestHelper.java | 106 ++-- ...anRepaymentScheduleInstallmentBuilder.java | 15 +- .../LoanScheduleTestDataHelper.java | 120 ++-- .../loanaccount/LoanTransactionBuilder.java | 20 +- .../loanaccount/MonetaryCurrencyBuilder.java | 4 +- .../portfolio/loanaccount/MoneyBuilder.java | 2 +- 668 files changed, 7791 insertions(+), 7582 deletions(-) diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/AccountingScenarioIntegrationTest.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/AccountingScenarioIntegrationTest.java index 2c94742c9..7792f3bb3 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/AccountingScenarioIntegrationTest.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/AccountingScenarioIntegrationTest.java @@ -1,6 +1,5 @@ package org.mifosplatform.integrationtests; - import java.util.HashMap; import org.junit.Before; @@ -24,173 +23,160 @@ import com.jayway.restassured.specification.ResponseSpecification; @SuppressWarnings("rawtypes") public class AccountingScenarioIntegrationTest { + private RequestSpecification requestSpec; private ResponseSpecification responseSpec; private final String DATE_OF_JOINING = "01 January 2011"; - private final Float LP_PRINCIPAL=10000.0f; + private final Float LP_PRINCIPAL = 10000.0f; private final String LP_REPAYMENTS = "5"; private final String LP_REPAYMENT_PERIOD = "2"; - private final String LP_INTEREST_RATE="1"; - private final String EXPECTED_DISBURSAL_DATE="04 March 2011"; - private final String LOAN_APPLICATION_SUBMISSION_DATE= "3 March 2011"; - private final String LOAN_TERM_FREQUENCY= "10"; + private final String LP_INTEREST_RATE = "1"; + private final String EXPECTED_DISBURSAL_DATE = "04 March 2011"; + private final String LOAN_APPLICATION_SUBMISSION_DATE = "3 March 2011"; + private final String LOAN_TERM_FREQUENCY = "10"; private final String INDIVIDUAL_LOAN = "individual"; - private final String REPAYMENT_DATE[]={"","04 May 2011","04 July 2011","04 September 2011","04 November 2011","04 January 2012"}; - private final Float REPAYMENT_AMOUNT [] = {.0f,2200.0f,3000.0f,900.0f,2000.0f,2500.0f}; + private final String REPAYMENT_DATE[] = { "", "04 May 2011", "04 July 2011", "04 September 2011", "04 November 2011", "04 January 2012" }; + private final Float REPAYMENT_AMOUNT[] = { .0f, 2200.0f, 3000.0f, 900.0f, 2000.0f, 2500.0f }; private final Float AMOUNT_TO_BE_WAIVE = 400.0f; private LoanTransactionHelper loanTransactionHelper; private AccountHelper accountHelper; private JournalEntryHelper journalEntryHelper; - @Before public void setup() { Utils.initializeRESTAssured(); - requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); - loanTransactionHelper = new LoanTransactionHelper(requestSpec,responseSpec); - accountHelper = new AccountHelper(requestSpec, responseSpec); - journalEntryHelper = new JournalEntryHelper(requestSpec, responseSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); + this.accountHelper = new AccountHelper(this.requestSpec, this.responseSpec); + this.journalEntryHelper = new JournalEntryHelper(this.requestSpec, this.responseSpec); } @Test public void checkAccountingFlow() { - Account assetAccount = accountHelper.createAssetAccount(); - Account incomeAccount = accountHelper.createIncomeAccount(); - Account expenseAccount= accountHelper.createExpenseAccount(); + final Account assetAccount = this.accountHelper.createAssetAccount(); + final Account incomeAccount = this.accountHelper.createIncomeAccount(); + final Account expenseAccount = this.accountHelper.createExpenseAccount(); - Integer loanProductID = createLoanProduct(assetAccount,incomeAccount,expenseAccount); + final Integer loanProductID = createLoanProduct(assetAccount, incomeAccount, expenseAccount); - Integer clientID = ClientHelper.createClient(requestSpec, responseSpec, DATE_OF_JOINING); - Integer loanID = applyForLoanApplication(clientID, loanProductID); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, this.DATE_OF_JOINING); + final Integer loanID = applyForLoanApplication(clientID, loanProductID); - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(requestSpec, responseSpec, loanID); + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - loanStatusHashMap = loanTransactionHelper.approveLoan(EXPECTED_DISBURSAL_DATE, loanID); + loanStatusHashMap = this.loanTransactionHelper.approveLoan(this.EXPECTED_DISBURSAL_DATE, loanID); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); - loanStatusHashMap = loanTransactionHelper.disburseLoan(EXPECTED_DISBURSAL_DATE, loanID); + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(this.EXPECTED_DISBURSAL_DATE, loanID); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - - //CHECK ACCOUNT ENTRIES + // CHECK ACCOUNT ENTRIES System.out.println("Entries ......"); final float PRINCIPAL_VALUE_FOR_EACH_PERIOD = 2000.0f; - final float TOTAL_INTEREST =1000.0f; - JournalEntry[] assetAccountInitialEntry = - { new JournalEntry(TOTAL_INTEREST, JournalEntry.TransactionType.DEBIT), - new JournalEntry(LP_PRINCIPAL, JournalEntry.TransactionType.CREDIT), - new JournalEntry(LP_PRINCIPAL, JournalEntry.TransactionType.DEBIT), - }; - journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, EXPECTED_DISBURSAL_DATE, assetAccountInitialEntry); + final float TOTAL_INTEREST = 1000.0f; + final JournalEntry[] assetAccountInitialEntry = { new JournalEntry(TOTAL_INTEREST, JournalEntry.TransactionType.DEBIT), + new JournalEntry(this.LP_PRINCIPAL, JournalEntry.TransactionType.CREDIT), + new JournalEntry(this.LP_PRINCIPAL, JournalEntry.TransactionType.DEBIT), }; + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.EXPECTED_DISBURSAL_DATE, assetAccountInitialEntry); System.out.println("CHECKING INCOME: ******************************************"); - JournalEntry incomeJournalEntry = new JournalEntry(TOTAL_INTEREST, JournalEntry.TransactionType.CREDIT); - journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount,EXPECTED_DISBURSAL_DATE, incomeJournalEntry); + final JournalEntry incomeJournalEntry = new JournalEntry(TOTAL_INTEREST, JournalEntry.TransactionType.CREDIT); + this.journalEntryHelper.checkJournalEntryForIncomeAccount(incomeAccount, this.EXPECTED_DISBURSAL_DATE, incomeJournalEntry); - //MAKE 1 + // MAKE 1 System.out.println("Repayment 1 ......"); - loanTransactionHelper.makeRepayment(REPAYMENT_DATE[1], REPAYMENT_AMOUNT[1], loanID); - float FIRST_INTEREST = 200.0f; - float FIRST_PRINCIPAL = 2000.0f; - float expected_value = LP_PRINCIPAL- PRINCIPAL_VALUE_FOR_EACH_PERIOD; - loanTransactionHelper.verifyRepaymentScheduleEntryFor(1, expected_value, loanID); - JournalEntry[] assetAccountFirstEntry= - { new JournalEntry(REPAYMENT_AMOUNT[1], JournalEntry.TransactionType.DEBIT), - new JournalEntry(FIRST_INTEREST, JournalEntry.TransactionType.CREDIT), - new JournalEntry(FIRST_PRINCIPAL, JournalEntry.TransactionType.CREDIT), - }; - journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, REPAYMENT_DATE[1],assetAccountFirstEntry); + this.loanTransactionHelper.makeRepayment(this.REPAYMENT_DATE[1], this.REPAYMENT_AMOUNT[1], loanID); + final float FIRST_INTEREST = 200.0f; + final float FIRST_PRINCIPAL = 2000.0f; + float expected_value = this.LP_PRINCIPAL - PRINCIPAL_VALUE_FOR_EACH_PERIOD; + this.loanTransactionHelper.verifyRepaymentScheduleEntryFor(1, expected_value, loanID); + final JournalEntry[] assetAccountFirstEntry = { new JournalEntry(this.REPAYMENT_AMOUNT[1], JournalEntry.TransactionType.DEBIT), + new JournalEntry(FIRST_INTEREST, JournalEntry.TransactionType.CREDIT), + new JournalEntry(FIRST_PRINCIPAL, JournalEntry.TransactionType.CREDIT), }; + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.REPAYMENT_DATE[1], assetAccountFirstEntry); System.out.println("Repayment 1 Done......"); - //REPAYMENT 2 + // REPAYMENT 2 System.out.println("Repayment 2 ......"); - loanTransactionHelper.makeRepayment(REPAYMENT_DATE[2], REPAYMENT_AMOUNT[2], loanID); - float SECOND_AND_THIRD_INTEREST = 400.0f; - float SECOND_PRINCIPAL = REPAYMENT_AMOUNT[2]-SECOND_AND_THIRD_INTEREST; + this.loanTransactionHelper.makeRepayment(this.REPAYMENT_DATE[2], this.REPAYMENT_AMOUNT[2], loanID); + final float SECOND_AND_THIRD_INTEREST = 400.0f; + final float SECOND_PRINCIPAL = this.REPAYMENT_AMOUNT[2] - SECOND_AND_THIRD_INTEREST; expected_value = expected_value - PRINCIPAL_VALUE_FOR_EACH_PERIOD; - loanTransactionHelper.verifyRepaymentScheduleEntryFor(2,expected_value,loanID); - JournalEntry[] assetAccountSecondEntry = { new JournalEntry(REPAYMENT_AMOUNT[2], JournalEntry.TransactionType.DEBIT), - new JournalEntry(SECOND_AND_THIRD_INTEREST, JournalEntry.TransactionType.CREDIT), - new JournalEntry(SECOND_PRINCIPAL, JournalEntry.TransactionType.CREDIT), - }; - journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, REPAYMENT_DATE[2], assetAccountSecondEntry); + this.loanTransactionHelper.verifyRepaymentScheduleEntryFor(2, expected_value, loanID); + final JournalEntry[] assetAccountSecondEntry = { new JournalEntry(this.REPAYMENT_AMOUNT[2], JournalEntry.TransactionType.DEBIT), + new JournalEntry(SECOND_AND_THIRD_INTEREST, JournalEntry.TransactionType.CREDIT), + new JournalEntry(SECOND_PRINCIPAL, JournalEntry.TransactionType.CREDIT), }; + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.REPAYMENT_DATE[2], assetAccountSecondEntry); System.out.println("Repayment 2 Done ......"); - //WAIVE INTEREST + // WAIVE INTEREST System.out.println("Waive Interest ......"); - loanTransactionHelper.waiveInterest(REPAYMENT_DATE[4], AMOUNT_TO_BE_WAIVE.toString(), loanID); + this.loanTransactionHelper.waiveInterest(this.REPAYMENT_DATE[4], this.AMOUNT_TO_BE_WAIVE.toString(), loanID); - JournalEntry waivedEntry = new JournalEntry(AMOUNT_TO_BE_WAIVE, JournalEntry.TransactionType.CREDIT); - journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, REPAYMENT_DATE[4],waivedEntry); + final JournalEntry waivedEntry = new JournalEntry(this.AMOUNT_TO_BE_WAIVE, JournalEntry.TransactionType.CREDIT); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.REPAYMENT_DATE[4], waivedEntry); - JournalEntry expenseJournalEntry = new JournalEntry(AMOUNT_TO_BE_WAIVE, JournalEntry.TransactionType.DEBIT); - journalEntryHelper.checkJournalEntryForExpenseAccount(expenseAccount, REPAYMENT_DATE[4], expenseJournalEntry); + final JournalEntry expenseJournalEntry = new JournalEntry(this.AMOUNT_TO_BE_WAIVE, JournalEntry.TransactionType.DEBIT); + this.journalEntryHelper.checkJournalEntryForExpenseAccount(expenseAccount, this.REPAYMENT_DATE[4], expenseJournalEntry); System.out.println("Waive Interest Done......"); - //REPAYMENT 3 + // REPAYMENT 3 System.out.println("Repayment 3 ......"); - loanTransactionHelper.makeRepayment(REPAYMENT_DATE[3], REPAYMENT_AMOUNT[3], loanID); + this.loanTransactionHelper.makeRepayment(this.REPAYMENT_DATE[3], this.REPAYMENT_AMOUNT[3], loanID); expected_value = expected_value - PRINCIPAL_VALUE_FOR_EACH_PERIOD; - JournalEntry[] assetAccountThirdEntry = { - new JournalEntry(REPAYMENT_AMOUNT[3], JournalEntry.TransactionType.DEBIT), - new JournalEntry(REPAYMENT_AMOUNT[3], JournalEntry.TransactionType.CREDIT) - }; - loanTransactionHelper.verifyRepaymentScheduleEntryFor(3, expected_value, loanID); - journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, REPAYMENT_DATE[3], assetAccountThirdEntry); + final JournalEntry[] assetAccountThirdEntry = { new JournalEntry(this.REPAYMENT_AMOUNT[3], JournalEntry.TransactionType.DEBIT), + new JournalEntry(this.REPAYMENT_AMOUNT[3], JournalEntry.TransactionType.CREDIT) }; + this.loanTransactionHelper.verifyRepaymentScheduleEntryFor(3, expected_value, loanID); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.REPAYMENT_DATE[3], assetAccountThirdEntry); System.out.println("Repayment 3 Done ......"); - //REPAYMENT 4 + // REPAYMENT 4 System.out.println("Repayment 4 ......"); - loanTransactionHelper.makeRepayment(REPAYMENT_DATE[4], REPAYMENT_AMOUNT[4], loanID); + this.loanTransactionHelper.makeRepayment(this.REPAYMENT_DATE[4], this.REPAYMENT_AMOUNT[4], loanID); expected_value = expected_value - PRINCIPAL_VALUE_FOR_EACH_PERIOD; - loanTransactionHelper.verifyRepaymentScheduleEntryFor(4, expected_value, loanID); - JournalEntry[] assetAccountFourthEntry = { new JournalEntry(REPAYMENT_AMOUNT[4], JournalEntry.TransactionType.DEBIT), - new JournalEntry(REPAYMENT_AMOUNT[4], JournalEntry.TransactionType.CREDIT) - }; - journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount,REPAYMENT_DATE[4],assetAccountFourthEntry); + this.loanTransactionHelper.verifyRepaymentScheduleEntryFor(4, expected_value, loanID); + final JournalEntry[] assetAccountFourthEntry = { new JournalEntry(this.REPAYMENT_AMOUNT[4], JournalEntry.TransactionType.DEBIT), + new JournalEntry(this.REPAYMENT_AMOUNT[4], JournalEntry.TransactionType.CREDIT) }; + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.REPAYMENT_DATE[4], assetAccountFourthEntry); System.out.println("Repayment 4 Done ......"); - //Repayment 5 + // Repayment 5 System.out.println("Repayment 5 ......"); - JournalEntry[] assetAccountFifthEntry = { new JournalEntry(REPAYMENT_AMOUNT[5], JournalEntry.TransactionType.DEBIT), - new JournalEntry(REPAYMENT_AMOUNT[5], JournalEntry.TransactionType.CREDIT) - }; + final JournalEntry[] assetAccountFifthEntry = { new JournalEntry(this.REPAYMENT_AMOUNT[5], JournalEntry.TransactionType.DEBIT), + new JournalEntry(this.REPAYMENT_AMOUNT[5], JournalEntry.TransactionType.CREDIT) }; expected_value = expected_value - PRINCIPAL_VALUE_FOR_EACH_PERIOD; - loanTransactionHelper.makeRepayment(REPAYMENT_DATE[5], REPAYMENT_AMOUNT[5], loanID); - loanTransactionHelper.verifyRepaymentScheduleEntryFor(5,expected_value,loanID); - journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, REPAYMENT_DATE[5], assetAccountFifthEntry); + this.loanTransactionHelper.makeRepayment(this.REPAYMENT_DATE[5], this.REPAYMENT_AMOUNT[5], loanID); + this.loanTransactionHelper.verifyRepaymentScheduleEntryFor(5, expected_value, loanID); + this.journalEntryHelper.checkJournalEntryForAssetAccount(assetAccount, this.REPAYMENT_DATE[5], assetAccountFifthEntry); System.out.println("Repayment 5 Done ......"); } - private Integer createLoanProduct(final Account ... accounts) { + private Integer createLoanProduct(final Account... accounts) { System.out.println("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); - String loanProductJSON = new LoanProductTestBuilder().withPrincipal(LP_PRINCIPAL.toString()).withRepaymentTypeAsMonth() - .withRepaymentAfterEvery(LP_REPAYMENT_PERIOD).withNumberOfRepayments(LP_REPAYMENTS).withRepaymentTypeAsMonth() - .withinterestRatePerPeriod(LP_INTEREST_RATE).withInterestRateFrequencyTypeAsMonths() - .withAmortizationTypeAsEqualPrincipalPayment().withInterestTypeAsFlat() - .withAccountingRuleAsAccrualBased(accounts) - .build(); - return loanTransactionHelper.getLoanProductId(loanProductJSON); + final String loanProductJSON = new LoanProductTestBuilder().withPrincipal(this.LP_PRINCIPAL.toString()).withRepaymentTypeAsMonth() + .withRepaymentAfterEvery(this.LP_REPAYMENT_PERIOD).withNumberOfRepayments(this.LP_REPAYMENTS).withRepaymentTypeAsMonth() + .withinterestRatePerPeriod(this.LP_INTEREST_RATE).withInterestRateFrequencyTypeAsMonths() + .withAmortizationTypeAsEqualPrincipalPayment().withInterestTypeAsFlat().withAccountingRuleAsAccrualBased(accounts).build(); + return this.loanTransactionHelper.getLoanProductId(loanProductJSON); } private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID) { System.out.println("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); - String loanApplicationJSON = new LoanApplicationTestBuilder().withPrincipal(LP_PRINCIPAL.toString()).withLoanTermFrequency(LOAN_TERM_FREQUENCY) - .withLoanTermFrequencyAsMonths().withNumberOfRepayments(LP_REPAYMENTS).withRepaymentEveryAfter(LP_REPAYMENT_PERIOD) - .withRepaymentFrequencyTypeAsMonths().withInterestRatePerPeriod(LP_INTEREST_RATE).withInterestTypeAsFlatBalance() + final String loanApplicationJSON = new LoanApplicationTestBuilder().withPrincipal(this.LP_PRINCIPAL.toString()) + .withLoanTermFrequency(this.LOAN_TERM_FREQUENCY).withLoanTermFrequencyAsMonths().withNumberOfRepayments(this.LP_REPAYMENTS) + .withRepaymentEveryAfter(this.LP_REPAYMENT_PERIOD).withRepaymentFrequencyTypeAsMonths() + .withInterestRatePerPeriod(this.LP_INTEREST_RATE).withInterestTypeAsFlatBalance() .withAmortizationTypeAsEqualPrincipalPayments().withInterestCalculationPeriodTypeSameAsRepaymentPeriod() - .withExpectedDisbursementDate(EXPECTED_DISBURSAL_DATE).withSubmittedOnDate(LOAN_APPLICATION_SUBMISSION_DATE) - .withLoanType(INDIVIDUAL_LOAN) - .build(clientID.toString(), loanProductID.toString()); - return loanTransactionHelper.getLoanId(loanApplicationJSON); + .withExpectedDisbursementDate(this.EXPECTED_DISBURSAL_DATE).withSubmittedOnDate(this.LOAN_APPLICATION_SUBMISSION_DATE) + .withLoanType(this.INDIVIDUAL_LOAN).build(clientID.toString(), loanProductID.toString()); + return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } } - diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/ClientLoanIntegrationTest.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/ClientLoanIntegrationTest.java index cd35a4079..1934eac5e 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/ClientLoanIntegrationTest.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/ClientLoanIntegrationTest.java @@ -34,27 +34,28 @@ public class ClientLoanIntegrationTest { @Before public void setup() { Utils.initializeRESTAssured(); - requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } @Test public void checkClientLoanCreateAndDisburseFlow() { - loanTransactionHelper = new LoanTransactionHelper(requestSpec, responseSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - Integer clientID = ClientHelper.createClient(requestSpec, responseSpec); - ClientHelper.verifyClientCreatedOnServer(requestSpec, responseSpec, clientID); - Integer loanProductID = createLoanProduct(); - Integer loanID = applyForLoanApplication(clientID, loanProductID); - ArrayList loanSchedule = loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, responseSpec, loanID); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); + final Integer loanProductID = createLoanProduct(); + final Integer loanID = applyForLoanApplication(clientID, loanProductID); + final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, + loanID); verifyLoanRepaymentSchedule(loanSchedule); } private Integer createLoanProduct() { System.out.println("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); - String loanProductJSON = new LoanProductTestBuilder() // + final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("12,000.00") // .withNumberOfRepayments("4") // .withRepaymentAfterEvery("1") // @@ -64,12 +65,12 @@ public class ClientLoanIntegrationTest { .withAmortizationTypeAsEqualInstallments() // .withInterestTypeAsDecliningBalance() // .build(); - return loanTransactionHelper.getLoanProductId(loanProductJSON); + return this.loanTransactionHelper.getLoanProductId(loanProductJSON); } private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID) { System.out.println("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); - String loanApplicationJSON = new LoanApplicationTestBuilder() // + final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal("12,000.00") // .withLoanTermFrequency("4") // .withLoanTermFrequencyAsMonths() // @@ -83,7 +84,7 @@ public class ClientLoanIntegrationTest { .withExpectedDisbursementDate("20 September 2011") // .withSubmittedOnDate("20 September 2011") // .build(clientID.toString(), loanProductID.toString()); - return loanTransactionHelper.getLoanId(loanApplicationJSON); + return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule) { diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/GroupLoanIntegrationTest.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/GroupLoanIntegrationTest.java index b309d9852..3750af75f 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/GroupLoanIntegrationTest.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/GroupLoanIntegrationTest.java @@ -22,8 +22,7 @@ import com.jayway.restassured.specification.RequestSpecification; import com.jayway.restassured.specification.ResponseSpecification; /** - * Group Loan Integration Test for checking Loan Application Repayment - * Schedule. + * Group Loan Integration Test for checking Loan Application Repayment Schedule. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class GroupLoanIntegrationTest { @@ -35,29 +34,30 @@ public class GroupLoanIntegrationTest { @Before public void setup() { Utils.initializeRESTAssured(); - requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } @Test public void checkGroupLoanCreateAndDisburseFlow() { - loanTransactionHelper = new LoanTransactionHelper(requestSpec, responseSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); - Integer clientID = ClientHelper.createClient(requestSpec, responseSpec); - Integer groupID = GroupHelper.createGroup(requestSpec, responseSpec, true); - groupID = GroupHelper.associateClient(requestSpec, responseSpec, groupID.toString(),clientID.toString()); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Integer groupID = GroupHelper.createGroup(this.requestSpec, this.responseSpec, true); + groupID = GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupID.toString(), clientID.toString()); - Integer loanProductID = createLoanProduct(); - Integer loanID = applyForLoanApplication(groupID, loanProductID); - ArrayList loanSchedule = loanTransactionHelper.getLoanRepaymentSchedule(requestSpec, responseSpec, loanID); + final Integer loanProductID = createLoanProduct(); + final Integer loanID = applyForLoanApplication(groupID, loanProductID); + final ArrayList loanSchedule = this.loanTransactionHelper.getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, + loanID); verifyLoanRepaymentSchedule(loanSchedule); } private Integer createLoanProduct() { System.out.println("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); - String loanProductJSON = new LoanProductTestBuilder() // + final String loanProductJSON = new LoanProductTestBuilder() // .withPrincipal("12,000.00") // .withNumberOfRepayments("4") // .withRepaymentAfterEvery("1") // @@ -67,12 +67,12 @@ public class GroupLoanIntegrationTest { .withAmortizationTypeAsEqualInstallments() // .withInterestTypeAsDecliningBalance() // .build(); - return loanTransactionHelper.getLoanProductId(loanProductJSON); + return this.loanTransactionHelper.getLoanProductId(loanProductJSON); } private Integer applyForLoanApplication(final Integer groupID, final Integer loanProductID) { System.out.println("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); - String loanApplicationJSON = new LoanApplicationTestBuilder() // + final String loanApplicationJSON = new LoanApplicationTestBuilder() // .withPrincipal("12,000.00") // .withLoanTermFrequency("4") // .withLoanTermFrequencyAsMonths() // @@ -85,10 +85,9 @@ public class GroupLoanIntegrationTest { .withInterestCalculationPeriodTypeSameAsRepaymentPeriod() // .withExpectedDisbursementDate("20 September 2011") // .withSubmittedOnDate("20 September 2011") // - .withLoanType("group") - .build(groupID.toString(), loanProductID.toString()); + .withLoanType("group").build(groupID.toString(), loanProductID.toString()); System.out.println(loanApplicationJSON); - return loanTransactionHelper.getLoanId(loanApplicationJSON); + return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } private void verifyLoanRepaymentSchedule(final ArrayList loanSchedule) { diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/GroupTest.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/GroupTest.java index 4b8374474..c35622a8a 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/GroupTest.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/GroupTest.java @@ -24,32 +24,32 @@ public class GroupTest { @Before public void setup() { Utils.initializeRESTAssured(); - requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } @Test public void checkGroupFunctions() { - Integer clientID = ClientHelper.createClient(requestSpec, responseSpec); - Integer groupID = GroupHelper.createGroup(requestSpec, responseSpec); - GroupHelper.verifyGroupCreatedOnServer(requestSpec, responseSpec, groupID); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec); + Integer groupID = GroupHelper.createGroup(this.requestSpec, this.responseSpec); + GroupHelper.verifyGroupCreatedOnServer(this.requestSpec, this.responseSpec, groupID); - groupID = GroupHelper.activateGroup(requestSpec, responseSpec, groupID.toString()); - GroupHelper.verifyGroupActivatedOnServer(requestSpec, responseSpec, groupID, true); + groupID = GroupHelper.activateGroup(this.requestSpec, this.responseSpec, groupID.toString()); + GroupHelper.verifyGroupActivatedOnServer(this.requestSpec, this.responseSpec, groupID, true); - groupID = GroupHelper.associateClient(requestSpec, responseSpec, groupID.toString(), clientID.toString()); - GroupHelper.verifyGroupMembers(requestSpec, responseSpec, groupID, clientID); + groupID = GroupHelper.associateClient(this.requestSpec, this.responseSpec, groupID.toString(), clientID.toString()); + GroupHelper.verifyGroupMembers(this.requestSpec, this.responseSpec, groupID, clientID); - groupID = GroupHelper.disAssociateClient(requestSpec, responseSpec, groupID.toString(), clientID.toString()); - GroupHelper.verifyEmptyGroupMembers(requestSpec, responseSpec, groupID); + groupID = GroupHelper.disAssociateClient(this.requestSpec, this.responseSpec, groupID.toString(), clientID.toString()); + GroupHelper.verifyEmptyGroupMembers(this.requestSpec, this.responseSpec, groupID); - String updatedGroupName = GroupHelper.randomNameGenerator("Group-", 5); - groupID = GroupHelper.updateGroup(requestSpec, responseSpec, updatedGroupName, groupID.toString()); - GroupHelper.verifyGroupDetails(requestSpec, responseSpec, groupID, "name", updatedGroupName); + final String updatedGroupName = GroupHelper.randomNameGenerator("Group-", 5); + groupID = GroupHelper.updateGroup(this.requestSpec, this.responseSpec, updatedGroupName, groupID.toString()); + GroupHelper.verifyGroupDetails(this.requestSpec, this.responseSpec, groupID, "name", updatedGroupName); - groupID = GroupHelper.createGroup(requestSpec, responseSpec); - GroupHelper.deleteGroup(requestSpec, responseSpec, groupID.toString()); - GroupHelper.verifyGroupDeleted(requestSpec, responseSpec, groupID); + groupID = GroupHelper.createGroup(this.requestSpec, this.responseSpec); + GroupHelper.deleteGroup(this.requestSpec, this.responseSpec, groupID.toString()); + GroupHelper.verifyGroupDeleted(this.requestSpec, this.responseSpec, groupID); } } \ No newline at end of file diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/LoanWithWaiveInterestAndWriteOffIntegrationTest.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/LoanWithWaiveInterestAndWriteOffIntegrationTest.java index e2200f7a9..faf3799f6 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/LoanWithWaiveInterestAndWriteOffIntegrationTest.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/LoanWithWaiveInterestAndWriteOffIntegrationTest.java @@ -18,9 +18,9 @@ import com.jayway.restassured.specification.RequestSpecification; import com.jayway.restassured.specification.ResponseSpecification; /** -* Client Loan Integration Test for checking Loan Disbursement with Waive -* Interest and Write-Off. -*/ + * Client Loan Integration Test for checking Loan Disbursement with Waive + * Interest and Write-Off. + */ @SuppressWarnings({ "rawtypes" }) public class LoanWithWaiveInterestAndWriteOffIntegrationTest { @@ -28,107 +28,108 @@ public class LoanWithWaiveInterestAndWriteOffIntegrationTest { private RequestSpecification requestSpec; private final String LP_PRINCIPAL = "12,000.00", LP_REPAYMENTS = "2", LP_REPAYMENT_PERIOD = "6", LP_INTEREST_RATE = "1", - PRINCIPAL = "4,500.00", LOAN_TERM_FREQUENCY = "18", NUMBER_OF_REPAYMENTS = "9", REPAYMENT_PERIOD = "2", - DISBURSEMENT_DATE = "30 October 2010", LOAN_APPLICATION_SUBMISSION_DATE = "23 September 2010", - EXPECTED_DISBURSAL_DATE = "28 October 2010", RATE_OF_INTEREST_PER_PERIOD = "2", - DATE_OF_JOINING = "04 March 2009",INTEREST_VALUE_AMOUNT = "40.00"; + PRINCIPAL = "4,500.00", LOAN_TERM_FREQUENCY = "18", NUMBER_OF_REPAYMENTS = "9", REPAYMENT_PERIOD = "2", + DISBURSEMENT_DATE = "30 October 2010", LOAN_APPLICATION_SUBMISSION_DATE = "23 September 2010", + EXPECTED_DISBURSAL_DATE = "28 October 2010", RATE_OF_INTEREST_PER_PERIOD = "2", DATE_OF_JOINING = "04 March 2009", + INTEREST_VALUE_AMOUNT = "40.00"; private LoanTransactionHelper loanTransactionHelper; @Before public void setup() { Utils.initializeRESTAssured(); - requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); - loanTransactionHelper = new LoanTransactionHelper(requestSpec,responseSpec); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); } @Test public void checkClientLoanCreateAndDisburseFlow() { // CREATE CLIENT - Integer clientID = ClientHelper.createClient(requestSpec, responseSpec, DATE_OF_JOINING); - ClientHelper.verifyClientCreatedOnServer(requestSpec, responseSpec, clientID); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, this.DATE_OF_JOINING); + ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID); // CREATE LOAN PRODUCT - Integer loanProductID = createLoanProduct(); + final Integer loanProductID = createLoanProduct(); // APPLY FOR LOAN - Integer loanID = applyForLoanApplication(clientID, loanProductID); + final Integer loanID = applyForLoanApplication(clientID, loanProductID); - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(requestSpec, responseSpec, loanID); + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); System.out.println("-----------------------------------APPROVE LOAN-----------------------------------------"); - loanStatusHashMap = loanTransactionHelper.approveLoan("28 September 2010", loanID); + loanStatusHashMap = this.loanTransactionHelper.approveLoan("28 September 2010", loanID); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); // UNDO APPROVAL - loanStatusHashMap = loanTransactionHelper.undoApproval(loanID); + loanStatusHashMap = this.loanTransactionHelper.undoApproval(loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); System.out.println("-----------------------------------RE-APPROVE LOAN-----------------------------------------"); - loanStatusHashMap = loanTransactionHelper.approveLoan("1 October 2010", loanID); + loanStatusHashMap = this.loanTransactionHelper.approveLoan("1 October 2010", loanID); LoanStatusChecker.verifyLoanIsApproved(loanStatusHashMap); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); // DISBURSE - loanStatusHashMap = loanTransactionHelper.disburseLoan(DISBURSEMENT_DATE, loanID); + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(this.DISBURSEMENT_DATE, loanID); System.out.println("DISBURSE " + loanStatusHashMap); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); // PERFORM REPAYMENTS AND CHECK LOAN STATUS - loanTransactionHelper.verifyRepaymentScheduleEntryFor(1, 4000.0F, loanID); - loanTransactionHelper.makeRepayment("1 January 2011", 540.0f, loanID); + this.loanTransactionHelper.verifyRepaymentScheduleEntryFor(1, 4000.0F, loanID); + this.loanTransactionHelper.makeRepayment("1 January 2011", 540.0f, loanID); - //UNDO DISBURSE LOAN - loanStatusHashMap=loanTransactionHelper.undoDisbursal(loanID); + // UNDO DISBURSE LOAN + loanStatusHashMap = this.loanTransactionHelper.undoDisbursal(loanID); LoanStatusChecker.verifyLoanIsWaitingForDisbursal(loanStatusHashMap); - //DIBURSE AGAIN - loanStatusHashMap = loanTransactionHelper.disburseLoan(DISBURSEMENT_DATE, loanID); + // DIBURSE AGAIN + loanStatusHashMap = this.loanTransactionHelper.disburseLoan(this.DISBURSEMENT_DATE, loanID); System.out.println("DISBURSE " + loanStatusHashMap); LoanStatusChecker.verifyLoanIsActive(loanStatusHashMap); - //MAKE REPAYMENTS + // MAKE REPAYMENTS final float repayment_with_interest = 540.0f; final float repayment_without_interest = 500.0f; - loanTransactionHelper.verifyRepaymentScheduleEntryFor(1, 4000.0F, loanID); - loanTransactionHelper.makeRepayment("1 January 2011",repayment_with_interest, loanID); - loanTransactionHelper.makeRepayment("1 March 2011", repayment_with_interest, loanID); - loanTransactionHelper.waiveInterest("1 May 2011", INTEREST_VALUE_AMOUNT, loanID); - loanTransactionHelper.makeRepayment("1 May 2011", repayment_without_interest, loanID); - loanTransactionHelper.makeRepayment("1 July 2011", repayment_with_interest, loanID); - loanTransactionHelper.waiveInterest("1 September 2011", INTEREST_VALUE_AMOUNT, loanID); - loanTransactionHelper.makeRepayment("1 September 2011", repayment_without_interest, loanID); - loanTransactionHelper.makeRepayment("1 November 2011", repayment_with_interest, loanID); - loanTransactionHelper.waiveInterest("1 January 2012", INTEREST_VALUE_AMOUNT, loanID); - loanTransactionHelper.makeRepayment("1 January 2012", repayment_without_interest, loanID); - loanTransactionHelper.verifyRepaymentScheduleEntryFor(7, 1000.0f, loanID); + this.loanTransactionHelper.verifyRepaymentScheduleEntryFor(1, 4000.0F, loanID); + this.loanTransactionHelper.makeRepayment("1 January 2011", repayment_with_interest, loanID); + this.loanTransactionHelper.makeRepayment("1 March 2011", repayment_with_interest, loanID); + this.loanTransactionHelper.waiveInterest("1 May 2011", this.INTEREST_VALUE_AMOUNT, loanID); + this.loanTransactionHelper.makeRepayment("1 May 2011", repayment_without_interest, loanID); + this.loanTransactionHelper.makeRepayment("1 July 2011", repayment_with_interest, loanID); + this.loanTransactionHelper.waiveInterest("1 September 2011", this.INTEREST_VALUE_AMOUNT, loanID); + this.loanTransactionHelper.makeRepayment("1 September 2011", repayment_without_interest, loanID); + this.loanTransactionHelper.makeRepayment("1 November 2011", repayment_with_interest, loanID); + this.loanTransactionHelper.waiveInterest("1 January 2012", this.INTEREST_VALUE_AMOUNT, loanID); + this.loanTransactionHelper.makeRepayment("1 January 2012", repayment_without_interest, loanID); + this.loanTransactionHelper.verifyRepaymentScheduleEntryFor(7, 1000.0f, loanID); // WRITE OFF LOAN AND CHECK ACCOUNT IS CLOSED - LoanStatusChecker.verifyLoanAccountIsClosed(loanTransactionHelper.writeOffLoan("1 March 2012", loanID)); + LoanStatusChecker.verifyLoanAccountIsClosed(this.loanTransactionHelper.writeOffLoan("1 March 2012", loanID)); } private Integer createLoanProduct() { System.out.println("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------"); - String loanProductJSON = new LoanProductTestBuilder().withPrincipal(LP_PRINCIPAL).withRepaymentTypeAsMonth() - .withRepaymentAfterEvery(LP_REPAYMENT_PERIOD).withNumberOfRepayments(LP_REPAYMENTS).withRepaymentTypeAsMonth() - .withinterestRatePerPeriod(LP_INTEREST_RATE).withInterestRateFrequencyTypeAsMonths() + final String loanProductJSON = new LoanProductTestBuilder().withPrincipal(this.LP_PRINCIPAL).withRepaymentTypeAsMonth() + .withRepaymentAfterEvery(this.LP_REPAYMENT_PERIOD).withNumberOfRepayments(this.LP_REPAYMENTS).withRepaymentTypeAsMonth() + .withinterestRatePerPeriod(this.LP_INTEREST_RATE).withInterestRateFrequencyTypeAsMonths() .withAmortizationTypeAsEqualPrincipalPayment().withInterestTypeAsFlat().build(); - return loanTransactionHelper.getLoanProductId(loanProductJSON); + return this.loanTransactionHelper.getLoanProductId(loanProductJSON); } private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID) { System.out.println("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------"); - String loanApplicationJSON = new LoanApplicationTestBuilder().withPrincipal(PRINCIPAL).withLoanTermFrequency(LOAN_TERM_FREQUENCY) - .withLoanTermFrequencyAsMonths().withNumberOfRepayments(NUMBER_OF_REPAYMENTS).withRepaymentEveryAfter(REPAYMENT_PERIOD) - .withRepaymentFrequencyTypeAsMonths().withInterestRatePerPeriod(RATE_OF_INTEREST_PER_PERIOD).withInterestTypeAsFlatBalance() - .withAmortizationTypeAsEqualInstallments().withInterestCalculationPeriodTypeSameAsRepaymentPeriod() - .withExpectedDisbursementDate(EXPECTED_DISBURSAL_DATE).withSubmittedOnDate(LOAN_APPLICATION_SUBMISSION_DATE) - .build(clientID.toString(), loanProductID.toString()); - return loanTransactionHelper.getLoanId(loanApplicationJSON); + final String loanApplicationJSON = new LoanApplicationTestBuilder().withPrincipal(this.PRINCIPAL) + .withLoanTermFrequency(this.LOAN_TERM_FREQUENCY).withLoanTermFrequencyAsMonths() + .withNumberOfRepayments(this.NUMBER_OF_REPAYMENTS).withRepaymentEveryAfter(this.REPAYMENT_PERIOD) + .withRepaymentFrequencyTypeAsMonths().withInterestRatePerPeriod(this.RATE_OF_INTEREST_PER_PERIOD) + .withInterestTypeAsFlatBalance().withAmortizationTypeAsEqualInstallments() + .withInterestCalculationPeriodTypeSameAsRepaymentPeriod().withExpectedDisbursementDate(this.EXPECTED_DISBURSAL_DATE) + .withSubmittedOnDate(this.LOAN_APPLICATION_SUBMISSION_DATE).build(clientID.toString(), loanProductID.toString()); + return this.loanTransactionHelper.getLoanId(loanApplicationJSON); } } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/LoanWithdrawnByApplicantIntegrationTest.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/LoanWithdrawnByApplicantIntegrationTest.java index 9f809bbad..78c77b84b 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/LoanWithdrawnByApplicantIntegrationTest.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/LoanWithdrawnByApplicantIntegrationTest.java @@ -27,33 +27,33 @@ public class LoanWithdrawnByApplicantIntegrationTest { @Before public void setup() { Utils.initializeRESTAssured(); - requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); - loanTransactionHelper = new LoanTransactionHelper(requestSpec, responseSpec); + this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec); } @Test public void loanWithdrawnByApplicant() { - Integer clientID = ClientHelper.createClient(requestSpec, responseSpec, "01 January 2012"); - Integer loanProductID = loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder().build()); - Integer loanID = applyForLoanApplication(clientID, loanProductID); + final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec, "01 January 2012"); + final Integer loanProductID = this.loanTransactionHelper.getLoanProductId(new LoanProductTestBuilder().build()); + final Integer loanID = applyForLoanApplication(clientID, loanProductID); - HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(requestSpec, responseSpec, loanID); + HashMap loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanIsPending(loanStatusHashMap); - loanTransactionHelper.withdrawLoanApplicationByClient("03 April 2012", loanID); - loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(requestSpec, responseSpec, loanID); + this.loanTransactionHelper.withdrawLoanApplicationByClient("03 April 2012", loanID); + loanStatusHashMap = LoanStatusChecker.getStatusOfLoan(this.requestSpec, this.responseSpec, loanID); LoanStatusChecker.verifyLoanAccountIsNotActive(loanStatusHashMap); } private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID) { - String loanApplication = new LoanApplicationTestBuilder().withPrincipal("5000").withLoanTermFrequency("5") + final String loanApplication = new LoanApplicationTestBuilder().withPrincipal("5000").withLoanTermFrequency("5") .withLoanTermFrequencyAsMonths().withNumberOfRepayments("5").withRepaymentEveryAfter("1") .withRepaymentFrequencyTypeAsMonths().withInterestRatePerPeriod("2").withExpectedDisbursementDate("04 April 2012") .withSubmittedOnDate("02 April 2012").build(clientID.toString(), loanProductID.toString()); - return loanTransactionHelper.getLoanId(loanApplication); + return this.loanTransactionHelper.getLoanId(loanApplication); } } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/XBRLIntegrationTest.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/XBRLIntegrationTest.java index 581e98eec..760d6e295 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/XBRLIntegrationTest.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/XBRLIntegrationTest.java @@ -27,20 +27,20 @@ public class XBRLIntegrationTest { @Before public void setUp() throws Exception { Utils.initializeRESTAssured(); - requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); - requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); - responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); + this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build(); + this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey()); + this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build(); } @Test public void shouldRetrieveTaxonomyList() { - xbrlHelper = new XBRLIntegrationTestHelper(requestSpec, responseSpec); + this.xbrlHelper = new XBRLIntegrationTestHelper(this.requestSpec, this.responseSpec); - ArrayList taxonomyList = xbrlHelper.getTaxonomyList(); - this.verifyTaxonomyList(taxonomyList); + final ArrayList taxonomyList = this.xbrlHelper.getTaxonomyList(); + verifyTaxonomyList(taxonomyList); } - private void verifyTaxonomyList(ArrayList taxonomyList) { + private void verifyTaxonomyList(final ArrayList taxonomyList) { System.out.println("--------------------VERIFYING TAXONOMY LIST--------------------------"); assertEquals("Checking for the 1st taxonomy", "AdministrativeExpense", taxonomyList.get(0).get("name")); } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/ClientHelper.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/ClientHelper.java index 53a449373..fbce5f344 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/ClientHelper.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/ClientHelper.java @@ -23,7 +23,7 @@ public class ClientHelper { } public static String getTestClientAsJSON(final String dateOfJoining) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("officeId", "1"); map.put("firstname", randomNameGenerator("Client_FirstName_", 5)); map.put("lastname", randomNameGenerator("Client_LastName_", 4)); @@ -39,9 +39,9 @@ public class ClientHelper { public static void verifyClientCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer generatedClientID) { System.out.println("------------------------------CHECK CLIENT DETAILS------------------------------------\n"); - String CLIENT_URL = "/mifosng-provider/api/v1/clients/" + generatedClientID + "?tenantIdentifier=default"; - Integer responseClientID = Utils.performServerGet(requestSpec, responseSpec, CLIENT_URL, "id"); - assertEquals("ERROR IN CREATING THE CLIENT",generatedClientID, responseClientID); + final String CLIENT_URL = "/mifosng-provider/api/v1/clients/" + generatedClientID + "?tenantIdentifier=default"; + final Integer responseClientID = Utils.performServerGet(requestSpec, responseSpec, CLIENT_URL, "id"); + assertEquals("ERROR IN CREATING THE CLIENT", generatedClientID, responseClientID); } public static String randomNameGenerator(final String prefix, final int lenOfRandomSuffix) { diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/GroupHelper.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/GroupHelper.java index 973da206c..e58b62600 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/GroupHelper.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/GroupHelper.java @@ -35,40 +35,42 @@ public class GroupHelper { public static Integer associateClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId, final String clientMember) { - String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + "?command=associateClients&tenantIdentifier=default"; + final String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + + "?command=associateClients&tenantIdentifier=default"; System.out.println("---------------------------------Associate Client To A GROUP---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, GROUP_ASSOCIATE_URL, associateClientAsJSON(clientMember), "groupId"); } public static Integer disAssociateClient(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId, final String clientMember) { - String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + "?command=disassociateClients&tenantIdentifier=default"; + final String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + + "?command=disassociateClients&tenantIdentifier=default"; System.out.println("---------------------------------Disassociate Client To A GROUP---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, GROUP_ASSOCIATE_URL, associateClientAsJSON(clientMember), "groupId"); } public static Integer activateGroup(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId) { - String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + "?command=activate&tenantIdentifier=default"; + final String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + "?command=activate&tenantIdentifier=default"; System.out.println("---------------------------------Activate A GROUP---------------------------------------------"); return Utils.performServerPost(requestSpec, responseSpec, GROUP_ASSOCIATE_URL, activateGroupAsJSON(""), "groupId"); } public static Integer updateGroup(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String name, final String groupId) { - String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + "?tenantIdentifier=default"; + final String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + "?tenantIdentifier=default"; System.out.println("---------------------------------UPDATE GROUP---------------------------------------------"); return Utils.performServerPut(requestSpec, responseSpec, GROUP_ASSOCIATE_URL, updateGroupAsJSON(name), "groupId"); } public static Integer deleteGroup(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final String groupId) { - String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + "?tenantIdentifier=default"; + final String GROUP_ASSOCIATE_URL = "/mifosng-provider/api/v1/groups/" + groupId + "?tenantIdentifier=default"; System.out.println("---------------------------------DELETE GROUP---------------------------------------------"); return Utils.performServerDelete(requestSpec, responseSpec, GROUP_ASSOCIATE_URL, "groupId"); } public static String getTestGroupAsJSON(final boolean active, final String activationDate) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("officeId", "1"); map.put("name", randomNameGenerator("Group_Name_", 5)); map.put("externalId", randomIDGenerator("ID_", 7)); @@ -77,16 +79,17 @@ public class GroupHelper { map.put("dateFormat", "dd MMMM yyyy"); map.put("locale", "en"); map.put("activationDate", activationDate); - } else + } else { map.put("active", "false"); + } System.out.println("map : " + map); return new Gson().toJson(map); } public static String associateClientAsJSON(final String clientMember) { - HashMap> map = new HashMap>(); - List list = new ArrayList(); + final HashMap> map = new HashMap>(); + final List list = new ArrayList(); list.add(clientMember); map.put("clientMembers", list); System.out.println("map : " + map); @@ -94,19 +97,20 @@ public class GroupHelper { } public static String activateGroupAsJSON(final String activationDate) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("dateFormat", "dd MMMM yyyy"); map.put("locale", "en"); - if (activationDate != "") + if (activationDate != "") { map.put("activationDate", activationDate); - else + } else { map.put("activationDate", "04 March 2011"); + } System.out.println("map : " + map); return new Gson().toJson(map); } public static String updateGroupAsJSON(final String name) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("name", name); System.out.println("map : " + map); return new Gson().toJson(map); @@ -115,24 +119,24 @@ public class GroupHelper { public static void verifyGroupCreatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer generatedGroupID) { System.out.println("------------------------------CHECK GROUP DETAILS------------------------------------\n"); - String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + "?tenantIdentifier=default"; - Integer responseGroupID = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "id"); + final String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + "?tenantIdentifier=default"; + final Integer responseGroupID = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "id"); assertEquals("ERROR IN CREATING THE GROUP", generatedGroupID, responseGroupID); } public static void verifyGroupDetails(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer generatedGroupID, final String field, final String expectedValue) { System.out.println("------------------------------CHECK GROUP DETAILS------------------------------------\n"); - String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + "?tenantIdentifier=default"; - String responseValue = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, field); + final String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + "?tenantIdentifier=default"; + final String responseValue = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, field); assertEquals("ERROR IN CREATING THE GROUP", expectedValue, responseValue); } public static void verifyGroupActivatedOnServer(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer generatedGroupID, final boolean generatedGroupStatus) { System.out.println("------------------------------CHECK GROUP STATUS------------------------------------\n"); - String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + "?tenantIdentifier=default"; - Boolean responseGroupStatus = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "active"); + final String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + "?tenantIdentifier=default"; + final Boolean responseGroupStatus = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "active"); assertEquals("ERROR IN ACTIVATING THE GROUP", generatedGroupStatus, responseGroupStatus); } @@ -140,7 +144,8 @@ public class GroupHelper { final Integer generatedGroupID, final Integer groupMember) { List list = new ArrayList(); System.out.println("------------------------------CHECK GROUP MEMBERS------------------------------------\n"); - String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + "?associations=clientMembers&tenantIdentifier=default"; + final String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + + "?associations=clientMembers&tenantIdentifier=default"; list = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "clientMembers"); assertTrue("ERROR IN GROUP MEMBER", list.toString().contains("id=" + groupMember.toString())); } @@ -149,7 +154,8 @@ public class GroupHelper { final Integer generatedGroupID) { List list = new ArrayList(); System.out.println("------------------------------CHECK EMPTY GROUP MEMBER LIST------------------------------------\n"); - String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + "?associations=clientMembers&tenantIdentifier=default"; + final String GROUP_URL = "/mifosng-provider/api/v1/groups/" + generatedGroupID + + "?associations=clientMembers&tenantIdentifier=default"; list = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "clientMembers"); assertEquals("GROUP MEMBER LIST NOT EMPTY", list, null); } @@ -158,7 +164,7 @@ public class GroupHelper { final Integer generatedGroupID) { List list = new ArrayList(); System.out.println("------------------------------CHECK GROUP DELETED------------------------------------\n"); - String GROUP_URL = "/mifosng-provider/api/v1/groups/?tenantIdentifier=default"; + final String GROUP_URL = "/mifosng-provider/api/v1/groups/?tenantIdentifier=default"; list = Utils.performServerGet(requestSpec, responseSpec, GROUP_URL, "pageItems"); assertFalse("GROUP NOT DELETED", list.toString().contains("id=" + generatedGroupID.toString())); diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/Utils.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/Utils.java index 747fb7045..29db23504 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/Utils.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/Utils.java @@ -6,6 +6,10 @@ import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Random; + import org.apache.commons.lang.StringUtils; import org.apache.http.conn.HttpHostConnectException; @@ -14,19 +18,13 @@ import com.jayway.restassured.path.json.JsonPath; import com.jayway.restassured.specification.RequestSpecification; import com.jayway.restassured.specification.ResponseSpecification; -import java.lang.System; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Random; - @SuppressWarnings("unchecked") public class Utils { private static final String LOGIN_URL = "/mifosng-provider/api/v1/authentication?username=mifos&password=password&tenantIdentifier=default"; - public static void initializeRESTAssured() { - RestAssured.baseURI ="https://localhost"; + RestAssured.baseURI = "https://localhost"; RestAssured.port = 8443; RestAssured.keystore("../keystore.jks", "openmf"); } @@ -34,14 +32,13 @@ public class Utils { public static String loginIntoServerAndGetBase64EncodedAuthenticationKey() { try { System.out.println("-----------------------------------LOGIN-----------------------------------------"); - String json = RestAssured.post(LOGIN_URL).asString(); + final String json = RestAssured.post(LOGIN_URL).asString(); assertThat("Failed to login into mifosx platform", StringUtils.isBlank(json), is(false)); return JsonPath.with(json).get("base64EncodedAuthenticationKey"); - } - catch (Exception e) { + } catch (final Exception e) { if (e instanceof HttpHostConnectException) { - HttpHostConnectException hh = (HttpHostConnectException) e; - fail("Failed to connect to mifosx platform:"+hh.getMessage()); + final HttpHostConnectException hh = (HttpHostConnectException) e; + fail("Failed to connect to mifosx platform:" + hh.getMessage()); } throw new RuntimeException(e); @@ -49,58 +46,51 @@ public class Utils { } public static T performServerGet(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final String getURL, final String jsonAttributeToGetBack) { - String json = given().spec(requestSpec) - .expect().spec(responseSpec).log().ifError() - .when().get(getURL).andReturn().asString(); + final String getURL, final String jsonAttributeToGetBack) { + final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().get(getURL).andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerPost(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { - String json = given().spec(requestSpec).body(jsonBodyToSend) - .expect().spec(responseSpec).log().ifError() - .when().post(postURL) + final String postURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { + final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().post(postURL) .andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerPut(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { - String json = given().spec(requestSpec).body(jsonBodyToSend) - .expect().spec(responseSpec).log().ifError() - .when().put(putURL) + final String putURL, final String jsonBodyToSend, final String jsonAttributeToGetBack) { + final String json = given().spec(requestSpec).body(jsonBodyToSend).expect().spec(responseSpec).log().ifError().when().put(putURL) .andReturn().asString(); return (T) from(json).get(jsonAttributeToGetBack); } public static T performServerDelete(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, - final String deleteURL, final String jsonAttributeToGetBack) { - String json = given().spec(requestSpec) - .expect().spec(responseSpec).log().ifError() - .when().delete(deleteURL) - .andReturn().asString(); + final String deleteURL, final String jsonAttributeToGetBack) { + final String json = given().spec(requestSpec).expect().spec(responseSpec).log().ifError().when().delete(deleteURL).andReturn() + .asString(); return (T) from(json).get(jsonAttributeToGetBack); } - public static String convertDateToURLFormat(String dateToBeConvert){ - SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy"); - SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); - String reformattedStr=""; + public static String convertDateToURLFormat(final String dateToBeConvert) { + final SimpleDateFormat oldFormat = new SimpleDateFormat("dd MMMMMM yyyy"); + final SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); + String reformattedStr = ""; try { reformattedStr = newFormat.format(oldFormat.parse(dateToBeConvert)); - } catch (ParseException e) { + } catch (final ParseException e) { e.printStackTrace(); } return reformattedStr; } public static String randomStringGenerator(final String prefix, final int len, final String sourceSetString) { - int lengthOfSource = sourceSetString.length(); - Random rnd = new Random(); - StringBuilder sb = new StringBuilder(len); - for (int i = 0; i < len; i++) + final int lengthOfSource = sourceSetString.length(); + final Random rnd = new Random(); + final StringBuilder sb = new StringBuilder(len); + for (int i = 0; i < len; i++) { sb.append((sourceSetString).charAt(rnd.nextInt(lengthOfSource))); + } return (prefix + (sb.toString())); } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/Account.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/Account.java index 84e9e7d88..6621ebe1f 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/Account.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/Account.java @@ -3,33 +3,33 @@ package org.mifosplatform.integrationtests.common.accounting; public class Account { public enum AccountType { - ASSET("1"), INCOME("4"), EXPENSE("5"), LIABILITY("2"),EQUITY("3"); + ASSET("1"), INCOME("4"), EXPENSE("5"), LIABILITY("2"), EQUITY("3"); - private final String accountValue ; + private final String accountValue; - AccountType(final String accountValue){ - this.accountValue=accountValue; + AccountType(final String accountValue) { + this.accountValue = accountValue; } + @Override public String toString() { - return accountValue; + return this.accountValue; } } private final AccountType accountType; private final Integer accountID; - - public Account(Integer accountID, AccountType accountType) { + public Account(final Integer accountID, final AccountType accountType) { this.accountID = accountID; this.accountType = accountType; } - public AccountType getAccountType(){ + public AccountType getAccountType() { return this.accountType; } - public Integer getAccountID(){ + public Integer getAccountID() { return this.accountID; } } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/AccountHelper.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/AccountHelper.java index 0a9180f3c..f356aac50 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/AccountHelper.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/AccountHelper.java @@ -1,41 +1,41 @@ package org.mifosplatform.integrationtests.common.accounting; +import org.mifosplatform.integrationtests.common.Utils; + import com.jayway.restassured.specification.RequestSpecification; import com.jayway.restassured.specification.ResponseSpecification; -import org.mifosplatform.integrationtests.common.Utils; public class AccountHelper { private final String CREATE_GL_ACCOUNT_URL = "/mifosng-provider/api/v1/glaccounts?tenantIdentifier=default"; private final String GL_ACCOUNT_ID_RESPONSE = "resourceId"; - private RequestSpecification requestSpec; - private ResponseSpecification responseSpec; + private final RequestSpecification requestSpec; + private final ResponseSpecification responseSpec; - public AccountHelper(RequestSpecification requestSpec, ResponseSpecification responseSpec) { + public AccountHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { this.requestSpec = requestSpec; this.responseSpec = responseSpec; } - public Account createAssetAccount(){ - String assetAccountJSON= new GLAccountBuilder() - .withAccountTypeAsAsset() - .build(); - Integer accountID = Utils.performServerPost(requestSpec, responseSpec, CREATE_GL_ACCOUNT_URL, assetAccountJSON, GL_ACCOUNT_ID_RESPONSE); + public Account createAssetAccount() { + final String assetAccountJSON = new GLAccountBuilder().withAccountTypeAsAsset().build(); + final Integer accountID = Utils.performServerPost(this.requestSpec, this.responseSpec, this.CREATE_GL_ACCOUNT_URL, + assetAccountJSON, this.GL_ACCOUNT_ID_RESPONSE); return new Account(accountID, Account.AccountType.ASSET); } - public Account createIncomeAccount(){ - String assetAccountJSON= new GLAccountBuilder() - .withAccountTypeAsIncome() - .build(); - Integer accountID = Utils.performServerPost(requestSpec, responseSpec, CREATE_GL_ACCOUNT_URL, assetAccountJSON, GL_ACCOUNT_ID_RESPONSE); + + public Account createIncomeAccount() { + final String assetAccountJSON = new GLAccountBuilder().withAccountTypeAsIncome().build(); + final Integer accountID = Utils.performServerPost(this.requestSpec, this.responseSpec, this.CREATE_GL_ACCOUNT_URL, + assetAccountJSON, this.GL_ACCOUNT_ID_RESPONSE); return new Account(accountID, Account.AccountType.INCOME); } - public Account createExpenseAccount(){ - String assetAccountJSON= new GLAccountBuilder() - .withAccountTypeAsExpense() - .build(); - Integer accountID = Utils.performServerPost(requestSpec, responseSpec, CREATE_GL_ACCOUNT_URL, assetAccountJSON, GL_ACCOUNT_ID_RESPONSE); + + public Account createExpenseAccount() { + final String assetAccountJSON = new GLAccountBuilder().withAccountTypeAsExpense().build(); + final Integer accountID = Utils.performServerPost(this.requestSpec, this.responseSpec, this.CREATE_GL_ACCOUNT_URL, + assetAccountJSON, this.GL_ACCOUNT_ID_RESPONSE); return new Account(accountID, Account.AccountType.EXPENSE); } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/GLAccountBuilder.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/GLAccountBuilder.java index 83c468a65..53868fff4 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/GLAccountBuilder.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/GLAccountBuilder.java @@ -29,7 +29,7 @@ public class GLAccountBuilder { private static String description = "DEFAULT_DESCRIPTION"; public String build() { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("name", GLAccountBuilder.name); map.put("glCode", GLAccountBuilder.GLCode); map.put("manualEntriesAllowed", GLAccountBuilder.manualEntriesAllowed); @@ -43,12 +43,12 @@ public class GLAccountBuilder { GLAccountBuilder.accountType = ASSET_ACCOUNT; GLAccountBuilder.GLCode = Utils.randomStringGenerator("ASSET_", 2); GLAccountBuilder.GLCode += Calendar.getInstance().getTimeInMillis() + ""; // Added - // unique - // timestamp - // for - // avoiding - // random - // collisions + // unique + // timestamp + // for + // avoiding + // random + // collisions return this; } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/JournalEntry.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/JournalEntry.java index 402a96e00..50c4adb0d 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/JournalEntry.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/JournalEntry.java @@ -1,11 +1,9 @@ package org.mifosplatform.integrationtests.common.accounting; - public class JournalEntry { public enum TransactionType { - CREDIT("CREDIT"), - DEBIT("DEBIT"); + CREDIT("CREDIT"), DEBIT("DEBIT"); private TransactionType(final String type) { this.type = type; @@ -15,22 +13,23 @@ public class JournalEntry { @Override public String toString() { - return type; + return this.type; } } + private final Float transactionAmount; private final TransactionType transactionType; - public JournalEntry(float transactionAmount, TransactionType type){ - this.transactionAmount=transactionAmount; + public JournalEntry(final float transactionAmount, final TransactionType type) { + this.transactionAmount = transactionAmount; this.transactionType = type; } - public Float getTransactionAmount(){ + public Float getTransactionAmount() { return this.transactionAmount; } - public String getTransactionType(){ + public String getTransactionType() { return this.transactionType.toString(); } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/JournalEntryHelper.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/JournalEntryHelper.java index 2727e2eb4..fd7b88073 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/JournalEntryHelper.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/accounting/JournalEntryHelper.java @@ -35,7 +35,7 @@ public class JournalEntryHelper { } private String getEntryValueFromJournalEntry(final ArrayList entryResponse, final int entryNumber) { - HashMap map = (HashMap) entryResponse.get(entryNumber).get("entryType"); + final HashMap map = (HashMap) entryResponse.get(entryNumber).get("entryType"); return (String) map.get("value"); } @@ -44,8 +44,8 @@ public class JournalEntryHelper { } private void checkJournalEntry(final Account account, final String date, final JournalEntry... accountEntries) { - String url = createURLForGettingAccountEntries(account, date); - ArrayList response = Utils.performServerGet(requestSpec, responseSpec, url, "pageItems"); + final String url = createURLForGettingAccountEntries(account, date); + final ArrayList response = Utils.performServerGet(this.requestSpec, this.responseSpec, url, "pageItems"); for (int i = 0; i < accountEntries.length; i++) { assertThat(getEntryValueFromJournalEntry(response, i), equalTo(accountEntries[i].getTransactionType())); assertThat(getTransactionAmountFromJournalEntry(response, i), equalTo(accountEntries[i].getTransactionAmount())); diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanApplicationTestBuilder.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanApplicationTestBuilder.java index f9bd1894b..a45684e7e 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanApplicationTestBuilder.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanApplicationTestBuilder.java @@ -35,28 +35,29 @@ public class LoanApplicationTestBuilder { public String build(final String ID, final String loanProductId) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("dateFormat", "dd MMMM yyyy"); map.put("locale", "en_GB"); - if (loanType == "group") + if (this.loanType == "group") { map.put("groupId", ID); - else + } else { map.put("clientId", ID); + } map.put("productId", loanProductId); - map.put("principal", principal); - map.put("loanTermFrequency", loanTermFrequency); - map.put("loanTermFrequencyType", loanTermFrequencyType); - map.put("numberOfRepayments", numberOfRepayment); - map.put("repaymentEvery", repaymentPeriod); - map.put("repaymentFrequencyType", repaymentFrequencyType); - map.put("interestRatePerPeriod", interestRate); - map.put("amortizationType", amortizationType); - map.put("interestType", interestType); - map.put("interestCalculationPeriodType", interestCalculationPeriodType); - map.put("transactionProcessingStrategyId", transactionProcessingID); - map.put("expectedDisbursementDate", expectedDisbursmentDate); - map.put("submittedOnDate", submittedOnDate); - map.put("loanType", loanType); + map.put("principal", this.principal); + map.put("loanTermFrequency", this.loanTermFrequency); + map.put("loanTermFrequencyType", this.loanTermFrequencyType); + map.put("numberOfRepayments", this.numberOfRepayment); + map.put("repaymentEvery", this.repaymentPeriod); + map.put("repaymentFrequencyType", this.repaymentFrequencyType); + map.put("interestRatePerPeriod", this.interestRate); + map.put("amortizationType", this.amortizationType); + map.put("interestType", this.interestType); + map.put("interestCalculationPeriodType", this.interestCalculationPeriodType); + map.put("transactionProcessingStrategyId", this.transactionProcessingID); + map.put("expectedDisbursementDate", this.expectedDisbursmentDate); + map.put("submittedOnDate", this.submittedOnDate); + map.put("loanType", this.loanType); return new Gson().toJson(map); } @@ -160,7 +161,7 @@ public class LoanApplicationTestBuilder { return this; } - public LoanApplicationTestBuilder withLoanType(final String loanType){ + public LoanApplicationTestBuilder withLoanType(final String loanType) { this.loanType = loanType; return this; } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanProductTestBuilder.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanProductTestBuilder.java index 2d75ae362..11520b81b 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanProductTestBuilder.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanProductTestBuilder.java @@ -3,11 +3,13 @@ package org.mifosplatform.integrationtests.common.loans; import java.util.HashMap; import java.util.Map; -import com.google.gson.Gson; import org.mifosplatform.integrationtests.common.ClientHelper; import org.mifosplatform.integrationtests.common.accounting.Account; +import com.google.gson.Gson; + public class LoanProductTestBuilder { + private static final String LOCALE = "en_GB"; private static final String DIGITS_AFTER_DECIMAL = "2"; private static final String INR = "INR"; @@ -15,227 +17,224 @@ public class LoanProductTestBuilder { private static final String WEEK = "1"; private static final String MONTHS = "2"; private static final String YEARS = "3"; - private static final String CALCULATION_PERIOD_SAME_AS_REPAYMENT_PERIOD="1"; - private static final String EQUAL_PRINCIPAL_PAYMENTS="0"; - private static final String EQUAL_INSTALLMENTS="1"; - private static final String DECLINING_BALANCE="0"; - private static final String FLAT_BALANCE="1"; - private static final String MIFOS_STANDARD_STRATEGY ="1"; + private static final String CALCULATION_PERIOD_SAME_AS_REPAYMENT_PERIOD = "1"; + private static final String EQUAL_PRINCIPAL_PAYMENTS = "0"; + private static final String EQUAL_INSTALLMENTS = "1"; + private static final String DECLINING_BALANCE = "0"; + private static final String FLAT_BALANCE = "1"; + private static final String MIFOS_STANDARD_STRATEGY = "1"; // private static final String HEAVENS_FAMILY_STRATEGY ="2"; // private static final String CREO_CORE_STRATEGY ="3"; // private static final String RBI_INDIA_STRATEGY ="4"; - private static final String NONE ="1"; - private static final String CASH_BASED ="2"; - private static final String ACCRUAL_BASED ="3"; - + private static final String NONE = "1"; + private static final String CASH_BASED = "2"; + private static final String ACCRUAL_BASED = "3"; private String nameOfLoanProduct = ClientHelper.randomNameGenerator("LOAN_PRODUCT_", 6); private String principal = "10000.00"; private String numberOfRepayments = "5"; private String repaymentFrequency = MONTHS; private String repaymentPeriod = "1"; - private String interestRatePerPeriod= "2"; + private String interestRatePerPeriod = "2"; private String interestRateFrequencyType = MONTHS; private String interestType = FLAT_BALANCE; - private String interestCalculationPeriodType=CALCULATION_PERIOD_SAME_AS_REPAYMENT_PERIOD; - private String inArrearsTolerance="0"; - private final String transactionProcessingStrategy=MIFOS_STANDARD_STRATEGY; - private String accountingRule =NONE; + private String interestCalculationPeriodType = CALCULATION_PERIOD_SAME_AS_REPAYMENT_PERIOD; + private String inArrearsTolerance = "0"; + private final String transactionProcessingStrategy = MIFOS_STANDARD_STRATEGY; + private String accountingRule = NONE; private final String currencyCode = INR; - private String amortizationType= EQUAL_INSTALLMENTS; + private String amortizationType = EQUAL_INSTALLMENTS; private String minPrincipal = "1000.00"; private String maxPrincipal = "100000.00"; private Account[] accountList = null; public String build() { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); - map.put("name", nameOfLoanProduct); - map.put("currencyCode", currencyCode); + map.put("name", this.nameOfLoanProduct); + map.put("currencyCode", this.currencyCode); map.put("locale", LOCALE); - map.put("digitsAfterDecimal",DIGITS_AFTER_DECIMAL); - map.put("principal", principal); - map.put("numberOfRepayments", numberOfRepayments); - map.put("repaymentEvery",repaymentPeriod ); - map.put("repaymentFrequencyType", repaymentFrequency); - map.put("interestRatePerPeriod", interestRatePerPeriod); - map.put("interestRateFrequencyType", interestRateFrequencyType); - map.put("amortizationType",amortizationType); - map.put("interestType", interestType); - map.put("interestCalculationPeriodType", interestCalculationPeriodType); - map.put("inArrearsTolerance", inArrearsTolerance); - map.put("transactionProcessingStrategyId", transactionProcessingStrategy); - map.put("accountingRule", accountingRule); - map.put("minPrincipal",minPrincipal); - map.put("maxPrincipal",maxPrincipal); + map.put("digitsAfterDecimal", DIGITS_AFTER_DECIMAL); + map.put("principal", this.principal); + map.put("numberOfRepayments", this.numberOfRepayments); + map.put("repaymentEvery", this.repaymentPeriod); + map.put("repaymentFrequencyType", this.repaymentFrequency); + map.put("interestRatePerPeriod", this.interestRatePerPeriod); + map.put("interestRateFrequencyType", this.interestRateFrequencyType); + map.put("amortizationType", this.amortizationType); + map.put("interestType", this.interestType); + map.put("interestCalculationPeriodType", this.interestCalculationPeriodType); + map.put("inArrearsTolerance", this.inArrearsTolerance); + map.put("transactionProcessingStrategyId", this.transactionProcessingStrategy); + map.put("accountingRule", this.accountingRule); + map.put("minPrincipal", this.minPrincipal); + map.put("maxPrincipal", this.maxPrincipal); - if(accountingRule.equals(ACCRUAL_BASED)){ + if (this.accountingRule.equals(ACCRUAL_BASED)) { map.putAll(getAccountMappingForAccrualBased()); - }else if(accountingRule.equals(CASH_BASED)){ + } else if (this.accountingRule.equals(CASH_BASED)) { map.putAll(getAccountMappingForCashBased()); } return new Gson().toJson(map); } - - public LoanProductTestBuilder withMinPrincipal(final String minPrincipal){ - this.minPrincipal=minPrincipal; - return this; - } - public LoanProductTestBuilder withMaxPrincipal(final String maxPrincipal){ - this.maxPrincipal=maxPrincipal; + public LoanProductTestBuilder withMinPrincipal(final String minPrincipal) { + this.minPrincipal = minPrincipal; return this; } - public LoanProductTestBuilder withLoanName(final String loanName){ - this.nameOfLoanProduct=loanName; + public LoanProductTestBuilder withMaxPrincipal(final String maxPrincipal) { + this.maxPrincipal = maxPrincipal; return this; } - public LoanProductTestBuilder withPrincipal(final String principal){ + + public LoanProductTestBuilder withLoanName(final String loanName) { + this.nameOfLoanProduct = loanName; + return this; + } + + public LoanProductTestBuilder withPrincipal(final String principal) { this.principal = principal; return this; } - public LoanProductTestBuilder withNumberOfRepayments(final String numberOfRepayment){ + public LoanProductTestBuilder withNumberOfRepayments(final String numberOfRepayment) { this.numberOfRepayments = numberOfRepayment; return this; } - - public LoanProductTestBuilder withRepaymentTypeAsMonth(){ + public LoanProductTestBuilder withRepaymentTypeAsMonth() { this.repaymentFrequency = MONTHS; return this; } - public LoanProductTestBuilder withRepaymentTypeAsWeek(){ + public LoanProductTestBuilder withRepaymentTypeAsWeek() { this.repaymentFrequency = WEEK; return this; } - public LoanProductTestBuilder withRepaymentTypeAsDays(){ + public LoanProductTestBuilder withRepaymentTypeAsDays() { this.repaymentFrequency = DAYS; return this; } - public LoanProductTestBuilder withRepaymentAfterEvery(final String repaymentAfterEvery){ - this.repaymentPeriod=repaymentAfterEvery; + public LoanProductTestBuilder withRepaymentAfterEvery(final String repaymentAfterEvery) { + this.repaymentPeriod = repaymentAfterEvery; return this; } - public LoanProductTestBuilder withInterestRateFrequencyTypeAsMonths(){ - this.interestRateFrequencyType=MONTHS; + public LoanProductTestBuilder withInterestRateFrequencyTypeAsMonths() { + this.interestRateFrequencyType = MONTHS; return this; } - public LoanProductTestBuilder withInterestRateFrequencyTypeAsYear(){ - this.interestRateFrequencyType=YEARS; + public LoanProductTestBuilder withInterestRateFrequencyTypeAsYear() { + this.interestRateFrequencyType = YEARS; return this; } public LoanProductTestBuilder withinterestRatePerPeriod(final String interestRatePerPeriod) { - this.interestRatePerPeriod=interestRatePerPeriod; + this.interestRatePerPeriod = interestRatePerPeriod; return this; } - public LoanProductTestBuilder withAmortizationTypeAsEqualPrincipalPayment(){ + public LoanProductTestBuilder withAmortizationTypeAsEqualPrincipalPayment() { this.amortizationType = EQUAL_PRINCIPAL_PAYMENTS; return this; } - public LoanProductTestBuilder withAmortizationTypeAsEqualInstallments(){ + public LoanProductTestBuilder withAmortizationTypeAsEqualInstallments() { this.amortizationType = EQUAL_INSTALLMENTS; return this; } - public LoanProductTestBuilder withInterestTypeAsFlat(){ - this.interestType=FLAT_BALANCE; + public LoanProductTestBuilder withInterestTypeAsFlat() { + this.interestType = FLAT_BALANCE; return this; } - public LoanProductTestBuilder withInterestTypeAsDecliningBalance (){ - this.interestType=DECLINING_BALANCE; + public LoanProductTestBuilder withInterestTypeAsDecliningBalance() { + this.interestType = DECLINING_BALANCE; return this; } - public LoanProductTestBuilder withInterestCalculationPeriodTypeAsDays (){ - this.interestCalculationPeriodType=DAYS; + public LoanProductTestBuilder withInterestCalculationPeriodTypeAsDays() { + this.interestCalculationPeriodType = DAYS; return this; } - public LoanProductTestBuilder withInterestCalculationPeriodTypeAsRepaymentPeriod (){ - this.interestCalculationPeriodType=CALCULATION_PERIOD_SAME_AS_REPAYMENT_PERIOD; + public LoanProductTestBuilder withInterestCalculationPeriodTypeAsRepaymentPeriod() { + this.interestCalculationPeriodType = CALCULATION_PERIOD_SAME_AS_REPAYMENT_PERIOD; return this; } - public LoanProductTestBuilder withInArrearsTolerance (final String amountCanBeWaved){ + public LoanProductTestBuilder withInArrearsTolerance(final String amountCanBeWaved) { this.inArrearsTolerance = amountCanBeWaved; return this; } - public LoanProductTestBuilder withAccountingRuleAsNone (){ - this.accountingRule= NONE; + public LoanProductTestBuilder withAccountingRuleAsNone() { + this.accountingRule = NONE; return this; } - public LoanProductTestBuilder withAccountingRuleAsCashBased (Account [] account_list){ - this.accountingRule= CASH_BASED; + public LoanProductTestBuilder withAccountingRuleAsCashBased(final Account[] account_list) { + this.accountingRule = CASH_BASED; this.accountList = account_list; return this; } - public LoanProductTestBuilder withAccountingRuleAsAccrualBased (Account[] account_list){ - this.accountingRule= ACCRUAL_BASED; + public LoanProductTestBuilder withAccountingRuleAsAccrualBased(final Account[] account_list) { + this.accountingRule = ACCRUAL_BASED; this.accountList = account_list; return this; } - private Map getAccountMappingForCashBased() { - Map map = new HashMap(); - for (int i=0;i getAccountMappingForCashBased() { + final Map map = new HashMap(); + for (int i = 0; i < this.accountList.length; i++) { + if (this.accountList[i].getAccountType().equals(Account.AccountType.ASSET)) { + final String ID = this.accountList[i].getAccountID().toString(); + map.put("fundSourceAccountId", ID); + map.put("loanPortfolioAccountId", ID); + map.put("transfersInSuspenseAccountId", ID); } - if(accountList[i].getAccountType().equals(Account.AccountType.INCOME)){ - String ID = accountList[i].getAccountID().toString(); - map.put("interestOnLoanAccountId",ID); - map.put("incomeFromFeeAccountId",ID); - map.put("incomeFromPenaltyAccountId",ID); + if (this.accountList[i].getAccountType().equals(Account.AccountType.INCOME)) { + final String ID = this.accountList[i].getAccountID().toString(); + map.put("interestOnLoanAccountId", ID); + map.put("incomeFromFeeAccountId", ID); + map.put("incomeFromPenaltyAccountId", ID); } - if(accountList[i].getAccountType().equals(Account.AccountType.EXPENSE)){ - String ID = accountList[i].getAccountID().toString(); - map.put("writeOffAccountId",ID); + if (this.accountList[i].getAccountType().equals(Account.AccountType.EXPENSE)) { + final String ID = this.accountList[i].getAccountID().toString(); + map.put("writeOffAccountId", ID); } } return map; } private Map getAccountMappingForAccrualBased() { - Map map = new HashMap(); - for (int i=0;i map = new HashMap(); + for (int i = 0; i < this.accountList.length; i++) { + if (this.accountList[i].getAccountType().equals(Account.AccountType.ASSET)) { + final String ID = this.accountList[i].getAccountID().toString(); + map.put("fundSourceAccountId", ID); + map.put("loanPortfolioAccountId", ID); + map.put("transfersInSuspenseAccountId", ID); + map.put("receivableInterestAccountId", ID); + map.put("receivableFeeAccountId", ID); + map.put("receivablePenaltyAccountId", ID); } - if(accountList[i].getAccountType().equals(Account.AccountType.INCOME)){ - String ID = accountList[i].getAccountID().toString(); - map.put("interestOnLoanAccountId",ID); - map.put("incomeFromFeeAccountId",ID); - map.put("incomeFromPenaltyAccountId",ID); + if (this.accountList[i].getAccountType().equals(Account.AccountType.INCOME)) { + final String ID = this.accountList[i].getAccountID().toString(); + map.put("interestOnLoanAccountId", ID); + map.put("incomeFromFeeAccountId", ID); + map.put("incomeFromPenaltyAccountId", ID); } - if(accountList[i].getAccountType().equals(Account.AccountType.EXPENSE)){ - String ID = accountList[i].getAccountID().toString(); - map.put("writeOffAccountId",ID); + if (this.accountList[i].getAccountType().equals(Account.AccountType.EXPENSE)) { + final String ID = this.accountList[i].getAccountID().toString(); + map.put("writeOffAccountId", ID); } } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanStatusChecker.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanStatusChecker.java index b61172fab..9501f726d 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanStatusChecker.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanStatusChecker.java @@ -5,9 +5,10 @@ import static org.junit.Assert.assertTrue; import java.util.HashMap; +import org.mifosplatform.integrationtests.common.Utils; + import com.jayway.restassured.specification.RequestSpecification; import com.jayway.restassured.specification.ResponseSpecification; -import org.mifosplatform.integrationtests.common.Utils; @SuppressWarnings("rawtypes") public class LoanStatusChecker { @@ -32,13 +33,13 @@ public class LoanStatusChecker { assertTrue(getStatus(loanStatusHashMap, "closed")); } - public static void verifyLoanAccountIsNotActive(final HashMap loanStatusHashMap) { + public static void verifyLoanAccountIsNotActive(final HashMap loanStatusHashMap) { assertFalse(getStatus(loanStatusHashMap, "active")); } public static HashMap getStatusOfLoan(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer loanID) { - String url = "/mifosng-provider/api/v1/loans/" + loanID + "?tenantIdentifier=default"; + final String url = "/mifosng-provider/api/v1/loans/" + loanID + "?tenantIdentifier=default"; return Utils.performServerGet(requestSpec, responseSpec, url, "status"); } diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanTransactionHelper.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanTransactionHelper.java index e54b09282..a6d06184e 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanTransactionHelper.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/loans/LoanTransactionHelper.java @@ -28,58 +28,53 @@ public class LoanTransactionHelper { private static final String MAKE_REPAYMENT_COMMAND = "repayment"; private static final String WITHDRAW_LOAN_APPLICATION_COMMAND = "withdrawnByApplicant"; - - public LoanTransactionHelper(final RequestSpecification requestSpec,final ResponseSpecification responseSpec){ - this.requestSpec = requestSpec; + public LoanTransactionHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { + this.requestSpec = requestSpec; this.responseSpec = responseSpec; } + public Integer getLoanProductId(final String loanProductJSON) { - return Utils.performServerPost(requestSpec, responseSpec, CREATE_LOAN_PRODUCT_URL, loanProductJSON, "resourceId"); + return Utils.performServerPost(this.requestSpec, this.responseSpec, CREATE_LOAN_PRODUCT_URL, loanProductJSON, "resourceId"); } public Integer getLoanId(final String loanApplicationJSON) { - return Utils.performServerPost(requestSpec, responseSpec, APPLY_LOAN_URL, loanApplicationJSON, "loanId"); + return Utils.performServerPost(this.requestSpec, this.responseSpec, APPLY_LOAN_URL, loanApplicationJSON, "loanId"); } public ArrayList getLoanRepaymentSchedule(final RequestSpecification requestSpec, final ResponseSpecification responseSpec, final Integer loanID) { - String URL = "/mifosng-provider/api/v1/loans/" + loanID + "?associations=repaymentSchedule&tenantIdentifier=default"; - HashMap response = Utils.performServerGet(requestSpec, responseSpec, URL, "repaymentSchedule"); + final String URL = "/mifosng-provider/api/v1/loans/" + loanID + "?associations=repaymentSchedule&tenantIdentifier=default"; + final HashMap response = Utils.performServerGet(requestSpec, responseSpec, URL, "repaymentSchedule"); return (ArrayList) response.get("periods"); } - public HashMap approveLoan(final String approvalDate, final Integer loanID) { - return performLoanTransaction(createLoanOperationURL(APPROVE_LOAN_COMMAND, loanID), - getApproveLoanAsJSON(approvalDate)); + public HashMap approveLoan(final String approvalDate, final Integer loanID) { + return performLoanTransaction(createLoanOperationURL(APPROVE_LOAN_COMMAND, loanID), getApproveLoanAsJSON(approvalDate)); } - public HashMap undoApproval(final Integer loanID) { - String undoBodyJson = "{'note':'UNDO APPROVAL'}"; + public HashMap undoApproval(final Integer loanID) { + final String undoBodyJson = "{'note':'UNDO APPROVAL'}"; return performLoanTransaction(createLoanOperationURL(UNDO_APPROVAL_LOAN_COMMAND, loanID), undoBodyJson); } - public HashMap disburseLoan(final String date, - final Integer loanID) { - return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), - getDisburseLoanAsJSON(date)); + public HashMap disburseLoan(final String date, final Integer loanID) { + return performLoanTransaction(createLoanOperationURL(DISBURSE_LOAN_COMMAND, loanID), getDisburseLoanAsJSON(date)); } - public HashMap undoDisbursal(final Integer loanID){ - String undoDisburseJson = "{'note' : 'UNDO DISBURSAL'}"; + public HashMap undoDisbursal(final Integer loanID) { + final String undoDisburseJson = "{'note' : 'UNDO DISBURSAL'}"; System.out.println("IN DISBURSE LOAN"); - String url =createLoanOperationURL(UNDO_DISBURSE_LOAN_COMMAND,loanID); + final String url = createLoanOperationURL(UNDO_DISBURSE_LOAN_COMMAND, loanID); System.out.println("IN DISBURSE LOAN URL " + url); return performLoanTransaction(createLoanOperationURL(UNDO_DISBURSE_LOAN_COMMAND, loanID), undoDisburseJson); } - public HashMap writeOffLoan(final String date, - final Integer loanID) { - return performLoanTransaction(createLoanTransactionURL(WRITE_OFF_LOAN_COMMAND, loanID), - getWriteOffBodyAsJSON(date)); + + public HashMap writeOffLoan(final String date, final Integer loanID) { + return performLoanTransaction(createLoanTransactionURL(WRITE_OFF_LOAN_COMMAND, loanID), getWriteOffBodyAsJSON(date)); } - public HashMap waiveInterest(final String date, final String amountToBeWaived, final Integer loanID) { - return performLoanTransaction(createLoanTransactionURL(WAIVE_INTEREST_COMMAND, loanID), - getWaiveBodyAsJSON(date, amountToBeWaived)); + public HashMap waiveInterest(final String date, final String amountToBeWaived, final Integer loanID) { + return performLoanTransaction(createLoanTransactionURL(WAIVE_INTEREST_COMMAND, loanID), getWaiveBodyAsJSON(date, amountToBeWaived)); } public HashMap makeRepayment(final String date, final Float amountToBePaid, final Integer loanID) { @@ -88,12 +83,12 @@ public class LoanTransactionHelper { } public HashMap withdrawLoanApplicationByClient(final String date, final Integer loanID) { - return performLoanTransaction(createLoanOperationURL(WITHDRAW_LOAN_APPLICATION_COMMAND,loanID), + return performLoanTransaction(createLoanOperationURL(WITHDRAW_LOAN_APPLICATION_COMMAND, loanID), getWithdrawLoanApplicationBodyAsJSON(date)); } private String getDisburseLoanAsJSON(final String actualDisbursementDate) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); map.put("actualDisbursementDate", actualDisbursementDate); @@ -102,7 +97,7 @@ public class LoanTransactionHelper { } private String getApproveLoanAsJSON(final String approvalDate) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); map.put("approvedOnDate", approvalDate); @@ -111,7 +106,7 @@ public class LoanTransactionHelper { } private String getRepaymentBodyAsJSON(final String transactionDate, final Float transactionAmount) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); map.put("transactionDate", transactionDate); @@ -121,7 +116,7 @@ public class LoanTransactionHelper { } private String getWriteOffBodyAsJSON(final String transactionDate) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("dateFormat", "dd MMMM yyyy"); map.put("locale", "en"); map.put("note", " LOAN WRITE OFF!!!"); @@ -130,7 +125,7 @@ public class LoanTransactionHelper { } private String getWaiveBodyAsJSON(final String transactionDate, final String amountToBeWaived) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); map.put("transactionDate", transactionDate); @@ -139,8 +134,8 @@ public class LoanTransactionHelper { return new Gson().toJson(map); } - private String getWithdrawLoanApplicationBodyAsJSON(final String withdrawDate){ - HashMap map = new HashMap(); + private String getWithdrawLoanApplicationBodyAsJSON(final String withdrawDate) { + final HashMap map = new HashMap(); map.put("locale", "en"); map.put("dateFormat", "dd MMMM yyyy"); map.put("withdrawnOnDate", withdrawDate); @@ -148,8 +143,9 @@ public class LoanTransactionHelper { return new Gson().toJson(map); } + public String getLoanCalculationBodyAsJSON(final String productID) { - HashMap map = new HashMap(); + final HashMap map = new HashMap(); map.put("dateFormat", "dd MMMM yyyy"); map.put("locale", "en_GB"); map.put("productId", productID); @@ -169,24 +165,26 @@ public class LoanTransactionHelper { return new Gson().toJson(map); } - private String createLoanOperationURL(final String command, final Integer loanID) { + private String createLoanOperationURL(final String command, final Integer loanID) { return "/mifosng-provider/api/v1/loans/" + loanID + "?command=" + command + "&tenantIdentifier=default"; } - private String createLoanTransactionURL(final String command, final Integer loanID) { + private String createLoanTransactionURL(final String command, final Integer loanID) { return "/mifosng-provider/api/v1/loans/" + loanID + "/transactions?command=" + command + "&tenantIdentifier=default"; } - private HashMap performLoanTransaction(final String postURLForLoanTransaction, final String jsonToBeSent) { + private HashMap performLoanTransaction(final String postURLForLoanTransaction, final String jsonToBeSent) { - HashMap response = Utils.performServerPost(requestSpec, responseSpec, postURLForLoanTransaction, jsonToBeSent, "changes"); + final HashMap response = Utils.performServerPost(this.requestSpec, this.responseSpec, postURLForLoanTransaction, jsonToBeSent, + "changes"); return (HashMap) response.get("status"); } @SuppressWarnings("unchecked") public void verifyRepaymentScheduleEntryFor(final int repaymentNumber, final float expectedPrincipalOutstanding, final Integer loanID) { System.out.println("---------------------------GETTING LOAN REPAYMENT SCHEDULE--------------------------------"); - ArrayList repaymentPeriods = getLoanRepaymentSchedule(requestSpec, responseSpec, loanID); - assertEquals("Mismatch in Principal Loan Balance Outstanding ", expectedPrincipalOutstanding, repaymentPeriods.get(repaymentNumber).get("principalLoanBalanceOutstanding")); + final ArrayList repaymentPeriods = getLoanRepaymentSchedule(this.requestSpec, this.responseSpec, loanID); + assertEquals("Mismatch in Principal Loan Balance Outstanding ", expectedPrincipalOutstanding, repaymentPeriods.get(repaymentNumber) + .get("principalLoanBalanceOutstanding")); } } \ No newline at end of file diff --git a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/xbrl/XBRLIntegrationTestHelper.java b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/xbrl/XBRLIntegrationTestHelper.java index 0bb5b4824..0a6981eb7 100644 --- a/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/xbrl/XBRLIntegrationTestHelper.java +++ b/mifosng-provider/src/integrationTest/java/org/mifosplatform/integrationtests/common/xbrl/XBRLIntegrationTestHelper.java @@ -17,19 +17,19 @@ public class XBRLIntegrationTestHelper { private static final String GET_TAXONOMY_LIST_URL = "/mifosng-provider/api/v1/mixtaxonomy?tenantIdentifier=default"; private static final String TAXONOMY_MAPPING_URL = "/mifosng-provider/api/v1/mixmapping?tenantIdentifier=default"; - public XBRLIntegrationTestHelper(RequestSpecification requestSpec, ResponseSpecification responseSpec) { + public XBRLIntegrationTestHelper(final RequestSpecification requestSpec, final ResponseSpecification responseSpec) { this.requestSpec = requestSpec; this.responseSpec = responseSpec; } public ArrayList getTaxonomyList() { - ArrayList response = Utils.performServerGet(requestSpec, responseSpec, GET_TAXONOMY_LIST_URL, ""); + final ArrayList response = Utils.performServerGet(this.requestSpec, this.responseSpec, GET_TAXONOMY_LIST_URL, ""); return response; } public HashMap getTaxonomyMapping() { - HashMap response = Utils.performServerGet(requestSpec, responseSpec, TAXONOMY_MAPPING_URL, "config"); + final HashMap response = Utils.performServerGet(this.requestSpec, this.responseSpec, TAXONOMY_MAPPING_URL, "config"); return response; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/closure/api/GLClosuresApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/closure/api/GLClosuresApiResource.java index 03eca1cd1..68d8b7d48 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/closure/api/GLClosuresApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/closure/api/GLClosuresApiResource.java @@ -76,7 +76,7 @@ public class GLClosuresApiResource { this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); final List glClosureDatas = this.glClosureReadPlatformService.retrieveAllGLClosures(officeId); - + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.apiJsonSerializerService.serialize(settings, glClosureDatas, RESPONSE_DATA_PARAMETERS); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingDropdownReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingDropdownReadPlatformServiceImpl.java index 2b73027ea..98306ebb8 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingDropdownReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingDropdownReadPlatformServiceImpl.java @@ -50,20 +50,21 @@ public class AccountingDropdownReadPlatformServiceImpl implements AccountingDrop @Override public Map> retrieveAccountMappingOptionsForLoanProducts() { - Map> accountOptions = new HashMap>(); - List assetAccountOptions = accountReadPlatformService.retrieveAllEnabledDetailGLAccounts(GLAccountType.ASSET); + final Map> accountOptions = new HashMap>(); + List assetAccountOptions = this.accountReadPlatformService.retrieveAllEnabledDetailGLAccounts(GLAccountType.ASSET); if (assetAccountOptions.isEmpty()) { assetAccountOptions = null; } accountOptions.put("assetAccountOptions", assetAccountOptions); - List incomeAccountOptions = accountReadPlatformService.retrieveAllEnabledDetailGLAccounts(GLAccountType.INCOME); + List incomeAccountOptions = this.accountReadPlatformService.retrieveAllEnabledDetailGLAccounts(GLAccountType.INCOME); if (incomeAccountOptions.isEmpty()) { incomeAccountOptions = null; } accountOptions.put("incomeAccountOptions", incomeAccountOptions); - List expenseAccountOptions = accountReadPlatformService.retrieveAllEnabledDetailGLAccounts(GLAccountType.EXPENSE); + List expenseAccountOptions = this.accountReadPlatformService + .retrieveAllEnabledDetailGLAccounts(GLAccountType.EXPENSE); if (expenseAccountOptions.isEmpty()) { expenseAccountOptions = null; } @@ -73,8 +74,8 @@ public class AccountingDropdownReadPlatformServiceImpl implements AccountingDrop @Override public Map> retrieveAccountMappingOptionsForSavingsProducts() { - Map> accountOptions = retrieveAccountMappingOptionsForLoanProducts(); - List liabilityAccountOptions = accountReadPlatformService + final Map> accountOptions = retrieveAccountMappingOptionsForLoanProducts(); + List liabilityAccountOptions = this.accountReadPlatformService .retrieveAllEnabledDetailGLAccounts(GLAccountType.LIABILITY); if (liabilityAccountOptions.isEmpty()) { liabilityAccountOptions = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingEnumerations.java index 7a7f09bba..a457ef948 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingEnumerations.java @@ -85,7 +85,7 @@ public class AccountingEnumerations { } public static EnumOptionData accountingRuleType(final AccountingRuleType type) { - EnumOptionData optionData = new EnumOptionData(type.getValue().longValue(), type.getCode(), type.toString()); + final EnumOptionData optionData = new EnumOptionData(type.getValue().longValue(), type.getCode(), type.toString()); return optionData; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingRuleType.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingRuleType.java index cf961a690..351dd39bc 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingRuleType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/common/AccountingRuleType.java @@ -19,13 +19,13 @@ public enum AccountingRuleType { private static final Map intToEnumMap = new HashMap(); static { - for (AccountingRuleType type : AccountingRuleType.values()) { + for (final AccountingRuleType type : AccountingRuleType.values()) { intToEnumMap.put(type.value, type); } } public static AccountingRuleType fromInt(final Integer ruleTypeValue) { - AccountingRuleType type = intToEnumMap.get(ruleTypeValue); + final AccountingRuleType type = intToEnumMap.get(ruleTypeValue); return type; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/command/GLAccountCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/command/GLAccountCommand.java index 1f498228a..a79e93a00 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/command/GLAccountCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/command/GLAccountCommand.java @@ -71,8 +71,9 @@ public class GLAccountCommand { baseDataValidator.reset().parameter(GLAccountJsonInputParams.MANUAL_ENTRIES_ALLOWED.getValue()).value(this.manualEntriesAllowed) .notBlank(); - - baseDataValidator.reset().parameter(GLAccountJsonInputParams.TAGID.getValue()).value(this.tagId).ignoreIfNull().longGreaterThanZero(); + + baseDataValidator.reset().parameter(GLAccountJsonInputParams.TAGID.getValue()).value(this.tagId).ignoreIfNull() + .longGreaterThanZero(); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } @@ -106,7 +107,8 @@ public class GLAccountCommand { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } - baseDataValidator.reset().parameter(GLAccountJsonInputParams.TAGID.getValue()).value(this.tagId).ignoreIfNull().longGreaterThanZero(); + baseDataValidator.reset().parameter(GLAccountJsonInputParams.TAGID.getValue()).value(this.tagId).ignoreIfNull() + .longGreaterThanZero(); } public boolean isHeaderAccount() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/domain/GLAccount.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/domain/GLAccount.java index 22b3959a2..775b7ac94 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/domain/GLAccount.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/domain/GLAccount.java @@ -83,7 +83,7 @@ public class GLAccount extends AbstractPersistable { this.tagId = tagId; } - public static GLAccount fromJson(final GLAccount parent, final JsonCommand command, CodeValue glAccountTagType) { + public static GLAccount fromJson(final GLAccount parent, final JsonCommand command, final CodeValue glAccountTagType) { final String name = command.stringValueOfParameterNamed(GLAccountJsonInputParams.NAME.getValue()); final String glCode = command.stringValueOfParameterNamed(GLAccountJsonInputParams.GL_CODE.getValue()); final boolean disabled = command.booleanPrimitiveValueOfParameterNamed(GLAccountJsonInputParams.DISABLED.getValue()); @@ -211,8 +211,8 @@ public class GLAccount extends AbstractPersistable { public void generateHierarchy() { - if (parent != null) { - this.hierarchy = this.parent.hierarchyOf(this.getId()); + if (this.parent != null) { + this.hierarchy = this.parent.hierarchyOf(getId()); } else { this.hierarchy = "."; } @@ -226,12 +226,12 @@ public class GLAccount extends AbstractPersistable { return GLAccountUsage.DETAIL.getValue().equals(this.usage); } - public void updateTagId(CodeValue tagID) { + public void updateTagId(final CodeValue tagID) { this.tagId = tagID; } - public void updateParentAccount(GLAccount parentAccount) { + public void updateParentAccount(final GLAccount parentAccount) { this.parent = parentAccount; - this.generateHierarchy(); + generateHierarchy(); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/serialization/GLAccountCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/serialization/GLAccountCommandFromApiJsonDeserializer.java index ac9301a79..cf0f19dad 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/serialization/GLAccountCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/serialization/GLAccountCommandFromApiJsonDeserializer.java @@ -58,7 +58,7 @@ public final class GLAccountCommandFromApiJsonDeserializer extends AbstractFromA final Integer usage = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(GLAccountJsonInputParams.USAGE.getValue(), element); final String description = this.fromApiJsonHelper.extractStringNamed(GLAccountJsonInputParams.DESCRIPTION.getValue(), element); final Long tagId = this.fromApiJsonHelper.extractLongNamed(GLAccountJsonInputParams.TAGID.getValue(), element); - + return new GLAccountCommand(id, name, parentId, glCode, disabled, manualEntriesAllowed, type, usage, description, tagId); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java index fddfb937c..1a92e353d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/glaccount/service/GLAccountWritePlatformServiceJpaRepositoryImpl.java @@ -75,7 +75,7 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount CodeValue glAccountTagType = null; final Long tagId = command.longValueOfParameterNamed(GLAccountJsonInputParams.TAGID.getValue()); final Long type = command.longValueOfParameterNamed(GLAccountJsonInputParams.TYPE.getValue()); - GLAccountType accountType = GLAccountType.fromInt(type.intValue()); + final GLAccountType accountType = GLAccountType.fromInt(type.intValue()); if (tagId != null) { glAccountTagType = retrieveTagId(tagId, accountType); @@ -113,7 +113,7 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount // is the new parent valid if (changesOnly.containsKey(GLAccountJsonInputParams.PARENT_ID.getValue())) { - GLAccount parentAccount = validateParentGLAccount(parentId); + final GLAccount parentAccount = validateParentGLAccount(parentId); glAccount.updateParentAccount(parentAccount); } @@ -203,7 +203,7 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount "Unknown data integrity issue with resource GL Account: " + realCause.getMessage()); } - private CodeValue retrieveTagId(Long tagId, GLAccountType accountType) { + private CodeValue retrieveTagId(final Long tagId, final GLAccountType accountType) { CodeValue glAccountTagType = null; if (accountType.isAssetType()) { glAccountTagType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/api/DateParam.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/api/DateParam.java index f0b051754..3011fc796 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/api/DateParam.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/api/DateParam.java @@ -26,9 +26,9 @@ public class DateParam { this.dateAsString = dateStr; } - public Date getDate(String parameterName,String dateFormat, String localeAsString) { - Locale locale = JsonParserHelper.localeFromString(localeAsString); - LocalDate localDate = JsonParserHelper.convertFrom(dateAsString, parameterName, dateFormat, locale); + public Date getDate(final String parameterName, final String dateFormat, final String localeAsString) { + final Locale locale = JsonParserHelper.localeFromString(localeAsString); + final LocalDate localDate = JsonParserHelper.convertFrom(this.dateAsString, parameterName, dateFormat, locale); return localDate.toDate(); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/api/JournalEntriesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/api/JournalEntriesApiResource.java index 6c2217b46..2dd5abff7 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/api/JournalEntriesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/api/JournalEntriesApiResource.java @@ -94,9 +94,9 @@ public class JournalEntriesApiResource { final SearchParameters searchParameters = SearchParameters.forJournalEntries(officeId, offset, limit, orderBy, sortOrder); - Page glJournalEntries = this.journalEntryReadPlatformService.retrieveAll(searchParameters, glAccountId, + final Page glJournalEntries = this.journalEntryReadPlatformService.retrieveAll(searchParameters, glAccountId, onlyManualEntries, fromDate, toDate, transactionId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.apiJsonSerializerService.serialize(settings, glJournalEntries, RESPONSE_DATA_PARAMETERS); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/ChargePaymentDTO.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/ChargePaymentDTO.java index 7dbde9413..0ef10af5f 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/ChargePaymentDTO.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/ChargePaymentDTO.java @@ -8,7 +8,7 @@ public class ChargePaymentDTO { private final BigDecimal amount; private final Long loanChargeId; - public ChargePaymentDTO(Long chargeId, Long loanChargeId, BigDecimal amount) { + public ChargePaymentDTO(final Long chargeId, final Long loanChargeId, final BigDecimal amount) { this.chargeId = chargeId; this.amount = amount; this.loanChargeId = loanChargeId; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/JournalEntryData.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/JournalEntryData.java index afaf36d95..f1e6ecd80 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/JournalEntryData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/JournalEntryData.java @@ -63,7 +63,8 @@ public class JournalEntryData { final Long glAccountId, final String glAccountCode, final EnumOptionData glAccountClassification, final LocalDate transactionDate, final EnumOptionData entryType, final BigDecimal amount, final String transactionId, final Boolean manualEntry, final EnumOptionData entityType, final Long entityId, final Long createdByUserId, - final LocalDate createdDate, final String createdByUserName, final String comments, final Boolean reversed, final String referenceNumber) { + final LocalDate createdDate, final String createdByUserName, final String comments, final Boolean reversed, + final String referenceNumber) { this.id = id; this.officeId = officeId; this.officeName = officeName; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/LoanDTO.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/LoanDTO.java index 9c4e7e3c9..c1c690eac 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/LoanDTO.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/LoanDTO.java @@ -82,7 +82,7 @@ public class LoanDTO { return this.currencyCode; } - public void setCurrencyCode(String currencyCode) { + public void setCurrencyCode(final String currencyCode) { this.currencyCode = currencyCode; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/SavingsDTO.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/SavingsDTO.java index fbd36dc6b..e63957aac 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/SavingsDTO.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/data/SavingsDTO.java @@ -33,7 +33,7 @@ public class SavingsDTO { return this.savingsId; } - public void setSavingsId(Long savingsId) { + public void setSavingsId(final Long savingsId) { this.savingsId = savingsId; } @@ -41,7 +41,7 @@ public class SavingsDTO { return this.savingsProductId; } - public void setSavingsProductId(Long savingsProductId) { + public void setSavingsProductId(final Long savingsProductId) { this.savingsProductId = savingsProductId; } @@ -49,7 +49,7 @@ public class SavingsDTO { return this.officeId; } - public void setOfficeId(Long officeId) { + public void setOfficeId(final Long officeId) { this.officeId = officeId; } @@ -57,7 +57,7 @@ public class SavingsDTO { return this.cashBasedAccountingEnabled; } - public void setCashBasedAccountingEnabled(boolean cashBasedAccountingEnabled) { + public void setCashBasedAccountingEnabled(final boolean cashBasedAccountingEnabled) { this.cashBasedAccountingEnabled = cashBasedAccountingEnabled; } @@ -65,7 +65,7 @@ public class SavingsDTO { return this.accrualBasedAccountingEnabled; } - public void setAccrualBasedAccountingEnabled(boolean accrualBasedAccountingEnabled) { + public void setAccrualBasedAccountingEnabled(final boolean accrualBasedAccountingEnabled) { this.accrualBasedAccountingEnabled = accrualBasedAccountingEnabled; } @@ -73,7 +73,7 @@ public class SavingsDTO { return this.newSavingsTransactions; } - public void setNewSavingsTransactions(List newSavingsTransactions) { + public void setNewSavingsTransactions(final List newSavingsTransactions) { this.newSavingsTransactions = newSavingsTransactions; } @@ -81,7 +81,7 @@ public class SavingsDTO { return this.currencyCode; } - public void setCurrencyCode(String currencyCode) { + public void setCurrencyCode(final String currencyCode) { this.currencyCode = currencyCode; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/exception/JournalEntryInvalidException.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/exception/JournalEntryInvalidException.java index 447865a44..6ff856299 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/exception/JournalEntryInvalidException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/exception/JournalEntryInvalidException.java @@ -16,8 +16,7 @@ public class JournalEntryInvalidException extends AbstractPlatformDomainRuleExce /*** enum of reasons for invalid Journal Entry **/ public static enum GL_JOURNAL_ENTRY_INVALID_REASON { - FUTURE_DATE, ACCOUNTING_CLOSED, NO_DEBITS_OR_CREDITS, DEBIT_CREDIT_SUM_MISMATCH_WITH_AMOUNT, DEBIT_CREDIT_SUM_MISMATCH, DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, GL_ACCOUNT_DISABLED, GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED, - INVALID_DEBIT_OR_CREDIT_ACCOUNTS; + FUTURE_DATE, ACCOUNTING_CLOSED, NO_DEBITS_OR_CREDITS, DEBIT_CREDIT_SUM_MISMATCH_WITH_AMOUNT, DEBIT_CREDIT_SUM_MISMATCH, DEBIT_CREDIT_ACCOUNT_OR_AMOUNT_EMPTY, GL_ACCOUNT_DISABLED, GL_ACCOUNT_MANUAL_ENTRIES_NOT_PERMITTED, INVALID_DEBIT_OR_CREDIT_ACCOUNTS; public String errorMessage() { if (name().toString().equalsIgnoreCase("FUTURE_DATE")) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorForLoanFactory.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorForLoanFactory.java index 98457f106..0e6c63c14 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorForLoanFactory.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorForLoanFactory.java @@ -13,10 +13,10 @@ import org.springframework.stereotype.Component; @Component public class AccountingProcessorForLoanFactory { - private ApplicationContext applicationContext; + private final ApplicationContext applicationContext; @Autowired - public AccountingProcessorForLoanFactory(ApplicationContext applicationContext) { + public AccountingProcessorForLoanFactory(final ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @@ -25,12 +25,12 @@ public class AccountingProcessorForLoanFactory { AccountingProcessorForLoan accountingProcessorForLoan = null; if (loanDTO.isCashBasedAccountingEnabled()) { - accountingProcessorForLoan = applicationContext - .getBean("cashBasedAccountingProcessorForLoan", AccountingProcessorForLoan.class); + accountingProcessorForLoan = this.applicationContext.getBean("cashBasedAccountingProcessorForLoan", + AccountingProcessorForLoan.class); } else if (loanDTO.isAccrualBasedAccountingEnabled()) { - accountingProcessorForLoan = applicationContext.getBean("accrualBasedAccountingProcessorForLoan", + accountingProcessorForLoan = this.applicationContext.getBean("accrualBasedAccountingProcessorForLoan", AccountingProcessorForLoan.class); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorForSavingsFactory.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorForSavingsFactory.java index 19f157344..c6ea92114 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorForSavingsFactory.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorForSavingsFactory.java @@ -13,10 +13,10 @@ import org.springframework.stereotype.Component; @Component public class AccountingProcessorForSavingsFactory { - private ApplicationContext applicationContext; + private final ApplicationContext applicationContext; @Autowired - public AccountingProcessorForSavingsFactory(ApplicationContext applicationContext) { + public AccountingProcessorForSavingsFactory(final ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @@ -30,7 +30,7 @@ public class AccountingProcessorForSavingsFactory { AccountingProcessorForSavings accountingProcessorForSavings = null; if (savingsDTO.isCashBasedAccountingEnabled()) { - accountingProcessorForSavings = applicationContext.getBean("cashBasedAccountingProcessorForSavings", + accountingProcessorForSavings = this.applicationContext.getBean("cashBasedAccountingProcessorForSavings", AccountingProcessorForSavings.class); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorHelper.java index 5034ee466..6dc54bf5e 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccountingProcessorHelper.java @@ -84,8 +84,8 @@ public class AccountingProcessorHelper { final boolean reversed = (Boolean) map.get("reversed"); final Long paymentTypeId = (Long) map.get("paymentTypeId"); - List feePayments = new ArrayList(); - List penaltyPayments = new ArrayList(); + final List feePayments = new ArrayList(); + final List penaltyPayments = new ArrayList(); // extract charge payment details (if exists) if (map.containsKey("loanChargesPaid")) { @SuppressWarnings("unchecked") @@ -95,7 +95,7 @@ public class AccountingProcessorHelper { final Long loanChargeId = (Long) loanChargePaid.get("chargeId"); final boolean isPenalty = (Boolean) loanChargePaid.get("isPenalty"); final BigDecimal chargeAmountPaid = (BigDecimal) loanChargePaid.get("amount"); - ChargePaymentDTO chargePaymentDTO = new ChargePaymentDTO(chargeId, loanChargeId, chargeAmountPaid); + final ChargePaymentDTO chargePaymentDTO = new ChargePaymentDTO(chargeId, loanChargeId, chargeAmountPaid); if (isPenalty) { penaltyPayments.add(chargePaymentDTO); } else { @@ -254,7 +254,7 @@ public class AccountingProcessorHelper { public void createCreditJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final CASH_ACCOUNTS_FOR_LOAN accountMappingType, final Long loanProductId, final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { - int accountMappingTypeId = accountMappingType.getValue(); + final int accountMappingTypeId = accountMappingType.getValue(); createCreditJournalEntryOrReversalForLoan(office, currencyCode, accountMappingTypeId, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, amount, isReversal); } @@ -262,7 +262,7 @@ public class AccountingProcessorHelper { public void createCreditJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final ACCRUAL_ACCOUNTS_FOR_LOAN accountMappingType, final Long loanProductId, final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { - int accountMappingTypeId = accountMappingType.getValue(); + final int accountMappingTypeId = accountMappingType.getValue(); createCreditJournalEntryOrReversalForLoan(office, currencyCode, accountMappingTypeId, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, amount, isReversal); } @@ -270,7 +270,7 @@ public class AccountingProcessorHelper { public void createDebitJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final CASH_ACCOUNTS_FOR_LOAN accountMappingType, final Long loanProductId, final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { - int accountMappingTypeId = accountMappingType.getValue(); + final int accountMappingTypeId = accountMappingType.getValue(); createDebitJournalEntryOrReversalForLoan(office, currencyCode, accountMappingTypeId, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, amount, isReversal); } @@ -278,7 +278,7 @@ public class AccountingProcessorHelper { public void createDebitJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final ACCRUAL_ACCOUNTS_FOR_LOAN accountMappingType, final Long loanProductId, final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { - int accountMappingTypeId = accountMappingType.getValue(); + final int accountMappingTypeId = accountMappingType.getValue(); createDebitJournalEntryOrReversalForLoan(office, currencyCode, accountMappingTypeId, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, amount, isReversal); } @@ -298,19 +298,19 @@ public class AccountingProcessorHelper { } } - public GLClosure getLatestClosureByBranch(long officeId) { + public GLClosure getLatestClosureByBranch(final long officeId) { return this.closureRepository.getLatestGLClosureByBranch(officeId); } - public Office getOfficeById(long officeId) { + public Office getOfficeById(final long officeId) { return this.officeRepository.findOne(officeId); } private void createJournalEntriesForLoan(final Office office, final String currencyCode, final int accountTypeToDebitId, final int accountTypeToCreditId, final Long loanProductId, final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount) { - GLAccount debitAccount = getLinkedGLAccountForLoanProduct(loanProductId, accountTypeToDebitId, paymentTypeId); - GLAccount creditAccount = getLinkedGLAccountForLoanProduct(loanProductId, accountTypeToCreditId, paymentTypeId); + final GLAccount debitAccount = getLinkedGLAccountForLoanProduct(loanProductId, accountTypeToDebitId, paymentTypeId); + final GLAccount creditAccount = getLinkedGLAccountForLoanProduct(loanProductId, accountTypeToCreditId, paymentTypeId); createDebitJournalEntryForLoan(office, currencyCode, debitAccount, loanId, transactionId, transactionDate, amount); createCreditJournalEntryForLoan(office, currencyCode, creditAccount, loanId, transactionId, transactionDate, amount); } @@ -318,8 +318,8 @@ public class AccountingProcessorHelper { private void createJournalEntriesForSavings(final Office office, final String currencyCode, final int accountTypeToDebitId, final int accountTypeToCreditId, final Long savingsProductId, final Long paymentTypeId, final Long savingsId, final String transactionId, final Date transactionDate, final BigDecimal amount) { - GLAccount debitAccount = getLinkedGLAccountForSavingsProduct(savingsProductId, accountTypeToDebitId, paymentTypeId); - GLAccount creditAccount = getLinkedGLAccountForSavingsProduct(savingsProductId, accountTypeToCreditId, paymentTypeId); + final GLAccount debitAccount = getLinkedGLAccountForSavingsProduct(savingsProductId, accountTypeToDebitId, paymentTypeId); + final GLAccount creditAccount = getLinkedGLAccountForSavingsProduct(savingsProductId, accountTypeToCreditId, paymentTypeId); createDebitJournalEntryForSavings(office, currencyCode, debitAccount, savingsId, transactionId, transactionDate, amount); createCreditJournalEntryForSavings(office, currencyCode, creditAccount, savingsId, transactionId, transactionDate, amount); } @@ -327,7 +327,7 @@ public class AccountingProcessorHelper { private void createDebitJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final int accountMappingTypeId, final Long loanProductId, final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { - GLAccount account = getLinkedGLAccountForLoanProduct(loanProductId, accountMappingTypeId, paymentTypeId); + final GLAccount account = getLinkedGLAccountForLoanProduct(loanProductId, accountMappingTypeId, paymentTypeId); if (isReversal) { createCreditJournalEntryForLoan(office, currencyCode, account, loanId, transactionId, transactionDate, amount); } else { @@ -343,25 +343,25 @@ public class AccountingProcessorHelper { * Map to track each account and the net credit to be made for a * particular account ***/ - Map creditDetailsMap = new LinkedHashMap(); - for (ChargePaymentDTO chargePaymentDTO : chargePaymentDTOs) { - Long chargeId = chargePaymentDTO.getChargeId(); - GLAccount chargeSpecificAccount = getLinkedGLAccountForLoanCharges(loanProductId, accountMappingTypeId, chargeId); + final Map creditDetailsMap = new LinkedHashMap(); + for (final ChargePaymentDTO chargePaymentDTO : chargePaymentDTOs) { + final Long chargeId = chargePaymentDTO.getChargeId(); + final GLAccount chargeSpecificAccount = getLinkedGLAccountForLoanCharges(loanProductId, accountMappingTypeId, chargeId); BigDecimal chargeSpecificAmount = chargePaymentDTO.getAmount(); // adjust net credit amount if the account is already present in the // map if (creditDetailsMap.containsKey(chargeSpecificAccount)) { - BigDecimal existingAmount = creditDetailsMap.get(chargeSpecificAccount); + final BigDecimal existingAmount = creditDetailsMap.get(chargeSpecificAccount); chargeSpecificAmount = chargeSpecificAmount.add(existingAmount); } creditDetailsMap.put(chargeSpecificAccount, chargeSpecificAmount); } BigDecimal totalCreditedAmount = BigDecimal.ZERO; - for (Map.Entry entry : creditDetailsMap.entrySet()) { - GLAccount account = entry.getKey(); - BigDecimal amount = entry.getValue(); + for (final Map.Entry entry : creditDetailsMap.entrySet()) { + final GLAccount account = entry.getKey(); + final BigDecimal amount = entry.getValue(); totalCreditedAmount = totalCreditedAmount.add(amount); if (isReversal) { createDebitJournalEntryForLoan(office, currencyCode, account, loanId, transactionId, transactionDate, amount); @@ -381,7 +381,7 @@ public class AccountingProcessorHelper { private void createCreditJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final int accountMappingTypeId, final Long loanProductId, final Long paymentTypeId, final Long loanId, final String transactionId, final Date transactionDate, final BigDecimal amount, final Boolean isReversal) { - GLAccount account = getLinkedGLAccountForLoanProduct(loanProductId, accountMappingTypeId, paymentTypeId); + final GLAccount account = getLinkedGLAccountForLoanProduct(loanProductId, accountMappingTypeId, paymentTypeId); if (isReversal) { createDebitJournalEntryForLoan(office, currencyCode, account, loanId, transactionId, transactionDate, amount); } else { @@ -430,7 +430,7 @@ public class AccountingProcessorHelper { * both cash and accrual accounts ***/ if (accountMappingTypeId == CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE.getValue()) { - ProductToGLAccountMapping paymentChannelSpecificAccountMapping = this.accountMappingRepository + final ProductToGLAccountMapping paymentChannelSpecificAccountMapping = this.accountMappingRepository .findByProductIdAndProductTypeAndFinancialAccountTypeAndPaymentTypeId(loanProductId, PortfolioProductType.LOAN.getValue(), accountMappingTypeId, paymentTypeId); if (paymentChannelSpecificAccountMapping != null) { @@ -454,7 +454,7 @@ public class AccountingProcessorHelper { // Vishwas TODO: remove this condition as it should always be true if (accountMappingTypeId == CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES.getValue() || accountMappingTypeId == CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_PENALTIES.getValue()) { - ProductToGLAccountMapping chargeSpecificIncomeAccountMapping = this.accountMappingRepository + final ProductToGLAccountMapping chargeSpecificIncomeAccountMapping = this.accountMappingRepository .findByProductIdAndProductTypeAndFinancialAccountTypeAndChargeId(loanProductId, PortfolioProductType.LOAN.getValue(), accountMappingTypeId, chargeId); if (chargeSpecificIncomeAccountMapping != null) { @@ -474,7 +474,7 @@ public class AccountingProcessorHelper { * both cash and accrual accounts ***/ if (accountMappingTypeId == CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE.getValue()) { - ProductToGLAccountMapping paymentChannelSpecificAccountMapping = this.accountMappingRepository + final ProductToGLAccountMapping paymentChannelSpecificAccountMapping = this.accountMappingRepository .findByProductIdAndProductTypeAndFinancialAccountTypeAndPaymentTypeId(savingsProductId, PortfolioProductType.SAVING.getValue(), accountMappingTypeId, paymentTypeId); if (paymentChannelSpecificAccountMapping != null) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccrualBasedAccountingProcessorForLoan.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccrualBasedAccountingProcessorForLoan.java index adefe9ed6..f8d84c9c0 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccrualBasedAccountingProcessorForLoan.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/AccrualBasedAccountingProcessorForLoan.java @@ -32,7 +32,7 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess final Office office = this.helper.getOfficeById(loanDTO.getOfficeId()); for (final LoanTransactionDTO loanTransactionDTO : loanDTO.getNewLoanTransactions()) { final Date transactionDate = loanTransactionDTO.getTransactionDate(); - helper.checkForBranchClosures(latestGLClosure, transactionDate); + this.helper.checkForBranchClosures(latestGLClosure, transactionDate); /** Handle Disbursements **/ if (loanTransactionDTO.getTransactionType().isDisbursement()) { @@ -54,7 +54,8 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess * Repayments and Repayments at disbursement ***/ else if (loanTransactionDTO.getTransactionType().isRepayment() - || loanTransactionDTO.getTransactionType().isRepaymentAtDisbursement() || loanTransactionDTO.getTransactionType().isChargePayment()) { + || loanTransactionDTO.getTransactionType().isRepaymentAtDisbursement() + || loanTransactionDTO.getTransactionType().isChargePayment()) { createJournalEntriesForRepaymentsAndWriteOffs(loanDTO, loanTransactionDTO, office, false, loanTransactionDTO .getTransactionType().isRepaymentAtDisbursement() || loanTransactionDTO.getTransactionType().isChargePayment()); } @@ -91,7 +92,7 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess // create journal entries for the disbursement (or disbursement // reversal) - helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, + this.helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, ACCRUAL_ACCOUNTS_FOR_LOAN.FUND_SOURCE, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, disbursalAmount, isReversed); @@ -122,9 +123,9 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess // create journal entries for recognising interest (or reversal) if (amount != null && !(amount.compareTo(BigDecimal.ZERO) == 0)) { - helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.INTEREST_RECEIVABLE, - ACCRUAL_ACCOUNTS_FOR_LOAN.INTEREST_ON_LOANS, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, - amount, isReversed); + this.helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, + ACCRUAL_ACCOUNTS_FOR_LOAN.INTEREST_RECEIVABLE, ACCRUAL_ACCOUNTS_FOR_LOAN.INTEREST_ON_LOANS, loanProductId, + paymentTypeId, loanId, transactionId, transactionDate, amount, isReversed); } } @@ -191,14 +192,14 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess // handle principal payment or writeOff (and reversals) if (principalAmount != null && !(principalAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(principalAmount); - helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, principalAmount, isReversal); + this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, + loanProductId, paymentTypeId, loanId, transactionId, transactionDate, principalAmount, isReversal); } // handle interest payment of writeOff (and reversals) if (interestAmount != null && !(interestAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(interestAmount); - helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.INTEREST_RECEIVABLE, + this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.INTEREST_RECEIVABLE, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, interestAmount, isReversal); } @@ -212,14 +213,14 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess feeAccountToCredit = ACCRUAL_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES; } - helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, feeAccountToCredit, loanProductId, paymentTypeId, + this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, feeAccountToCredit, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, feesAmount, isReversal); } // handle penalties payment of writeOff (and reversals) if (penaltiesAmount != null && !(penaltiesAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(penaltiesAmount); - helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.PENALTIES_RECEIVABLE, + this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.PENALTIES_RECEIVABLE, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, penaltiesAmount, isReversal); } @@ -228,11 +229,11 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess * reversals) ***/ if (writeOff) { - helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.LOSSES_WRITTEN_OFF, + this.helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.LOSSES_WRITTEN_OFF, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, totalDebitAmount, isReversal); } else { - helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.FUND_SOURCE, loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, totalDebitAmount, isReversal); + this.helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.FUND_SOURCE, + loanProductId, paymentTypeId, loanId, transactionId, transactionDate, totalDebitAmount, isReversal); } } @@ -269,13 +270,13 @@ public class AccrualBasedAccountingProcessorForLoan implements AccountingProcess // create journal entries for the fees application (or reversal) if (feesAmount != null && !(feesAmount.compareTo(BigDecimal.ZERO) == 0)) { - helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.FEES_RECEIVABLE, - ACCRUAL_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, - feesAmount, isReversed); + this.helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, + ACCRUAL_ACCOUNTS_FOR_LOAN.FEES_RECEIVABLE, ACCRUAL_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES, loanProductId, paymentTypeId, + loanId, transactionId, transactionDate, feesAmount, isReversed); } // create journal entries for the penalties application (or reversal) else if (penaltiesAmount != null && !(penaltiesAmount.compareTo(BigDecimal.ZERO) == 0)) { - helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, + this.helper.createAccrualBasedJournalEntriesAndReversalsForLoan(office, currencyCode, ACCRUAL_ACCOUNTS_FOR_LOAN.PENALTIES_RECEIVABLE, ACCRUAL_ACCOUNTS_FOR_LOAN.INCOME_FROM_PENALTIES, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, penaltiesAmount, isReversed); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/CashBasedAccountingProcessorForLoan.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/CashBasedAccountingProcessorForLoan.java index c1f0dc15f..66da5ee67 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/CashBasedAccountingProcessorForLoan.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/CashBasedAccountingProcessorForLoan.java @@ -27,7 +27,7 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF } @Override - public void createJournalEntriesForLoan(LoanDTO loanDTO) { + public void createJournalEntriesForLoan(final LoanDTO loanDTO) { final GLClosure latestGLClosure = this.helper.getLatestClosureByBranch(loanDTO.getOfficeId()); // final Office office = // this.helper.getOfficeById(loanDTO.getOfficeId()); @@ -40,7 +40,7 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF final Long paymentTypeId = loanTransactionDTO.getPaymentTypeId(); final Long loanId = loanDTO.getLoanId(); - helper.checkForBranchClosures(latestGLClosure, transactionDate); + this.helper.checkForBranchClosures(latestGLClosure, transactionDate); /** Handle Disbursements and reversals of disbursements **/ if (loanTransactionDTO.getTransactionType().isDisbursement()) { @@ -51,7 +51,7 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF * Repayments and Repayments at disbursement ***/ else if (loanTransactionDTO.getTransactionType().isRepayment() - || loanTransactionDTO.getTransactionType().isRepaymentAtDisbursement() + || loanTransactionDTO.getTransactionType().isRepaymentAtDisbursement() || loanTransactionDTO.getTransactionType().isChargePayment()) { createJournalEntriesForRepayments(loanDTO, loanTransactionDTO, office); } @@ -62,9 +62,9 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF **/ else if (loanTransactionDTO.getTransactionType().isWriteOff() && !loanTransactionDTO.isReversed()) { final BigDecimal principalAmount = loanTransactionDTO.getPrincipal(); - helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.LOSSES_WRITTEN_OFF, - CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, - principalAmount, false); + this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, + CASH_ACCOUNTS_FOR_LOAN.LOSSES_WRITTEN_OFF, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, loanProductId, paymentTypeId, + loanId, transactionId, transactionDate, principalAmount, false); } else if (loanTransactionDTO.getTransactionType().isInitiateTransfer() || loanTransactionDTO.getTransactionType().isApproveTransfer() || loanTransactionDTO.getTransactionType().isWithdrawTransfer()) { @@ -98,7 +98,7 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF final boolean isReversal = loanTransactionDTO.isReversed(); final Long paymentTypeId = loanTransactionDTO.getPaymentTypeId(); - helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, + this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, disbursalAmount, isReversal); } @@ -132,32 +132,32 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF if (principalAmount != null && !(principalAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(principalAmount); - helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, principalAmount, isReversal); + this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, + loanProductId, paymentTypeId, loanId, transactionId, transactionDate, principalAmount, isReversal); } if (interestAmount != null && !(interestAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(interestAmount); - helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.INTEREST_ON_LOANS, loanProductId, - paymentTypeId, loanId, transactionId, transactionDate, interestAmount, isReversal); + this.helper.createCreditJournalEntryOrReversalForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.INTEREST_ON_LOANS, + loanProductId, paymentTypeId, loanId, transactionId, transactionDate, interestAmount, isReversal); } if (feesAmount != null && !(feesAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(feesAmount); - helper.createCreditJournalEntryOrReversalForLoanCharges(office, currencyCode, + this.helper.createCreditJournalEntryOrReversalForLoanCharges(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES.getValue(), loanProductId, loanId, transactionId, transactionDate, feesAmount, isReversal, loanTransactionDTO.getFeePayments()); } if (penaltiesAmount != null && !(penaltiesAmount.compareTo(BigDecimal.ZERO) == 0)) { totalDebitAmount = totalDebitAmount.add(penaltiesAmount); - helper.createCreditJournalEntryOrReversalForLoanCharges(office, currencyCode, + this.helper.createCreditJournalEntryOrReversalForLoanCharges(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_PENALTIES.getValue(), loanProductId, loanId, transactionId, transactionDate, penaltiesAmount, isReversal, loanTransactionDTO.getPenaltyPayments()); } /*** create a single debit entry (or reversal) for the entire amount **/ - helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE, loanProductId, + this.helper.createDebitJournalEntryOrReversalForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE, loanProductId, paymentTypeId, loanId, transactionId, transactionDate, totalDebitAmount, isReversal); } @@ -188,12 +188,12 @@ public class CashBasedAccountingProcessorForLoan implements AccountingProcessorF // final Long paymentTypeId = loanTransactionDTO.getPaymentTypeId(); if (loanTransactionDTO.getTransactionType().isInitiateTransfer()) { - helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.TRANSFERS_SUSPENSE, + this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.TRANSFERS_SUSPENSE, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, loanProductId, null, loanId, transactionId, transactionDate, principalAmount, isReversal); } else if (loanTransactionDTO.getTransactionType().isApproveTransfer() || loanTransactionDTO.getTransactionType().isWithdrawTransfer()) { - helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, + this.helper.createCashBasedJournalEntriesAndReversalsForLoan(office, currencyCode, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO, CASH_ACCOUNTS_FOR_LOAN.TRANSFERS_SUSPENSE, loanProductId, null, loanId, transactionId, transactionDate, principalAmount, isReversal); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/CashBasedAccountingProcessorForSavings.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/CashBasedAccountingProcessorForSavings.java index 0b342b5b0..718e85ab3 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/CashBasedAccountingProcessorForSavings.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/CashBasedAccountingProcessorForSavings.java @@ -27,7 +27,7 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess } @Override - public void createJournalEntriesForSavings(SavingsDTO savingsDTO) { + public void createJournalEntriesForSavings(final SavingsDTO savingsDTO) { final GLClosure latestGLClosure = this.helper.getLatestClosureByBranch(savingsDTO.getOfficeId()); final Long savingsProductId = savingsDTO.getSavingsProductId(); final Long savingsId = savingsDTO.getSavingsId(); @@ -40,20 +40,20 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess final boolean isReversal = savingsTransactionDTO.isReversed(); final BigDecimal amount = savingsTransactionDTO.getAmount(); - helper.checkForBranchClosures(latestGLClosure, transactionDate); + this.helper.checkForBranchClosures(latestGLClosure, transactionDate); /** Handle Deposits and reversals of deposits **/ if (savingsTransactionDTO.getTransactionType().isDeposit()) { - helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, + this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } /** Handle withdrawals and reversals of withdrawals **/ else if (savingsTransactionDTO.getTransactionType().isWithdrawal()) { - helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, - CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, savingsProductId, paymentTypeId, savingsId, transactionId, - transactionDate, amount, isReversal); + this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, + CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE, savingsProductId, + paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } /** @@ -61,29 +61,29 @@ public class CashBasedAccountingProcessorForSavings implements AccountingProcess * Applications **/ else if (savingsTransactionDTO.getTransactionType().isInterestPosting()) { - helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, + this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, CASH_ACCOUNTS_FOR_SAVINGS.INTEREST_ON_SAVINGS, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } /** Handle Fees Deductions and reversals of Fees Deductions **/ else if (savingsTransactionDTO.getTransactionType().isFeeDeduction()) { - helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, - CASH_ACCOUNTS_FOR_SAVINGS.INCOME_FROM_FEES, savingsProductId, paymentTypeId, savingsId, transactionId, - transactionDate, amount, isReversal); + this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, + CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, CASH_ACCOUNTS_FOR_SAVINGS.INCOME_FROM_FEES, savingsProductId, + paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } /** Handle Transfers proposal **/ else if (savingsTransactionDTO.getTransactionType().isInitiateTransfer()) { - helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, - CASH_ACCOUNTS_FOR_SAVINGS.TRANSFERS_SUSPENSE, savingsProductId, paymentTypeId, savingsId, transactionId, - transactionDate, amount, isReversal); + this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, + CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, CASH_ACCOUNTS_FOR_SAVINGS.TRANSFERS_SUSPENSE, savingsProductId, + paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } /** Handle Transfer Withdrawal or Acceptance **/ else if (savingsTransactionDTO.getTransactionType().isWithdrawTransfer() || savingsTransactionDTO.getTransactionType().isApproveTransfer()) { - helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, + this.helper.createCashBasedJournalEntriesAndReversalsForSavings(office, currencyCode, CASH_ACCOUNTS_FOR_SAVINGS.TRANSFERS_SUSPENSE, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL, savingsProductId, paymentTypeId, savingsId, transactionId, transactionDate, amount, isReversal); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/JournalEntryReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/JournalEntryReadPlatformServiceImpl.java index e3fbbdc7c..17f65e6c9 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/JournalEntryReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/JournalEntryReadPlatformServiceImpl.java @@ -100,9 +100,9 @@ public class JournalEntryReadPlatformServiceImpl implements JournalEntryReadPlat public Page retrieveAll(final SearchParameters searchParameters, final Long glAccountId, final Boolean onlyManualEntries, final Date fromDate, final Date toDate, final String transactionId) { - StringBuilder sqlBuilder = new StringBuilder(200); + final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); - sqlBuilder.append(journalEntryMapper.schema()); + sqlBuilder.append(this.journalEntryMapper.schema()); final Object[] objectArray = new Object[5]; int arrayPos = 0; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/JournalEntryWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/JournalEntryWritePlatformServiceJpaRepositoryImpl.java index 0aab3fd7d..506f42a08 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/JournalEntryWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/journalentry/service/JournalEntryWritePlatformServiceJpaRepositoryImpl.java @@ -172,14 +172,15 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa } } - private void validateDebitOrCreditArrayForExistingGLAccount(GLAccount glaccount, SingleDebitOrCreditEntryCommand[] creditOrDebits) { + private void validateDebitOrCreditArrayForExistingGLAccount(final GLAccount glaccount, + final SingleDebitOrCreditEntryCommand[] creditOrDebits) { /** * If a glaccount is assigned for a rule the credits or debits array * should have only one entry and it must be same as existing account */ if (creditOrDebits.length != 1) { throw new JournalEntryInvalidException( GL_JOURNAL_ENTRY_INVALID_REASON.INVALID_DEBIT_OR_CREDIT_ACCOUNTS, null, null, null); } - for (SingleDebitOrCreditEntryCommand creditOrDebit : creditOrDebits) { + for (final SingleDebitOrCreditEntryCommand creditOrDebit : creditOrDebits) { if (!glaccount.getId().equals(creditOrDebit.getGlAccountId())) { throw new JournalEntryInvalidException( GL_JOURNAL_ENTRY_INVALID_REASON.INVALID_DEBIT_OR_CREDIT_ACCOUNTS, null, null, null); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/data/ChargeToGLAccountMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/data/ChargeToGLAccountMapper.java index 8558ab1de..70d87ba6f 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/data/ChargeToGLAccountMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/data/ChargeToGLAccountMapper.java @@ -12,7 +12,7 @@ public class ChargeToGLAccountMapper { @SuppressWarnings("unused") private final long incomeAccountId; - public ChargeToGLAccountMapper(long chargeId, long incomeAccountId) { + public ChargeToGLAccountMapper(final long chargeId, final long incomeAccountId) { this.chargeId = chargeId; this.incomeAccountId = incomeAccountId; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/data/PaymentTypeToGLAccountMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/data/PaymentTypeToGLAccountMapper.java index 03ab03fe4..37bb31831 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/data/PaymentTypeToGLAccountMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/data/PaymentTypeToGLAccountMapper.java @@ -12,7 +12,7 @@ public class PaymentTypeToGLAccountMapper { @SuppressWarnings("unused") private final long fundSourceAccountId; - public PaymentTypeToGLAccountMapper(long paymentTypeId, long fundSourceAccountId) { + public PaymentTypeToGLAccountMapper(final long paymentTypeId, final long fundSourceAccountId) { this.paymentTypeId = paymentTypeId; this.fundSourceAccountId = fundSourceAccountId; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/domain/ProductToGLAccountMapping.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/domain/ProductToGLAccountMapping.java index 1341dcc7a..92c2ad962 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/domain/ProductToGLAccountMapping.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/domain/ProductToGLAccountMapping.java @@ -113,7 +113,7 @@ public class ProductToGLAccountMapping extends AbstractPersistable { return this.paymentType; } - public void setPaymentType(CodeValue paymentType) { + public void setPaymentType(final CodeValue paymentType) { this.paymentType = paymentType; } @@ -121,7 +121,7 @@ public class ProductToGLAccountMapping extends AbstractPersistable { return this.charge; } - public void setCharge(Charge charge) { + public void setCharge(final Charge charge) { this.charge = charge; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/serialization/ProductToGLAccountMappingFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/serialization/ProductToGLAccountMappingFromApiJsonDeserializer.java index 56daa93a0..5f08d7c58 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/serialization/ProductToGLAccountMappingFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/serialization/ProductToGLAccountMappingFromApiJsonDeserializer.java @@ -151,28 +151,28 @@ public final class ProductToGLAccountMappingFromApiJsonDeserializer { if (isCashBasedAccounting(accountingRuleType)) { - final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( + final Long savingsControlAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()) .value(savingsControlAccountId).notNull().integerGreaterThanZero(); - final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( + final Long savingsReferenceAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).notNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero(); - final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( + final Long interestOnSavingsAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).notNull().integerGreaterThanZero(); - final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), - element); + final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed( + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .notNull().integerGreaterThanZero(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingHelper.java index 46b266811..c8d4ed92a 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingHelper.java @@ -97,8 +97,8 @@ public class ProductToGLAccountMappingHelper { * @param changes */ public void savePaymentChannelToFundSourceMappings(final JsonCommand command, final JsonElement element, final Long productId, - Map changes, final PortfolioProductType portfolioProductType) { - JsonArray paymentChannelMappingArray = fromApiJsonHelper.extractJsonArrayNamed( + final Map changes, final PortfolioProductType portfolioProductType) { + final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); if (paymentChannelMappingArray != null) { if (changes != null) { @@ -124,7 +124,7 @@ public class ProductToGLAccountMappingHelper { * @param changes */ public void saveChargesToIncomeAccountMappings(final JsonCommand command, final JsonElement element, final Long productId, - Map changes, final PortfolioProductType portfolioProductType, final boolean isPenalty) { + final Map changes, final PortfolioProductType portfolioProductType, final boolean isPenalty) { String arrayName; if (isPenalty) { arrayName = LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(); @@ -132,7 +132,7 @@ public class ProductToGLAccountMappingHelper { arrayName = LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(); } - JsonArray chargeToIncomeAccountMappingArray = fromApiJsonHelper.extractJsonArrayNamed(arrayName, element); + final JsonArray chargeToIncomeAccountMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed(arrayName, element); if (chargeToIncomeAccountMappingArray != null) { if (changes != null) { changes.put(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(), @@ -154,33 +154,33 @@ public class ProductToGLAccountMappingHelper { * @param changes */ public void updateChargeToIncomeAccountMappings(final JsonCommand command, final JsonElement element, final Long productId, - Map changes, final PortfolioProductType portfolioProductType, boolean isPenalty) { + final Map changes, final PortfolioProductType portfolioProductType, final boolean isPenalty) { // find all existing payment Channel to Fund source Mappings List existingChargeToIncomeAccountMappings; String arrayFragmentName; if (isPenalty) { - existingChargeToIncomeAccountMappings = accountMappingRepository.findAllPenaltyToIncomeAccountMappings(productId, + existingChargeToIncomeAccountMappings = this.accountMappingRepository.findAllPenaltyToIncomeAccountMappings(productId, portfolioProductType.getValue()); arrayFragmentName = LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(); } else { - existingChargeToIncomeAccountMappings = accountMappingRepository.findAllFeeToIncomeAccountMappings(productId, + existingChargeToIncomeAccountMappings = this.accountMappingRepository.findAllFeeToIncomeAccountMappings(productId, portfolioProductType.getValue()); arrayFragmentName = LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(); } - JsonArray chargeToIncomeAccountMappingArray = fromApiJsonHelper.extractJsonArrayNamed(arrayFragmentName, element); + final JsonArray chargeToIncomeAccountMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed(arrayFragmentName, element); /** * Variable stores a map representation of charges (key) and their * associated income Id's (value) extracted from the passed in * Jsoncommand **/ - Map inputChargeToIncomeAccountMap = new HashMap(); + final Map inputChargeToIncomeAccountMap = new HashMap(); /*** * Variable stores all charges which have already been mapped to Income * Accounts in the system **/ - Set existingCharges = new HashSet(); + final Set existingCharges = new HashSet(); if (chargeToIncomeAccountMappingArray != null) { if (changes != null) { changes.put(arrayFragmentName, command.jsonFragment(arrayFragmentName)); @@ -195,7 +195,7 @@ public class ProductToGLAccountMappingHelper { // If input map is empty, delete all existing mappings if (inputChargeToIncomeAccountMap.size() == 0) { - accountMappingRepository.deleteInBatch(existingChargeToIncomeAccountMappings); + this.accountMappingRepository.deleteInBatch(existingChargeToIncomeAccountMappings); }/** * Else,
* update existing mappings OR
@@ -206,30 +206,30 @@ public class ProductToGLAccountMappingHelper { * **/ else { - for (ProductToGLAccountMapping chargeToIncomeAccountMapping : existingChargeToIncomeAccountMappings) { - Long currentCharge = chargeToIncomeAccountMapping.getCharge().getId(); + for (final ProductToGLAccountMapping chargeToIncomeAccountMapping : existingChargeToIncomeAccountMappings) { + final Long currentCharge = chargeToIncomeAccountMapping.getCharge().getId(); existingCharges.add(currentCharge); // update existing mappings (if required) if (inputChargeToIncomeAccountMap.containsKey(currentCharge)) { - Long newGLAccountId = inputChargeToIncomeAccountMap.get(currentCharge); + final Long newGLAccountId = inputChargeToIncomeAccountMap.get(currentCharge); if (newGLAccountId != chargeToIncomeAccountMapping.getGlAccount().getId()) { final GLAccount glAccount = getAccountByIdAndType(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue(), GLAccountType.INCOME, newGLAccountId); chargeToIncomeAccountMapping.setGlAccount(glAccount); - accountMappingRepository.save(chargeToIncomeAccountMapping); + this.accountMappingRepository.save(chargeToIncomeAccountMapping); } }// deleted payment type else { - accountMappingRepository.delete(chargeToIncomeAccountMapping); + this.accountMappingRepository.delete(chargeToIncomeAccountMapping); } } // create new mappings - Set incomingCharges = inputChargeToIncomeAccountMap.keySet(); + final Set incomingCharges = inputChargeToIncomeAccountMap.keySet(); incomingCharges.removeAll(existingCharges); // incomingPaymentTypes now only contains the newly added // payment Type mappings - for (Long newCharge : incomingCharges) { - Long newGLAccountId = inputChargeToIncomeAccountMap.get(newCharge); + for (final Long newCharge : incomingCharges) { + final Long newGLAccountId = inputChargeToIncomeAccountMap.get(newCharge); saveChargeToFundSourceMapping(productId, newCharge, newGLAccountId, portfolioProductType, isPenalty); } } @@ -243,22 +243,22 @@ public class ProductToGLAccountMappingHelper { * @param changes */ public void updatePaymentChannelToFundSourceMappings(final JsonCommand command, final JsonElement element, final Long productId, - Map changes, final PortfolioProductType portfolioProductType) { + final Map changes, final PortfolioProductType portfolioProductType) { // find all existing payment Channel to Fund source Mappings - List existingPaymentChannelToFundSourceMappings = accountMappingRepository + final List existingPaymentChannelToFundSourceMappings = this.accountMappingRepository .findAllPaymentTypeToFundSourceMappings(productId, portfolioProductType.getValue()); - JsonArray paymentChannelMappingArray = fromApiJsonHelper.extractJsonArrayNamed( + final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); /** * Variable stores a map representation of Payment channels (key) and * their fund sources (value) extracted from the passed in Jsoncommand **/ - Map inputPaymentChannelFundSourceMap = new HashMap(); + final Map inputPaymentChannelFundSourceMap = new HashMap(); /*** * Variable stores all payment types which have already been mapped to * Fund Sources in the system **/ - Set existingPaymentTypes = new HashSet(); + final Set existingPaymentTypes = new HashSet(); if (paymentChannelMappingArray != null) { if (changes != null) { changes.put(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), @@ -274,7 +274,7 @@ public class ProductToGLAccountMappingHelper { // If input map is empty, delete all existing mappings if (inputPaymentChannelFundSourceMap.size() == 0) { - accountMappingRepository.deleteInBatch(existingPaymentChannelToFundSourceMappings); + this.accountMappingRepository.deleteInBatch(existingPaymentChannelToFundSourceMappings); }/** * Else,
* update existing mappings OR
@@ -285,30 +285,30 @@ public class ProductToGLAccountMappingHelper { * **/ else { - for (ProductToGLAccountMapping existingPaymentChannelToFundSourceMapping : existingPaymentChannelToFundSourceMappings) { - Long currentPaymentChannelId = existingPaymentChannelToFundSourceMapping.getPaymentType().getId(); + for (final ProductToGLAccountMapping existingPaymentChannelToFundSourceMapping : existingPaymentChannelToFundSourceMappings) { + final Long currentPaymentChannelId = existingPaymentChannelToFundSourceMapping.getPaymentType().getId(); existingPaymentTypes.add(currentPaymentChannelId); // update existing mappings (if required) if (inputPaymentChannelFundSourceMap.containsKey(currentPaymentChannelId)) { - Long newGLAccountId = inputPaymentChannelFundSourceMap.get(currentPaymentChannelId); + final Long newGLAccountId = inputPaymentChannelFundSourceMap.get(currentPaymentChannelId); if (newGLAccountId != existingPaymentChannelToFundSourceMapping.getGlAccount().getId()) { final GLAccount glAccount = getAccountByIdAndType(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), GLAccountType.ASSET, newGLAccountId); existingPaymentChannelToFundSourceMapping.setGlAccount(glAccount); - accountMappingRepository.save(existingPaymentChannelToFundSourceMapping); + this.accountMappingRepository.save(existingPaymentChannelToFundSourceMapping); } }// deleted payment type else { - accountMappingRepository.delete(existingPaymentChannelToFundSourceMapping); + this.accountMappingRepository.delete(existingPaymentChannelToFundSourceMapping); } } // create new mappings - Set incomingPaymentTypes = inputPaymentChannelFundSourceMap.keySet(); + final Set incomingPaymentTypes = inputPaymentChannelFundSourceMap.keySet(); incomingPaymentTypes.removeAll(existingPaymentTypes); // incomingPaymentTypes now only contains the newly added // payment Type mappings - for (Long newPaymentType : incomingPaymentTypes) { - Long newGLAccountId = inputPaymentChannelFundSourceMap.get(newPaymentType); + for (final Long newPaymentType : incomingPaymentTypes) { + final Long newGLAccountId = inputPaymentChannelFundSourceMap.get(newPaymentType); savePaymentChannelToFundSourceMapping(productId, newPaymentType, newGLAccountId, portfolioProductType); } } @@ -321,7 +321,7 @@ public class ProductToGLAccountMappingHelper { */ private void savePaymentChannelToFundSourceMapping(final Long productId, final Long paymentTypeId, final Long paymentTypeSpecificFundAccountId, final PortfolioProductType portfolioProductType) { - CodeValue paymentType = codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( + final CodeValue paymentType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( PaymentDetailConstants.paymentTypeCodeName, paymentTypeId); final GLAccount glAccount = getAccountByIdAndType(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), GLAccountType.ASSET, paymentTypeSpecificFundAccountId); @@ -336,7 +336,7 @@ public class ProductToGLAccountMappingHelper { */ private void saveChargeToFundSourceMapping(final Long productId, final Long chargeId, final Long incomeAccountId, final PortfolioProductType portfolioProductType, final boolean isPenalty) { - Charge charge = chargeRepositoryWrapper.findOneWithNotFoundDetection(chargeId); + final Charge charge = this.chargeRepositoryWrapper.findOneWithNotFoundDetection(chargeId); // TODO Vishwas: Need to validate if given charge is fee or Penalty // based on input condition diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformServiceImpl.java index d6db8dea2..c4e494969 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingReadPlatformServiceImpl.java @@ -145,7 +145,7 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product } @Override - public Map fetchAccountMappingDetailsForSavingsProduct(Long savingsProductId, Integer accountingType) { + public Map fetchAccountMappingDetailsForSavingsProduct(final Long savingsProductId, final Integer accountingType) { final Map accountMappingDetails = new LinkedHashMap(8); final ProductToGLAccountMappingMapper rm = new ProductToGLAccountMappingMapper(); @@ -180,12 +180,12 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product } @Override - public List fetchPaymentTypeToFundSourceMappingsForLoanProduct(Long loanProductId) { + public List fetchPaymentTypeToFundSourceMappingsForLoanProduct(final Long loanProductId) { return fetchPaymentTypeToFundSourceMappings(PortfolioProductType.LOAN, loanProductId); } @Override - public List fetchPaymentTypeToFundSourceMappingsForSavingsProduct(Long savingsProductId) { + public List fetchPaymentTypeToFundSourceMappingsForSavingsProduct(final Long savingsProductId) { return fetchPaymentTypeToFundSourceMappings(PortfolioProductType.SAVING, savingsProductId); } @@ -194,8 +194,8 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product * @param paymentTypeToGLAccountMappers * @return */ - private List fetchPaymentTypeToFundSourceMappings(PortfolioProductType portfolioProductType, - Long loanProductId) { + private List fetchPaymentTypeToFundSourceMappings(final PortfolioProductType portfolioProductType, + final Long loanProductId) { final ProductToGLAccountMappingMapper rm = new ProductToGLAccountMappingMapper(); final String sql = "select " + rm.schema() + " and product_id = ? and payment_type is not null"; @@ -209,24 +209,24 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product } final Long glAccountId = (Long) productToGLAccountMap.get("glAccountId"); final Long paymentTypeId = (Long) productToGLAccountMap.get("paymentTypeId"); - PaymentTypeToGLAccountMapper paymentTypeToGLAccountMapper = new PaymentTypeToGLAccountMapper(paymentTypeId, glAccountId); + final PaymentTypeToGLAccountMapper paymentTypeToGLAccountMapper = new PaymentTypeToGLAccountMapper(paymentTypeId, glAccountId); paymentTypeToGLAccountMappers.add(paymentTypeToGLAccountMapper); } return paymentTypeToGLAccountMappers; } @Override - public List fetchFeeToIncomeAccountMappingsForLoanProduct(Long loanProductId) { + public List fetchFeeToIncomeAccountMappingsForLoanProduct(final Long loanProductId) { return fetchChargeToIncomeAccountMappings(PortfolioProductType.LOAN, loanProductId, false); } @Override - public List fetchPenaltyToIncomeAccountMappingsForLoanProduct(Long loanProductId) { + public List fetchPenaltyToIncomeAccountMappingsForLoanProduct(final Long loanProductId) { return fetchChargeToIncomeAccountMappings(PortfolioProductType.LOAN, loanProductId, true); } - private List fetchChargeToIncomeAccountMappings(PortfolioProductType portfolioProductType, Long loanProductId, - boolean penalty) { + private List fetchChargeToIncomeAccountMappings(final PortfolioProductType portfolioProductType, + final Long loanProductId, final boolean penalty) { final ProductToGLAccountMappingMapper rm = new ProductToGLAccountMappingMapper(); String sql = "select " + rm.schema() + " and product_id = ? and mapping.charge_id is not null and charge.is_penalty="; if (penalty) { @@ -244,7 +244,7 @@ public class ProductToGLAccountMappingReadPlatformServiceImpl implements Product } final Long glAccountId = (Long) chargeToIncomeAccountMap.get("glAccountId"); final Long chargeId = (Long) chargeToIncomeAccountMap.get("chargeId"); - ChargeToGLAccountMapper chargeToGLAccountMapper = new ChargeToGLAccountMapper(chargeId, glAccountId); + final ChargeToGLAccountMapper chargeToGLAccountMapper = new ChargeToGLAccountMapper(chargeId, glAccountId); chargeToGLAccountMappers.add(chargeToGLAccountMapper); } return chargeToGLAccountMappers; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformServiceImpl.java index 5a8e18e8f..5ac062f57 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/ProductToGLAccountMappingWritePlatformServiceImpl.java @@ -37,8 +37,8 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc @Autowired public ProductToGLAccountMappingWritePlatformServiceImpl(final FromJsonHelper fromApiJsonHelper, final ProductToGLAccountMappingFromApiJsonDeserializer deserializer, - LoanProductToGLAccountMappingHelper loanProductToGLAccountMappingHelper, - SavingsProductToGLAccountMappingHelper savingsProductToGLAccountMappingHelper) { + final LoanProductToGLAccountMappingHelper loanProductToGLAccountMappingHelper, + final SavingsProductToGLAccountMappingHelper savingsProductToGLAccountMappingHelper) { this.fromApiJsonHelper = fromApiJsonHelper; this.deserializer = deserializer; this.loanProductToGLAccountMappingHelper = loanProductToGLAccountMappingHelper; @@ -57,84 +57,84 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc break; case CASH_BASED: // asset - loanProductToGLAccountMappingHelper + this.loanProductToGLAccountMappingHelper .saveLoanToAssetAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), loanProductId, CASH_ACCOUNTS_FOR_LOAN.FUND_SOURCE.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), loanProductId, CASH_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), loanProductId, CASH_ACCOUNTS_FOR_LOAN.TRANSFERS_SUSPENSE.getValue()); // income - loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), loanProductId, CASH_ACCOUNTS_FOR_LOAN.INTEREST_ON_LOANS.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), loanProductId, CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), loanProductId, CASH_ACCOUNTS_FOR_LOAN.INCOME_FROM_PENALTIES.getValue()); // expenses - loanProductToGLAccountMappingHelper.saveLoanToExpenseAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToExpenseAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), loanProductId, CASH_ACCOUNTS_FOR_LOAN.LOSSES_WRITTEN_OFF.getValue()); // advanced accounting mappings - loanProductToGLAccountMappingHelper.savePaymentChannelToFundSourceMappings(command, element, loanProductId, null); - loanProductToGLAccountMappingHelper.saveChargesToIncomeAccountMappings(command, element, loanProductId, null); + this.loanProductToGLAccountMappingHelper.savePaymentChannelToFundSourceMappings(command, element, loanProductId, null); + this.loanProductToGLAccountMappingHelper.saveChargesToIncomeAccountMappings(command, element, loanProductId, null); break; case ACCRUAL_BASED: // assets (including receivables) - loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.FUND_SOURCE.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.LOAN_PORTFOLIO.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.TRANSFERS_SUSPENSE.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.INTEREST_RECEIVABLE.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.FEES_RECEIVABLE.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToAssetAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.PENALTIES_RECEIVABLE.getValue()); // income - loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.INTEREST_ON_LOANS.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.INCOME_FROM_FEES.getValue()); - loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToIncomeAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.INCOME_FROM_PENALTIES.getValue()); // expenses - loanProductToGLAccountMappingHelper.saveLoanToExpenseAccountMapping(element, + this.loanProductToGLAccountMappingHelper.saveLoanToExpenseAccountMapping(element, LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), loanProductId, ACCRUAL_ACCOUNTS_FOR_LOAN.LOSSES_WRITTEN_OFF.getValue()); // advanced accounting mappings - loanProductToGLAccountMappingHelper.savePaymentChannelToFundSourceMappings(command, element, loanProductId, null); - loanProductToGLAccountMappingHelper.saveChargesToIncomeAccountMappings(command, element, loanProductId, null); + this.loanProductToGLAccountMappingHelper.savePaymentChannelToFundSourceMappings(command, element, loanProductId, null); + this.loanProductToGLAccountMappingHelper.saveChargesToIncomeAccountMappings(command, element, loanProductId, null); break; } } @Override @Transactional - public void createSavingProductToGLAccountMapping(Long savingProductId, JsonCommand command) { + public void createSavingProductToGLAccountMapping(final Long savingProductId, final JsonCommand command) { final JsonElement element = this.fromApiJsonHelper.parse(command.json()); final Integer accountingRuleTypeId = this.fromApiJsonHelper.extractIntegerNamed(accountingRuleParamName, element, Locale.getDefault()); @@ -145,30 +145,30 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc break; case CASH_BASED: // asset - savingsProductToGLAccountMappingHelper.saveSavingsToAssetAccountMapping(element, + this.savingsProductToGLAccountMappingHelper.saveSavingsToAssetAccountMapping(element, SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), savingProductId, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_REFERENCE.getValue()); // income - savingsProductToGLAccountMappingHelper.saveSavingsToIncomeAccountMapping(element, + this.savingsProductToGLAccountMappingHelper.saveSavingsToIncomeAccountMapping(element, SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), savingProductId, CASH_ACCOUNTS_FOR_SAVINGS.INCOME_FROM_FEES.getValue()); // expenses - savingsProductToGLAccountMappingHelper.saveSavingsToExpenseAccountMapping(element, + this.savingsProductToGLAccountMappingHelper.saveSavingsToExpenseAccountMapping(element, SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), savingProductId, CASH_ACCOUNTS_FOR_SAVINGS.INTEREST_ON_SAVINGS.getValue()); // liability - savingsProductToGLAccountMappingHelper.saveSavingsToLiabilityAccountMapping(element, + this.savingsProductToGLAccountMappingHelper.saveSavingsToLiabilityAccountMapping(element, SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), savingProductId, CASH_ACCOUNTS_FOR_SAVINGS.SAVINGS_CONTROL.getValue()); - savingsProductToGLAccountMappingHelper.saveSavingsToLiabilityAccountMapping(element, + this.savingsProductToGLAccountMappingHelper.saveSavingsToLiabilityAccountMapping(element, SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), savingProductId, CASH_ACCOUNTS_FOR_SAVINGS.TRANSFERS_SUSPENSE.getValue()); // advanced accounting mappings - savingsProductToGLAccountMappingHelper.savePaymentChannelToFundSourceMappings(command, element, savingProductId, null); + this.savingsProductToGLAccountMappingHelper.savePaymentChannelToFundSourceMappings(command, element, savingProductId, null); break; /*** Do not have accrual based accounting for now ***/ case ACCRUAL_BASED: @@ -195,23 +195,23 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc ***/ if (accountingRuleChanged) { this.deserializer.validateForLoanProductCreate(command.json()); - loanProductToGLAccountMappingHelper.deleteLoanProductToGLAccountMapping(loanProductId); + this.loanProductToGLAccountMappingHelper.deleteLoanProductToGLAccountMapping(loanProductId); createLoanProductToGLAccountMapping(loanProductId, command); - changes = loanProductToGLAccountMappingHelper.populateChangesForNewLoanProductToGLAccountMappingCreation(element, + changes = this.loanProductToGLAccountMappingHelper.populateChangesForNewLoanProductToGLAccountMappingCreation(element, accountingRuleType); }/*** else examine and update individual changes ***/ else { - loanProductToGLAccountMappingHelper.handleChangesToLoanProductToGLAccountMappings(loanProductId, changes, element, + this.loanProductToGLAccountMappingHelper.handleChangesToLoanProductToGLAccountMappings(loanProductId, changes, element, accountingRuleType); - loanProductToGLAccountMappingHelper.updatePaymentChannelToFundSourceMappings(command, element, loanProductId, changes); - loanProductToGLAccountMappingHelper.updateChargesToIncomeAccountMappings(command, element, loanProductId, changes); + this.loanProductToGLAccountMappingHelper.updatePaymentChannelToFundSourceMappings(command, element, loanProductId, changes); + this.loanProductToGLAccountMappingHelper.updateChargesToIncomeAccountMappings(command, element, loanProductId, changes); } return changes; } @Override - public Map updateSavingsProductToGLAccountMapping(Long savingsProductId, JsonCommand command, - boolean accountingRuleChanged, int accountingRuleTypeId) { + public Map updateSavingsProductToGLAccountMapping(final Long savingsProductId, final JsonCommand command, + final boolean accountingRuleChanged, final int accountingRuleTypeId) { /*** * Variable tracks all accounting mapping properties that have been * updated @@ -226,15 +226,16 @@ public class ProductToGLAccountMappingWritePlatformServiceImpl implements Produc ***/ if (accountingRuleChanged) { this.deserializer.validateForSavingsProductCreate(command.json()); - savingsProductToGLAccountMappingHelper.deleteSavingsProductToGLAccountMapping(savingsProductId); + this.savingsProductToGLAccountMappingHelper.deleteSavingsProductToGLAccountMapping(savingsProductId); createSavingProductToGLAccountMapping(savingsProductId, command); - changes = savingsProductToGLAccountMappingHelper.populateChangesForNewSavingsProductToGLAccountMappingCreation(element, + changes = this.savingsProductToGLAccountMappingHelper.populateChangesForNewSavingsProductToGLAccountMappingCreation(element, accountingRuleType); }/*** else examine and update individual changes ***/ else { - savingsProductToGLAccountMappingHelper.handleChangesToSavingsProductToGLAccountMappings(savingsProductId, changes, element, - accountingRuleType); - savingsProductToGLAccountMappingHelper.updatePaymentChannelToFundSourceMappings(command, element, savingsProductId, changes); + this.savingsProductToGLAccountMappingHelper.handleChangesToSavingsProductToGLAccountMappings(savingsProductId, changes, + element, accountingRuleType); + this.savingsProductToGLAccountMappingHelper.updatePaymentChannelToFundSourceMappings(command, element, savingsProductId, + changes); } return changes; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/SavingsProductToGLAccountMappingHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/SavingsProductToGLAccountMappingHelper.java index 1b5d41353..30825cc97 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/SavingsProductToGLAccountMappingHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/producttoaccountmapping/service/SavingsProductToGLAccountMappingHelper.java @@ -28,9 +28,9 @@ import com.google.gson.JsonElement; public class SavingsProductToGLAccountMappingHelper extends ProductToGLAccountMappingHelper { @Autowired - public SavingsProductToGLAccountMappingHelper(GLAccountRepository glAccountRepository, - ProductToGLAccountMappingRepository glAccountMappingRepository, FromJsonHelper fromApiJsonHelper, - CodeValueRepositoryWrapper codeValueRepositoryWrapper, ChargeRepositoryWrapper chargeRepositoryWrapper) { + public SavingsProductToGLAccountMappingHelper(final GLAccountRepository glAccountRepository, + final ProductToGLAccountMappingRepository glAccountMappingRepository, final FromJsonHelper fromApiJsonHelper, + final CodeValueRepositoryWrapper codeValueRepositoryWrapper, final ChargeRepositoryWrapper chargeRepositoryWrapper) { super(glAccountRepository, glAccountMappingRepository, fromApiJsonHelper, codeValueRepositoryWrapper, chargeRepositoryWrapper); } @@ -85,12 +85,12 @@ public class SavingsProductToGLAccountMappingHelper extends ProductToGLAccountMa /*** Abstractions for payments channel related to savings products ***/ public void savePaymentChannelToFundSourceMappings(final JsonCommand command, final JsonElement element, final Long productId, - Map changes) { + final Map changes) { savePaymentChannelToFundSourceMappings(command, element, productId, changes, PortfolioProductType.SAVING); } public void updatePaymentChannelToFundSourceMappings(final JsonCommand command, final JsonElement element, final Long productId, - Map changes) { + final Map changes) { updatePaymentChannelToFundSourceMappings(command, element, productId, changes, PortfolioProductType.SAVING); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/api/AccountingRuleApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/api/AccountingRuleApiResource.java index b3d414980..6839dee74 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/api/AccountingRuleApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/api/AccountingRuleApiResource.java @@ -107,22 +107,24 @@ public class AccountingRuleApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllAccountingRules(@Context final UriInfo uriInfo) { - - final AppUser currentUser = context.authenticatedUser(); + + final AppUser currentUser = this.context.authenticatedUser(); currentUser.validateHasReadPermission(this.resourceNameForPermission); - + final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - + final Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); boolean isAssociationParametersExists = false; if (!associationParameters.isEmpty()) { if (associationParameters.contains("all")) { - isAssociationParametersExists = true; // If true, retrieve additional fields for journal entry form. + isAssociationParametersExists = true; // If true, retrieve + // additional fields for + // journal entry form. } } - final List accountingRuleDatas = this.accountingRuleReadPlatformService.retrieveAllAccountingRules(hierarchySearchString, - isAssociationParametersExists); + final List accountingRuleDatas = this.accountingRuleReadPlatformService.retrieveAllAccountingRules( + hierarchySearchString, isAssociationParametersExists); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.apiJsonSerializerService.serialize(settings, accountingRuleDatas, RESPONSE_DATA_PARAMETERS); @@ -189,10 +191,14 @@ public class AccountingRuleApiResource { final Collection allowedTagOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(AccountingConstants.ASSESTS_TAG_OPTION_CODE_NAME); - allowedTagOptions.addAll(this.codeValueReadPlatformService.retrieveCodeValuesByCode(AccountingConstants.LIABILITIES_TAG_OPTION_CODE_NAME)); - allowedTagOptions.addAll(this.codeValueReadPlatformService.retrieveCodeValuesByCode(AccountingConstants.EQUITY_TAG_OPTION_CODE_NAME)); - allowedTagOptions.addAll(this.codeValueReadPlatformService.retrieveCodeValuesByCode(AccountingConstants.INCOME_TAG_OPTION_CODE_NAME)); - allowedTagOptions.addAll(this.codeValueReadPlatformService.retrieveCodeValuesByCode(AccountingConstants.EXPENSES_TAG_OPTION_CODE_NAME)); + allowedTagOptions.addAll(this.codeValueReadPlatformService + .retrieveCodeValuesByCode(AccountingConstants.LIABILITIES_TAG_OPTION_CODE_NAME)); + allowedTagOptions.addAll(this.codeValueReadPlatformService + .retrieveCodeValuesByCode(AccountingConstants.EQUITY_TAG_OPTION_CODE_NAME)); + allowedTagOptions.addAll(this.codeValueReadPlatformService + .retrieveCodeValuesByCode(AccountingConstants.INCOME_TAG_OPTION_CODE_NAME)); + allowedTagOptions.addAll(this.codeValueReadPlatformService + .retrieveCodeValuesByCode(AccountingConstants.EXPENSES_TAG_OPTION_CODE_NAME)); if (accountingRuleData == null) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/data/AccountingTagRuleData.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/data/AccountingTagRuleData.java index 6185f8970..70aa3551d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/data/AccountingTagRuleData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/data/AccountingTagRuleData.java @@ -23,7 +23,7 @@ public class AccountingTagRuleData { } public CodeValueData getTag() { - return tag; + return this.tag; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/exception/AccountingRuleDuplicateException.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/exception/AccountingRuleDuplicateException.java index 90b443820..addd18606 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/exception/AccountingRuleDuplicateException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/exception/AccountingRuleDuplicateException.java @@ -13,10 +13,10 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class AccountingRuleDuplicateException extends AbstractPlatformDomainRuleException { - public AccountingRuleDuplicateException(String name) { + public AccountingRuleDuplicateException(final String name) { super("error.msg.accounting.rule.duplicate", "An accounting rule with the name " + name + " already exists" + name); } - + public AccountingRuleDuplicateException() { super("error.msg.accounting.rule.tag.duplicate", "The accounting rule already have the tags which you defined"); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/service/AccountingRuleReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/service/AccountingRuleReadPlatformServiceImpl.java index b2e6d4890..57f1b8c07 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/service/AccountingRuleReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/service/AccountingRuleReadPlatformServiceImpl.java @@ -141,7 +141,8 @@ public class AccountingRuleReadPlatformServiceImpl implements AccountingRuleRead } @Override - public List retrieveAllAccountingRules(final String hierarchySearchString, final boolean isAssociationParametersExists) { + public List retrieveAllAccountingRules(final String hierarchySearchString, + final boolean isAssociationParametersExists) { final AccountingRuleDataExtractor resultSetExtractor = new AccountingRuleDataExtractor(this.jdbcTemplate, this.glAccountReadPlatformService, isAssociationParametersExists); Object[] arguments = new Object[] {}; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/service/AccountingRuleWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/service/AccountingRuleWritePlatformServiceJpaRepositoryImpl.java index c728872e4..3fbddd9f0 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/service/AccountingRuleWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/accounting/rule/service/AccountingRuleWritePlatformServiceJpaRepositoryImpl.java @@ -112,7 +112,7 @@ public class AccountingRuleWritePlatformServiceJpaRepositoryImpl implements Acco // get the GL Accounts or tags to Debit and Credit final String[] debitTags = command.arrayValueOfParameterNamed(AccountingRuleJsonInputParams.DEBIT_ACCOUNT_TAGS.getValue()); final String[] creditTags = command.arrayValueOfParameterNamed(AccountingRuleJsonInputParams.CREDIT_ACCOUNT_TAGS.getValue()); - final Set incomingDebitTags = debitTags == null ? new HashSet(): new HashSet(Arrays.asList(debitTags)); + final Set incomingDebitTags = debitTags == null ? new HashSet() : new HashSet(Arrays.asList(debitTags)); final Set incomingCreditTags = creditTags == null ? new HashSet() : new HashSet(Arrays.asList(creditTags)); final Long accountToDebitId = command.longValueOfParameterNamed(AccountingRuleJsonInputParams.ACCOUNT_TO_DEBIT.getValue()); final Long accountToCreditId = command.longValueOfParameterNamed(AccountingRuleJsonInputParams.ACCOUNT_TO_CREDIT.getValue()); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/api/AuditsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/api/AuditsApiResource.java index f9b103759..4c1d7c60b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/api/AuditsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/api/AuditsApiResource.java @@ -74,17 +74,17 @@ public class AuditsApiResource { @QueryParam("groupId") final Integer groupId, @QueryParam("clientId") final Integer clientId, @QueryParam("loanid") final Integer loanId, @QueryParam("savingsAccountId") final Integer savingsAccountId) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final String extraCriteria = getExtraCriteria(actionName, entityName, resourceId, makerId, makerDateTimeFrom, makerDateTimeTo, checkerId, checkerDateTimeFrom, checkerDateTimeTo, processingResult, officeId, groupId, clientId, loanId, savingsAccountId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final Collection auditEntries = this.auditReadPlatformService.retrieveAuditEntries(extraCriteria, settings.isIncludeJson()); - return this.toApiJsonSerializer.serialize(settings, auditEntries, RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, auditEntries, this.RESPONSE_DATA_PARAMETERS); } @GET @@ -93,12 +93,12 @@ public class AuditsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAuditEntry(@PathParam("auditId") final Long auditId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final AuditData auditEntry = this.auditReadPlatformService.retrieveAuditEntry(auditId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, auditEntry, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, auditEntry, this.RESPONSE_DATA_PARAMETERS); } @GET @@ -107,9 +107,9 @@ public class AuditsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAuditSearchTemplate(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final AuditSearchData auditSearchData = this.auditReadPlatformService.retrieveSearchTemplate("audit"); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/api/MakercheckersApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/api/MakercheckersApiResource.java index 061907a8e..79d1556ff 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/api/MakercheckersApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/api/MakercheckersApiResource.java @@ -77,12 +77,12 @@ public class MakercheckersApiResource { final String extraCriteria = getExtraCriteria(actionName, entityName, resourceId, makerId, makerDateTimeFrom, makerDateTimeTo, officeId, groupId, clientId, loanId, savingsAccountId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final Collection entries = this.readPlatformService.retrieveAllEntriesToBeChecked(extraCriteria, settings.isIncludeJson()); - return this.toApiJsonSerializerAudit.serialize(settings, entries, RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializerAudit.serialize(settings, entries, this.RESPONSE_DATA_PARAMETERS); } @GET @@ -91,7 +91,7 @@ public class MakercheckersApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAuditSearchTemplate(@Context final UriInfo uriInfo) { - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final AuditSearchData auditSearchData = this.readPlatformService.retrieveSearchTemplate("makerchecker"); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandProcessingResultType.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandProcessingResultType.java index cc9725069..ba5daf124 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandProcessingResultType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandProcessingResultType.java @@ -21,11 +21,11 @@ public enum CommandProcessingResultType { } public Integer getValue() { - return value; + return this.value; } public String getCode() { - return code; + return this.code; } public static CommandProcessingResultType fromInt(final Integer typeValue) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandSource.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandSource.java index 3aa5ab685..dccfb199a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandSource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandSource.java @@ -25,175 +25,162 @@ import org.springframework.data.jpa.domain.AbstractPersistable; @Table(name = "m_portfolio_command_source") public class CommandSource extends AbstractPersistable { - @Column(name = "action_name", nullable = true, length = 100) - private String actionName; + @Column(name = "action_name", nullable = true, length = 100) + private String actionName; - @Column(name = "entity_name", nullable = true, length = 100) - private String entityName; + @Column(name = "entity_name", nullable = true, length = 100) + private String entityName; - @Column(name = "office_id") - private Long officeId; + @Column(name = "office_id") + private Long officeId; - @Column(name = "group_id") - private Long groupId; + @Column(name = "group_id") + private Long groupId; - @Column(name = "client_id") - private Long clientId; + @Column(name = "client_id") + private Long clientId; - @Column(name = "loan_id") - private Long loanId; + @Column(name = "loan_id") + private Long loanId; - @Column(name = "savings_account_id") - private Long savingsId; + @Column(name = "savings_account_id") + private Long savingsId; - @Column(name = "api_get_url", length = 100) - private String resourceGetUrl; + @Column(name = "api_get_url", length = 100) + private String resourceGetUrl; - @Column(name = "resource_id") - private Long resourceId; + @Column(name = "resource_id") + private Long resourceId; - @Column(name = "subresource_id") - private Long subresourceId; + @Column(name = "subresource_id") + private Long subresourceId; - @Column(name = "command_as_json", length = 1000) - private String commandAsJson; + @Column(name = "command_as_json", length = 1000) + private String commandAsJson; - @ManyToOne - @JoinColumn(name = "maker_id", nullable = false) - private AppUser maker; + @ManyToOne + @JoinColumn(name = "maker_id", nullable = false) + private AppUser maker; - @Column(name = "made_on_date", nullable = false) - @Temporal(TemporalType.TIMESTAMP) - private Date madeOnDate; + @Column(name = "made_on_date", nullable = false) + @Temporal(TemporalType.TIMESTAMP) + private Date madeOnDate; - @ManyToOne - @JoinColumn(name = "checker_id", nullable = true) - private AppUser checker; + @ManyToOne + @JoinColumn(name = "checker_id", nullable = true) + private AppUser checker; - @Column(name = "checked_on_date", nullable = true) - @Temporal(TemporalType.TIMESTAMP) - private Date checkedOnDate; + @Column(name = "checked_on_date", nullable = true) + @Temporal(TemporalType.TIMESTAMP) + private Date checkedOnDate; - @Column(name = "processing_result_enum", nullable = false) - private Integer processingResult; + @Column(name = "processing_result_enum", nullable = false) + private Integer processingResult; - @Column(name = "product_id") - private Long productId; + @Column(name = "product_id") + private Long productId; - public static CommandSource fullEntryFrom(final CommandWrapper wrapper, - final JsonCommand command, final AppUser maker) { - return new CommandSource(wrapper.actionName(), wrapper.entityName(), - wrapper.getHref(), command.entityId(), command.subentityId(), - command.json(), maker, DateTime.now()); - } + public static CommandSource fullEntryFrom(final CommandWrapper wrapper, final JsonCommand command, final AppUser maker) { + return new CommandSource(wrapper.actionName(), wrapper.entityName(), wrapper.getHref(), command.entityId(), command.subentityId(), + command.json(), maker, DateTime.now()); + } - protected CommandSource() { - // - } + protected CommandSource() { + // + } - private CommandSource(final String actionName, final String entityName, - final String href, final Long resourceId, final Long subresourceId, - final String commandSerializedAsJson, final AppUser maker, - final DateTime madeOnDateTime) { - this.actionName = actionName; - this.entityName = entityName; - this.resourceGetUrl = href; - this.resourceId = resourceId; - this.subresourceId = subresourceId; - this.commandAsJson = commandSerializedAsJson; - this.maker = maker; - this.madeOnDate = madeOnDateTime.toDate(); - this.processingResult = CommandProcessingResultType.PROCESSED - .getValue(); - } + private CommandSource(final String actionName, final String entityName, final String href, final Long resourceId, + final Long subresourceId, final String commandSerializedAsJson, final AppUser maker, final DateTime madeOnDateTime) { + this.actionName = actionName; + this.entityName = entityName; + this.resourceGetUrl = href; + this.resourceId = resourceId; + this.subresourceId = subresourceId; + this.commandAsJson = commandSerializedAsJson; + this.maker = maker; + this.madeOnDate = madeOnDateTime.toDate(); + this.processingResult = CommandProcessingResultType.PROCESSED.getValue(); + } - public void markAsChecked(final AppUser checker, - final DateTime checkedOnDate) { - this.checker = checker; - this.checkedOnDate = checkedOnDate.toDate(); - this.processingResult = CommandProcessingResultType.PROCESSED - .getValue(); - } + public void markAsChecked(final AppUser checker, final DateTime checkedOnDate) { + this.checker = checker; + this.checkedOnDate = checkedOnDate.toDate(); + this.processingResult = CommandProcessingResultType.PROCESSED.getValue(); + } - public void updateResourceId(final Long resourceId) { - this.resourceId = resourceId; - } + public void updateResourceId(final Long resourceId) { + this.resourceId = resourceId; + } - public void updateSubresourceId(final Long subresourceId) { - this.subresourceId = subresourceId; - } + public void updateSubresourceId(final Long subresourceId) { + this.subresourceId = subresourceId; + } - public void updateJsonTo(final String json) { - this.commandAsJson = json; - } + public void updateJsonTo(final String json) { + this.commandAsJson = json; + } - public Long resourceId() { - return this.resourceId; - } + public Long resourceId() { + return this.resourceId; + } - public Long subresourceId() { - return this.subresourceId; - } + public Long subresourceId() { + return this.subresourceId; + } - public boolean hasJson() { - return StringUtils.isNotBlank(this.commandAsJson); - } + public boolean hasJson() { + return StringUtils.isNotBlank(this.commandAsJson); + } - public String json() { - return this.commandAsJson; - } + public String json() { + return this.commandAsJson; + } - public String getActionName() { - return this.actionName; - } + public String getActionName() { + return this.actionName; + } - public String getEntityName() { - return this.entityName; - } + public String getEntityName() { + return this.entityName; + } - public String getPermissionCode() { - return this.actionName + "_" + this.entityName; - } + public String getPermissionCode() { + return this.actionName + "_" + this.entityName; + } - public Long getResourceId() { - return this.resourceId; - } + public Long getResourceId() { + return this.resourceId; + } - public Long getSubresourceId() { - return this.subresourceId; - } + public Long getSubresourceId() { + return this.subresourceId; + } - public void markAsAwaitingApproval() { - this.processingResult = CommandProcessingResultType.AWAITING_APPROVAL - .getValue(); - } + public void markAsAwaitingApproval() { + this.processingResult = CommandProcessingResultType.AWAITING_APPROVAL.getValue(); + } - public boolean isMarkedAsAwaitingApproval() { - if (this.processingResult - .equals(CommandProcessingResultType.AWAITING_APPROVAL - .getValue())) { - return true; - } + public boolean isMarkedAsAwaitingApproval() { + if (this.processingResult.equals(CommandProcessingResultType.AWAITING_APPROVAL.getValue())) { return true; } - return false; - } + return false; + } - public void updateForAudit(final Long officeId, final Long groupId, - final Long clientId, final Long loanId, final Long savingsId, - final Long productId) { - this.officeId = officeId; - this.groupId = groupId; - this.clientId = clientId; - this.loanId = loanId; - this.savingsId = savingsId; - this.productId = productId; - } + public void updateForAudit(final Long officeId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId, + final Long productId) { + this.officeId = officeId; + this.groupId = groupId; + this.clientId = clientId; + this.loanId = loanId; + this.savingsId = savingsId; + this.productId = productId; + } - public String getResourceGetUrl() { - return this.resourceGetUrl; - } + public String getResourceGetUrl() { + return this.resourceGetUrl; + } - public Long getProductId() { - return this.productId; - } + public Long getProductId() { + return this.productId; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandWrapper.java index 033877b3b..4975a18c5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/domain/CommandWrapper.java @@ -185,8 +185,8 @@ public class CommandWrapper { public boolean isUpdate() { // permissions resource has special update which involves no resource. - return isPermissionResource() && isUpdateOperation() || isCurrencyResource() && isUpdateOperation() || isCacheResource() && isUpdateOperation() - || isUpdateOperation() && this.entityId != null; + return isPermissionResource() && isUpdateOperation() || isCurrencyResource() && isUpdateOperation() || isCacheResource() + && isUpdateOperation() || isUpdateOperation() && this.entityId != null; } public boolean isUpdateOperation() { @@ -445,7 +445,7 @@ public class CommandWrapper { public boolean isSavingsAccountResource() { return this.entityName.equalsIgnoreCase("SAVINGSACCOUNT"); } - + public boolean isRejectionOfSavingsAccountApplication() { return this.actionName.equalsIgnoreCase("REJECT") && this.entityName.equalsIgnoreCase("SAVINGSACCOUNT"); } @@ -501,7 +501,7 @@ public class CommandWrapper { public boolean isSavingsAccountChargeResource() { return this.entityName.equalsIgnoreCase("SAVINGSACCOUNTCHARGE"); } - + public boolean isAddSavingsAccountCharge() { return this.actionName.equalsIgnoreCase("CREATE") && this.entityName.equalsIgnoreCase("SAVINGSACCOUNTCHARGE"); } @@ -517,11 +517,11 @@ public class CommandWrapper { public boolean isWaiveSavingsAccountCharge() { return this.actionName.equalsIgnoreCase("WAIVE") && this.entityName.equalsIgnoreCase("SAVINGSACCOUNTCHARGE"); } - + public boolean isPaySavingsAccountCharge() { return this.actionName.equalsIgnoreCase("PAY") && this.entityName.equalsIgnoreCase("SAVINGSACCOUNTCHARGE"); } - + public boolean isCalendarResource() { return this.entityName.equalsIgnoreCase("CALENDAR"); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/exception/UnsupportedCommandException.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/exception/UnsupportedCommandException.java index 5ed9b32aa..92f7de968 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/exception/UnsupportedCommandException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/exception/UnsupportedCommandException.java @@ -18,6 +18,6 @@ public class UnsupportedCommandException extends RuntimeException { } public String getUnsupportedCommandName() { - return unsupportedCommandName; + return this.unsupportedCommandName; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/AuditReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/AuditReadPlatformServiceImpl.java index 80771a55e..bd05296de 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/AuditReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/AuditReadPlatformServiceImpl.java @@ -79,7 +79,9 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { public String schema(final boolean includeJson, final String hierarchy) { String commandAsJsonString = ""; - if (includeJson) commandAsJsonString = ", aud.command_as_json as commandAsJson "; + if (includeJson) { + commandAsJsonString = ", aud.command_as_json as commandAsJson "; + } String partSql = " aud.id as id, aud.action_name as actionName, aud.entity_name as entityName," + " aud.resource_id as resourceId, aud.subresource_id as subresourceId," @@ -120,16 +122,16 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { // commandAsJson might not be on the select list of columns try { commandAsJson = rs.getString("commandAsJson"); - } catch (SQLException e) { + } catch (final SQLException e) { commandAsJson = null; } - String officeName = rs.getString("officeName"); - String groupLevelName = rs.getString("groupLevelName"); - String groupName = rs.getString("groupName"); - String clientName = rs.getString("clientName"); - String loanAccountNo = rs.getString("loanAccountNo"); - String savingsAccountNo = rs.getString("savingsAccountNo"); + final String officeName = rs.getString("officeName"); + final String groupLevelName = rs.getString("groupLevelName"); + final String groupName = rs.getString("groupName"); + final String clientName = rs.getString("clientName"); + final String loanAccountNo = rs.getString("loanAccountNo"); + final String savingsAccountNo = rs.getString("savingsAccountNo"); return new AuditData(id, actionName, entityName, resourceId, subresourceId, maker, madeOnDate, checker, checkedOnDate, processingResult, commandAsJson, officeName, groupLevelName, groupName, clientName, loanAccountNo, savingsAccountNo); @@ -140,7 +142,9 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { public Collection retrieveAuditEntries(final String extraCriteria, final boolean includeJson) { String updatedExtraCriteria = ""; - if (StringUtils.isNotBlank(extraCriteria)) updatedExtraCriteria = " where (" + extraCriteria + ")"; + if (StringUtils.isNotBlank(extraCriteria)) { + updatedExtraCriteria = " where (" + extraCriteria + ")"; + } updatedExtraCriteria += " order by aud.id DESC"; return retrieveEntries("audit", updatedExtraCriteria, includeJson); @@ -150,10 +154,11 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { public Collection retrieveAllEntriesToBeChecked(final String extraCriteria, final boolean includeJson) { String updatedExtraCriteria = ""; - if (StringUtils.isNotBlank(extraCriteria)) + if (StringUtils.isNotBlank(extraCriteria)) { updatedExtraCriteria = " where (" + extraCriteria + ")" + " and aud.processing_result_enum = 2"; - else + } else { updatedExtraCriteria = " where aud.processing_result_enum = 2"; + } updatedExtraCriteria += " order by aud.id"; @@ -165,8 +170,8 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { if (!(useType.equals("audit") || useType.equals("makerchecker"))) { throw new PlatformDataIntegrityException( "error.msg.invalid.auditSearchTemplate.useType", "Invalid Audit Search Template UseType: " + useType); } - AppUser currentUser = context.authenticatedUser(); - String hierarchy = currentUser.getOffice().getHierarchy(); + final AppUser currentUser = this.context.authenticatedUser(); + final String hierarchy = currentUser.getOffice().getHierarchy(); final AuditMapper rm = new AuditMapper(); String sql = "select " + rm.schema(includeJson, hierarchy); @@ -194,7 +199,7 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { @Override public AuditData retrieveAuditEntry(final Long auditId) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final AuditMapper rm = new AuditMapper(); @@ -220,10 +225,10 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { commandAsJsonMap.remove("officeId"); Long officeId = null; - String officeIdStr = auditObject.get("officeId").getAsString(); + final String officeIdStr = auditObject.get("officeId").getAsString(); if (StringUtils.isNotBlank(officeIdStr)) { officeId = Long.valueOf(officeIdStr); - OfficeData office = this.officeReadPlatformService.retrieveOffice(officeId); + final OfficeData office = this.officeReadPlatformService.retrieveOffice(officeId); commandAsJsonMap.put("officeName", office.name()); } else { commandAsJsonMap.put("officeName", ""); @@ -234,10 +239,10 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { commandAsJsonMap.remove("clientId"); Long clientId = null; - String clientIdStr = auditObject.get("clientId").getAsString(); + final String clientIdStr = auditObject.get("clientId").getAsString(); if (StringUtils.isNotBlank(clientIdStr)) { clientId = Long.valueOf(clientIdStr); - ClientData client = this.clientReadPlatformService.retrieveOne(clientId); + final ClientData client = this.clientReadPlatformService.retrieveOne(clientId); commandAsJsonMap.put("clientName", client.displayName()); } else { commandAsJsonMap.put("clientName", ""); @@ -248,10 +253,10 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { commandAsJsonMap.remove("productId"); Long productId = null; - String productIdStr = auditObject.get("productId").getAsString(); + final String productIdStr = auditObject.get("productId").getAsString(); if (StringUtils.isNotBlank(productIdStr)) { productId = Long.valueOf(productIdStr); - LoanProductData loanProduct = this.loanProductReadPlatformService.retrieveLoanProduct(productId); + final LoanProductData loanProduct = this.loanProductReadPlatformService.retrieveLoanProduct(productId); commandAsJsonMap.put("productName", loanProduct.getName()); } else { commandAsJsonMap.put("productName", ""); @@ -262,10 +267,10 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { commandAsJsonMap.remove("loanOfficerId"); Long loanOfficerId = null; - String loanOfficerIdStr = auditObject.get("loanOfficerId").getAsString(); + final String loanOfficerIdStr = auditObject.get("loanOfficerId").getAsString(); if (StringUtils.isNotBlank(loanOfficerIdStr)) { loanOfficerId = Long.valueOf(loanOfficerIdStr); - StaffData officer = this.staffReadPlatformService.retrieveStaff(loanOfficerId); + final StaffData officer = this.staffReadPlatformService.retrieveStaff(loanOfficerId); commandAsJsonMap.put("loanOfficerName", officer.getDisplayName()); } else { commandAsJsonMap.put("loanOfficerName", ""); @@ -275,7 +280,7 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { final String[] enumTypes = { "loanTermFrequencyType", "repaymentFrequencyType", "amortizationType", "interestType", "interestCalculationPeriodType", "interestRateFrequencyType" }; - for (String typeName : enumTypes) { + for (final String typeName : enumTypes) { if (commandAsJsonMap.containsKey(typeName)) { commandAsJsonMap.remove(typeName); @@ -301,25 +306,25 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { if (!(useType.equals("audit") || useType.equals("makerchecker"))) { throw new PlatformDataIntegrityException( "error.msg.invalid.auditSearchTemplate.useType", "Invalid Audit Search Template UseType: " + useType); } - AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); - final Collection appUsers = appUserReadPlatformService.retrieveSearchTemplate(); + final Collection appUsers = this.appUserReadPlatformService.retrieveSearchTemplate(); String sql = " SELECT distinct(action_name) as actionName FROM m_permission p "; sql += makercheckerCapabilityOnly(useType, currentUser); sql += " order by if(action_name in ('CREATE', 'DELETE', 'UPDATE'), action_name, 'ZZZ'), action_name"; - ActionNamesMapper mapper = new ActionNamesMapper(); - List actionNames = this.jdbcTemplate.query(sql, mapper, new Object[] {}); + final ActionNamesMapper mapper = new ActionNamesMapper(); + final List actionNames = this.jdbcTemplate.query(sql, mapper, new Object[] {}); sql = " select distinct(entity_name) as entityName from m_permission p "; sql += makercheckerCapabilityOnly(useType, currentUser); sql += " order by if(grouping = 'datatable', 'ZZZ', entity_name), entity_name"; - EntityNamesMapper mapper2 = new EntityNamesMapper(); - List entityNames = this.jdbcTemplate.query(sql, mapper2, new Object[] {}); + final EntityNamesMapper mapper2 = new EntityNamesMapper(); + final List entityNames = this.jdbcTemplate.query(sql, mapper2, new Object[] {}); Collection processingResults = null; if (useType.equals("audit")) { - ProcessingResultsMapper mapper3 = new ProcessingResultsMapper(); + final ProcessingResultsMapper mapper3 = new ProcessingResultsMapper(); processingResults = this.jdbcTemplate.query(mapper3.schema(), mapper3, new Object[] {}); } @@ -370,8 +375,8 @@ public class AuditReadPlatformServiceImpl implements AuditReadPlatformService { @Override public ProcessingResultLookup mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - Long id = JdbcSupport.getLong(rs, "id"); - String processingResult = rs.getString("processingResult"); + final Long id = JdbcSupport.getLong(rs, "id"); + final String processingResult = rs.getString("processingResult"); return new ProcessingResultLookup(id, processingResult); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java index 15c2b3caf..362259eb6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/CommandWrapperBuilder.java @@ -490,20 +490,20 @@ public class CommandWrapperBuilder { this.href = "/loans/" + loanId + "/charges/" + loanChargeId; return this; } - + public CommandWrapperBuilder payLoanCharge(final Long loanId, final Long loanChargeId) { this.actionName = "PAY"; this.entityName = "LOANCHARGE"; this.entityId = loanChargeId; this.loanId = loanId; - if(loanChargeId == null){ + if (loanChargeId == null) { this.href = "/loans/" + loanId; - }else{ - this.href = "/loans/" + loanId + "/charges/" + loanChargeId; + } else { + this.href = "/loans/" + loanId + "/charges/" + loanChargeId; } return this; } - + public CommandWrapperBuilder deleteLoanCharge(final Long loanId, final Long loanChargeId) { this.actionName = "DELETE"; this.entityName = "LOANCHARGE"; @@ -866,7 +866,6 @@ public class CommandWrapperBuilder { return this; } - public CommandWrapperBuilder createAccountTransfer() { this.actionName = "CREATE"; this.entityName = "ACCOUNTTRANSFER"; @@ -941,7 +940,7 @@ public class CommandWrapperBuilder { this.href = "/savingsaccounts/" + accountId + "?command=applyAnnualFees"; return this; } - + public CommandWrapperBuilder createSavingsAccountCharge(final Long savingsAccountId) { this.actionName = "CREATE"; this.entityName = "SAVINGSACCOUNTCHARGE"; @@ -978,7 +977,7 @@ public class CommandWrapperBuilder { return this; } - + public CommandWrapperBuilder deleteSavingsAccountCharge(final Long savingsAccountId, final Long savingsAccountChargeId) { this.actionName = "DELETE"; this.entityName = "SAVINGSACCOUNTCHARGE"; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java index 29fdbf742..e506b75f4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/PortfolioCommandSourceWritePlatformServiceImpl.java @@ -47,7 +47,7 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio boolean isApprovedByChecker = false; // check if is update of own account details - if (wrapper.isUpdateOfOwnUserDetails(context.authenticatedUser().getId())) { + if (wrapper.isUpdateOfOwnUserDetails(this.context.authenticatedUser().getId())) { // then allow this operation to proceed. // maker checker doesnt mean anything here. isApprovedByChecker = true; // set to true in case permissions have @@ -56,7 +56,7 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio } else { // if not user changing their own details - check user has // permission to perform specific task. - context.authenticatedUser().validateHasPermissionTo(wrapper.getTaskPermissionName()); + this.context.authenticatedUser().validateHasPermissionTo(wrapper.getTaskPermissionName()); } validateIsUpdateAllowed(); @@ -70,7 +70,7 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio wrapper.getTransactionId(), wrapper.getHref(), wrapper.getProductId()); result = this.processAndLogCommandService.processAndLogCommand(wrapper, command, isApprovedByChecker); - } catch (RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { + } catch (final RollbackTransactionAsCommandIsNotApprovedByCheckerException e) { result = this.processAndLogCommandService.logCommand(e.getCommandSourceResult()); } @@ -81,7 +81,7 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio @Override public CommandProcessingResult approveEntry(final Long makerCheckerId) { - CommandSource commandSourceInput = validateMakerCheckerTransaction(makerCheckerId); + final CommandSource commandSourceInput = validateMakerCheckerTransaction(makerCheckerId); validateIsUpdateAllowed(); final CommandWrapper wrapper = CommandWrapper.fromExistingCommand(makerCheckerId, commandSourceInput.getActionName(), @@ -115,13 +115,13 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio if (commandSourceInput == null) { throw new CommandNotFoundException(makerCheckerId); } if (!(commandSourceInput.isMarkedAsAwaitingApproval())) { throw new CommandNotAwaitingApprovalException(makerCheckerId); } - context.authenticatedUser().validateHasCheckerPermissionTo(commandSourceInput.getPermissionCode()); + this.context.authenticatedUser().validateHasCheckerPermissionTo(commandSourceInput.getPermissionCode()); return commandSourceInput; } private boolean validateIsUpdateAllowed() { - return schedulerJobRunnerReadService.isUpdatesAllowed(); + return this.schedulerJobRunnerReadService.isUpdatesAllowed(); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java index 334a989f3..70ad36a57 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/commands/service/SynchronousCommandProcessingService.java @@ -111,8 +111,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer } else { throw new UnsupportedCommandException(wrapper.commandName()); } - } - else if (wrapper.isConfigurationResource()) { + } else if (wrapper.isConfigurationResource()) { handler = this.applicationContext.getBean("updateGlobalConfigurationCommandHandler", NewCommandSourceHandler.class); } else if (wrapper.isDatatableResource()) { if (wrapper.isCreateDatatable()) { @@ -442,7 +441,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer handler = this.applicationContext.getBean("paySavingsAccountChargeCommandHandler", NewCommandSourceHandler.class); } else { throw new UnsupportedCommandException(wrapper.commandName()); - } + } } else if (wrapper.isCalendarResource()) { if (wrapper.isCreate()) { handler = this.applicationContext.getBean("createCalendarCommandHandler", NewCommandSourceHandler.class); @@ -476,7 +475,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer handler = this.applicationContext.getBean("unassignRoleCommandHandler", NewCommandSourceHandler.class); } else if (wrapper.isUpdateGroupRole()) { handler = this.applicationContext.getBean("updateGroupRoleCommandHandler", NewCommandSourceHandler.class); - } else if (wrapper.isAssignStaff()) { + } else if (wrapper.isAssignStaff()) { handler = this.applicationContext.getBean("assignGroupStaffCommandHandler", NewCommandSourceHandler.class); } else if (wrapper.isTransferClientsBetweenGroups()) { handler = this.applicationContext.getBean("transferClientsBetweenGroupsCommandHandler", NewCommandSourceHandler.class); @@ -534,9 +533,9 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer } } else if (wrapper.isXBRLMappingResource()) { - if (wrapper.isUpdate()) { - handler = this.applicationContext.getBean("updateTaxonomyMappingCommandHandler", NewCommandSourceHandler.class); - } else { + if (wrapper.isUpdate()) { + handler = this.applicationContext.getBean("updateTaxonomyMappingCommandHandler", NewCommandSourceHandler.class); + } else { throw new UnsupportedCommandException(wrapper.commandName()); } } else if (wrapper.isHolidayResource()) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/CacheEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/CacheEnumerations.java index ef916a011..e5e9cbd55 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/CacheEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/CacheEnumerations.java @@ -15,8 +15,7 @@ public class CacheEnumerations { } public static EnumOptionData cacheType(final CacheType cacheType) { - EnumOptionData optionData = new EnumOptionData(CacheType.INVALID.getValue().longValue(), CacheType.INVALID.getCode(), - "Invalid"); + EnumOptionData optionData = new EnumOptionData(CacheType.INVALID.getValue().longValue(), CacheType.INVALID.getCode(), "Invalid"); switch (cacheType) { case INVALID: optionData = new EnumOptionData(CacheType.INVALID.getValue().longValue(), CacheType.INVALID.getCode(), "Invalid"); @@ -25,7 +24,8 @@ public class CacheEnumerations { optionData = new EnumOptionData(CacheType.NO_CACHE.getValue().longValue(), CacheType.NO_CACHE.getCode(), "No cache"); break; case SINGLE_NODE: - optionData = new EnumOptionData(CacheType.SINGLE_NODE.getValue().longValue(), CacheType.SINGLE_NODE.getCode(), "Single node"); + optionData = new EnumOptionData(CacheType.SINGLE_NODE.getValue().longValue(), CacheType.SINGLE_NODE.getCode(), + "Single node"); break; case MULTI_NODE: optionData = new EnumOptionData(CacheType.MULTI_NODE.getValue().longValue(), CacheType.MULTI_NODE.getCode(), "Multi node"); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/service/CacheWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/service/CacheWritePlatformServiceJpaRepositoryImpl.java index e73a6c1c4..e367e31ec 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/service/CacheWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/service/CacheWritePlatformServiceJpaRepositoryImpl.java @@ -36,7 +36,7 @@ public class CacheWritePlatformServiceJpaRepositoryImpl implements CacheWritePla final Map changes = this.cacheService.switchToCache(ehCacheEnabled, toCacheType); if (!changes.isEmpty()) { - this.configurationDomainService.updateCache(toCacheType); + this.configurationDomainService.updateCache(toCacheType); } return changes; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/service/RuntimeDelegatingCacheManager.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/service/RuntimeDelegatingCacheManager.java index d70d02d47..97c457eda 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/service/RuntimeDelegatingCacheManager.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/cache/service/RuntimeDelegatingCacheManager.java @@ -20,7 +20,7 @@ import org.springframework.stereotype.Component; /** * At present this implementation of {@link CacheManager} just delegates to the * real {@link CacheManager} to use. - * + * * By default it is {@link NoOpCacheManager} but we can change that by checking * some persisted configuration in the database on startup and allow user to * switch implementation through UI/API diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/CodeConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/CodeConstants.java index c965376db..91b24d4ba 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/CodeConstants.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/CodeConstants.java @@ -11,7 +11,8 @@ import java.util.Set; public class CodeConstants { /*** - * Enum of all parameters passed in while creating/updating a code and code value + * Enum of all parameters passed in while creating/updating a code and code + * value ***/ public static enum CODEVALUE_JSON_INPUT_PARAMS { CODEVALUE_ID("id"), NAME("name"), POSITION("position"); @@ -24,7 +25,7 @@ public class CodeConstants { private static final Set values = new HashSet(); static { - for (CODEVALUE_JSON_INPUT_PARAMS type : CODEVALUE_JSON_INPUT_PARAMS.values()) { + for (final CODEVALUE_JSON_INPUT_PARAMS type : CODEVALUE_JSON_INPUT_PARAMS.values()) { values.add(type.value); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/api/CodeValuesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/api/CodeValuesApiResource.java index 47d417547..ec7c06779 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/api/CodeValuesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/api/CodeValuesApiResource.java @@ -77,7 +77,7 @@ public class CodeValuesApiResource { final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, codeValues, this.RESPONSE_DATA_PARAMETERS); } - + @GET @Path("{codeValueId}") @Consumes({ MediaType.APPLICATION_JSON }) @@ -112,7 +112,8 @@ public class CodeValuesApiResource { public String updateCodeValue(@PathParam("codeId") final Long codeId, @PathParam("codeValueId") final Long codeValueId, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCodeValue(codeId, codeValueId).withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateCodeValue(codeId, codeValueId) + .withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/api/CodesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/api/CodesApiResource.java index 4161a6f08..f5393703c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/api/CodesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/api/CodesApiResource.java @@ -69,12 +69,12 @@ public class CodesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveCodes(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Collection codes = this.readPlatformService.retrieveAllCodes(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, codes, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, codes, this.RESPONSE_DATA_PARAMETERS); } @POST @@ -97,8 +97,8 @@ public class CodesApiResource { final CodeData code = this.readPlatformService.retrieveCode(codeId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, code, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, code, this.RESPONSE_DATA_PARAMETERS); } @PUT diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/data/CodeData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/data/CodeData.java index d8c65237d..925dbe430 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/data/CodeData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/data/CodeData.java @@ -27,8 +27,8 @@ public class CodeData implements Serializable { this.name = name; this.systemDefined = systemDefined; } - - public Long getCodeId(){ + + public Long getCodeId() { return this.id; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/data/CodeValueData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/data/CodeValueData.java index 0aa3df036..7852da730 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/data/CodeValueData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/data/CodeValueData.java @@ -10,7 +10,7 @@ import java.io.Serializable; /** * Immutable data object represent code-value data in system. */ -public class CodeValueData implements Serializable{ +public class CodeValueData implements Serializable { private final Long id; @@ -35,6 +35,6 @@ public class CodeValueData implements Serializable{ } public Long getId() { - return id; + return this.id; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/domain/Code.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/domain/Code.java index 62a28f082..932f33aa7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/domain/Code.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/domain/Code.java @@ -59,7 +59,7 @@ public class Code extends AbstractPersistable { public Map update(final JsonCommand command) { - if (systemDefined) { throw new SystemDefinedCodeCannotBeChangedException(); } + if (this.systemDefined) { throw new SystemDefinedCodeCannotBeChangedException(); } final Map actualChanges = new LinkedHashMap(1); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/domain/CodeValue.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/domain/CodeValue.java index 549722db0..ab0586096 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/domain/CodeValue.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/domain/CodeValue.java @@ -22,85 +22,73 @@ import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.springframework.data.jpa.domain.AbstractPersistable; @Entity -@Table(name = "m_code_value", uniqueConstraints = { @UniqueConstraint(columnNames = { - "code_id", "code_value" }, name = "code_value_duplicate") }) +@Table(name = "m_code_value", uniqueConstraints = { @UniqueConstraint(columnNames = { "code_id", "code_value" }, name = "code_value_duplicate") }) public class CodeValue extends AbstractPersistable { - @Column(name = "code_value", length = 100) - private String label; + @Column(name = "code_value", length = 100) + private String label; - @Column(name = "order_position") - private int position; + @Column(name = "order_position") + private int position; - @ManyToOne - @JoinColumn(name = "code_id", nullable = false) - private Code code; + @ManyToOne + @JoinColumn(name = "code_id", nullable = false) + private Code code; - public static CodeValue createNew(final Code code, final String label, - final int position) { - return new CodeValue(code, label, position); - } + public static CodeValue createNew(final Code code, final String label, final int position) { + return new CodeValue(code, label, position); + } - protected CodeValue() { - // - } + protected CodeValue() { + // + } - private CodeValue(final Code code, final String label, final int position) { - this.code = code; - this.label = StringUtils.defaultIfEmpty(label, null); - this.position = position; - } + private CodeValue(final Code code, final String label, final int position) { + this.code = code; + this.label = StringUtils.defaultIfEmpty(label, null); + this.position = position; + } - public String label() { - return this.label; - } + public String label() { + return this.label; + } - public int position() { - return this.position; - } + public int position() { + return this.position; + } - public static CodeValue fromJson(final Code code, final JsonCommand command) { + public static CodeValue fromJson(final Code code, final JsonCommand command) { - final String label = command - .stringValueOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.NAME - .getValue()); - Integer position = command - .integerValueSansLocaleOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.POSITION - .getValue()); - if (position == null) { - position = new Integer(0); - } - return new CodeValue(code, label, position.intValue()); - } + final String label = command.stringValueOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.NAME.getValue()); + Integer position = command.integerValueSansLocaleOfParameterNamed(CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue()); + if (position == null) { + position = new Integer(0); + } + return new CodeValue(code, label, position.intValue()); + } - public Map update(final JsonCommand command) { + public Map update(final JsonCommand command) { - final Map actualChanges = new LinkedHashMap( - 2); + final Map actualChanges = new LinkedHashMap(2); - final String labelParamName = CODEVALUE_JSON_INPUT_PARAMS.NAME - .getValue(); - if (command.isChangeInStringParameterNamed(labelParamName, this.label)) { - final String newValue = command - .stringValueOfParameterNamed(labelParamName); - actualChanges.put(labelParamName, newValue); - this.label = StringUtils.defaultIfEmpty(newValue, null); - } + final String labelParamName = CODEVALUE_JSON_INPUT_PARAMS.NAME.getValue(); + if (command.isChangeInStringParameterNamed(labelParamName, this.label)) { + final String newValue = command.stringValueOfParameterNamed(labelParamName); + actualChanges.put(labelParamName, newValue); + this.label = StringUtils.defaultIfEmpty(newValue, null); + } - final String positionParamName = CODEVALUE_JSON_INPUT_PARAMS.POSITION - .getValue(); - if (command.isChangeInIntegerSansLocaleParameterNamed( - positionParamName, this.position)) { - final Integer newValue = command - .integerValueSansLocaleOfParameterNamed(positionParamName); - actualChanges.put(positionParamName, newValue); - this.position = newValue.intValue(); - } + final String positionParamName = CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue(); + if (command.isChangeInIntegerSansLocaleParameterNamed(positionParamName, this.position)) { + final Integer newValue = command.integerValueSansLocaleOfParameterNamed(positionParamName); + actualChanges.put(positionParamName, newValue); + this.position = newValue.intValue(); + } - return actualChanges; - } + return actualChanges; + } - public CodeValueData toData() { - return CodeValueData.instance(getId(), this.label, this.position); - } + public CodeValueData toData() { + return CodeValueData.instance(getId(), this.label, this.position); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/exception/SystemDefinedCodeCannotBeChangedException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/exception/SystemDefinedCodeCannotBeChangedException.java index ff55da917..f94e0770a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/exception/SystemDefinedCodeCannotBeChangedException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/exception/SystemDefinedCodeCannotBeChangedException.java @@ -8,7 +8,8 @@ package org.mifosplatform.infrastructure.codes.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * A {@link AbstractPlatformDomainRuleException} thrown when someone attempts to update or delete a system defined code. + * A {@link AbstractPlatformDomainRuleException} thrown when someone attempts to + * update or delete a system defined code. */ public class SystemDefinedCodeCannotBeChangedException extends AbstractPlatformDomainRuleException { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/serialization/CodeCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/serialization/CodeCommandFromApiJsonDeserializer.java index 3185af1aa..7be885df1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/serialization/CodeCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/serialization/CodeCommandFromApiJsonDeserializer.java @@ -46,14 +46,14 @@ public final class CodeCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -63,14 +63,14 @@ public final class CodeCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("code"); - final JsonElement element = fromApiJsonHelper.parse(json); - if (fromApiJsonHelper.parameterExists("name", element)) { - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + if (this.fromApiJsonHelper.parameterExists("name", element)) { + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/serialization/CodeValueCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/serialization/CodeValueCommandFromApiJsonDeserializer.java index 60c60ee38..afad9dac6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/serialization/CodeValueCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/serialization/CodeValueCommandFromApiJsonDeserializer.java @@ -56,9 +56,8 @@ public final class CodeValueCommandFromApiJsonDeserializer { baseDataValidator.reset().parameter(CODEVALUE_JSON_INPUT_PARAMS.NAME.getValue()).value(name).notBlank().notExceedingLengthOf(100); if (this.fromApiJsonHelper.parameterExists(CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue(), element)) { - //Validate input value is a valid Integer - this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue(), - element); + // Validate input value is a valid Integer + this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue(), element); } throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -82,9 +81,8 @@ public final class CodeValueCommandFromApiJsonDeserializer { } if (this.fromApiJsonHelper.parameterExists(CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue(), element)) { - //Validate input value is a valid Integer - this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue(), - element); + // Validate input value is a valid Integer + this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CODEVALUE_JSON_INPUT_PARAMS.POSITION.getValue(), element); } throwExceptionIfValidationWarningsExist(dataValidationErrors); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeReadPlatformService.java index 2dc83bbac..02aa5be2f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeReadPlatformService.java @@ -14,6 +14,6 @@ public interface CodeReadPlatformService { Collection retrieveAllCodes(); CodeData retrieveCode(Long codeId); - + CodeData retriveCode(String codeName); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeReadPlatformServiceImpl.java index b52060376..2678b8b3a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeReadPlatformServiceImpl.java @@ -52,7 +52,7 @@ public class CodeReadPlatformServiceImpl implements CodeReadPlatformService { @Override @Cacheable(value = "codes", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('CD')") public Collection retrieveAllCodes() { - context.authenticatedUser(); + this.context.authenticatedUser(); final CodeMapper rm = new CodeMapper(); final String sql = "select " + rm.schema() + " order by c.code_name"; @@ -63,27 +63,27 @@ public class CodeReadPlatformServiceImpl implements CodeReadPlatformService { @Override public CodeData retrieveCode(final Long codeId) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); final CodeMapper rm = new CodeMapper(); final String sql = "select " + rm.schema() + " where c.id = ?"; return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { codeId }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new CodeNotFoundException(codeId); } } @Override - public CodeData retriveCode(String codeName) { + public CodeData retriveCode(final String codeName) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); final CodeMapper rm = new CodeMapper(); final String sql = "select " + rm.schema() + " where c.code_name = ?"; return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { codeName }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new CodeNotFoundException(codeName); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeValueReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeValueReadPlatformServiceImpl.java index 27a7e388d..1d92d0657 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeValueReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeValueReadPlatformServiceImpl.java @@ -51,7 +51,7 @@ public class CodeValueReadPlatformServiceImpl implements CodeValueReadPlatformSe @Override public Collection retrieveCodeValuesByCode(final String code) { - context.authenticatedUser(); + this.context.authenticatedUser(); final CodeValueDataMapper rm = new CodeValueDataMapper(); final String sql = "select " + rm.schema() + "where c.code_name like ? order by position"; @@ -61,9 +61,9 @@ public class CodeValueReadPlatformServiceImpl implements CodeValueReadPlatformSe @Override @Cacheable(value = "code_values", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#codeId+'cv')") - public Collection retrieveAllCodeValues(Long codeId) { + public Collection retrieveAllCodeValues(final Long codeId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final CodeValueDataMapper rm = new CodeValueDataMapper(); final String sql = "select " + rm.schema() + "where cv.code_id = ? order by position"; @@ -72,9 +72,9 @@ public class CodeValueReadPlatformServiceImpl implements CodeValueReadPlatformSe } @Override - public CodeValueData retrieveCodeValue(Long codeValueId) { + public CodeValueData retrieveCodeValue(final Long codeValueId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final CodeValueDataMapper rm = new CodeValueDataMapper(); final String sql = "select " + rm.schema() + "where cv.id = ? order by position"; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeValueWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeValueWritePlatformServiceJpaRepositoryImpl.java index d9a8b9a5a..348ae7cfa 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeValueWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeValueWritePlatformServiceJpaRepositoryImpl.java @@ -68,7 +68,7 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue .withCommandId(command.commandId()) // .withEntityId(codeValue.getId()) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleCodeValueDataIntegrityIssues(command, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -115,7 +115,7 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue .withEntityId(codeValueId) // .with(changes) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleCodeValueDataIntegrityIssues(command, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -137,7 +137,7 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue final CodeValue codeValueToDelete = this.codeValueRepositoryWrapper.findOneWithNotFoundDetection(codeValueId); - boolean removed = code.remove(codeValueToDelete); + final boolean removed = code.remove(codeValueToDelete); if (removed) { this.codeRepository.saveAndFlush(code); } @@ -145,7 +145,7 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue return new CommandProcessingResultBuilder() // .withEntityId(codeValueId) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { logger.error(dve.getMessage(), dve); throw new PlatformDataIntegrityException("error.msg.code.value.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + dve.getMostSpecificCause().getMessage()); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java index 3ce2e33ff..1756b94e8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/codes/service/CodeWritePlatformServiceJpaRepositoryImpl.java @@ -48,7 +48,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf public CommandProcessingResult createCode(final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); @@ -56,7 +56,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf this.codeRepository.save(code); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(code.getId()).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleCodeDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -68,7 +68,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf public CommandProcessingResult updateCode(final Long codeId, final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); @@ -84,7 +84,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf .withEntityId(codeId) // .with(changes) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleCodeDataIntegrityIssues(command, dve); return null; } @@ -95,7 +95,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf @CacheEvict(value = "codes", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('cv')") public CommandProcessingResult deleteCode(final Long codeId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final Code code = retrieveCodeBy(codeId); if (code.isSystemDefined()) { throw new SystemDefinedCodeCannotBeChangedException(); } @@ -103,7 +103,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf try { this.codeRepository.delete(code); this.codeRepository.flush(); - } catch (DataIntegrityViolationException e) { + } catch (final DataIntegrityViolationException e) { throw new PlatformDataIntegrityException("error.msg.cund.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + e.getMostSpecificCause()); } @@ -121,7 +121,7 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf * is. */ private void handleCodeDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("code_name")) { final String name = command.stringValueOfParameterNamed("name"); throw new PlatformDataIntegrityException("error.msg.code.duplicate.name", "A code with name '" + name + "' already exists", diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/GlobalConfigurationApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/GlobalConfigurationApiResource.java index ced9130f5..a98929123 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/GlobalConfigurationApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/api/GlobalConfigurationApiResource.java @@ -68,12 +68,12 @@ public class GlobalConfigurationApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveConfiguration(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final GlobalConfigurationData configurationData = this.readPlatformService.retrieveGlobalConfiguration(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, configurationData, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, configurationData, this.RESPONSE_DATA_PARAMETERS); } @PUT @@ -81,9 +81,9 @@ public class GlobalConfigurationApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String updateConfiguration(@Context final UriInfo uriInfo) { - Map configurationParameters = ApiParameterHelper.asMap(uriInfo.getQueryParameters()); + final Map configurationParameters = ApiParameterHelper.asMap(uriInfo.getQueryParameters()); - Map globalConfiguration = new HashMap(); + final Map globalConfiguration = new HashMap(); globalConfiguration.put("globalConfiguration", configurationParameters); final String apiRequestJson = this.toApiJsonSerializer.serialize(globalConfiguration); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/data/GlobalConfigurationPropertyData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/data/GlobalConfigurationPropertyData.java index 0fcd8ca3e..63a0de1a1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/data/GlobalConfigurationPropertyData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/data/GlobalConfigurationPropertyData.java @@ -11,9 +11,9 @@ package org.mifosplatform.infrastructure.configuration.data; public class GlobalConfigurationPropertyData { @SuppressWarnings("unused") - private String name; + private final String name; @SuppressWarnings("unused") - private boolean enabled; + private final boolean enabled; public GlobalConfigurationPropertyData(final String name, final boolean enabled) { this.name = name; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/data/S3CredentialsData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/data/S3CredentialsData.java index 914fe2474..2bb235f6e 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/data/S3CredentialsData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/data/S3CredentialsData.java @@ -6,7 +6,7 @@ public class S3CredentialsData { private final String accessKey; private final String secretKey; - public S3CredentialsData(String bucketName, String accessKey, String secretKey) { + public S3CredentialsData(final String bucketName, final String accessKey, final String secretKey) { this.bucketName = bucketName; this.accessKey = accessKey; this.secretKey = secretKey; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/ConfigurationDomainService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/ConfigurationDomainService.java index f205bb537..b7198c257 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/ConfigurationDomainService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/ConfigurationDomainService.java @@ -10,12 +10,20 @@ import org.mifosplatform.infrastructure.cache.domain.CacheType; public interface ConfigurationDomainService { boolean isMakerCheckerEnabledForTask(String taskPermissionCode); + boolean isAmazonS3Enabled(); + boolean isRescheduleFutureRepaymentsEnabled(); + boolean isRescheduleRepaymentsOnHolidaysEnabled(); + boolean allowTransactionsOnHolidayEnabled(); + boolean allowTransactionsOnNonWorkingDayEnabled(); + boolean isConstraintApproachEnabledForDatatables(); + boolean isEhcacheEnabled(); + void updateCache(CacheType cacheType); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/ConfigurationDomainServiceJpa.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/ConfigurationDomainServiceJpa.java index 9ca5cd2e8..35665b6ca 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/ConfigurationDomainServiceJpa.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/ConfigurationDomainServiceJpa.java @@ -7,8 +7,8 @@ package org.mifosplatform.infrastructure.configuration.domain; import org.apache.commons.lang.StringUtils; import org.mifosplatform.infrastructure.cache.domain.CacheType; -import org.mifosplatform.infrastructure.cache.domain.PlatformCacheRepository; import org.mifosplatform.infrastructure.cache.domain.PlatformCache; +import org.mifosplatform.infrastructure.cache.domain.PlatformCacheRepository; import org.mifosplatform.infrastructure.configuration.exception.GlobalConfigurationPropertyNotFoundException; import org.mifosplatform.useradministration.domain.Permission; import org.mifosplatform.useradministration.domain.PermissionRepository; @@ -26,8 +26,7 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService @Autowired public ConfigurationDomainServiceJpa(final PermissionRepository permissionRepository, - final GlobalConfigurationRepository globalConfigurationRepository, - final PlatformCacheRepository cacheTypeRepository) { + final GlobalConfigurationRepository globalConfigurationRepository, final PlatformCacheRepository cacheTypeRepository) { this.permissionRepository = permissionRepository; this.globalConfigurationRepository = globalConfigurationRepository; this.cacheTypeRepository = cacheTypeRepository; @@ -48,20 +47,24 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService } @Override - public boolean isAmazonS3Enabled(){ + public boolean isAmazonS3Enabled() { return this.globalConfigurationRepository.findOneByName("amazon-S3").isEnabled(); } @Override public boolean isRescheduleFutureRepaymentsEnabled() { final String rescheduleRepaymentsConfigurationProperty = "reschedule-future-repayments"; - final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByName(rescheduleRepaymentsConfigurationProperty); + final GlobalConfigurationProperty property = this.globalConfigurationRepository + .findOneByName(rescheduleRepaymentsConfigurationProperty); if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(rescheduleRepaymentsConfigurationProperty); } return property.isEnabled(); } - /* (non-Javadoc) - * @see org.mifosplatform.infrastructure.configuration.domain.ConfigurationDomainService#isHolidaysEnabled() + /* + * (non-Javadoc) + * + * @see org.mifosplatform.infrastructure.configuration.domain. + * ConfigurationDomainService#isHolidaysEnabled() */ @Override public boolean isRescheduleRepaymentsOnHolidaysEnabled() { @@ -82,7 +85,8 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService @Override public boolean allowTransactionsOnNonWorkingDayEnabled() { final String allowTransactionsOnNonWorkingDayProperty = "allow-transactions-on-non_workingday"; - final GlobalConfigurationProperty property = this.globalConfigurationRepository.findOneByName(allowTransactionsOnNonWorkingDayProperty); + final GlobalConfigurationProperty property = this.globalConfigurationRepository + .findOneByName(allowTransactionsOnNonWorkingDayProperty); if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(allowTransactionsOnNonWorkingDayProperty); } return property.isEnabled(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/GlobalConfigurationProperty.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/GlobalConfigurationProperty.java index f40370be7..ad22aabad 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/GlobalConfigurationProperty.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/domain/GlobalConfigurationProperty.java @@ -30,7 +30,7 @@ public class GlobalConfigurationProperty extends AbstractPersistable { this.name = name; this.enabled = enabled; } - + public boolean isEnabled() { return this.enabled; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/serialization/GlobalConfigurationCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/serialization/GlobalConfigurationCommandFromApiJsonDeserializer.java index b45ba202a..bf946e701 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/serialization/GlobalConfigurationCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/serialization/GlobalConfigurationCommandFromApiJsonDeserializer.java @@ -47,8 +47,8 @@ public final class GlobalConfigurationCommandFromApiJsonDeserializer extends if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); - return fromApiJsonHelper.fromJson(json, UpdateGlobalConfigurationCommand.class); + return this.fromApiJsonHelper.fromJson(json, UpdateGlobalConfigurationCommand.class); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java index f2b3af82f..0e5ededec 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ConfigurationReadPlatformServiceImpl.java @@ -30,16 +30,16 @@ public class ConfigurationReadPlatformServiceImpl implements ConfigurationReadPl this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); - rm = new GlobalConfigurationRowMapper(); + this.rm = new GlobalConfigurationRowMapper(); } @Override public GlobalConfigurationData retrieveGlobalConfiguration() { - context.authenticatedUser(); + this.context.authenticatedUser(); final String sql = "SELECT c.name, c.enabled FROM c_configuration c order by c.id"; - final List globalConfiguration = this.jdbcTemplate.query(sql, rm, new Object[] {}); + final List globalConfiguration = this.jdbcTemplate.query(sql, this.rm, new Object[] {}); return new GlobalConfigurationData(globalConfiguration); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ExternalServicesReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ExternalServicesReadPlatformServiceImpl.java index e1f2ce2e1..254657bee 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ExternalServicesReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/ExternalServicesReadPlatformServiceImpl.java @@ -24,7 +24,7 @@ public class ExternalServicesReadPlatformServiceImpl implements ExternalServices private static final class S3CredentialsDataExtractor implements ResultSetExtractor { @Override - public S3CredentialsData extractData(ResultSet rs) throws SQLException, DataAccessException { + public S3CredentialsData extractData(final ResultSet rs) throws SQLException, DataAccessException { String accessKey = null; String bucketName = null; String secretKey = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java index 812a73e1c..8797373af 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/configuration/service/GlobalConfigurationWritePlatformServiceJpaRepositoryImpl.java @@ -30,7 +30,8 @@ public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements @Autowired public GlobalConfigurationWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, - final GlobalConfigurationRepository codeRepository, final GlobalConfigurationCommandFromApiJsonDeserializer fromApiJsonDeserializer) { + final GlobalConfigurationRepository codeRepository, + final GlobalConfigurationCommandFromApiJsonDeserializer fromApiJsonDeserializer) { this.context = context; this.repository = codeRepository; this.fromApiJsonDeserializer = fromApiJsonDeserializer; @@ -40,30 +41,30 @@ public class GlobalConfigurationWritePlatformServiceJpaRepositoryImpl implements @Override public CommandProcessingResult update(final JsonCommand command) { - context.authenticatedUser(); - + this.context.authenticatedUser(); + final UpdateGlobalConfigurationCommand configurationCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json()); - + final Map params = configurationCommand.getGlobalConfiguration(); - + final Map changes = new LinkedHashMap(params.size()); final Map propertiesMap = new LinkedHashMap(1); - for (String propertyName : params.keySet()) { + for (final String propertyName : params.keySet()) { final GlobalConfigurationProperty property = retrieveBy(propertyName); - - Boolean value = params.get(propertyName); - boolean updated = property.updateTo(value); - + + final Boolean value = params.get(propertyName); + final boolean updated = property.updateTo(value); + if (updated) { - propertiesMap.put(propertyName, value); + propertiesMap.put(propertyName, value); this.repository.save(property); } } - + if (!propertiesMap.isEmpty()) { changes.put("globalConfiguration", propertiesMap); } - + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).with(changes).build(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ApiParameterHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ApiParameterHelper.java index adec2c8f7..191abb7cf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ApiParameterHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ApiParameterHelper.java @@ -58,7 +58,7 @@ public class ApiParameterHelper { public static boolean prettyPrint(final MultivaluedMap queryParams) { boolean prettyPrint = false; if (queryParams.getFirst("pretty") != null) { - String prettyPrintValue = queryParams.getFirst("pretty"); + final String prettyPrintValue = queryParams.getFirst("pretty"); prettyPrint = "true".equalsIgnoreCase(prettyPrintValue); } return prettyPrint; @@ -67,7 +67,7 @@ public class ApiParameterHelper { public static Locale extractLocale(final MultivaluedMap queryParams) { Locale locale = null; if (queryParams.getFirst("locale") != null) { - String localeAsString = queryParams.getFirst("locale"); + final String localeAsString = queryParams.getFirst("locale"); locale = JsonParserHelper.localeFromString(localeAsString); } return locale; @@ -76,7 +76,7 @@ public class ApiParameterHelper { public static boolean exportCsv(final MultivaluedMap queryParams) { boolean exportCsv = false; if (queryParams.getFirst("exportCSV") != null) { - String exportCsvValue = queryParams.getFirst("exportCSV"); + final String exportCsvValue = queryParams.getFirst("exportCSV"); exportCsv = "true".equalsIgnoreCase(exportCsvValue); } return exportCsv; @@ -85,7 +85,7 @@ public class ApiParameterHelper { public static boolean exportPdf(final MultivaluedMap queryParams) { boolean exportPDF = false; if (queryParams.getFirst("exportPDF") != null) { - String exportPdfValue = queryParams.getFirst("exportPDF"); + final String exportPdfValue = queryParams.getFirst("exportPDF"); exportPDF = "true".equalsIgnoreCase(exportPdfValue); } return exportPDF; @@ -94,7 +94,7 @@ public class ApiParameterHelper { public static boolean parameterType(final MultivaluedMap queryParams) { boolean parameterType = false; if (queryParams.getFirst("parameterType") != null) { - String parameterTypeValue = queryParams.getFirst("parameterType"); + final String parameterTypeValue = queryParams.getFirst("parameterType"); parameterType = "true".equalsIgnoreCase(parameterTypeValue); } return parameterType; @@ -103,7 +103,7 @@ public class ApiParameterHelper { public static boolean template(final MultivaluedMap queryParams) { boolean template = false; if (queryParams.getFirst("template") != null) { - String prettyPrintValue = queryParams.getFirst("template"); + final String prettyPrintValue = queryParams.getFirst("template"); template = "true".equalsIgnoreCase(prettyPrintValue); } return template; @@ -112,7 +112,7 @@ public class ApiParameterHelper { public static boolean makerCheckerable(final MultivaluedMap queryParams) { boolean makerCheckerable = false; if (queryParams.getFirst("makerCheckerable") != null) { - String prettyPrintValue = queryParams.getFirst("makerCheckerable"); + final String prettyPrintValue = queryParams.getFirst("makerCheckerable"); makerCheckerable = "true".equalsIgnoreCase(prettyPrintValue); } return makerCheckerable; @@ -121,7 +121,7 @@ public class ApiParameterHelper { public static boolean includeJson(final MultivaluedMap queryParams) { boolean includeJson = false; if (queryParams.getFirst("includeJson") != null) { - String includeJsonValue = queryParams.getFirst("includeJson"); + final String includeJsonValue = queryParams.getFirst("includeJson"); includeJson = "true".equalsIgnoreCase(includeJsonValue); } return includeJson; @@ -130,28 +130,28 @@ public class ApiParameterHelper { public static boolean genericResultSet(final MultivaluedMap queryParams) { boolean genericResultSet = false; if (queryParams.getFirst("genericResultSet") != null) { - String genericResultSetValue = queryParams.getFirst("genericResultSet"); + final String genericResultSetValue = queryParams.getFirst("genericResultSet"); genericResultSet = "true".equalsIgnoreCase(genericResultSetValue); } return genericResultSet; } - public static boolean genericResultSetPassed(MultivaluedMap queryParams) { + public static boolean genericResultSetPassed(final MultivaluedMap queryParams) { return queryParams.getFirst("genericResultSet") != null; } - public static String sqlEncodeString(String str) { - String singleQuote = "'"; - String twoSingleQuotes = "''"; + public static String sqlEncodeString(final String str) { + final String singleQuote = "'"; + final String twoSingleQuotes = "''"; return singleQuote + StringUtils.replace(str, singleQuote, twoSingleQuotes, -1) + singleQuote; } - public static Map asMap(MultivaluedMap queryParameters) { + public static Map asMap(final MultivaluedMap queryParameters) { final Map map = new HashMap(queryParameters.size()); - for (String parameterName : queryParameters.keySet()) { - List values = queryParameters.get(parameterName); + for (final String parameterName : queryParameters.keySet()) { + final List values = queryParameters.get(parameterName); map.put(parameterName, values.get(0)); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ApiRequestParameterHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ApiRequestParameterHelper.java index b73492ee0..d92013a6e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ApiRequestParameterHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ApiRequestParameterHelper.java @@ -29,7 +29,7 @@ public class ApiRequestParameterHelper { public ApiRequestJsonSerializationSettings process(final MultivaluedMap queryParameters, final Set mandatoryResponseParameters) { - Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(queryParameters); + final Set responseParameters = ApiParameterHelper.extractFieldsForResponseIfProvided(queryParameters); if (!responseParameters.isEmpty()) { responseParameters.addAll(mandatoryResponseParameters); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/JsonCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/JsonCommand.java index cda3deb09..a76c15ad8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/JsonCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/JsonCommand.java @@ -26,7 +26,7 @@ import com.google.gson.JsonElement; /** * Immutable representation of a command. - * + * * Wraps the provided JSON with convenience functions for extracting parameter * values and checking for changes against an existing value. */ @@ -68,7 +68,8 @@ public final class JsonCommand { public JsonCommand(final Long commandId, final String jsonCommand, final JsonElement parsedCommand, final FromJsonHelper fromApiJsonHelper, final String entityName, final Long resourceId, final Long subresourceId, final Long groupId, final Long clientId, final Long loanId, final Long savingsId, final Long codeId, - final String supportedEntityType, final Long supportedEntityId, final String transactionId, final String url, final Long productId) { + final String supportedEntityType, final Long supportedEntityId, final String transactionId, final String url, + final Long productId) { this.commandId = commandId; this.jsonCommand = jsonCommand; this.parsedCommand = parsedCommand; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/JsonQuery.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/JsonQuery.java index 77393fb9e..643de4a16 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/JsonQuery.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/JsonQuery.java @@ -46,7 +46,7 @@ public final class JsonQuery { public String json() { return this.jsonQuery; } - + public JsonElement parsedJson() { return this.parsedQuery; } @@ -118,7 +118,7 @@ public final class JsonQuery { } private boolean parameterExists(final String parameterName) { - return this.fromApiJsonHelper.parameterExists(parameterName, parsedQuery); + return this.fromApiJsonHelper.parameterExists(parameterName, this.parsedQuery); } public boolean hasParameter(final String parameterName) { @@ -136,11 +136,11 @@ public final class JsonQuery { public Map mapValueOfParameterNamed(final String parameterName) { final Type typeOfMap = new TypeToken>() {}.getType(); - if (parsedQuery.getAsJsonObject().has(parameterName)) { - parsedQuery.getAsJsonObject().get(parameterName); + if (this.parsedQuery.getAsJsonObject().has(parameterName)) { + this.parsedQuery.getAsJsonObject().get(parameterName); } - return this.fromApiJsonHelper.extractMap(typeOfMap, jsonQuery); + return this.fromApiJsonHelper.extractMap(typeOfMap, this.jsonQuery); } public boolean isChangeInLongParameterNamed(final String parameterName, final Long existingValue) { @@ -153,7 +153,7 @@ public final class JsonQuery { } public Long longValueOfParameterNamed(final String parameterName) { - return this.fromApiJsonHelper.extractLongNamed(parameterName, parsedQuery); + return this.fromApiJsonHelper.extractLongNamed(parameterName, this.parsedQuery); } public boolean isChangeInLocalDateParameterNamed(final String parameterName, final LocalDate existingValue) { @@ -166,7 +166,7 @@ public final class JsonQuery { } public LocalDate localDateValueOfParameterNamed(final String parameterName) { - return this.fromApiJsonHelper.extractLocalDateNamed(parameterName, parsedQuery); + return this.fromApiJsonHelper.extractLocalDateNamed(parameterName, this.parsedQuery); } public boolean isChangeInStringParameterNamed(final String parameterName, final String existingValue) { @@ -179,7 +179,7 @@ public final class JsonQuery { } public String stringValueOfParameterNamed(final String parameterName) { - final String value = this.fromApiJsonHelper.extractStringNamed(parameterName, parsedQuery); + final String value = this.fromApiJsonHelper.extractStringNamed(parameterName, this.parsedQuery); return StringUtils.defaultIfEmpty(value, ""); } @@ -193,7 +193,7 @@ public final class JsonQuery { } public BigDecimal bigDecimalValueOfParameterNamed(final String parameterName) { - return this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(parameterName, parsedQuery); + return this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(parameterName, this.parsedQuery); } public boolean isChangeInIntegerParameterNamed(final String parameterName, final Integer existingValue) { @@ -206,7 +206,7 @@ public final class JsonQuery { } public Integer integerValueOfParameterNamed(final String parameterName) { - return this.fromApiJsonHelper.extractIntegerWithLocaleNamed(parameterName, parsedQuery); + return this.fromApiJsonHelper.extractIntegerWithLocaleNamed(parameterName, this.parsedQuery); } public boolean isChangeInBooleanParameterNamed(final String parameterName, final Boolean existingValue) { @@ -222,14 +222,14 @@ public final class JsonQuery { * Returns {@link Boolean} that could possibly be null. */ public Boolean booleanObjectValueOfParameterNamed(final String parameterName) { - return this.fromApiJsonHelper.extractBooleanNamed(parameterName, parsedQuery); + return this.fromApiJsonHelper.extractBooleanNamed(parameterName, this.parsedQuery); } /** * always returns true or false */ public boolean booleanPrimitiveValueOfParameterNamed(final String parameterName) { - final Boolean value = this.fromApiJsonHelper.extractBooleanNamed(parameterName, parsedQuery); + final Boolean value = this.fromApiJsonHelper.extractBooleanNamed(parameterName, this.parsedQuery); return (Boolean) ObjectUtils.defaultIfNull(value, Boolean.FALSE); } @@ -243,7 +243,7 @@ public final class JsonQuery { } public String[] arrayValueOfParameterNamed(final String parameterName) { - return this.fromApiJsonHelper.extractArrayNamed(parameterName, parsedQuery); + return this.fromApiJsonHelper.extractArrayNamed(parameterName, this.parsedQuery); } public boolean isChangeInPasswordParameterNamed(final String parameterName, final String existingValue, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ParameterListExclusionStrategy.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ParameterListExclusionStrategy.java index 931ff56ac..89840c095 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ParameterListExclusionStrategy.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/api/ParameterListExclusionStrategy.java @@ -23,13 +23,13 @@ public class ParameterListExclusionStrategy implements ExclusionStrategy { } @Override - public boolean shouldSkipField(FieldAttributes f) { - return parameterNamesToSkip.contains(f.getName()); + public boolean shouldSkipField(final FieldAttributes f) { + return this.parameterNamesToSkip.contains(f.getName()); } @SuppressWarnings("unused") @Override - public boolean shouldSkipClass(Class clazz) { + public boolean shouldSkipClass(final Class clazz) { return false; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiErrorMessageArg.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiErrorMessageArg.java index 74f7069ae..6a2943c85 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiErrorMessageArg.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiErrorMessageArg.java @@ -5,31 +5,30 @@ */ package org.mifosplatform.infrastructure.core.data; - public class ApiErrorMessageArg { - - /** - * The actual value of the parameter (if any) as passed to API. - */ - private Object value; - public static ApiErrorMessageArg from(Object object) { - return new ApiErrorMessageArg(object); - } - - protected ApiErrorMessageArg() { - // - } + /** + * The actual value of the parameter (if any) as passed to API. + */ + private Object value; - public ApiErrorMessageArg(Object object) { - this.value = object; - } + public static ApiErrorMessageArg from(final Object object) { + return new ApiErrorMessageArg(object); + } - public Object getValue() { - return value; - } + protected ApiErrorMessageArg() { + // + } - public void setValue(Object value) { - this.value = value; - } + public ApiErrorMessageArg(final Object object) { + this.value = object; + } + + public Object getValue() { + return this.value; + } + + public void setValue(final Object value) { + this.value = value; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiGlobalErrorResponse.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiGlobalErrorResponse.java index d88677fc3..faacb05e1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiGlobalErrorResponse.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiGlobalErrorResponse.java @@ -48,7 +48,7 @@ public class ApiGlobalErrorResponse { public static ApiGlobalErrorResponse unAuthenticated() { - ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); + final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("401"); globalErrorResponse.setDeveloperMessage("Invalid authentication details were passed in api request."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.not.authenticated"); @@ -59,7 +59,7 @@ public class ApiGlobalErrorResponse { public static ApiGlobalErrorResponse invalidTenantIdentifier() { - ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); + final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("401"); globalErrorResponse.setDeveloperMessage("Invalid tenant details were passed in api request."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.invalid.tenant.identifier"); @@ -69,14 +69,14 @@ public class ApiGlobalErrorResponse { } public static ApiGlobalErrorResponse unAuthorized(final String defaultUserMessage) { - ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); + final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("403"); globalErrorResponse .setDeveloperMessage("The user associated with credentials passed on this request does not have sufficient privileges to perform this action."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.not.authorized"); globalErrorResponse.setDefaultUserMessage("Insufficient privileges to perform this action."); - List errors = new ArrayList(); + final List errors = new ArrayList(); errors.add(ApiParameterError.generalError("error.msg.not.authorized", defaultUserMessage)); globalErrorResponse.setErrors(errors); @@ -85,13 +85,13 @@ public class ApiGlobalErrorResponse { public static ApiGlobalErrorResponse domainRuleViolation(final String globalisationMessageCode, final String defaultUserMessage, final Object... defaultUserMessageArgs) { - ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); + final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("403"); globalErrorResponse.setDeveloperMessage("Request was understood but caused a domain rule violation."); globalErrorResponse.setUserMessageGlobalisationCode("validation.msg.domain.rule.violation"); globalErrorResponse.setDefaultUserMessage("Errors contain reason for domain rule violation."); - List errors = new ArrayList(); + final List errors = new ArrayList(); errors.add(ApiParameterError.generalError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); @@ -101,13 +101,13 @@ public class ApiGlobalErrorResponse { public static ApiGlobalErrorResponse notFound(final String globalisationMessageCode, final String defaultUserMessage, final Object... defaultUserMessageArgs) { - ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); + final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("404"); globalErrorResponse.setDeveloperMessage("The requested resource is not available."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.resource.not.found"); globalErrorResponse.setDefaultUserMessage("The requested resource is not available."); - List errors = new ArrayList(); + final List errors = new ArrayList(); errors.add(ApiParameterError.resourceIdentifierNotFound(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); @@ -117,13 +117,13 @@ public class ApiGlobalErrorResponse { public static ApiGlobalErrorResponse dataIntegrityError(final String globalisationMessageCode, final String defaultUserMessage, final String parameterName, final Object... defaultUserMessageArgs) { - ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); + final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("403"); globalErrorResponse.setDeveloperMessage("The request caused a data integrity issue to be fired by the database."); globalErrorResponse.setUserMessageGlobalisationCode(globalisationMessageCode); globalErrorResponse.setDefaultUserMessage(defaultUserMessage); - List errors = new ArrayList(); + final List errors = new ArrayList(); errors.add(ApiParameterError.parameterError(globalisationMessageCode, defaultUserMessage, parameterName, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); @@ -133,7 +133,7 @@ public class ApiGlobalErrorResponse { public static ApiGlobalErrorResponse badClientRequest(final String globalisationMessageCode, final String defaultUserMessage, final List errors) { - ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); + final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("400"); globalErrorResponse .setDeveloperMessage("The request was invalid. This typically will happen due to validation errors which are provided."); @@ -148,29 +148,29 @@ public class ApiGlobalErrorResponse { public static ApiGlobalErrorResponse serverSideError(final String globalisationMessageCode, final String defaultUserMessage, final Object... defaultUserMessageArgs) { - ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); + final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("500"); globalErrorResponse.setDeveloperMessage("An unexpected error occured on the platform server."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.platform.server.side.error"); globalErrorResponse.setDefaultUserMessage("An unexpected error occured on the platform server."); - List errors = new ArrayList(); + final List errors = new ArrayList(); errors.add(ApiParameterError.generalError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); return globalErrorResponse; } - + public static ApiGlobalErrorResponse serviceUnavailable(final String globalisationMessageCode, final String defaultUserMessage, final Object... defaultUserMessageArgs) { - ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); + final ApiGlobalErrorResponse globalErrorResponse = new ApiGlobalErrorResponse(); globalErrorResponse.setHttpStatusCode("503"); globalErrorResponse.setDeveloperMessage("The server is currently unable to handle the request , please try after some time."); globalErrorResponse.setUserMessageGlobalisationCode("error.msg.platform.service.unavailable"); globalErrorResponse.setDefaultUserMessage("The server is currently unable to handle the request , please try after some time."); - List errors = new ArrayList(); + final List errors = new ArrayList(); errors.add(ApiParameterError.generalError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs)); globalErrorResponse.setErrors(errors); @@ -188,7 +188,7 @@ public class ApiGlobalErrorResponse { @XmlElementWrapper(name = "errors") @XmlElement(name = "errorResponse") public List getErrors() { - return errors; + return this.errors; } public void setErrors(final List errors) { @@ -196,7 +196,7 @@ public class ApiGlobalErrorResponse { } public String getDeveloperMessage() { - return developerMessage; + return this.developerMessage; } public void setDeveloperMessage(final String developerMessage) { @@ -204,7 +204,7 @@ public class ApiGlobalErrorResponse { } public String getHttpStatusCode() { - return httpStatusCode; + return this.httpStatusCode; } public void setHttpStatusCode(final String httpStatusCode) { @@ -212,7 +212,7 @@ public class ApiGlobalErrorResponse { } public String getDefaultUserMessage() { - return defaultUserMessage; + return this.defaultUserMessage; } public void setDefaultUserMessage(final String defaultUserMessage) { @@ -220,7 +220,7 @@ public class ApiGlobalErrorResponse { } public String getUserMessageGlobalisationCode() { - return userMessageGlobalisationCode; + return this.userMessageGlobalisationCode; } public void setUserMessageGlobalisationCode(final String userMessageGlobalisationCode) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiParameterError.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiParameterError.java index 2a90854e5..905043376 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiParameterError.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/ApiParameterError.java @@ -44,19 +44,19 @@ public class ApiParameterError { */ private List args = new ArrayList(); - public static ApiParameterError generalError(String globalisationMessageCode, String defaultUserMessage, - Object... defaultUserMessageArgs) { + public static ApiParameterError generalError(final String globalisationMessageCode, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { return new ApiParameterError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs); } - public static ApiParameterError resourceIdentifierNotFound(String globalisationMessageCode, String defaultUserMessage, - Object... defaultUserMessageArgs) { + public static ApiParameterError resourceIdentifierNotFound(final String globalisationMessageCode, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { return new ApiParameterError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs); } public static ApiParameterError parameterError(final String globalisationMessageCode, final String defaultUserMessage, final String parameterName, final Object... defaultUserMessageArgs) { - ApiParameterError error = new ApiParameterError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs); + final ApiParameterError error = new ApiParameterError(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs); error.setParameterName(parameterName); return error; } @@ -70,9 +70,9 @@ public class ApiParameterError { this.developerMessage = defaultUserMessage; this.defaultUserMessage = defaultUserMessage; - List messageArgs = new ArrayList(); + final List messageArgs = new ArrayList(); if (defaultUserMessageArgs != null) { - for (Object object : defaultUserMessageArgs) { + for (final Object object : defaultUserMessageArgs) { messageArgs.add(ApiErrorMessageArg.from(object)); } } @@ -82,50 +82,50 @@ public class ApiParameterError { } public String getDeveloperMessage() { - return developerMessage; + return this.developerMessage; } - public void setDeveloperMessage(String developerMessage) { + public void setDeveloperMessage(final String developerMessage) { this.developerMessage = developerMessage; } public String getDefaultUserMessage() { - return defaultUserMessage; + return this.defaultUserMessage; } - public void setDefaultUserMessage(String defaultUserMessage) { + public void setDefaultUserMessage(final String defaultUserMessage) { this.defaultUserMessage = defaultUserMessage; } public String getUserMessageGlobalisationCode() { - return userMessageGlobalisationCode; + return this.userMessageGlobalisationCode; } - public void setUserMessageGlobalisationCode(String userMessageGlobalisationCode) { + public void setUserMessageGlobalisationCode(final String userMessageGlobalisationCode) { this.userMessageGlobalisationCode = userMessageGlobalisationCode; } public String getParameterName() { - return parameterName; + return this.parameterName; } - public void setParameterName(String parameterName) { + public void setParameterName(final String parameterName) { this.parameterName = parameterName; } public Object getValue() { - return value; + return this.value; } - public void setValue(Object value) { + public void setValue(final Object value) { this.value = value; } public List getArgs() { - return args; + return this.args; } - public void setArgs(List args) { + public void setArgs(final List args) { this.args = args; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/CommandProcessingResultBuilder.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/CommandProcessingResultBuilder.java index dfa4b7937..6fc9bfda4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/CommandProcessingResultBuilder.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/CommandProcessingResultBuilder.java @@ -26,8 +26,8 @@ public class CommandProcessingResultBuilder { private Long productId; public CommandProcessingResult build() { - return CommandProcessingResult.fromDetails(commandId, officeId, groupId, clientId, loanId, savingsId, resourceIdentifier, entityId, - transactionId, changes, productId); + return CommandProcessingResult.fromDetails(this.commandId, this.officeId, this.groupId, this.clientId, this.loanId, this.savingsId, + this.resourceIdentifier, this.entityId, this.transactionId, this.changes, this.productId); } public CommandProcessingResultBuilder withCommandId(final Long withCommandId) { @@ -79,7 +79,7 @@ public class CommandProcessingResultBuilder { this.transactionId = withTransactionId; return this; } - + public CommandProcessingResultBuilder withProductId(final Long productId) { this.productId = productId; return this; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/DataValidatorBuilder.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/DataValidatorBuilder.java index 0e9c76e28..4768c1fe3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/DataValidatorBuilder.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/DataValidatorBuilder.java @@ -37,7 +37,7 @@ public class DataValidatorBuilder { } public DataValidatorBuilder reset() { - return new DataValidatorBuilder(dataValidationErrors).resource(resource); + return new DataValidatorBuilder(this.dataValidationErrors).resource(this.resource); } public DataValidatorBuilder resource(final String resource) { @@ -67,211 +67,215 @@ public class DataValidatorBuilder { } public DataValidatorBuilder andNotBlank(final String linkedParameterName, final String linkedValue) { - if (value == null && linkedValue == null && ignoreNullValue) { return this; } + if (this.value == null && linkedValue == null && this.ignoreNullValue) { return this; } if (StringUtils.isBlank(linkedValue)) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".") - .append(linkedParameterName).append(".cannot.be.empty.when.").append(parameter).append(".is.populated"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(linkedParameterName) - .append(" cannot be empty when ").append(parameter).append(" is populated."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - linkedParameterName, linkedValue, value); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(linkedParameterName).append(".cannot.be.empty.when.").append(this.parameter).append(".is.populated"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(linkedParameterName) + .append(" cannot be empty when ").append(this.parameter).append(" is populated."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), linkedParameterName, linkedValue, this.value); + this.dataValidationErrors.add(error); } return this; } public void failWithCode(final String errorCode) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(this.parameter) - .append(".").append(errorCode); - StringBuilder defaultEnglishMessage = new StringBuilder("Failed data validation due to: ").append(errorCode).append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".").append(errorCode); + final StringBuilder defaultEnglishMessage = new StringBuilder("Failed data validation due to: ").append(errorCode).append("."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, this.value); - dataValidationErrors.add(error); + this.dataValidationErrors.add(error); } public void failWithCodeNoParameterAddedToErrorCode(final String errorCode) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(errorCode); - StringBuilder defaultEnglishMessage = new StringBuilder("Failed data validation due to: ").append(errorCode).append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".").append(errorCode); + final StringBuilder defaultEnglishMessage = new StringBuilder("Failed data validation due to: ").append(errorCode).append("."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), this.parameter, this.value); - dataValidationErrors.add(error); + this.dataValidationErrors.add(error); } public DataValidatorBuilder equalToParameter(final String linkedParameterName, final Object linkedValue) { - if (value == null && linkedValue == null && ignoreNullValue) { return this; } + if (this.value == null && linkedValue == null && this.ignoreNullValue) { return this; } - if (value != null && !value.equals(linkedValue)) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".") - .append(linkedParameterName).append(".not.equal.to.").append(parameter); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(linkedParameterName) - .append(" is not equal to ").append(parameter).append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - linkedParameterName, linkedValue, value); - dataValidationErrors.add(error); + if (this.value != null && !this.value.equals(linkedValue)) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(linkedParameterName).append(".not.equal.to.").append(this.parameter); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(linkedParameterName) + .append(" is not equal to ").append(this.parameter).append("."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), linkedParameterName, linkedValue, this.value); + this.dataValidationErrors.add(error); } return this; } public DataValidatorBuilder notSameAsParameter(final String linkedParameterName, final Object linkedValue) { - if (value == null && linkedValue == null && ignoreNullValue) { return this; } + if (this.value == null && linkedValue == null && this.ignoreNullValue) { return this; } - if (value != null && value.equals(linkedValue)) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".") - .append(linkedParameterName).append(".same.as.").append(parameter); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(linkedParameterName).append(" is same as ") - .append(parameter).append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - linkedParameterName, linkedValue, value); - dataValidationErrors.add(error); + if (this.value != null && this.value.equals(linkedValue)) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(linkedParameterName).append(".same.as.").append(this.parameter); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(linkedParameterName) + .append(" is same as ").append(this.parameter).append("."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), linkedParameterName, linkedValue, this.value); + this.dataValidationErrors.add(error); } return this; } - /***FIXME: Vishwas, why does this method have a parameter? Seems wrong***/ + /*** FIXME: Vishwas, why does this method have a parameter? Seems wrong ***/ public DataValidatorBuilder trueOrFalseRequired(final boolean trueOfFalseFieldProvided) { - if (!trueOfFalseFieldProvided && !ignoreNullValue) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".must.be.true.or.false"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append( + if (!trueOfFalseFieldProvided && !this.ignoreNullValue) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".must.be.true.or.false"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( " must be set as true or false."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter); + this.dataValidationErrors.add(error); } return this; } public DataValidatorBuilder notNull() { - if (value == null && !ignoreNullValue) { + if (this.value == null && !this.ignoreNullValue) { String realParameterName = this.parameter; - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter); - if (this.arrayIndex != null && StringUtils.isNotBlank(arrayPart)) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter); + if (this.arrayIndex != null && StringUtils.isNotBlank(this.arrayPart)) { validationErrorCode.append(".").append(this.arrayPart); - realParameterName = new StringBuilder(parameter).append('[').append(this.arrayIndex).append("][").append(arrayPart) - .append(']').toString(); + realParameterName = new StringBuilder(this.parameter).append('[').append(this.arrayIndex).append("][") + .append(this.arrayPart).append(']').toString(); } validationErrorCode.append(".cannot.be.blank"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(realParameterName).append(" is mandatory."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - realParameterName, arrayIndex); - dataValidationErrors.add(error); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(realParameterName).append( + " is mandatory."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), realParameterName, this.arrayIndex); + this.dataValidationErrors.add(error); } return this; } public DataValidatorBuilder notBlank() { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value == null || StringUtils.isBlank(value.toString())) { + if (this.value == null || StringUtils.isBlank(this.value.toString())) { String realParameterName = this.parameter; - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter); - if (this.arrayIndex != null && StringUtils.isNotBlank(arrayPart)) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter); + if (this.arrayIndex != null && StringUtils.isNotBlank(this.arrayPart)) { validationErrorCode.append(".").append(this.arrayPart); - realParameterName = new StringBuilder(parameter).append('[').append(this.arrayIndex).append("][").append(arrayPart) - .append(']').toString(); + realParameterName = new StringBuilder(this.parameter).append('[').append(this.arrayIndex).append("][") + .append(this.arrayPart).append(']').toString(); } validationErrorCode.append(".cannot.be.blank"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(realParameterName).append(" is mandatory."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - realParameterName, arrayIndex); - dataValidationErrors.add(error); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(realParameterName).append( + " is mandatory."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), realParameterName, this.arrayIndex); + this.dataValidationErrors.add(error); } return this; } public DataValidatorBuilder notExceedingLengthOf(final Integer maxLength) { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null && value.toString().trim().length() > maxLength) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".exceeds.max.length"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append(" exceeds max length of ") - .append(maxLength).append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter, maxLength, value.toString()); - dataValidationErrors.add(error); + if (this.value != null && this.value.toString().trim().length() > maxLength) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".exceeds.max.length"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" exceeds max length of ").append(maxLength).append("."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, maxLength, this.value.toString()); + this.dataValidationErrors.add(error); } return this; } public DataValidatorBuilder inMinMaxRange(final Integer min, final Integer max) { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null) { - Integer number = Integer.valueOf(value.toString()); + if (this.value != null) { + final Integer number = Integer.valueOf(this.value.toString()); if (number < min || number > max) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.not.within.expected.range"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append(" must be between ") - .append(min).append(" and ").append(max).append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, number, min, max); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.not.within.expected.range"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be between ").append(min).append(" and ").append(max).append("."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, number, min, max); + this.dataValidationErrors.add(error); } } return this; } public DataValidatorBuilder isOneOfTheseValues(final Object... values) { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - List valuesList = Arrays.asList(values); - String valuesListStr = StringUtils.join(valuesList, ", "); + final List valuesList = Arrays.asList(values); + final String valuesListStr = StringUtils.join(valuesList, ", "); if (this.value == null || !valuesList.contains(this.value)) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.not.one.of.expected.enumerations"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append(" must be one of [ ") - .append(valuesListStr).append(" ] ").append("."); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.not.one.of.expected.enumerations"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be one of [ ").append(valuesListStr).append(" ] ").append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter, this.value, values); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, this.value, values); - dataValidationErrors.add(error); + this.dataValidationErrors.add(error); } return this; } public DataValidatorBuilder isNotOneOfTheseValues(final Object... values) { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null) { - List valuesList = Arrays.asList(values); - String valuesListStr = StringUtils.join(valuesList, ", "); + if (this.value != null) { + final List valuesList = Arrays.asList(values); + final String valuesListStr = StringUtils.join(valuesList, ", "); if (valuesList.contains(this.value)) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.one.of.unwanted.enumerations"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter) + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.one.of.unwanted.enumerations"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) .append(" must not be any of [ ").append(valuesListStr).append(" ] ").append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, this.value, values); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, this.value, values); - dataValidationErrors.add(error); + this.dataValidationErrors.add(error); } } return this; } public DataValidatorBuilder positiveAmount() { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null) { - BigDecimal number = BigDecimal.valueOf(Double.valueOf(value.toString())); + if (this.value != null) { + final BigDecimal number = BigDecimal.valueOf(Double.valueOf(this.value.toString())); if (number.compareTo(BigDecimal.ZERO) <= 0) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".not.greater.than.zero"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append( + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".not.greater.than.zero"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( " must be greater than 0."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, number, 0); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, number, 0); + this.dataValidationErrors.add(error); } } return this; @@ -281,18 +285,18 @@ public class DataValidatorBuilder { * should be used with .notNull() before it */ public DataValidatorBuilder zeroOrPositiveAmount() { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null) { - BigDecimal number = BigDecimal.valueOf(Double.valueOf(value.toString())); + if (this.value != null) { + final BigDecimal number = BigDecimal.valueOf(Double.valueOf(this.value.toString())); if (number.compareTo(BigDecimal.ZERO) < 0) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".not.zero.or.greater"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append( + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".not.zero.or.greater"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( " must be greater than or equal to 0."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, number, 0); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, number, 0); + this.dataValidationErrors.add(error); } } return this; @@ -302,18 +306,18 @@ public class DataValidatorBuilder { * should be used with .notNull() before it */ public DataValidatorBuilder integerZeroOrGreater() { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null) { - Integer number = Integer.valueOf(value.toString()); + if (this.value != null) { + final Integer number = Integer.valueOf(this.value.toString()); if (number < 0) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".not.zero.or.greater"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append( + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".not.zero.or.greater"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( " must be zero or greater."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, number, 0); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, number, 0); + this.dataValidationErrors.add(error); } } return this; @@ -323,18 +327,18 @@ public class DataValidatorBuilder { * should be used with .notNull() before it */ public DataValidatorBuilder integerGreaterThanZero() { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null) { - Integer number = Integer.valueOf(value.toString()); + if (this.value != null) { + final Integer number = Integer.valueOf(this.value.toString()); if (number < 1) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".not.greater.than.zero"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append( + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".not.greater.than.zero"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( " must be greater than 0."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, number, 0); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, number, 0); + this.dataValidationErrors.add(error); } } return this; @@ -344,67 +348,67 @@ public class DataValidatorBuilder { * should be used with .notNull() before it */ public DataValidatorBuilder longGreaterThanZero() { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null) { - Long number = Long.valueOf(value.toString()); + if (this.value != null) { + final Long number = Long.valueOf(this.value.toString()); if (number < 1) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".not.greater.than.zero"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append( + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".not.greater.than.zero"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( " must be greater than 0."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, number, 0); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, number, 0); + this.dataValidationErrors.add(error); } } return this; } public DataValidatorBuilder arrayNotEmpty() { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - Object[] array = (Object[]) value; + final Object[] array = (Object[]) this.value; if (ObjectUtils.isEmpty(array)) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".cannot.be.empty"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append( + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".cannot.be.empty"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( " cannot be empty. You must select at least one."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter); + this.dataValidationErrors.add(error); } return this; } public DataValidatorBuilder jsonArrayNotEmpty() { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - JsonArray array = (JsonArray) value; - if (value != null && !array.iterator().hasNext()) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".cannot.be.empty"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append( + final JsonArray array = (JsonArray) this.value; + if (this.value != null && !array.iterator().hasNext()) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".cannot.be.empty"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( " cannot be empty. You must select at least one."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter); + this.dataValidationErrors.add(error); } return this; } public void expectedArrayButIsNot() { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.not.an.array"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append(" is not an array."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.not.an.array"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append(" is not an array."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), + this.parameter); + this.dataValidationErrors.add(error); } public DataValidatorBuilder anyOfNotNull(final Object... object) { boolean hasData = false; - for (Object obj : object) { + for (final Object obj : object) { if (obj != null) { hasData = true; break; @@ -412,100 +416,105 @@ public class DataValidatorBuilder { } if (!hasData) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".no.parameters.for.update"); - StringBuilder defaultEnglishMessage = new StringBuilder("No parameters passed for update."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - "id"); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append( + ".no.parameters.for.update"); + final StringBuilder defaultEnglishMessage = new StringBuilder("No parameters passed for update."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), "id"); + this.dataValidationErrors.add(error); } return this; } public DataValidatorBuilder inValidValue(final String parameterValueCode, final Object invalidValue) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".invalid.").append(parameterValueCode); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append(" has an invalid value."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter, invalidValue); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".invalid.").append(parameterValueCode); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( + " has an invalid value."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), + this.parameter, invalidValue); + this.dataValidationErrors.add(error); return this; } public DataValidatorBuilder mustBeBlankWhenParameterProvided(final String parameterName, final Object parameterValue) { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value == null && parameterValue != null) { return this; } + if (this.value == null && parameterValue != null) { return this; } - if (value != null && StringUtils.isBlank(value.toString()) && parameterValue != null + if (this.value != null && StringUtils.isBlank(this.value.toString()) && parameterValue != null && StringUtils.isNotBlank(parameterValue.toString())) { return this; } - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".cannot.also.be.provided.when.").append(parameterName).append(".is.populated"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter) + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".cannot.also.be.provided.when.").append(parameterName).append(".is.populated"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) .append(" cannot also be provided when ").append(parameterName).append(" is populated."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter, value, parameterName, parameterValue); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), + this.parameter, this.value, parameterName, parameterValue); + this.dataValidationErrors.add(error); return this; } public DataValidatorBuilder mustBeBlankWhenParameterProvidedIs(final String parameterName, final Object parameterValue) { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value == null && parameterValue != null) { return this; } + if (this.value == null && parameterValue != null) { return this; } - if (value != null && StringUtils.isBlank(value.toString()) && parameterValue != null + if (this.value != null && StringUtils.isBlank(this.value.toString()) && parameterValue != null && StringUtils.isNotBlank(parameterValue.toString())) { return this; } - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".cannot.also.be.provided.when.").append(parameterName).append(".is.").append(parameterValue); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter) + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".cannot.also.be.provided.when.").append(parameterName).append(".is.") + .append(parameterValue); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) .append(" cannot also be provided when ").append(parameterName).append(" is ").append(parameterValue); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter, value, parameterName, parameterValue); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), + this.parameter, this.value, parameterName, parameterValue); + this.dataValidationErrors.add(error); return this; } public DataValidatorBuilder cantBeBlankWhenParameterProvidedIs(final String parameterName, final Object parameterValue) { - if (value != null && StringUtils.isNotBlank(value.toString())) { return this; } + if (this.value != null && StringUtils.isNotBlank(this.value.toString())) { return this; } - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".must.be.provided.when.").append(parameterName).append(".is.").append(parameterValue); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append(" must be provided when ") - .append(parameterName).append(" is ").append(parameterValue); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter, value, parameterName, parameterValue); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".must.be.provided.when.").append(parameterName).append(".is.").append(parameterValue); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) + .append(" must be provided when ").append(parameterName).append(" is ").append(parameterValue); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), + this.parameter, this.value, parameterName, parameterValue); + this.dataValidationErrors.add(error); return this; } public DataValidatorBuilder comapareMinimumAndMaximumAmounts(final BigDecimal minimumBalance, final BigDecimal maximumBalance) { - if (minimumBalance != null && maximumBalance != null) + if (minimumBalance != null && maximumBalance != null) { if (maximumBalance.compareTo(minimumBalance) == -1) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.not.within.expected.range"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(" minimum amount ").append(minimumBalance) - .append(" should less than maximum amount ").append(maximumBalance).append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, minimumBalance, maximumBalance); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.not.within.expected.range"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(" minimum amount ") + .append(minimumBalance).append(" should less than maximum amount ").append(maximumBalance).append("."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, minimumBalance, maximumBalance); + this.dataValidationErrors.add(error); return this; } + } return this; } public DataValidatorBuilder inMinAndMaxAmountRange(final BigDecimal minimumAmount, final BigDecimal maximumAmount) { - if (minimumAmount != null && maximumAmount != null && value != null) { - BigDecimal amount = BigDecimal.valueOf(Double.valueOf(value.toString())); + if (minimumAmount != null && maximumAmount != null && this.value != null) { + final BigDecimal amount = BigDecimal.valueOf(Double.valueOf(this.value.toString())); if (amount.compareTo(minimumAmount) == -1 || amount.compareTo(maximumAmount) == 1) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".amount.is.not.within.min.max.range"); - StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(parameter).append(" amount ").append(amount) - .append(" must be between ").append(minimumAmount).append(" and ").append(maximumAmount).append(" ."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, amount, minimumAmount, maximumAmount); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".amount.is.not.within.min.max.range"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(this.parameter).append(" amount ") + .append(amount).append(" must be between ").append(minimumAmount).append(" and ").append(maximumAmount) + .append(" ."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, amount, minimumAmount, maximumAmount); + this.dataValidationErrors.add(error); return this; } } @@ -513,16 +522,16 @@ public class DataValidatorBuilder { } public DataValidatorBuilder notLessThanMin(final BigDecimal min) { - if (min != null && value != null) { - BigDecimal amount = BigDecimal.valueOf(Double.valueOf(value.toString())); + if (min != null && this.value != null) { + final BigDecimal amount = BigDecimal.valueOf(Double.valueOf(this.value.toString())); if (amount.compareTo(min) == -1) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.less.than.min"); - StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(parameter).append(" value ").append(amount) - .append(" must not be less than minimum value ").append(min); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, amount, min); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.less.than.min"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(this.parameter).append(" value ") + .append(amount).append(" must not be less than minimum value ").append(min); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, amount, min); + this.dataValidationErrors.add(error); return this; } } @@ -530,16 +539,16 @@ public class DataValidatorBuilder { } public DataValidatorBuilder notGreaterThanMax(final BigDecimal max) { - if (max != null && value != null) { - BigDecimal amount = BigDecimal.valueOf(Double.valueOf(value.toString())); + if (max != null && this.value != null) { + final BigDecimal amount = BigDecimal.valueOf(Double.valueOf(this.value.toString())); if (amount.compareTo(max) == 1) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.greater.than.max"); - StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(parameter).append(" value ").append(amount) - .append(" must not be more than maximum value ").append(max); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, amount, max); - dataValidationErrors.add(error); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.greater.than.max"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(this.parameter).append(" value ") + .append(amount).append(" must not be more than maximum value ").append(max); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, amount, max); + this.dataValidationErrors.add(error); return this; } } @@ -547,34 +556,35 @@ public class DataValidatorBuilder { } public DataValidatorBuilder comapareMinAndMaxOfTwoBigDecmimalNos(final BigDecimal min, final BigDecimal max) { - if (min != null && max != null) + if (min != null && max != null) { if (max.compareTo(min) == -1) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.not.within.expected.range"); - StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(" min number ").append(min) + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.not.within.expected.range"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(" min number ").append(min) .append(" should less than max number ").append(max).append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, min, max); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, min, max); + this.dataValidationErrors.add(error); return this; } + } return this; } public DataValidatorBuilder isValidRecurringRule(final String recurringRule) { if (StringUtils.isNotBlank(recurringRule)) { try { - RRule rRule = new RRule(recurringRule); + final RRule rRule = new RRule(recurringRule); rRule.validate(); - } catch (ValidationException e) { - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.recurring.rule", - "The Recurring Rule value: " + recurringRule + " is not valid.", parameter, recurringRule); - dataValidationErrors.add(error); + } catch (final ValidationException e) { + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.recurring.rule", + "The Recurring Rule value: " + recurringRule + " is not valid.", this.parameter, recurringRule); + this.dataValidationErrors.add(error); return this; - } catch (ParseException e) { - ApiParameterError error = ApiParameterError.parameterError("validation.msg.recurring.rule.parsing.error", - "Error in pasring the Recurring Rule value: " + recurringRule + ".", parameter, recurringRule); - dataValidationErrors.add(error); + } catch (final ParseException e) { + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.recurring.rule.parsing.error", + "Error in pasring the Recurring Rule value: " + recurringRule + ".", this.parameter, recurringRule); + this.dataValidationErrors.add(error); return this; } } @@ -582,54 +592,54 @@ public class DataValidatorBuilder { } public DataValidatorBuilder notLessThanMin(final Integer min) { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null && min != null) { - Integer number = Integer.valueOf(value.toString()); + if (this.value != null && min != null) { + final Integer number = Integer.valueOf(this.value.toString()); if (number < min) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.less.than.min"); - StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(parameter) + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.less.than.min"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(this.parameter) .append(" must be greater than minimum value ").append(min); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, number, min); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, number, min); + this.dataValidationErrors.add(error); } } return this; } public DataValidatorBuilder notGreaterThanMax(final Integer max) { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null && max != null) { - Integer number = Integer.valueOf(value.toString()); + if (this.value != null && max != null) { + final Integer number = Integer.valueOf(this.value.toString()); if (number > max) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".is.greater.than.max"); - StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(parameter) + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".is.greater.than.max"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The ").append(this.parameter) .append(" must be less than maximum value ").append(max); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, number, max); - dataValidationErrors.add(error); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, number, max); + this.dataValidationErrors.add(error); } } return this; } public DataValidatorBuilder matchesRegularExpression(final String expression) { - if (value == null && ignoreNullValue) { return this; } + if (this.value == null && this.ignoreNullValue) { return this; } - if (value != null && !value.toString().matches(expression)) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".does.not.match.regexp"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter) + if (this.value != null && !this.value.toString().matches(expression)) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".does.not.match.regexp"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter) .append(" must match the provided regular expression [ ").append(expression).append(" ] ").append("."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameter, this.value, expression); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), this.parameter, this.value, expression); - dataValidationErrors.add(error); + this.dataValidationErrors.add(error); } return this; @@ -669,9 +679,9 @@ public class DataValidatorBuilder { * the beginning and can contain whitespaces in between and length * allowed is 0-25 chars. */ - String regex = "^\\+?[0-9. ()-]{0,25}$"; - Pattern pattern = Pattern.compile(regex); - Matcher matcher = pattern.matcher(this.value.toString()); + final String regex = "^\\+?[0-9. ()-]{0,25}$"; + final Pattern pattern = Pattern.compile(regex); + final Matcher matcher = pattern.matcher(this.value.toString()); if (matcher.matches()) { validationErr = false; } @@ -688,14 +698,14 @@ public class DataValidatorBuilder { } public DataValidatorBuilder validateCronExpression() { - if (value != null && !CronExpression.isValidExpression(this.value.toString().trim())) { - final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(resource).append(".").append(parameter) - .append(".invalid"); - final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameter).append( + if (this.value != null && !CronExpression.isValidExpression(this.value.toString().trim())) { + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.").append(this.resource).append(".") + .append(this.parameter).append(".invalid"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(this.parameter).append( " value is not a valid cron expression"); final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), - defaultEnglishMessage.toString(), parameter, this.value); - dataValidationErrors.add(error); + defaultEnglishMessage.toString(), this.parameter, this.value); + this.dataValidationErrors.add(error); } return this; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/EnumOptionData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/EnumOptionData.java index 1f39ee0d2..f169603cd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/EnumOptionData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/data/EnumOptionData.java @@ -24,10 +24,10 @@ public class EnumOptionData { } public Long getId() { - return id; + return this.id; } public String getCode() { - return code; + return this.code; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/AbstractAuditableCustom.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/AbstractAuditableCustom.java index 14fb5b79e..a029c9fc7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/AbstractAuditableCustom.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/AbstractAuditableCustom.java @@ -21,13 +21,16 @@ import org.springframework.data.jpa.domain.AbstractAuditable; import org.springframework.data.jpa.domain.AbstractPersistable; /** - * A custom copy of {@link AbstractAuditable} to override the column names used on database. + * A custom copy of {@link AbstractAuditable} to override the column names used + * on database. * * Abstract base class for auditable entities. Stores the audition values in * persistent fields. * - * @param the auditing type. Typically some kind of user. - * @param the type of the auditing type's identifier + * @param + * the auditing type. Typically some kind of user. + * @param + * the type of the auditing type's identifier */ @MappedSuperclass public abstract class AbstractAuditableCustom extends AbstractPersistable implements Auditable { @@ -35,26 +38,26 @@ public abstract class AbstractAuditableCustom extend private static final long serialVersionUID = 141481953116476081L; @OneToOne - @JoinColumn(name="createdby_id") - private U createdBy; + @JoinColumn(name = "createdby_id") + private U createdBy; - @Column(name="created_date") + @Column(name = "created_date") @Temporal(TemporalType.TIMESTAMP) - private Date createdDate; + private Date createdDate; @OneToOne - @JoinColumn(name="lastmodifiedby_id") - private U lastModifiedBy; + @JoinColumn(name = "lastmodifiedby_id") + private U lastModifiedBy; - @Column(name="lastmodified_date") + @Column(name = "lastmodified_date") @Temporal(TemporalType.TIMESTAMP) - private Date lastModifiedDate; + private Date lastModifiedDate; - /* - * (non-Javadoc) - * - * @see org.springframework.data.domain.Auditable#getCreatedBy() - */ + /* + * (non-Javadoc) + * + * @see org.springframework.data.domain.Auditable#getCreatedBy() + */ @Override public U getCreatedBy() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/AuditorAwareImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/AuditorAwareImpl.java index 5486cfad0..293e90b09 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/AuditorAwareImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/AuditorAwareImpl.java @@ -22,16 +22,16 @@ public class AuditorAwareImpl implements AuditorAware { public AppUser getCurrentAuditor() { AppUser currentUser = null; - SecurityContext securityContext = SecurityContextHolder.getContext(); + final SecurityContext securityContext = SecurityContextHolder.getContext(); if (securityContext != null) { - Authentication authentication = securityContext.getAuthentication(); + final Authentication authentication = securityContext.getAuthentication(); if (authentication != null) { currentUser = (AppUser) authentication.getPrincipal(); } else { - currentUser = this.retrieveSuperUser(); + currentUser = retrieveSuperUser(); } } else { - currentUser = this.retrieveSuperUser(); + currentUser = retrieveSuperUser(); } return currentUser; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/Base64EncodedImage.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/Base64EncodedImage.java index c2a161a78..5f8f25695 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/Base64EncodedImage.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/Base64EncodedImage.java @@ -10,16 +10,16 @@ public class Base64EncodedImage { private final String base64EncodedString; private final String fileExtension; - public Base64EncodedImage(String base64EncodedString, String fileExtension) { + public Base64EncodedImage(final String base64EncodedString, final String fileExtension) { this.base64EncodedString = base64EncodedString; this.fileExtension = fileExtension; } public String getBase64EncodedString() { - return base64EncodedString; + return this.base64EncodedString; } public String getFileExtension() { - return fileExtension; + return this.fileExtension; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/EmailDetail.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/EmailDetail.java index 962002e46..fd7e0a72c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/EmailDetail.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/EmailDetail.java @@ -7,31 +7,31 @@ package org.mifosplatform.infrastructure.core.domain; public class EmailDetail { - private final String organisationName; - private final String username; - private final String contactName; - private final String address; + private final String organisationName; + private final String username; + private final String contactName; + private final String address; - public EmailDetail(String organisationName, String contactName, String address, String username) { - this.organisationName = organisationName; - this.contactName = contactName; - this.address = address; - this.username = username; - } + public EmailDetail(final String organisationName, final String contactName, final String address, final String username) { + this.organisationName = organisationName; + this.contactName = contactName; + this.address = address; + this.username = username; + } - public String getOrganisationName() { - return this.organisationName; - } + public String getOrganisationName() { + return this.organisationName; + } - public String getUsername() { - return this.username; - } + public String getUsername() { + return this.username; + } - public String getContactName() { - return this.contactName; - } + public String getContactName() { + return this.contactName; + } - public String getAddress() { - return this.address; - } + public String getAddress() { + return this.address; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/JdbcSupport.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/JdbcSupport.java index 45d59db3e..dc5ae9378 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/JdbcSupport.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/JdbcSupport.java @@ -23,7 +23,7 @@ public class JdbcSupport { public static DateTime getDateTime(final ResultSet rs, final String columnName) throws SQLException { DateTime dateTime = null; - Timestamp dateValue = rs.getTimestamp(columnName); + final Timestamp dateValue = rs.getTimestamp(columnName); if (dateValue != null) { dateTime = new DateTime(dateValue.getTime()); } @@ -48,7 +48,7 @@ public class JdbcSupport { } public static Integer getIntegerDefaultToNullIfZero(final ResultSet rs, final String columnName) throws SQLException { - Integer value = (Integer) JdbcUtils.getResultSetValue(rs, rs.findColumn(columnName), Integer.class); + final Integer value = (Integer) JdbcUtils.getResultSetValue(rs, rs.findColumn(columnName), Integer.class); return defaultToNullIfZero(value); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/Tenant.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/Tenant.java index 79c8c3189..ab275fcbd 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/Tenant.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/domain/Tenant.java @@ -15,10 +15,9 @@ public class Tenant { private final String schemaUsername; private final String schemaPassword; private final String timezoneId; - - public Tenant(final Long id, final String name, final String schemaName, final String schemaServer, - final String schemaServerPort, final String schemaUsername, final String schemaPassword, String timezoneId) { + public Tenant(final Long id, final String name, final String schemaName, final String schemaServer, final String schemaServerPort, + final String schemaUsername, final String schemaPassword, final String timezoneId) { this.id = id; this.name = name; this.schemaName = schemaName; @@ -27,39 +26,39 @@ public class Tenant { this.schemaUsername = schemaUsername; this.schemaPassword = schemaPassword; this.timezoneId = timezoneId; - + } public Long getId() { - return id; + return this.id; } public String getName() { - return name; + return this.name; } public String getSchemaName() { - return schemaName; + return this.schemaName; } public String getSchemaServer() { - return schemaServer; + return this.schemaServer; } public String getSchemaServerPort() { - return schemaServerPort; + return this.schemaServerPort; } public String getSchemaUsername() { - return schemaUsername; + return this.schemaUsername; } public String getSchemaPassword() { - return schemaPassword; + return this.schemaPassword; } - + public String getTimezoneId() { - return timezoneId; + return this.timezoneId; } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformDomainRuleException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformDomainRuleException.java index 0277831cf..94060d928 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformDomainRuleException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformDomainRuleException.java @@ -15,21 +15,22 @@ public abstract class AbstractPlatformDomainRuleException extends RuntimeExcepti private final String defaultUserMessage; private final Object[] defaultUserMessageArgs; - public AbstractPlatformDomainRuleException(final String globalisationMessageCode, final String defaultUserMessage, final Object... defaultUserMessageArgs) { + public AbstractPlatformDomainRuleException(final String globalisationMessageCode, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { this.globalisationMessageCode = globalisationMessageCode; this.defaultUserMessage = defaultUserMessage; this.defaultUserMessageArgs = defaultUserMessageArgs; } public String getGlobalisationMessageCode() { - return globalisationMessageCode; + return this.globalisationMessageCode; } public String getDefaultUserMessage() { - return defaultUserMessage; + return this.defaultUserMessage; } public Object[] getDefaultUserMessageArgs() { - return defaultUserMessageArgs; + return this.defaultUserMessageArgs; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformResourceNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformResourceNotFoundException.java index 8d6707be1..cf6f835cf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformResourceNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformResourceNotFoundException.java @@ -23,14 +23,14 @@ public abstract class AbstractPlatformResourceNotFoundException extends RuntimeE } public String getGlobalisationMessageCode() { - return globalisationMessageCode; + return this.globalisationMessageCode; } public String getDefaultUserMessage() { - return defaultUserMessage; + return this.defaultUserMessage; } public Object[] getDefaultUserMessageArgs() { - return defaultUserMessageArgs; + return this.defaultUserMessageArgs; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformServiceUnavailableException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformServiceUnavailableException.java index 784674f70..1e665ae3c 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformServiceUnavailableException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/AbstractPlatformServiceUnavailableException.java @@ -23,14 +23,14 @@ public abstract class AbstractPlatformServiceUnavailableException extends Runtim } public String getGlobalisationMessageCode() { - return globalisationMessageCode; + return this.globalisationMessageCode; } public String getDefaultUserMessage() { - return defaultUserMessage; + return this.defaultUserMessage; } public Object[] getDefaultUserMessageArgs() { - return defaultUserMessageArgs; + return this.defaultUserMessageArgs; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformApiDataValidationException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformApiDataValidationException.java index 7eecc0f81..f165663ff 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformApiDataValidationException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformApiDataValidationException.java @@ -32,14 +32,14 @@ public class PlatformApiDataValidationException extends RuntimeException { } public String getGlobalisationMessageCode() { - return globalisationMessageCode; + return this.globalisationMessageCode; } public String getDefaultUserMessage() { - return defaultUserMessage; + return this.defaultUserMessage; } public List getErrors() { - return errors; + return this.errors; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformDataIntegrityException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformDataIntegrityException.java index 07c25bfbd..a187fd0b7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformDataIntegrityException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformDataIntegrityException.java @@ -33,18 +33,18 @@ public class PlatformDataIntegrityException extends RuntimeException { } public String getGlobalisationMessageCode() { - return globalisationMessageCode; + return this.globalisationMessageCode; } public String getDefaultUserMessage() { - return defaultUserMessage; + return this.defaultUserMessage; } public Object[] getDefaultUserMessageArgs() { - return defaultUserMessageArgs; + return this.defaultUserMessageArgs; } public String getParameterName() { - return parameterName; + return this.parameterName; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformInternalServerException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformInternalServerException.java index e706fc6b8..20e20e3a5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformInternalServerException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformInternalServerException.java @@ -14,21 +14,22 @@ public class PlatformInternalServerException extends RuntimeException { private final String defaultUserMessage; private final Object[] defaultUserMessageArgs; - public PlatformInternalServerException(String globalisationMessageCode, String defaultUserMessage, Object... defaultUserMessageArgs) { + public PlatformInternalServerException(final String globalisationMessageCode, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { this.globalisationMessageCode = globalisationMessageCode; this.defaultUserMessage = defaultUserMessage; this.defaultUserMessageArgs = defaultUserMessageArgs; } public String getGlobalisationMessageCode() { - return globalisationMessageCode; + return this.globalisationMessageCode; } public String getDefaultUserMessage() { - return defaultUserMessage; + return this.defaultUserMessage; } public Object[] getDefaultUserMessageArgs() { - return defaultUserMessageArgs; + return this.defaultUserMessageArgs; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformServiceUnavailableException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformServiceUnavailableException.java index 6fd03f5e3..3cff11dd2 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformServiceUnavailableException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/PlatformServiceUnavailableException.java @@ -2,10 +2,9 @@ package org.mifosplatform.infrastructure.core.exception; public class PlatformServiceUnavailableException extends AbstractPlatformServiceUnavailableException { - public PlatformServiceUnavailableException(String globalisationMessageCode, String defaultUserMessage, - Object... defaultUserMessageArgs) { + public PlatformServiceUnavailableException(final String globalisationMessageCode, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs); } - } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/UnrecognizedQueryParamException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/UnrecognizedQueryParamException.java index 56122c3c2..12f86f9b8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/UnrecognizedQueryParamException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/UnrecognizedQueryParamException.java @@ -18,11 +18,11 @@ public class UnrecognizedQueryParamException extends RuntimeException { } public String getQueryParamKey() { - return queryParamKey; + return this.queryParamKey; } public String getQueryParamValue() { - return queryParamValue; + return this.queryParamValue; } public Object[] getSupportedParams() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/UnsupportedParameterException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/UnsupportedParameterException.java index 5f52911a6..0019d3fc9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/UnsupportedParameterException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exception/UnsupportedParameterException.java @@ -15,11 +15,11 @@ public class UnsupportedParameterException extends RuntimeException { private final List unsupportedParameters; - public UnsupportedParameterException(List unsupportedParameters) { + public UnsupportedParameterException(final List unsupportedParameters) { this.unsupportedParameters = unsupportedParameters; } public List getUnsupportedParameters() { - return unsupportedParameters; + return this.unsupportedParameters; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/BadCredentialsExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/BadCredentialsExceptionMapper.java index 3f019d708..2e76ed088 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/BadCredentialsExceptionMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/BadCredentialsExceptionMapper.java @@ -30,7 +30,7 @@ import org.springframework.stereotype.Component; public class BadCredentialsExceptionMapper implements ExceptionMapper { @Override - public Response toResponse(@SuppressWarnings("unused") BadCredentialsException exception) { + public Response toResponse(@SuppressWarnings("unused") final BadCredentialsException exception) { return Response.status(Status.UNAUTHORIZED).entity(ApiGlobalErrorResponse.unAuthenticated()).type(MediaType.APPLICATION_JSON) .build(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/InvalidJsonExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/InvalidJsonExceptionMapper.java index 51bb400ec..b47081ee6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/InvalidJsonExceptionMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/InvalidJsonExceptionMapper.java @@ -28,10 +28,10 @@ public class InvalidJsonExceptionMapper implements ExceptionMapper { @Override - public Response toResponse(PlatformDataIntegrityException exception) { + public Response toResponse(final PlatformDataIntegrityException exception) { - ApiGlobalErrorResponse dataIntegrityError = ApiGlobalErrorResponse.dataIntegrityError(exception.getGlobalisationMessageCode(), - exception.getDefaultUserMessage(), exception.getParameterName(), exception.getDefaultUserMessageArgs()); + final ApiGlobalErrorResponse dataIntegrityError = ApiGlobalErrorResponse.dataIntegrityError( + exception.getGlobalisationMessageCode(), exception.getDefaultUserMessage(), exception.getParameterName(), + exception.getDefaultUserMessageArgs()); return Response.status(Status.FORBIDDEN).entity(dataIntegrityError).type(MediaType.APPLICATION_JSON).build(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformDomainRuleExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformDomainRuleExceptionMapper.java index a1c0a1c3f..3c779b823 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformDomainRuleExceptionMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformDomainRuleExceptionMapper.java @@ -29,10 +29,10 @@ import org.springframework.stereotype.Component; public class PlatformDomainRuleExceptionMapper implements ExceptionMapper { @Override - public Response toResponse(AbstractPlatformDomainRuleException exception) { + public Response toResponse(final AbstractPlatformDomainRuleException exception) { - ApiGlobalErrorResponse notFoundErrorResponse = ApiGlobalErrorResponse.domainRuleViolation(exception.getGlobalisationMessageCode(), - exception.getDefaultUserMessage(), exception.getDefaultUserMessageArgs()); + final ApiGlobalErrorResponse notFoundErrorResponse = ApiGlobalErrorResponse.domainRuleViolation( + exception.getGlobalisationMessageCode(), exception.getDefaultUserMessage(), exception.getDefaultUserMessageArgs()); // request understood but not carried out due to it violating some // domain/business logic return Response.status(Status.FORBIDDEN).entity(notFoundErrorResponse).type(MediaType.APPLICATION_JSON).build(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformInternalServerExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformInternalServerExceptionMapper.java index e0131fffe..6b854e894 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformInternalServerExceptionMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformInternalServerExceptionMapper.java @@ -29,9 +29,9 @@ import org.springframework.stereotype.Component; public class PlatformInternalServerExceptionMapper implements ExceptionMapper { @Override - public Response toResponse(PlatformInternalServerException exception) { + public Response toResponse(final PlatformInternalServerException exception) { - ApiGlobalErrorResponse notFoundErrorResponse = ApiGlobalErrorResponse.notFound(exception.getGlobalisationMessageCode(), + final ApiGlobalErrorResponse notFoundErrorResponse = ApiGlobalErrorResponse.notFound(exception.getGlobalisationMessageCode(), exception.getDefaultUserMessage(), exception.getDefaultUserMessageArgs()); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(notFoundErrorResponse).type(MediaType.APPLICATION_JSON).build(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformResourceNotFoundExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformResourceNotFoundExceptionMapper.java index 8373238bf..9ffe3e6ee 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformResourceNotFoundExceptionMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformResourceNotFoundExceptionMapper.java @@ -30,9 +30,9 @@ import org.springframework.stereotype.Component; public class PlatformResourceNotFoundExceptionMapper implements ExceptionMapper { @Override - public Response toResponse(AbstractPlatformResourceNotFoundException exception) { + public Response toResponse(final AbstractPlatformResourceNotFoundException exception) { - ApiGlobalErrorResponse notFoundErrorResponse = ApiGlobalErrorResponse.notFound(exception.getGlobalisationMessageCode(), + final ApiGlobalErrorResponse notFoundErrorResponse = ApiGlobalErrorResponse.notFound(exception.getGlobalisationMessageCode(), exception.getDefaultUserMessage(), exception.getDefaultUserMessageArgs()); return Response.status(Status.NOT_FOUND).entity(notFoundErrorResponse).type(MediaType.APPLICATION_JSON).build(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformServiceUnavailableExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformServiceUnavailableExceptionMapper.java index be0040db0..03b140021 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformServiceUnavailableExceptionMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/PlatformServiceUnavailableExceptionMapper.java @@ -26,8 +26,8 @@ import org.springframework.stereotype.Component; public class PlatformServiceUnavailableExceptionMapper implements ExceptionMapper { @Override - public Response toResponse(AbstractPlatformServiceUnavailableException exception) { - ApiGlobalErrorResponse serviceUnavailableExceptionResponse = ApiGlobalErrorResponse.serviceUnavailable( + public Response toResponse(final AbstractPlatformServiceUnavailableException exception) { + final ApiGlobalErrorResponse serviceUnavailableExceptionResponse = ApiGlobalErrorResponse.serviceUnavailable( exception.getGlobalisationMessageCode(), exception.getDefaultUserMessage(), exception.getDefaultUserMessageArgs()); return Response.status(Status.SERVICE_UNAVAILABLE).entity(serviceUnavailableExceptionResponse).type(MediaType.APPLICATION_JSON) .build(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnAuthenticatedUserExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnAuthenticatedUserExceptionMapper.java index e3465565a..5a0519cb7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnAuthenticatedUserExceptionMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnAuthenticatedUserExceptionMapper.java @@ -26,7 +26,7 @@ import org.springframework.stereotype.Component; public class UnAuthenticatedUserExceptionMapper implements ExceptionMapper { @Override - public Response toResponse(@SuppressWarnings("unused") UnAuthenticatedUserException exception) { + public Response toResponse(@SuppressWarnings("unused") final UnAuthenticatedUserException exception) { // Status code 401 really reads as: "Unauthenticated": return Response.status(Status.UNAUTHORIZED).entity(ApiGlobalErrorResponse.unAuthenticated()).type(MediaType.APPLICATION_JSON) .build(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnsupportedCommandExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnsupportedCommandExceptionMapper.java index 760017e82..d7ce4cc7b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnsupportedCommandExceptionMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnsupportedCommandExceptionMapper.java @@ -32,18 +32,18 @@ public class UnsupportedCommandExceptionMapper implements ExceptionMapper errors = new ArrayList(); + final List errors = new ArrayList(); - StringBuilder validationErrorCode = new StringBuilder("error.msg.command.unsupported"); - StringBuilder defaultEnglishMessage = new StringBuilder("The command ").append(exception.getUnsupportedCommandName()).append( + final StringBuilder validationErrorCode = new StringBuilder("error.msg.command.unsupported"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The command ").append(exception.getUnsupportedCommandName()).append( " is not supported."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), + final 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); + final 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(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnsupportedParameterExceptionMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnsupportedParameterExceptionMapper.java index d37057200..b4bf54d33 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnsupportedParameterExceptionMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/exceptionmapper/UnsupportedParameterExceptionMapper.java @@ -32,19 +32,20 @@ public class UnsupportedParameterExceptionMapper implements ExceptionMapper errors = new ArrayList(); + final List errors = new ArrayList(); - for (String parameterName : exception.getUnsupportedParameters()) { - StringBuilder validationErrorCode = new StringBuilder("error.msg.parameter.unsupported"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameterName).append(" is not supported."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - parameterName, parameterName); + for (final String parameterName : exception.getUnsupportedParameters()) { + final StringBuilder validationErrorCode = new StringBuilder("error.msg.parameter.unsupported"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter ").append(parameterName).append( + " is not supported."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), parameterName, parameterName); errors.add(error); } - ApiGlobalErrorResponse invalidParameterError = ApiGlobalErrorResponse.badClientRequest("validation.msg.validation.errors.exist", - "Validation errors exist.", errors); + final 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(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/filters/ResponseCorsFilter.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/filters/ResponseCorsFilter.java index 4adf82c55..c8dc9b234 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/filters/ResponseCorsFilter.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/filters/ResponseCorsFilter.java @@ -19,15 +19,15 @@ import com.sun.jersey.spi.container.ContainerResponseFilter; public class ResponseCorsFilter implements ContainerResponseFilter { @Override - public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { + public ContainerResponse filter(final ContainerRequest request, final ContainerResponse response) { - ResponseBuilder resp = Response.fromResponse(response.getResponse()); + final ResponseBuilder resp = Response.fromResponse(response.getResponse()); resp.header("Access-Control-Allow-Origin", "*") // .header("Access-Control-Expose-Headers", "X-Mifos-Platform-TenantId") .header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); - String reqHead = request.getHeaderValue("Access-Control-Request-Headers"); + final String reqHead = request.getHeaderValue("Access-Control-Request-Headers"); if (null != reqHead && !reqHead.equals(null)) { resp.header("Access-Control-Allow-Headers", reqHead); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandProcessingResultJsonSerializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandProcessingResultJsonSerializer.java index 094edcf25..985046ce2 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandProcessingResultJsonSerializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandProcessingResultJsonSerializer.java @@ -17,9 +17,14 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** - *

A google gson implementation of {@link ExcludeNothingJsonSerializer} contract.

+ *

+ * A google gson implementation of {@link ExcludeNothingJsonSerializer} + * contract. + *

* - *

It serializes all fields of any Java {@link Object} passed to it.

+ *

+ * It serializes all fields of any Java {@link Object} passed to it. + *

*/ @Component public final class CommandProcessingResultJsonSerializer { @@ -27,12 +32,12 @@ public final class CommandProcessingResultJsonSerializer { private final Gson gson; public CommandProcessingResultJsonSerializer() { - GsonBuilder builder = new GsonBuilder(); + final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(LocalDate.class, new JodaLocalDateAdapter()); builder.registerTypeAdapter(DateTime.class, new JodaDateTimeAdapter()); builder.registerTypeAdapter(MonthDay.class, new JodaMonthDayAdapter()); builder.serializeNulls(); - + this.gson = builder.create(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandSerializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandSerializer.java index 015ba02ac..c8a2c919c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandSerializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandSerializer.java @@ -5,7 +5,6 @@ */ package org.mifosplatform.infrastructure.core.serialization; - /** * Service for serializing commands into another format. * diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandSerializerDefaultToJson.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandSerializerDefaultToJson.java index 0c7e3a564..2b5f38645 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandSerializerDefaultToJson.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/CommandSerializerDefaultToJson.java @@ -9,8 +9,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** - * Implementation of {@link CommandSerializer} that serializes - * the commands into JSON using google-gson. + * Implementation of {@link CommandSerializer} that serializes the commands into + * JSON using google-gson. */ @Component public class CommandSerializerDefaultToJson implements CommandSerializer { @@ -18,12 +18,13 @@ public class CommandSerializerDefaultToJson implements CommandSerializer { private final ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson excludeNothingWithPrettyPrintingOff; @Autowired - public CommandSerializerDefaultToJson(final ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson excludeNothingWithPrettyPrintingOff) { + public CommandSerializerDefaultToJson( + final ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson excludeNothingWithPrettyPrintingOff) { this.excludeNothingWithPrettyPrintingOff = excludeNothingWithPrettyPrintingOff; } @Override - public String serializeCommandToJson(Object command) { - return excludeNothingWithPrettyPrintingOff.serialize(command); + public String serializeCommandToJson(final Object command) { + return this.excludeNothingWithPrettyPrintingOff.serialize(command); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/DatatableCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/DatatableCommandFromApiJsonDeserializer.java index 1236bd6f7..510222fdd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/DatatableCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/DatatableCommandFromApiJsonDeserializer.java @@ -29,25 +29,25 @@ import com.google.gson.reflect.TypeToken; @Component public class DatatableCommandFromApiJsonDeserializer { - private final static String DATATABLE_NAME_REGEX_PATTERN = "^[a-zA-Z][a-zA-Z0-9\\-_\\s]{0,48}[a-zA-Z0-9]$"; - private final static String DATATABLE_COLUMN_NAME_REGEX_PATTERN = "^[a-zA-Z][a-zA-Z0-9\\-_\\s]{0,}[a-zA-Z0-9]$"; - /** + private final static String DATATABLE_NAME_REGEX_PATTERN = "^[a-zA-Z][a-zA-Z0-9\\-_\\s]{0,48}[a-zA-Z0-9]$"; + private final static String DATATABLE_COLUMN_NAME_REGEX_PATTERN = "^[a-zA-Z][a-zA-Z0-9\\-_\\s]{0,}[a-zA-Z0-9]$"; + /** * The parameters supported for this command. */ - private final Set supportedParametersForCreate = new HashSet(Arrays.asList( - "datatableName", "apptableName", "multiRow", "columns")); - private final Set supportedParametersForCreateColumns = new HashSet(Arrays.asList( - "name", "type", "length", "mandatory", "code")); - private final Set supportedParametersForUpdate = new HashSet(Arrays.asList( - "apptableName", "changeColumns", "addColumns", "dropColumns")); - private final Set supportedParametersForAddColumns = new HashSet(Arrays.asList( - "name", "type", "length", "mandatory", "after", "code")); - private final Set supportedParametersForChangeColumns = new HashSet(Arrays.asList( - "name", "newName", "length", "mandatory", "after", "code", "newCode")); - private final Set supportedParametersForDropColumns = new HashSet(Arrays.asList( - "name")); + private final Set supportedParametersForCreate = new HashSet(Arrays.asList("datatableName", "apptableName", "multiRow", + "columns")); + private final Set supportedParametersForCreateColumns = new HashSet(Arrays.asList("name", "type", "length", + "mandatory", "code")); + private final Set supportedParametersForUpdate = new HashSet(Arrays.asList("apptableName", "changeColumns", + "addColumns", "dropColumns")); + private final Set supportedParametersForAddColumns = new HashSet(Arrays.asList("name", "type", "length", "mandatory", + "after", "code")); + private final Set supportedParametersForChangeColumns = new HashSet(Arrays.asList("name", "newName", "length", + "mandatory", "after", "code", "newCode")); + private final Set supportedParametersForDropColumns = new HashSet(Arrays.asList("name")); private final Object[] supportedColumnTypes = { "String", "Number", "Decimal", "Date", "Text", "Dropdown" }; - private final Object[] supportedApptableNames = { "m_loan", "m_savings_account", "m_client", "m_group", "m_center", "m_office", "m_savings_product", "m_product_loan" }; + private final Object[] supportedApptableNames = { "m_loan", "m_savings_account", "m_client", "m_group", "m_center", "m_office", + "m_savings_product", "m_product_loan" }; private final FromJsonHelper fromApiJsonHelper; @@ -57,84 +57,79 @@ public class DatatableCommandFromApiJsonDeserializer { } private void validateType(final DataValidatorBuilder baseDataValidator, final JsonElement column) { - final String type = fromApiJsonHelper.extractStringNamed("type", column); - baseDataValidator.reset().parameter("type").value(type).notBlank() - .isOneOfTheseValues(supportedColumnTypes); + final String type = this.fromApiJsonHelper.extractStringNamed("type", column); + baseDataValidator.reset().parameter("type").value(type).notBlank().isOneOfTheseValues(this.supportedColumnTypes); - if (type != null && type.equals("String")) { - if (fromApiJsonHelper.parameterExists("length", column)) { - final String lengthStr = fromApiJsonHelper.extractStringNamed("length", column); - if (lengthStr != null && !StringUtils.isWhitespace(lengthStr) - && StringUtils.isNumeric(lengthStr) && StringUtils.isNotBlank(lengthStr)) { - Integer length = Integer.parseInt(lengthStr); - baseDataValidator.reset().parameter("length").value(length).positiveAmount(); - } else if (StringUtils.isBlank(lengthStr) || StringUtils.isWhitespace(lengthStr)) { - baseDataValidator.reset().parameter("length").failWithCode("must.be.provided.when.type.is.String"); - } else if (!StringUtils.isNumeric(lengthStr)) { - baseDataValidator.reset().parameter("length").failWithCode("not.greater.than.zero"); - } - } else { - baseDataValidator.reset().parameter("length").failWithCode("must.be.provided.when.type.is.String"); - } - } else { - baseDataValidator.reset().parameter("length").mustBeBlankWhenParameterProvidedIs("type", type); - } - - final String code = fromApiJsonHelper.extractStringNamed("code", column); - if (type != null && type.equals("Dropdown")) { - if (code != null) { - baseDataValidator.reset().parameter("code").value(code).notBlank() - .matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN); - } else { - baseDataValidator.reset().parameter("code").value(code) - .cantBeBlankWhenParameterProvidedIs("type", type); - } - } else { - baseDataValidator.reset().parameter("code").value(code).mustBeBlankWhenParameterProvided("type", type); - } + if (type != null && type.equals("String")) { + if (this.fromApiJsonHelper.parameterExists("length", column)) { + final String lengthStr = this.fromApiJsonHelper.extractStringNamed("length", column); + if (lengthStr != null && !StringUtils.isWhitespace(lengthStr) && StringUtils.isNumeric(lengthStr) + && StringUtils.isNotBlank(lengthStr)) { + final Integer length = Integer.parseInt(lengthStr); + baseDataValidator.reset().parameter("length").value(length).positiveAmount(); + } else if (StringUtils.isBlank(lengthStr) || StringUtils.isWhitespace(lengthStr)) { + baseDataValidator.reset().parameter("length").failWithCode("must.be.provided.when.type.is.String"); + } else if (!StringUtils.isNumeric(lengthStr)) { + baseDataValidator.reset().parameter("length").failWithCode("not.greater.than.zero"); + } + } else { + baseDataValidator.reset().parameter("length").failWithCode("must.be.provided.when.type.is.String"); + } + } else { + baseDataValidator.reset().parameter("length").mustBeBlankWhenParameterProvidedIs("type", type); + } + + final String code = this.fromApiJsonHelper.extractStringNamed("code", column); + if (type != null && type.equals("Dropdown")) { + if (code != null) { + baseDataValidator.reset().parameter("code").value(code).notBlank().matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN); + } else { + baseDataValidator.reset().parameter("code").value(code).cantBeBlankWhenParameterProvidedIs("type", type); + } + } else { + baseDataValidator.reset().parameter("code").value(code).mustBeBlankWhenParameterProvided("type", type); + } } public void validateForCreate(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParametersForCreate); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForCreate); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable"); - final JsonElement element = fromApiJsonHelper.parse(json); - - final String datatableName = fromApiJsonHelper.extractStringNamed("datatableName", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + + final String datatableName = this.fromApiJsonHelper.extractStringNamed("datatableName", element); baseDataValidator.reset().parameter("datatableName").value(datatableName).notBlank().notExceedingLengthOf(50) - .matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN); - - final String apptableName = fromApiJsonHelper.extractStringNamed("apptableName", element); + .matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN); + + final String apptableName = this.fromApiJsonHelper.extractStringNamed("apptableName", element); baseDataValidator.reset().parameter("apptableName").value(apptableName).notBlank().notExceedingLengthOf(50) - .isOneOfTheseValues(supportedApptableNames); + .isOneOfTheseValues(this.supportedApptableNames); final String fkColumnName = (apptableName != null) ? apptableName.substring(2) + "_id" : ""; - final Boolean multiRow = fromApiJsonHelper.extractBooleanNamed("multiRow", element); - baseDataValidator.reset().parameter("multiRow").value(multiRow).ignoreIfNull().notBlank() - .isOneOfTheseValues(true, false); + final Boolean multiRow = this.fromApiJsonHelper.extractBooleanNamed("multiRow", element); + baseDataValidator.reset().parameter("multiRow").value(multiRow).ignoreIfNull().notBlank().isOneOfTheseValues(true, false); - final JsonArray columns = fromApiJsonHelper.extractJsonArrayNamed("columns", element); + final JsonArray columns = this.fromApiJsonHelper.extractJsonArrayNamed("columns", element); baseDataValidator.reset().parameter("columns").value(columns).notNull().jsonArrayNotEmpty(); if (columns != null) { - for (JsonElement column : columns) { - fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), supportedParametersForCreateColumns); + for (final JsonElement column : columns) { + this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), this.supportedParametersForCreateColumns); - final String name = fromApiJsonHelper.extractStringNamed("name", column); - baseDataValidator.reset().parameter("name").value(name).notBlank() - .isNotOneOfTheseValues("id", fkColumnName).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); + final String name = this.fromApiJsonHelper.extractStringNamed("name", column); + baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName) + .matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); - validateType(baseDataValidator, column); + validateType(baseDataValidator, column); - final Boolean mandatory = fromApiJsonHelper.extractBooleanNamed("mandatory", column); - baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank() - .isOneOfTheseValues(true, false); - } + final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column); + baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false); + } } throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -142,110 +137,102 @@ public class DatatableCommandFromApiJsonDeserializer { public void validateForUpdate(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - // Because all parameters are optional, a check to see if at least one parameter - // has been specified is necessary in order to avoid JSON requests with no parameters - if (!json.matches("(?s)\\A\\{.*?(\\\".*?\\\"\\s*?:\\s*?)+.*?\\}\\z")) { - throw new PlatformDataIntegrityException("error.msg.invalid.request.body.no.parameters", - "Provided JSON request body does not have any parameters."); - } + // Because all parameters are optional, a check to see if at least one + // parameter + // has been specified is necessary in order to avoid JSON requests with + // no parameters + if (!json.matches("(?s)\\A\\{.*?(\\\".*?\\\"\\s*?:\\s*?)+.*?\\}\\z")) { throw new PlatformDataIntegrityException( + "error.msg.invalid.request.body.no.parameters", "Provided JSON request body does not have any parameters."); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParametersForUpdate); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParametersForUpdate); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable"); - final JsonElement element = fromApiJsonHelper.parse(json); - final String apptableName = fromApiJsonHelper.extractStringNamed("apptableName", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final String apptableName = this.fromApiJsonHelper.extractStringNamed("apptableName", element); baseDataValidator.reset().parameter("apptableName").value(apptableName).ignoreIfNull().notBlank() - .isOneOfTheseValues(supportedApptableNames); + .isOneOfTheseValues(this.supportedApptableNames); final String fkColumnName = (apptableName != null) ? apptableName.substring(2) + "_id" : ""; - final JsonArray changeColumns = fromApiJsonHelper.extractJsonArrayNamed("changeColumns", element); + final JsonArray changeColumns = this.fromApiJsonHelper.extractJsonArrayNamed("changeColumns", element); baseDataValidator.reset().parameter("changeColumns").value(changeColumns).ignoreIfNull().jsonArrayNotEmpty(); if (changeColumns != null) { - for (JsonElement column : changeColumns) { - fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), supportedParametersForChangeColumns); + for (final JsonElement column : changeColumns) { + this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), this.supportedParametersForChangeColumns); - final String name = fromApiJsonHelper.extractStringNamed("name", column); - baseDataValidator.reset().parameter("name").value(name).notBlank() - .isNotOneOfTheseValues("id", fkColumnName).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); + final String name = this.fromApiJsonHelper.extractStringNamed("name", column); + baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName) + .matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); - final String newName = fromApiJsonHelper.extractStringNamed("newName", column); - baseDataValidator.reset().parameter("newName").value(newName).ignoreIfNull().notBlank() - .notExceedingLengthOf(50).isNotOneOfTheseValues("id", fkColumnName) - .matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN); + final String newName = this.fromApiJsonHelper.extractStringNamed("newName", column); + baseDataValidator.reset().parameter("newName").value(newName).ignoreIfNull().notBlank().notExceedingLengthOf(50) + .isNotOneOfTheseValues("id", fkColumnName).matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN); - if (fromApiJsonHelper.parameterExists("length", column)) { - final String lengthStr = fromApiJsonHelper.extractStringNamed("length", column); - if (StringUtils.isWhitespace(lengthStr) || !StringUtils.isNumeric(lengthStr) - || StringUtils.isBlank(lengthStr)) { - baseDataValidator.reset().parameter("length").failWithCode("not.greater.than.zero"); - } else { - Integer length = Integer.parseInt(lengthStr); - baseDataValidator.reset().parameter("length").value(length).ignoreIfNull().notBlank() - .positiveAmount(); - } - } + if (this.fromApiJsonHelper.parameterExists("length", column)) { + final String lengthStr = this.fromApiJsonHelper.extractStringNamed("length", column); + if (StringUtils.isWhitespace(lengthStr) || !StringUtils.isNumeric(lengthStr) || StringUtils.isBlank(lengthStr)) { + baseDataValidator.reset().parameter("length").failWithCode("not.greater.than.zero"); + } else { + final Integer length = Integer.parseInt(lengthStr); + baseDataValidator.reset().parameter("length").value(length).ignoreIfNull().notBlank().positiveAmount(); + } + } - final String code = fromApiJsonHelper.extractStringNamed("code", column); - baseDataValidator.reset().parameter("code").value(code).ignoreIfNull().notBlank() - .notExceedingLengthOf(100).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); + final String code = this.fromApiJsonHelper.extractStringNamed("code", column); + baseDataValidator.reset().parameter("code").value(code).ignoreIfNull().notBlank().notExceedingLengthOf(100) + .matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); - final String newCode = fromApiJsonHelper.extractStringNamed("newCode", column); - baseDataValidator.reset().parameter("newCode").value(newCode).ignoreIfNull().notBlank() - .notExceedingLengthOf(100).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); + final String newCode = this.fromApiJsonHelper.extractStringNamed("newCode", column); + baseDataValidator.reset().parameter("newCode").value(newCode).ignoreIfNull().notBlank().notExceedingLengthOf(100) + .matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); - if (StringUtils.isBlank(code) && StringUtils.isNotBlank(newCode)) { - baseDataValidator.reset().parameter("code").value(code) - .cantBeBlankWhenParameterProvidedIs("newCode", newCode); - } + if (StringUtils.isBlank(code) && StringUtils.isNotBlank(newCode)) { + baseDataValidator.reset().parameter("code").value(code).cantBeBlankWhenParameterProvidedIs("newCode", newCode); + } - final Boolean mandatory = fromApiJsonHelper.extractBooleanNamed("mandatory", column); - baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank() - .isOneOfTheseValues(true, false); + final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column); + baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false); - final Boolean after = fromApiJsonHelper.extractBooleanNamed("after", column); - baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank() - .isOneOfTheseValues(true, false); - } + final Boolean after = this.fromApiJsonHelper.extractBooleanNamed("after", column); + baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false); + } } - final JsonArray addColumns = fromApiJsonHelper.extractJsonArrayNamed("addColumns", element); + final JsonArray addColumns = this.fromApiJsonHelper.extractJsonArrayNamed("addColumns", element); baseDataValidator.reset().parameter("addColumns").value(addColumns).ignoreIfNull().jsonArrayNotEmpty(); if (addColumns != null) { - for (JsonElement column : addColumns) { - fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), supportedParametersForAddColumns); + for (final JsonElement column : addColumns) { + this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), this.supportedParametersForAddColumns); - final String name = fromApiJsonHelper.extractStringNamed("name", column); - baseDataValidator.reset().parameter("name").value(name).notBlank() - .isNotOneOfTheseValues("id", fkColumnName).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); + final String name = this.fromApiJsonHelper.extractStringNamed("name", column); + baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName) + .matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); - validateType(baseDataValidator, column); + validateType(baseDataValidator, column); - final Boolean mandatory = fromApiJsonHelper.extractBooleanNamed("mandatory", column); - baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank() - .isOneOfTheseValues(true, false); + final Boolean mandatory = this.fromApiJsonHelper.extractBooleanNamed("mandatory", column); + baseDataValidator.reset().parameter("mandatory").value(mandatory).ignoreIfNull().notBlank().isOneOfTheseValues(true, false); - final Boolean after = fromApiJsonHelper.extractBooleanNamed("after", column); - baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank() - .isOneOfTheseValues(true, false); - } + final Boolean after = this.fromApiJsonHelper.extractBooleanNamed("after", column); + baseDataValidator.reset().parameter("after").value(after).ignoreIfNull().notBlank().isOneOfTheseValues(true, false); + } } - final JsonArray dropColumns = fromApiJsonHelper.extractJsonArrayNamed("dropColumns", element); + final JsonArray dropColumns = this.fromApiJsonHelper.extractJsonArrayNamed("dropColumns", element); baseDataValidator.reset().parameter("dropColumns").value(dropColumns).ignoreIfNull().jsonArrayNotEmpty(); - if (dropColumns != null) { - for (JsonElement column : dropColumns) { - fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), supportedParametersForDropColumns); + if (dropColumns != null) { + for (final JsonElement column : dropColumns) { + this.fromApiJsonHelper.checkForUnsupportedParameters(column.getAsJsonObject(), this.supportedParametersForDropColumns); - final String name = fromApiJsonHelper.extractStringNamed("name", column); - baseDataValidator.reset().parameter("name").value(name).notBlank() - .isNotOneOfTheseValues("id", fkColumnName).matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); - } + final String name = this.fromApiJsonHelper.extractStringNamed("name", column); + baseDataValidator.reset().parameter("name").value(name).notBlank().isNotOneOfTheseValues("id", fkColumnName) + .matchesRegularExpression(DATATABLE_COLUMN_NAME_REGEX_PATTERN); + } } throwExceptionIfValidationWarningsExist(dataValidationErrors); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/DefaultToApiJsonSerializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/DefaultToApiJsonSerializer.java index ae77e6deb..23bc6b38a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/DefaultToApiJsonSerializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/DefaultToApiJsonSerializer.java @@ -30,14 +30,13 @@ public final class DefaultToApiJsonSerializer implements ToApiJsonSerializer< public DefaultToApiJsonSerializer( final ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson excludeNothingWithPrettyPrintingOff, final ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson excludeNothingWithPrettyPrintingOn, - final CommandProcessingResultJsonSerializer commandProcessingResultSerializer, - final GoogleGsonSerializerHelper helper) { + final CommandProcessingResultJsonSerializer commandProcessingResultSerializer, final GoogleGsonSerializerHelper helper) { this.excludeNothingWithPrettyPrintingOff = excludeNothingWithPrettyPrintingOff; this.excludeNothingWithPrettyPrintingOn = excludeNothingWithPrettyPrintingOn; this.commandProcessingResultSerializer = commandProcessingResultSerializer; this.helper = helper; } - + @Override public String serializeResult(final Object object) { return this.commandProcessingResultSerializer.serialize(object); @@ -47,11 +46,11 @@ public final class DefaultToApiJsonSerializer implements ToApiJsonSerializer< public String serialize(final Object object) { return this.excludeNothingWithPrettyPrintingOff.serialize(object); } - + @Override - public String serializePretty(boolean prettyOn, final Object object) { + public String serializePretty(final boolean prettyOn, final Object object) { String json = ""; - + if (prettyOn) { json = this.excludeNothingWithPrettyPrintingOn.serialize(object); } else { @@ -75,15 +74,16 @@ public final class DefaultToApiJsonSerializer implements ToApiJsonSerializer< } @Override - public String serialize(ApiRequestJsonSerializationSettings settings, Page singleObject, Set supportedResponseParameters) { + public String serialize(final ApiRequestJsonSerializationSettings settings, final Page singleObject, + final Set supportedResponseParameters) { final Gson delegatedSerializer = findAppropriateSerializer(settings, supportedResponseParameters); return serializeWithSettings(delegatedSerializer, settings, singleObject); } - + private String serializeWithSettings(final Gson gson, final ApiRequestJsonSerializationSettings settings, final Object[] dataObject) { String json = null; if (gson != null) { - json = helper.serializedJsonFrom(gson, dataObject); + json = this.helper.serializedJsonFrom(gson, dataObject); } else { if (settings.isPrettyPrint()) { json = this.excludeNothingWithPrettyPrintingOn.serialize(dataObject); @@ -93,11 +93,11 @@ public final class DefaultToApiJsonSerializer implements ToApiJsonSerializer< } return json; } - + private String serializeWithSettings(final Gson gson, final ApiRequestJsonSerializationSettings settings, final Object dataObject) { String json = null; if (gson != null) { - json = helper.serializedJsonFrom(gson, dataObject); + json = this.helper.serializedJsonFrom(gson, dataObject); } else { if (settings.isPrettyPrint()) { json = this.excludeNothingWithPrettyPrintingOn.serialize(dataObject); @@ -111,7 +111,7 @@ public final class DefaultToApiJsonSerializer implements ToApiJsonSerializer< private Gson findAppropriateSerializer(final ApiRequestJsonSerializationSettings settings, final Set supportedResponseParameters) { Gson gson = null; if (settings.isPartialResponseRequired()) { - gson = helper.createGsonBuilderWithParameterExclusionSerializationStrategy(supportedResponseParameters, + gson = this.helper.createGsonBuilderWithParameterExclusionSerializationStrategy(supportedResponseParameters, settings.isPrettyPrint(), settings.getParametersForPartialResponse()); } return gson; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson.java index 6630662e7..026247878 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson.java @@ -17,9 +17,14 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** - *

A google gson implementation of {@link ExcludeNothingJsonSerializer} contract.

+ *

+ * A google gson implementation of {@link ExcludeNothingJsonSerializer} + * contract. + *

* - *

It serializes all fields of any Java {@link Object} passed to it.

+ *

+ * It serializes all fields of any Java {@link Object} passed to it. + *

*/ @Component public final class ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson { @@ -27,11 +32,11 @@ public final class ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson { private final Gson gson; public ExcludeNothingWithPrettyPrintingOffJsonSerializerGoogleGson() { - GsonBuilder builder = new GsonBuilder(); + final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(LocalDate.class, new JodaLocalDateAdapter()); builder.registerTypeAdapter(DateTime.class, new JodaDateTimeAdapter()); builder.registerTypeAdapter(MonthDay.class, new JodaMonthDayAdapter()); - + this.gson = builder.create(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson.java index cb301db97..ea119d1f8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson.java @@ -17,9 +17,14 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** - *

A google gson implementation of {@link ExcludeNothingJsonSerializer} contract.

+ *

+ * A google gson implementation of {@link ExcludeNothingJsonSerializer} + * contract. + *

* - *

It serializes all fields of any Java {@link Object} passed to it.

+ *

+ * It serializes all fields of any Java {@link Object} passed to it. + *

*/ @Component public final class ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson { @@ -27,12 +32,12 @@ public final class ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson { private final Gson gson; public ExcludeNothingWithPrettyPrintingOnJsonSerializerGoogleGson() { - GsonBuilder builder = new GsonBuilder(); + final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(LocalDate.class, new JodaLocalDateAdapter()); builder.registerTypeAdapter(DateTime.class, new JodaDateTimeAdapter()); builder.registerTypeAdapter(MonthDay.class, new JodaMonthDayAdapter()); builder.setPrettyPrinting(); - + this.gson = builder.create(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/FromCommandJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/FromCommandJsonDeserializer.java index 91ccad604..ad50e4143 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/FromCommandJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/FromCommandJsonDeserializer.java @@ -13,6 +13,6 @@ public interface FromCommandJsonDeserializer { T commandFromCommandJson(final String json); T commandFromCommandJson(final Long resourceId, final String json); - + T commandFromCommandJson(final Long resourceId, final String json, final boolean makerCheckerApproval); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/FromJsonHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/FromJsonHelper.java index b88500db2..19c8d8766 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/FromJsonHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/FromJsonHelper.java @@ -38,8 +38,8 @@ public class FromJsonHelper { public FromJsonHelper() { this.gsonConverter = new Gson(); - helperDelegator = new JsonParserHelper(); - parser = new JsonParser(); + this.helperDelegator = new JsonParserHelper(); + this.parser = new JsonParser(); } public Map extractMap(final Type typeOfMap, final String json) { @@ -69,10 +69,10 @@ public class FromJsonHelper { public void checkForUnsupportedParameters(final Type typeOfMap, final String json, final Set supportedParams) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Map requestMap = gsonConverter.fromJson(json, typeOfMap); + final Map requestMap = this.gsonConverter.fromJson(json, typeOfMap); - List unsupportedParameterList = new ArrayList(); - for (String providedParameter : requestMap.keySet()) { + final List unsupportedParameterList = new ArrayList(); + for (final String providedParameter : requestMap.keySet()) { if (!supportedParams.contains(providedParameter)) { unsupportedParameterList.add(providedParameter); } @@ -80,14 +80,14 @@ public class FromJsonHelper { if (!unsupportedParameterList.isEmpty()) { throw new UnsupportedParameterException(unsupportedParameterList); } } - + public void checkForUnsupportedParameters(final JsonObject object, final Set supportedParams) { if (object == null) { throw new InvalidParameterException(); } - Set> entries = object.entrySet(); - List unsupportedParameterList = new ArrayList(); - - for (Entry providedParameter : entries) { + final Set> entries = object.entrySet(); + final List unsupportedParameterList = new ArrayList(); + + for (final Entry providedParameter : entries) { if (!supportedParams.contains(providedParameter.getKey())) { unsupportedParameterList.add(providedParameter.getKey()); } @@ -100,119 +100,120 @@ public class FromJsonHelper { JsonElement parsedElement = null; if (StringUtils.isNotBlank(json)) { - parsedElement = parser.parse(json); + parsedElement = this.parser.parse(json); } return parsedElement; } public boolean parameterExists(final String parameterName, final JsonElement element) { - return helperDelegator.parameterExists(parameterName, element); + return this.helperDelegator.parameterExists(parameterName, element); } public String extractStringNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractStringNamed(parameterName, element, new HashSet()); + return this.helperDelegator.extractStringNamed(parameterName, element, new HashSet()); } public String extractStringNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractStringNamed(parameterName, element, parametersPassedInRequest); + return this.helperDelegator.extractStringNamed(parameterName, element, parametersPassedInRequest); } public Long extractLongNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractLongNamed(parameterName, element, new HashSet()); + return this.helperDelegator.extractLongNamed(parameterName, element, new HashSet()); } public Long extractLongNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractLongNamed(parameterName, element, parametersPassedInRequest); + return this.helperDelegator.extractLongNamed(parameterName, element, parametersPassedInRequest); } public JsonArray extractJsonArrayNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractJsonArrayNamed(parameterName, element); + return this.helperDelegator.extractJsonArrayNamed(parameterName, element); } public String[] extractArrayNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractArrayNamed(parameterName, element, new HashSet()); + return this.helperDelegator.extractArrayNamed(parameterName, element, new HashSet()); } public String[] extractArrayNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractArrayNamed(parameterName, element, parametersPassedInRequest); + return this.helperDelegator.extractArrayNamed(parameterName, element, parametersPassedInRequest); } public Boolean extractBooleanNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractBooleanNamed(parameterName, element, new HashSet()); + return this.helperDelegator.extractBooleanNamed(parameterName, element, new HashSet()); } public Boolean extractBooleanNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractBooleanNamed(parameterName, element, parametersPassedInRequest); + return this.helperDelegator.extractBooleanNamed(parameterName, element, parametersPassedInRequest); } public MonthDay extractMonthDayNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractMonthDayNamed(parameterName, element); + return this.helperDelegator.extractMonthDayNamed(parameterName, element); } public LocalDate extractLocalDateNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractLocalDateNamed(parameterName, element, new HashSet()); + return this.helperDelegator.extractLocalDateNamed(parameterName, element, new HashSet()); } public LocalDate extractLocalDateNamed(final String parameterName, final JsonElement element, final String dateFormat, final Locale locale) { - return helperDelegator.extractLocalDateNamed(parameterName, element.getAsJsonObject(), dateFormat, locale, new HashSet()); + return this.helperDelegator.extractLocalDateNamed(parameterName, element.getAsJsonObject(), dateFormat, locale, + new HashSet()); } public LocalDate extractLocalDateNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractLocalDateNamed(parameterName, element, parametersPassedInRequest); + return this.helperDelegator.extractLocalDateNamed(parameterName, element, parametersPassedInRequest); } public LocalDate extractLocalDateAsArrayNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractLocalDateAsArrayNamed(parameterName, element, parametersPassedInRequest); + return this.helperDelegator.extractLocalDateAsArrayNamed(parameterName, element, parametersPassedInRequest); } public BigDecimal extractBigDecimalWithLocaleNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractBigDecimalWithLocaleNamed(parameterName, element, new HashSet()); + return this.helperDelegator.extractBigDecimalWithLocaleNamed(parameterName, element, new HashSet()); } public BigDecimal extractBigDecimalWithLocaleNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractBigDecimalWithLocaleNamed(parameterName, element, parametersPassedInRequest); + return this.helperDelegator.extractBigDecimalWithLocaleNamed(parameterName, element, parametersPassedInRequest); } public BigDecimal extractBigDecimalNamed(final String parameterName, final JsonElement element, final Locale locale) { - return helperDelegator.extractBigDecimalNamed(parameterName, element.getAsJsonObject(), locale, new HashSet()); + return this.helperDelegator.extractBigDecimalNamed(parameterName, element.getAsJsonObject(), locale, new HashSet()); } public BigDecimal extractBigDecimalNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractBigDecimalNamed(parameterName, element.getAsJsonObject(), Locale.US, parametersPassedInRequest); + return this.helperDelegator.extractBigDecimalNamed(parameterName, element.getAsJsonObject(), Locale.US, parametersPassedInRequest); } public Integer extractIntegerWithLocaleNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractIntegerWithLocaleNamed(parameterName, element.getAsJsonObject(), new HashSet()); + return this.helperDelegator.extractIntegerWithLocaleNamed(parameterName, element.getAsJsonObject(), new HashSet()); } public Integer extractIntegerSansLocaleNamed(final String parameterName, final JsonElement element) { - return helperDelegator.extractIntegerSansLocaleNamed(parameterName, element.getAsJsonObject(), new HashSet()); + return this.helperDelegator.extractIntegerSansLocaleNamed(parameterName, element.getAsJsonObject(), new HashSet()); } public Integer extractIntegerWithLocaleNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractIntegerWithLocaleNamed(parameterName, element.getAsJsonObject(), parametersPassedInRequest); + return this.helperDelegator.extractIntegerWithLocaleNamed(parameterName, element.getAsJsonObject(), parametersPassedInRequest); } public Integer extractIntegerNamed(final String parameterName, final JsonElement element, final Locale locale) { - return helperDelegator.extractIntegerNamed(parameterName, element.getAsJsonObject(), locale, new HashSet()); + return this.helperDelegator.extractIntegerNamed(parameterName, element.getAsJsonObject(), locale, new HashSet()); } public Integer extractIntegerNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { - return helperDelegator.extractIntegerNamed(parameterName, element.getAsJsonObject(), Locale.US, parametersPassedInRequest); + return this.helperDelegator.extractIntegerNamed(parameterName, element.getAsJsonObject(), Locale.US, parametersPassedInRequest); } public Locale extractLocaleParameter(final JsonObject element) { - return helperDelegator.extractLocaleParameter(element); + return this.helperDelegator.extractLocaleParameter(element); } public String extractDateFormatParameter(final JsonObject element) { - return helperDelegator.extractDateFormatParameter(element); + return this.helperDelegator.extractDateFormatParameter(element); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/JsonParserHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/JsonParserHelper.java index 50ba29431..38c89021c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/JsonParserHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/JsonParserHelper.java @@ -42,11 +42,11 @@ public class JsonParserHelper { public Boolean extractBooleanNamed(final String parameterName, final JsonElement element, final Set requestParamatersDetected) { Boolean value = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { requestParamatersDetected.add(parameterName); - JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); + final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); value = primitive.getAsBoolean(); } } @@ -56,10 +56,10 @@ public class JsonParserHelper { public Long extractLongNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { Long longValue = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { parametersPassedInRequest.add(parameterName); - JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); + final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); final String stringValue = primitive.getAsString(); if (StringUtils.isNotBlank(stringValue)) { longValue = Long.valueOf(stringValue); @@ -72,7 +72,7 @@ public class JsonParserHelper { public String extractStringNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { String stringValue = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { parametersPassedInRequest.add(parameterName); final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); @@ -100,11 +100,11 @@ public class JsonParserHelper { final Set modifiedParameters) { BigDecimal value = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { modifiedParameters.add(parameterName); - JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); - String valueAsString = primitive.getAsString(); + final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); + final String valueAsString = primitive.getAsString(); if (StringUtils.isNotBlank(valueAsString)) { value = convertFrom(valueAsString, parameterName, locale); } @@ -130,8 +130,8 @@ public class JsonParserHelper { final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { modifiedParameters.add(parameterName); - JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); - String valueAsString = primitive.getAsString(); + final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); + final String valueAsString = primitive.getAsString(); if (StringUtils.isNotBlank(valueAsString)) { value = convertToInteger(valueAsString, parameterName, locale); } @@ -156,10 +156,10 @@ public class JsonParserHelper { final Set parametersPassedInRequest) { Integer intValue = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { parametersPassedInRequest.add(parameterName); - JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); + final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); final String stringValue = primitive.getAsString(); if (StringUtils.isNotBlank(stringValue)) { intValue = convertToIntegerSanLocale(stringValue, parameterName); @@ -172,7 +172,7 @@ public class JsonParserHelper { public String extractDateFormatParameter(final JsonObject element) { String value = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); final String dateFormatParameter = "dateFormat"; if (object.has(dateFormatParameter) && object.get(dateFormatParameter).isJsonPrimitive()) { @@ -186,7 +186,7 @@ public class JsonParserHelper { public String extractMonthDayFormatParameter(final JsonObject element) { String value = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); final String monthDayFormatParameter = "monthDayFormat"; if (object.has(monthDayFormatParameter) && object.get(monthDayFormatParameter).isJsonPrimitive()) { @@ -200,7 +200,7 @@ public class JsonParserHelper { public Locale extractLocaleParameter(final JsonObject element) { Locale clientApplicationLocale = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); String locale = null; final String localeParameter = "locale"; @@ -216,10 +216,10 @@ public class JsonParserHelper { public String[] extractArrayNamed(final String parameterName, final JsonElement element, final Set parametersPassedInRequest) { String[] arrayValue = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName)) { parametersPassedInRequest.add(parameterName); - JsonArray array = object.get(parameterName).getAsJsonArray(); + final JsonArray array = object.get(parameterName).getAsJsonArray(); arrayValue = new String[array.size()]; for (int i = 0; i < array.size(); i++) { arrayValue[i] = array.get(i).getAsString(); @@ -233,7 +233,7 @@ public class JsonParserHelper { JsonArray jsonArray = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName)) { jsonArray = object.get(parameterName).getAsJsonArray(); } @@ -249,7 +249,7 @@ public class JsonParserHelper { final Set parametersPassedInCommand) { LocalDate value = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonArray()) { @@ -257,9 +257,9 @@ public class JsonParserHelper { final JsonArray dateArray = object.get(parameterName).getAsJsonArray(); - Integer year = dateArray.get(0).getAsInt(); - Integer month = dateArray.get(1).getAsInt(); - Integer day = dateArray.get(2).getAsInt(); + final Integer year = dateArray.get(0).getAsInt(); + final Integer month = dateArray.get(1).getAsInt(); + final Integer day = dateArray.get(2).getAsInt(); value = new LocalDate().withYearOfEra(year).withMonthOfYear(month).withDayOfMonth(day); } @@ -273,7 +273,7 @@ public class JsonParserHelper { MonthDay value = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); final String monthDayFormat = extractMonthDayFormatParameter(object); final Locale clientApplicationLocale = extractLocaleParameter(object); @@ -286,14 +286,14 @@ public class JsonParserHelper { final Locale clientApplicationLocale) { MonthDay value = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { final JsonPrimitive primitive = object.get(parameterName).getAsJsonPrimitive(); final String valueAsString = primitive.getAsString(); if (StringUtils.isNotBlank(valueAsString)) { - DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat).withLocale(clientApplicationLocale); + final DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat).withLocale(clientApplicationLocale); value = MonthDay.parse(valueAsString.toLowerCase(clientApplicationLocale), formatter); } } @@ -308,7 +308,7 @@ public class JsonParserHelper { LocalDate value = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); final String dateFormat = extractDateFormatParameter(object); final Locale clientApplicationLocale = extractLocaleParameter(object); @@ -321,7 +321,7 @@ public class JsonParserHelper { final Locale clientApplicationLocale, final Set parametersPassedInCommand) { LocalDate value = null; if (element.isJsonObject()) { - JsonObject object = element.getAsJsonObject(); + final JsonObject object = element.getAsJsonObject(); if (object.has(parameterName) && object.get(parameterName).isJsonPrimitive()) { @@ -343,18 +343,18 @@ public class JsonParserHelper { if (StringUtils.isBlank(dateFormat) || clientApplicationLocale == null) { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); if (StringUtils.isBlank(dateFormat)) { - String defaultMessage = new StringBuilder("The parameter '" + parameterName + final 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); + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.dateFormat.parameter", + defaultMessage, parameterName); dataValidationErrors.add(error); } if (clientApplicationLocale == null) { - String defaultMessage = new StringBuilder("The parameter '" + parameterName + final 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, + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); dataValidationErrors.add(error); } @@ -368,9 +368,9 @@ public class JsonParserHelper { // 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 " + } catch (final IllegalArgumentException e) { + final List dataValidationErrors = new ArrayList(); + final 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); @@ -387,10 +387,10 @@ public class JsonParserHelper { if (clientApplicationLocale == null) { - List dataValidationErrors = new ArrayList(); - String defaultMessage = new StringBuilder("The parameter '" + parameterName + final List dataValidationErrors = new ArrayList(); + final 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, + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); dataValidationErrors.add(error); @@ -405,21 +405,21 @@ public class JsonParserHelper { String source = numericalValueFormatted.trim(); - NumberFormat format = NumberFormat.getInstance(clientApplicationLocale); - DecimalFormat df = (DecimalFormat) format; - DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); + final NumberFormat format = NumberFormat.getInstance(clientApplicationLocale); + final DecimalFormat df = (DecimalFormat) format; + final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); df.setParseBigDecimal(true); // http://bugs.sun.com/view_bug.do?bug_id=4510618 - char groupingSeparator = symbols.getGroupingSeparator(); + final char groupingSeparator = symbols.getGroupingSeparator(); if (groupingSeparator == '\u00a0') { source = source.replaceAll(" ", Character.toString('\u00a0')); } - Number parsedNumber = df.parse(source); + final Number parsedNumber = df.parse(source); - double parsedNumberDouble = parsedNumber.doubleValue(); - int parsedNumberInteger = parsedNumber.intValue(); + final double parsedNumberDouble = parsedNumber.doubleValue(); + final int parsedNumberInteger = parsedNumber.intValue(); if (source.contains(Character.toString(symbols.getDecimalSeparator()))) { throw new ParseException(source, 0); } @@ -430,10 +430,10 @@ public class JsonParserHelper { } return number; - } catch (ParseException e) { + } catch (final ParseException e) { - List dataValidationErrors = new ArrayList(); - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.integer.format", "The parameter " + final List dataValidationErrors = new ArrayList(); + final 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); error.setValue(numericalValueFormatted); @@ -454,11 +454,12 @@ public class JsonParserHelper { } return number; - } catch (NumberFormatException e) { + } catch (final NumberFormatException e) { - List dataValidationErrors = new ArrayList(); - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.integer", "The parameter " + parameterName - + " has value: " + numericalValueFormatted + " which is invalid integer.", parameterName, numericalValueFormatted); + final List dataValidationErrors = new ArrayList(); + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.integer", "The parameter " + + parameterName + " has value: " + numericalValueFormatted + " which is invalid integer.", parameterName, + numericalValueFormatted); error.setValue(numericalValueFormatted); dataValidationErrors.add(error); @@ -471,10 +472,10 @@ public class JsonParserHelper { if (clientApplicationLocale == null) { - List dataValidationErrors = new ArrayList(); - String defaultMessage = new StringBuilder("The parameter '" + parameterName + final List dataValidationErrors = new ArrayList(); + final 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, + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName); dataValidationErrors.add(error); @@ -489,25 +490,25 @@ public class JsonParserHelper { String source = numericalValueFormatted.trim(); - NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale); - DecimalFormat df = (DecimalFormat) format; - DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); + final NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale); + final DecimalFormat df = (DecimalFormat) format; + final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); // http://bugs.sun.com/view_bug.do?bug_id=4510618 - char groupingSeparator = symbols.getGroupingSeparator(); + final char groupingSeparator = symbols.getGroupingSeparator(); if (groupingSeparator == '\u00a0') { source = source.replaceAll(" ", Character.toString('\u00a0')); } - NumberFormatter numberFormatter = new NumberFormatter(); - Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale); + final NumberFormatter numberFormatter = new NumberFormatter(); + final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale); number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue())); } return number; - } catch (ParseException e) { + } catch (final ParseException e) { - List dataValidationErrors = new ArrayList(); - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.decimal.format", "The parameter " + final List dataValidationErrors = new ArrayList(); + final 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); error.setValue(numericalValueFormatted); @@ -518,12 +519,12 @@ public class JsonParserHelper { } } - /***TODO: Vishwas move all Locale related code to a separate Utils class***/ + /*** TODO: Vishwas move all Locale related code to a separate Utils class ***/ public static Locale localeFromString(final String localeAsString) { if (StringUtils.isBlank(localeAsString)) { - List dataValidationErrors = new ArrayList(); - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", + final List dataValidationErrors = new ArrayList(); + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", "The parameter locale is invalid. It cannot be blank.", "locale"); dataValidationErrors.add(error); @@ -535,7 +536,7 @@ public class JsonParserHelper { String countryCode = ""; String variantCode = ""; - String[] localeParts = localeAsString.split("_"); + final String[] localeParts = localeAsString.split("_"); if (localeParts != null && localeParts.length == 1) { languageCode = localeParts[0]; @@ -557,19 +558,19 @@ public class JsonParserHelper { private static Locale localeFrom(final String languageCode, final String courntryCode, final String variantCode) { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); - List allowedLanguages = Arrays.asList(Locale.getISOLanguages()); + final List allowedLanguages = Arrays.asList(Locale.getISOLanguages()); if (!allowedLanguages.contains(languageCode.toLowerCase())) { - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", + final 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()); + final List allowedCountries = Arrays.asList(Locale.getISOCountries()); if (!allowedCountries.contains(courntryCode)) { - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.locale.format", "The parameter locale has an invalid country value " + courntryCode + " .", "locale", courntryCode); dataValidationErrors.add(error); } @@ -585,7 +586,7 @@ public class JsonParserHelper { Locale clientApplicationLocale = null; String locale = null; if (object.has("locale") && object.get("locale").isJsonPrimitive()) { - JsonPrimitive primitive = object.get("locale").getAsJsonPrimitive(); + final JsonPrimitive primitive = object.get("locale").getAsJsonPrimitive(); locale = primitive.getAsString(); clientApplicationLocale = localeFromString(locale); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ToApiJsonSerializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ToApiJsonSerializer.java index 44796bd2a..b51f047b6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ToApiJsonSerializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/serialization/ToApiJsonSerializer.java @@ -13,14 +13,14 @@ import org.mifosplatform.infrastructure.core.service.Page; public interface ToApiJsonSerializer { String serialize(Object object); - + String serializePretty(boolean prettyOn, Object object); - + String serializeResult(Object object); String serialize(ApiRequestJsonSerializationSettings settings, Collection collection, Set supportedResponseParameters); String serialize(ApiRequestJsonSerializationSettings settings, T single, Set supportedResponseParameters); - + String serialize(ApiRequestJsonSerializationSettings settings, Page singleObject, Set supportedResponseParameters); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/DateUtils.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/DateUtils.java index 9b06e6496..9a56e0b41 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/DateUtils.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/DateUtils.java @@ -45,12 +45,12 @@ public class DateUtils { public static LocalDate parseLocalDate(final String stringDate, final String pattern) { try { - DateTimeFormatter dateStringFormat = DateTimeFormat.forPattern(pattern); - DateTime dateTime = dateStringFormat.parseDateTime(stringDate); + final DateTimeFormatter dateStringFormat = DateTimeFormat.forPattern(pattern); + final DateTime dateTime = dateStringFormat.parseDateTime(stringDate); return dateTime.toLocalDate(); - } catch (IllegalArgumentException e) { - List dataValidationErrors = new ArrayList(); - ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.date.pattern", "The parameter date (" + } catch (final IllegalArgumentException e) { + final List dataValidationErrors = new ArrayList(); + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.invalid.date.pattern", "The parameter date (" + stringDate + ") is invalid w.r.t. pattern " + pattern, "date", stringDate, pattern); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/GmailBackedPlatformEmailService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/GmailBackedPlatformEmailService.java index 410a1f166..64a452bc7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/GmailBackedPlatformEmailService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/GmailBackedPlatformEmailService.java @@ -17,12 +17,12 @@ public class GmailBackedPlatformEmailService implements PlatformEmailService { @Override public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) { - Email email = new SimpleEmail(); + final Email email = new SimpleEmail(); - String authuserName = "support@cloudmicrofinance.com"; + final String authuserName = "support@cloudmicrofinance.com"; - String authuser = "support@cloudmicrofinance.com"; - String authpwd = "support80"; + final String authuser = "support@cloudmicrofinance.com"; + final String authpwd = "support80"; // Very Important, Don't use email.setAuthentication() email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd)); @@ -32,19 +32,24 @@ public class GmailBackedPlatformEmailService implements PlatformEmailService { email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true"); email.setFrom(authuser, authuserName); - StringBuilder subjectBuilder = new StringBuilder().append("MifosX Prototype Demo: ").append(emailDetail.getContactName()).append(" user account creation."); + final StringBuilder subjectBuilder = new StringBuilder().append("MifosX Prototype Demo: ").append(emailDetail.getContactName()) + .append(" user account creation."); email.setSubject(subjectBuilder.toString()); - String sendToEmail = emailDetail.getAddress(); + final String sendToEmail = emailDetail.getAddress(); - StringBuilder messageBuilder = new StringBuilder().append("You are receiving this email as your email account: ").append(sendToEmail).append(" has being used to create a user account for an organisation named [").append(emailDetail.getOrganisationName()).append("] on MifosX Prototype Demo.").append("You can login using the following credentials: username: ").append(emailDetail.getUsername()).append(" password: ").append(unencodedPassword); + final StringBuilder messageBuilder = new StringBuilder().append("You are receiving this email as your email account: ") + .append(sendToEmail).append(" has being used to create a user account for an organisation named [") + .append(emailDetail.getOrganisationName()).append("] on MifosX Prototype Demo.") + .append("You can login using the following credentials: username: ").append(emailDetail.getUsername()) + .append(" password: ").append(unencodedPassword); email.setMsg(messageBuilder.toString()); email.addTo(sendToEmail, emailDetail.getContactName()); email.send(); - } catch (EmailException e) { + } catch (final EmailException e) { throw new PlatformEmailSendException(e); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/Page.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/Page.java index 2c51f92ab..17166d719 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/Page.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/Page.java @@ -22,6 +22,6 @@ public class Page { } public List getPageItems() { - return pageItems; + return this.pageItems; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/PlatformEmailService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/PlatformEmailService.java index afdec8058..1b00ffb23 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/PlatformEmailService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/PlatformEmailService.java @@ -7,7 +7,6 @@ package org.mifosplatform.infrastructure.core.service; import org.mifosplatform.infrastructure.core.domain.EmailDetail; - public interface PlatformEmailService { void sendToUserAccount(EmailDetail emailDetail, String unencodedPassword); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/RoutingDataSource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/RoutingDataSource.java index 163fa419f..af307ef0b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/RoutingDataSource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/RoutingDataSource.java @@ -37,7 +37,7 @@ public class RoutingDataSource extends AbstractDataSource { } private DataSource determineTargetDataSource() { - return dataSourceServiceFactory.determineDataSourceService().retrieveDataSource(); + return this.dataSourceServiceFactory.determineDataSourceService().retrieveDataSource(); } @Override diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/RoutingDataSourceServiceFactory.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/RoutingDataSourceServiceFactory.java index d7c025c71..d6dde9665 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/RoutingDataSourceServiceFactory.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/RoutingDataSourceServiceFactory.java @@ -22,7 +22,7 @@ public class RoutingDataSourceServiceFactory { if (ThreadLocalContextUtil.CONTEXT_TENANTS.equalsIgnoreCase(ThreadLocalContextUtil.getDataSourceContext())) { serviceName = "dataSourceForTenants"; } - return applicationContext.getBean(serviceName, RoutingDataSourceService.class); + return this.applicationContext.getBean(serviceName, RoutingDataSourceService.class); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/TenantDatabaseUpgradeService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/TenantDatabaseUpgradeService.java index 8873b84f2..57a497955 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/TenantDatabaseUpgradeService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/TenantDatabaseUpgradeService.java @@ -32,10 +32,10 @@ public class TenantDatabaseUpgradeService { @PostConstruct public void upgradeAllTenants() { - List tenants = tenantDetailsService.findAllTenants(); - for (MifosPlatformTenant tenant : tenants) { + final List tenants = this.tenantDetailsService.findAllTenants(); + for (final MifosPlatformTenant tenant : tenants) { if (tenant.isAutoUpdateEnabled()) { - Flyway flyway = new Flyway(); + final Flyway flyway = new Flyway(); flyway.setDataSource(tenant.databaseURL(), tenant.getSchemaUsername(), tenant.getSchemaPassword()); flyway.setLocations("sql"); flyway.setOutOfOrder(true); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/TomcatJdbcDataSourcePerTenantService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/TomcatJdbcDataSourcePerTenantService.java index 663870b9e..996aafb69 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/TomcatJdbcDataSourcePerTenantService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/core/service/TomcatJdbcDataSourcePerTenantService.java @@ -42,7 +42,7 @@ public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceSe // default to tenant database datasource DataSource tenantDataSource = this.tenantDataSource; - MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); + final MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); if (tenant != null) { synchronized (this.tenantToDataSourceMap) { // if tenant information available switch to appropriate @@ -64,9 +64,9 @@ public class TomcatJdbcDataSourcePerTenantService implements RoutingDataSourceSe // see // http://www.tomcatexpert.com/blog/2010/04/01/configuring-jdbc-pool-high-concurrency - String jdbcUrl = tenant.databaseURL(); + final String jdbcUrl = tenant.databaseURL(); - PoolConfiguration poolConfiguration = new PoolProperties(); + final PoolConfiguration poolConfiguration = new PoolProperties(); poolConfiguration.setDriverClassName("com.mysql.jdbc.Driver"); poolConfiguration.setName(tenant.getSchemaName() + "_pool"); poolConfiguration.setUrl(jdbcUrl); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DatatablesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DatatablesApiResource.java index b1ac99140..35ae92dc3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DatatablesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/DatatablesApiResource.java @@ -74,40 +74,35 @@ public class DatatablesApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String createDatatable(final String apiRequestBodyAsJson) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .createDBDatatable(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); + final CommandWrapper commandRequest = new CommandWrapperBuilder().createDBDatatable(apiRequestBodyAsJson).build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + return this.toApiJsonSerializer.serialize(result); } @PUT @Path("{datatableName}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String updateDatatable(@PathParam("datatableName") final String datatableName, - final String apiRequestBodyAsJson) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .updateDBDatatable(datatableName, apiRequestBodyAsJson).build(); + public String updateDatatable(@PathParam("datatableName") final String datatableName, final String apiRequestBodyAsJson) { - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateDBDatatable(datatableName, apiRequestBodyAsJson).build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + return this.toApiJsonSerializer.serialize(result); } @DELETE @Path("{datatableName}") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) - public String deleteDatatable(@PathParam("datatableName") final String datatableName, - final String apiRequestBodyAsJson) { - - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .deleteDBDatatable(datatableName, apiRequestBodyAsJson).build(); + public String deleteDatatable(@PathParam("datatableName") final String datatableName, final String apiRequestBodyAsJson) { - final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); + final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteDBDatatable(datatableName, apiRequestBodyAsJson).build(); + + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + return this.toApiJsonSerializer.serialize(result); } @POST @@ -154,10 +149,10 @@ public class DatatablesApiResource { public String getDatatable(@PathParam("datatable") final String datatable, @PathParam("apptableId") final Long apptableId, @QueryParam("order") final String order, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasDatatableReadPermission(datatable); + this.context.authenticatedUser().validateHasDatatableReadPermission(datatable); - GenericResultsetData results = this.readWriteNonCoreDataService.retrieveDataTableGenericResultSet(datatable, apptableId, order, - null); + final GenericResultsetData results = this.readWriteNonCoreDataService.retrieveDataTableGenericResultSet(datatable, apptableId, + order, null); String json = ""; final boolean genericResultSet = ApiParameterHelper.genericResultSet(uriInfo.getQueryParameters()); @@ -178,10 +173,10 @@ public class DatatablesApiResource { public String getDatatableManyEntry(@PathParam("datatable") final String datatable, @PathParam("apptableId") final Long apptableId, @PathParam("datatableId") final Long datatableId, @QueryParam("order") final String order, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasDatatableReadPermission(datatable); + this.context.authenticatedUser().validateHasDatatableReadPermission(datatable); - GenericResultsetData results = this.readWriteNonCoreDataService.retrieveDataTableGenericResultSet(datatable, apptableId, order, - datatableId); + final GenericResultsetData results = this.readWriteNonCoreDataService.retrieveDataTableGenericResultSet(datatable, apptableId, + order, datatableId); String json = ""; final boolean genericResultSet = ApiParameterHelper.genericResultSet(uriInfo.getQueryParameters()); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/ReportsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/ReportsApiResource.java index 98c17aa10..7419f5047 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/ReportsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/ReportsApiResource.java @@ -41,135 +41,110 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class ReportsApiResource { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet( - Arrays.asList("id", "reportName", "reportType", "reportSubType", - "reportCategory", "description", "reportSql", "coreReport", - "useReport", "reportParameters")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "reportName", "reportType", + "reportSubType", "reportCategory", "description", "reportSql", "coreReport", "useReport", "reportParameters")); - private final String resourceNameForPermissions = "REPORT"; - private final PlatformSecurityContext context; - private final ToApiJsonSerializer toApiJsonSerializer; - private final ReadReportingService readReportingService; - private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; - private final ApiRequestParameterHelper apiRequestParameterHelper; + private final String resourceNameForPermissions = "REPORT"; + private final PlatformSecurityContext context; + private final ToApiJsonSerializer toApiJsonSerializer; + private final ReadReportingService readReportingService; + private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; + private final ApiRequestParameterHelper apiRequestParameterHelper; - @Autowired - public ReportsApiResource( - final PlatformSecurityContext context, - final ReadReportingService readReportingService, - final ToApiJsonSerializer toApiJsonSerializer, - PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final ApiRequestParameterHelper apiRequestParameterHelper) { - this.context = context; - this.readReportingService = readReportingService; - this.toApiJsonSerializer = toApiJsonSerializer; - this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; - this.apiRequestParameterHelper = apiRequestParameterHelper; - } + @Autowired + public ReportsApiResource(final PlatformSecurityContext context, final ReadReportingService readReportingService, + final ToApiJsonSerializer toApiJsonSerializer, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final ApiRequestParameterHelper apiRequestParameterHelper) { + this.context = context; + this.readReportingService = readReportingService; + this.toApiJsonSerializer = toApiJsonSerializer; + this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; + this.apiRequestParameterHelper = apiRequestParameterHelper; + } - @GET - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveReportList(@Context final UriInfo uriInfo) { + @GET + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveReportList(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission( - resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final Collection result = this.readReportingService - .retrieveReportList(); + final Collection result = this.readReportingService.retrieveReportList(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, result, - RESPONSE_DATA_PARAMETERS); - } + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, result, this.RESPONSE_DATA_PARAMETERS); + } - @GET - @Path("{id}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveReport(@PathParam("id") final Long id, - @Context final UriInfo uriInfo) { + @GET + @Path("{id}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveReport(@PathParam("id") final Long id, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission( - resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ReportData result = this.readReportingService - .retrieveReport(id); + final ReportData result = this.readReportingService.retrieveReport(id); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - if (settings.isTemplate()) { - result.appendedTemplate(this.readReportingService - .getAllowedParameters()); - } - return this.toApiJsonSerializer.serialize(settings, result, - RESPONSE_DATA_PARAMETERS); - } + if (settings.isTemplate()) { + result.appendedTemplate(this.readReportingService.getAllowedParameters()); + } + return this.toApiJsonSerializer.serialize(settings, result, this.RESPONSE_DATA_PARAMETERS); + } - @GET - @Path("template") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String retrieveOfficeTemplate(@Context final UriInfo uriInfo) { + @GET + @Path("template") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String retrieveOfficeTemplate(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission( - resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - ReportData result = new ReportData(); - result.appendedTemplate(this.readReportingService - .getAllowedParameters()); + final ReportData result = new ReportData(); + result.appendedTemplate(this.readReportingService.getAllowedParameters()); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper - .process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, result, - RESPONSE_DATA_PARAMETERS); - } + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, result, this.RESPONSE_DATA_PARAMETERS); + } - @POST - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String createReport(final String apiRequestBodyAsJson) { + @POST + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String createReport(final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .createReport().withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().createReport().withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } + return this.toApiJsonSerializer.serialize(result); + } - @PUT - @Path("{id}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String updateReport(@PathParam("id") final Long id, - final String apiRequestBodyAsJson) { + @PUT + @Path("{id}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String updateReport(@PathParam("id") final Long id, final String apiRequestBodyAsJson) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .updateReport(id).withJson(apiRequestBodyAsJson).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().updateReport(id).withJson(apiRequestBodyAsJson).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } + return this.toApiJsonSerializer.serialize(result); + } - @DELETE - @Path("{id}") - @Consumes({ MediaType.APPLICATION_JSON }) - @Produces({ MediaType.APPLICATION_JSON }) - public String deleteReport(@PathParam("id") final Long id) { + @DELETE + @Path("{id}") + @Consumes({ MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_JSON }) + public String deleteReport(@PathParam("id") final Long id) { - final CommandWrapper commandRequest = new CommandWrapperBuilder() - .deleteReport(id).build(); + final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteReport(id).build(); - final CommandProcessingResult result = this.commandsSourceWritePlatformService - .logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); - return this.toApiJsonSerializer.serialize(result); - } + return this.toApiJsonSerializer.serialize(result); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/RunreportsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/RunreportsApiResource.java index 9a9b40dcf..7bd4c9759 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/RunreportsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/api/RunreportsApiResource.java @@ -62,12 +62,12 @@ public class RunreportsApiResource { @Produces({ MediaType.APPLICATION_JSON, "application/x-msdownload", "application/vnd.ms-excel", "application/pdf", "text/html" }) public Response runReport(@PathParam("reportName") final String reportName, @Context final UriInfo uriInfo) { - MultivaluedMap queryParams = uriInfo.getQueryParameters(); + final MultivaluedMap queryParams = uriInfo.getQueryParameters(); - boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); - boolean exportCsv = ApiParameterHelper.exportCsv(uriInfo.getQueryParameters()); - boolean parameterType = ApiParameterHelper.parameterType(uriInfo.getQueryParameters()); - boolean exportPdf = ApiParameterHelper.exportPdf(uriInfo.getQueryParameters()); + final boolean prettyPrint = ApiParameterHelper.prettyPrint(uriInfo.getQueryParameters()); + final boolean exportCsv = ApiParameterHelper.exportCsv(uriInfo.getQueryParameters()); + final boolean parameterType = ApiParameterHelper.parameterType(uriInfo.getQueryParameters()); + final boolean exportPdf = ApiParameterHelper.exportPdf(uriInfo.getQueryParameters()); checkUserPermissionForReport(reportName, parameterType); @@ -75,8 +75,8 @@ public class RunreportsApiResource { if (!parameterType) { parameterTypeValue = "report"; if (this.readExtraDataAndReportingService.getReportType(reportName).equalsIgnoreCase("Pentaho")) { - Map reportParams = getReportParams(queryParams, true); - Locale locale = ApiParameterHelper.extractLocale(queryParams); + final Map reportParams = getReportParams(queryParams, true); + final Locale locale = ApiParameterHelper.extractLocale(queryParams); return this.readExtraDataAndReportingService.processPentahoRequest(reportName, queryParams.getFirst("output-type"), reportParams, locale); } @@ -87,12 +87,13 @@ public class RunreportsApiResource { // PDF format if (exportPdf) { - Map reportParams = getReportParams(queryParams, false); - String pdfFileName = this.readExtraDataAndReportingService.retrieveReportPDF(reportName, parameterTypeValue, reportParams); + final Map reportParams = getReportParams(queryParams, false); + final String pdfFileName = this.readExtraDataAndReportingService + .retrieveReportPDF(reportName, parameterTypeValue, reportParams); - File file = new File(pdfFileName); + final File file = new File(pdfFileName); - ResponseBuilder response = Response.ok(file); + final ResponseBuilder response = Response.ok(file); response.header("Content-Disposition", "attachment; filename=\"" + pdfFileName + "\""); response.header("content-Type", "application/pdf"); @@ -101,10 +102,10 @@ public class RunreportsApiResource { } if (!exportCsv) { - Map reportParams = getReportParams(queryParams, false); + final Map reportParams = getReportParams(queryParams, false); - GenericResultsetData result = this.readExtraDataAndReportingService.retrieveGenericResultset(reportName, parameterTypeValue, - reportParams); + final GenericResultsetData result = this.readExtraDataAndReportingService.retrieveGenericResultset(reportName, + parameterTypeValue, reportParams); String json = ""; final boolean genericResultSetIsPassed = ApiParameterHelper.genericResultSetPassed(uriInfo.getQueryParameters()); @@ -123,8 +124,9 @@ public class RunreportsApiResource { } // CSV Export - Map reportParams = getReportParams(queryParams, false); - StreamingOutput result = this.readExtraDataAndReportingService.retrieveReportCSV(reportName, parameterTypeValue, reportParams); + final Map reportParams = getReportParams(queryParams, false); + final StreamingOutput result = this.readExtraDataAndReportingService + .retrieveReportCSV(reportName, parameterTypeValue, reportParams); return Response.ok().entity(result).type("application/x-msdownload") .header("Content-Disposition", "attachment;filename=" + reportName.replaceAll(" ", "") + ".csv").build(); @@ -135,7 +137,7 @@ public class RunreportsApiResource { // Anyone can run a 'report' that is simply getting possible parameter // (dropdown listbox) values. if (!parameterType) { - AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); if (currentUser.hasNotPermissionForReport(reportName)) { throw new NoAuthorizationException("Not authorised to run report: " + reportName); } } @@ -143,17 +145,18 @@ public class RunreportsApiResource { private Map getReportParams(final MultivaluedMap queryParams, final Boolean isPentaho) { - Map reportParams = new HashMap(); - Set keys = queryParams.keySet(); + final Map reportParams = new HashMap(); + final Set keys = queryParams.keySet(); String pKey; String pValue; - for (String k : keys) { + for (final String k : keys) { if (k.startsWith("R_")) { - if (isPentaho) + if (isPentaho) { pKey = k.substring(2); - else + } else { pKey = "${" + k.substring(2) + "}"; + } pValue = queryParams.get(k).get(0); reportParams.put(pKey, pValue); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DatatableData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DatatableData.java index 99a5c59b5..fd111b1dc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DatatableData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/DatatableData.java @@ -18,14 +18,14 @@ public class DatatableData { private final String registeredTableName; @SuppressWarnings("unused") private final List columnHeaderData; - + public static DatatableData create(final String applicationTableName, final String registeredTableName, - final List columnHeaderData) { + final List columnHeaderData) { return new DatatableData(applicationTableName, registeredTableName, columnHeaderData); } private DatatableData(final String applicationTableName, final String registeredTableName, - final List columnHeaderData) { + final List columnHeaderData) { this.applicationTableName = applicationTableName; this.registeredTableName = registeredTableName; this.columnHeaderData = columnHeaderData; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/GenericResultsetData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/GenericResultsetData.java index 5b70bace9..fd349b5f6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/GenericResultsetData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/GenericResultsetData.java @@ -21,17 +21,17 @@ public final class GenericResultsetData { } public List getColumnHeaders() { - return columnHeaders; + return this.columnHeaders; } public List getData() { - return data; + return this.data; } public String getColTypeOfColumnNamed(final String columnName) { String colType = null; - for (ResultsetColumnHeaderData columnHeader : this.columnHeaders) { + for (final ResultsetColumnHeaderData columnHeader : this.columnHeaders) { if (columnHeader.isNamed(columnName)) { colType = columnHeader.getColumnType(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportData.java index 9ef690acb..d6c6a2fe5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportData.java @@ -11,87 +11,83 @@ import java.util.List; final public class ReportData { - @SuppressWarnings("unused") - private final Long id; - @SuppressWarnings("unused") - private final String reportName; - @SuppressWarnings("unused") - private final String reportType; - @SuppressWarnings("unused") - private final String reportSubType; - @SuppressWarnings("unused") - private final String reportCategory; - @SuppressWarnings("unused") - private final String description; - @SuppressWarnings("unused") - private final String reportSql; - @SuppressWarnings("unused") - private final Boolean coreReport; - @SuppressWarnings("unused") - private final Boolean useReport; - @SuppressWarnings("unused") - private final Collection reportParameters; + @SuppressWarnings("unused") + private final Long id; + @SuppressWarnings("unused") + private final String reportName; + @SuppressWarnings("unused") + private final String reportType; + @SuppressWarnings("unused") + private final String reportSubType; + @SuppressWarnings("unused") + private final String reportCategory; + @SuppressWarnings("unused") + private final String description; + @SuppressWarnings("unused") + private final String reportSql; + @SuppressWarnings("unused") + private final Boolean coreReport; + @SuppressWarnings("unused") + private final Boolean useReport; + @SuppressWarnings("unused") + private final Collection reportParameters; - @SuppressWarnings("unused") - private List allowedReportTypes; - @SuppressWarnings("unused") - private List allowedReportSubTypes; - @SuppressWarnings("unused") - private Collection allowedParameters; + @SuppressWarnings("unused") + private List allowedReportTypes; + @SuppressWarnings("unused") + private List allowedReportSubTypes; + @SuppressWarnings("unused") + private Collection allowedParameters; - public ReportData(final Long id, final String reportName, - final String reportType, final String reportSubType, - final String reportCategory, final String description, - final String reportSql, final Boolean coreReport, - final Boolean useReport, - final Collection reportParameters) { - this.id = id; - this.reportName = reportName; - this.reportType = reportType; - this.reportSubType = reportSubType; - this.reportCategory = reportCategory; - this.description = description; - this.reportParameters = reportParameters; - this.reportSql = reportSql; - this.coreReport = coreReport; - this.useReport = useReport; - this.allowedReportTypes = null; - this.allowedReportSubTypes = null; - this.allowedParameters = null; - } + public ReportData(final Long id, final String reportName, final String reportType, final String reportSubType, + final String reportCategory, final String description, final String reportSql, final Boolean coreReport, + final Boolean useReport, final Collection reportParameters) { + this.id = id; + this.reportName = reportName; + this.reportType = reportType; + this.reportSubType = reportSubType; + this.reportCategory = reportCategory; + this.description = description; + this.reportParameters = reportParameters; + this.reportSql = reportSql; + this.coreReport = coreReport; + this.useReport = useReport; + this.allowedReportTypes = null; + this.allowedReportSubTypes = null; + this.allowedParameters = null; + } - public ReportData() { - this.id = null; - this.reportName = null; - this.reportType = null; - this.reportSubType = null; - this.reportCategory = null; - this.description = null; - this.reportParameters = null; - this.reportSql = null; - this.coreReport = null; - this.useReport = null; - this.allowedReportTypes = null; - this.allowedReportSubTypes = null; - this.allowedParameters = null; - } + public ReportData() { + this.id = null; + this.reportName = null; + this.reportType = null; + this.reportSubType = null; + this.reportCategory = null; + this.description = null; + this.reportParameters = null; + this.reportSql = null; + this.coreReport = null; + this.useReport = null; + this.allowedReportTypes = null; + this.allowedReportSubTypes = null; + this.allowedParameters = null; + } - public void appendedTemplate( - final Collection allowedParameters) { + public void appendedTemplate(final Collection allowedParameters) { - List reportTypes = new ArrayList(); - reportTypes.add("Table"); - reportTypes.add("Pentaho"); - reportTypes.add("Chart"); - this.allowedReportTypes = reportTypes; + final List reportTypes = new ArrayList(); + reportTypes.add("Table"); + reportTypes.add("Pentaho"); + reportTypes.add("Chart"); + this.allowedReportTypes = reportTypes; - List reportSubTypes = new ArrayList(); - reportSubTypes.add("Bar"); - reportSubTypes.add("Pie"); - this.allowedReportSubTypes = reportSubTypes; + final List reportSubTypes = new ArrayList(); + reportSubTypes.add("Bar"); + reportSubTypes.add("Pie"); + this.allowedReportSubTypes = reportSubTypes; - this.allowedParameters = allowedParameters; + this.allowedParameters = allowedParameters; - } + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportParameterData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportParameterData.java index 0c6174c77..c90208407 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportParameterData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportParameterData.java @@ -8,20 +8,19 @@ package org.mifosplatform.infrastructure.dataqueries.data; /* used to show list of parameters used by a report and also for getting a list of parameters available (the reportParameterName is left null */ final public class ReportParameterData { - @SuppressWarnings("unused") - private final Long id; - @SuppressWarnings("unused") - private final Long parameterId; - @SuppressWarnings("unused") - private final String parameterName; - @SuppressWarnings("unused") - private final String reportParameterName; + @SuppressWarnings("unused") + private final Long id; + @SuppressWarnings("unused") + private final Long parameterId; + @SuppressWarnings("unused") + private final String parameterName; + @SuppressWarnings("unused") + private final String reportParameterName; - public ReportParameterData(final Long id, final Long parameterId, - final String reportParameterName, final String parameterName) { - this.id = id; - this.parameterId = parameterId; - this.parameterName = parameterName; - this.reportParameterName = reportParameterName; - } + public ReportParameterData(final Long id, final Long parameterId, final String reportParameterName, final String parameterName) { + this.id = id; + this.parameterId = parameterId; + this.parameterName = parameterName; + this.reportParameterName = reportParameterName; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportParameterJoinData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportParameterJoinData.java index dbd1ef775..df63bd442 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportParameterJoinData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ReportParameterJoinData.java @@ -7,92 +7,89 @@ package org.mifosplatform.infrastructure.dataqueries.data; final public class ReportParameterJoinData { - private final Long reportId; - private final String reportName; - private final String reportType; - private final String reportSubType; - private final String reportCategory; - private final String description; - private final String reportSql; - private final Boolean coreReport; - private final Boolean useReport; + private final Long reportId; + private final String reportName; + private final String reportType; + private final String reportSubType; + private final String reportCategory; + private final String description; + private final String reportSql; + private final Boolean coreReport; + private final Boolean useReport; - private final Long reportParameterId; - private final Long parameterId; - private final String reportParameterName; - private final String parameterName; + private final Long reportParameterId; + private final Long parameterId; + private final String reportParameterName; + private final String parameterName; - public ReportParameterJoinData(final Long reportId, - final String reportName, final String reportType, - final String reportSubType, final String reportCategory, - final String description, final String reportSql, - final Boolean coreReport, final Boolean useReport, - final Long reportParameterId, final Long parameterId, - final String reportParameterName, final String parameterName) { - this.reportId = reportId; - this.reportName = reportName; - this.reportType = reportType; - this.reportSubType = reportSubType; - this.reportCategory = reportCategory; - this.description = description; - this.reportSql = reportSql; - this.coreReport = coreReport; - this.useReport = useReport; - this.reportParameterId = reportParameterId; - this.parameterId = parameterId; - this.reportParameterName = reportParameterName; - this.parameterName = parameterName; - } + public ReportParameterJoinData(final Long reportId, final String reportName, final String reportType, final String reportSubType, + final String reportCategory, final String description, final String reportSql, final Boolean coreReport, + final Boolean useReport, final Long reportParameterId, final Long parameterId, final String reportParameterName, + final String parameterName) { + this.reportId = reportId; + this.reportName = reportName; + this.reportType = reportType; + this.reportSubType = reportSubType; + this.reportCategory = reportCategory; + this.description = description; + this.reportSql = reportSql; + this.coreReport = coreReport; + this.useReport = useReport; + this.reportParameterId = reportParameterId; + this.parameterId = parameterId; + this.reportParameterName = reportParameterName; + this.parameterName = parameterName; + } - public Long getReportId() { - return reportId; - } + public Long getReportId() { + return this.reportId; + } - public String getReportName() { - return reportName; - } + public String getReportName() { + return this.reportName; + } - public String getReportType() { - return reportType; - } + public String getReportType() { + return this.reportType; + } - public String getReportSubType() { - return reportSubType; - } + public String getReportSubType() { + return this.reportSubType; + } - public String getReportCategory() { - return reportCategory; - } + public String getReportCategory() { + return this.reportCategory; + } - public String getReportSql() { - return reportSql; - } + public String getReportSql() { + return this.reportSql; + } - public Boolean getCoreReport() { - return coreReport; - } + public Boolean getCoreReport() { + return this.coreReport; + } - public Boolean getUseReport() { - return useReport; - } + public Boolean getUseReport() { + return this.useReport; + } - public Long getReportParameterId() { - return reportParameterId; - } + public Long getReportParameterId() { + return this.reportParameterId; + } - public Long getParameterId() { - return parameterId; - } + public Long getParameterId() { + return this.parameterId; + } - public String getReportParameterName() { - return reportParameterName; - } + public String getReportParameterName() { + return this.reportParameterName; + } - public String getParameterName() { - return parameterName; - } + public String getParameterName() { + return this.parameterName; + } - public String getDescription() { - return description; - } + public String getDescription() { + return this.description; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetColumnHeaderData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetColumnHeaderData.java index edc870db3..cd51c1078 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetColumnHeaderData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetColumnHeaderData.java @@ -39,14 +39,14 @@ public final class ResultsetColumnHeaderData { public static ResultsetColumnHeaderData detailed(final String columnName, final String columnType, final Long columnLength, final boolean columnNullable, final boolean columnIsPrimaryKey, final List columnValues, - String columnCode) { + final String columnCode) { return new ResultsetColumnHeaderData(columnName, columnType, columnLength, columnNullable, columnIsPrimaryKey, columnValues, columnCode); } private ResultsetColumnHeaderData(final String columnName, final String columnType, final Long columnLength, final boolean columnNullable, final boolean columnIsPrimaryKey, final List columnValues, - String columnCode) { + final String columnCode) { this.columnName = columnName; this.columnType = columnType; this.columnLength = columnLength; @@ -119,7 +119,7 @@ public final class ResultsetColumnHeaderData { private boolean isDate() { return "date".equalsIgnoreCase(this.columnType); } - + private boolean isDateTime() { return "datetime".equalsIgnoreCase(this.columnType); } @@ -167,9 +167,9 @@ public final class ResultsetColumnHeaderData { public String getColumnType() { return this.columnType; } - + public Long getColumnLength() { - return this.columnLength; + return this.columnLength; } public String getColumnDisplayType() { @@ -210,7 +210,7 @@ public final class ResultsetColumnHeaderData { public boolean isColumnValueAllowed(final String match) { boolean allowed = false; - for (ResultsetColumnValueData allowedValue : this.columnValues) { + for (final ResultsetColumnValueData allowedValue : this.columnValues) { if (allowedValue.matches(match)) { allowed = true; } @@ -228,7 +228,7 @@ public final class ResultsetColumnHeaderData { public boolean isColumnCodeAllowed(final Integer match) { boolean allowed = false; - for (ResultsetColumnValueData allowedValue : this.columnValues) { + for (final ResultsetColumnValueData allowedValue : this.columnValues) { if (allowedValue.codeMatches(match)) { allowed = true; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetRowData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetRowData.java index 4c78a4d5f..20831e784 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetRowData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/data/ResultsetRowData.java @@ -20,6 +20,6 @@ public class ResultsetRowData { } public List getRow() { - return row; + return this.row; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/Report.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/Report.java index 4d621f737..8c9fa4f43 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/Report.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/Report.java @@ -74,13 +74,27 @@ public final class Report extends AbstractPersistable { boolean useReport = false; String reportSql = null; - if (command.parameterExists("reportName")) reportName = command.stringValueOfParameterNamed("reportName"); - if (command.parameterExists("reportType")) reportType = command.stringValueOfParameterNamed("reportType"); - if (command.parameterExists("reportSubType")) reportSubType = command.stringValueOfParameterNamed("reportSubType"); - if (command.parameterExists("reportCategory")) reportCategory = command.stringValueOfParameterNamed("reportCategory"); - if (command.parameterExists("description")) description = command.stringValueOfParameterNamed("description"); - if (command.parameterExists("useReport")) useReport = command.booleanPrimitiveValueOfParameterNamed("useReport"); - if (command.parameterExists("reportSql")) reportSql = command.stringValueOfParameterNamed("reportSql"); + if (command.parameterExists("reportName")) { + reportName = command.stringValueOfParameterNamed("reportName"); + } + if (command.parameterExists("reportType")) { + reportType = command.stringValueOfParameterNamed("reportType"); + } + if (command.parameterExists("reportSubType")) { + reportSubType = command.stringValueOfParameterNamed("reportSubType"); + } + if (command.parameterExists("reportCategory")) { + reportCategory = command.stringValueOfParameterNamed("reportCategory"); + } + if (command.parameterExists("description")) { + description = command.stringValueOfParameterNamed("description"); + } + if (command.parameterExists("useReport")) { + useReport = command.booleanPrimitiveValueOfParameterNamed("useReport"); + } + if (command.parameterExists("reportSql")) { + reportSql = command.stringValueOfParameterNamed("reportSql"); + } return new Report(reportName, reportType, reportSubType, reportCategory, description, useReport, reportSql); } @@ -151,7 +165,7 @@ public final class Report extends AbstractPersistable { final String reportParametersParamName = "reportParameters"; if (command.hasParameter(reportParametersParamName)) { - JsonArray jsonArray = command.arrayOfParameterNamed(reportParametersParamName); + final JsonArray jsonArray = command.arrayOfParameterNamed(reportParametersParamName); if (jsonArray != null) { actualChanges.put(reportParametersParamName, command.jsonFragment(reportParametersParamName)); } @@ -173,12 +187,12 @@ public final class Report extends AbstractPersistable { } public boolean isCoreReport() { - return coreReport; + return this.coreReport; } public ReportParameterUsage findReportParameterById(final Long reportParameterId) { ReportParameterUsage reportParameterUsage = null; - for (ReportParameterUsage rpu : this.reportParameterUsages) { + for (final ReportParameterUsage rpu : this.reportParameterUsages) { if (rpu.hasIdOf(reportParameterId)) { reportParameterUsage = rpu; break; @@ -229,11 +243,11 @@ public final class Report extends AbstractPersistable { } public String getReportName() { - return reportName; + return this.reportName; } public boolean update(final Set newReportParameterUsages) { - if (newReportParameterUsages == null) return false; + if (newReportParameterUsages == null) { return false; } boolean updated = false; @@ -247,7 +261,7 @@ public final class Report extends AbstractPersistable { private boolean changeInReportParameters(final Set newReportParameterUsages) { - if (!(this.reportParameterUsages.equals(newReportParameterUsages))) return true; + if (!(this.reportParameterUsages.equals(newReportParameterUsages))) { return true; } return false; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/ReportParameterUsage.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/ReportParameterUsage.java index eb705e52f..09524b9cf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/ReportParameterUsage.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/domain/ReportParameterUsage.java @@ -45,9 +45,9 @@ public final class ReportParameterUsage extends AbstractPersistable { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } - ReportParameterUsage rhs = (ReportParameterUsage) obj; + final ReportParameterUsage rhs = (ReportParameterUsage) obj; return new EqualsBuilder().appendSuper(super.equals(obj)) // - .append(this.getId(), rhs.getId()) // + .append(getId(), rhs.getId()) // .append(this.report.getId(), rhs.report.getId()) // .append(this.parameter.getId(), rhs.parameter.getId()) // .append(this.reportParameterName, rhs.reportParameterName) // @@ -57,7 +57,7 @@ public final class ReportParameterUsage extends AbstractPersistable { @Override public int hashCode() { return new HashCodeBuilder(3, 5) // - .append(this.getId()) // + .append(getId()) // .append(this.report.getId()) // .append(this.parameter.getId()) // .append(this.reportParameterName) // diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/exception/ReportNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/exception/ReportNotFoundException.java index 86fad5dc3..69dd74ec8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/exception/ReportNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/exception/ReportNotFoundException.java @@ -15,6 +15,7 @@ public class ReportNotFoundException extends AbstractPlatformResourceNotFoundExc public ReportNotFoundException(final String reportSql) { super("error.msg.report.name.not.found", "Reporting meta-data entry not found.", "Input sql: " + reportSql); } + public ReportNotFoundException(final Long id) { super("error.msg.report.parameter.id.invalid", "Report Parameter with identifier " + id + " does not exist", id); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/CreateDatatableEntryCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/CreateDatatableEntryCommandHandler.java index deee0fec3..9dcc950d0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/CreateDatatableEntryCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/CreateDatatableEntryCommandHandler.java @@ -28,7 +28,7 @@ public class CreateDatatableEntryCommandHandler implements NewCommandSourceHandl @Override public CommandProcessingResult processCommand(final JsonCommand command) { - CommandProcessingResult commandProcessingResult = this.writePlatformService.createNewDatatableEntry(command.entityName(), + final CommandProcessingResult commandProcessingResult = this.writePlatformService.createNewDatatableEntry(command.entityName(), command.entityId(), command); return new CommandProcessingResultBuilder() // diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteDatatableCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteDatatableCommandHandler.java index 4b7d067fc..61a18561a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteDatatableCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteDatatableCommandHandler.java @@ -27,14 +27,11 @@ public class DeleteDatatableCommandHandler implements NewCommandSourceHandler { @Transactional @Override public CommandProcessingResult processCommand(final JsonCommand command) { - - final String datatableName = command.getUrl().replaceAll("/datatables/", ""); - - this.writePlatformService.deleteDatatable(datatableName); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withResourceIdAsString(datatableName) - .build(); + final String datatableName = command.getUrl().replaceAll("/datatables/", ""); + + this.writePlatformService.deleteDatatable(datatableName); + + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withResourceIdAsString(datatableName).build(); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteOneToManyDatatableEntryCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteOneToManyDatatableEntryCommandHandler.java index 0a791f123..04d51b027 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteOneToManyDatatableEntryCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteOneToManyDatatableEntryCommandHandler.java @@ -28,7 +28,7 @@ public class DeleteOneToManyDatatableEntryCommandHandler implements NewCommandSo @Override public CommandProcessingResult processCommand(final JsonCommand command) { - CommandProcessingResult commandProcessingResult = this.writePlatformService.deleteDatatableEntry(command.entityName(), + final CommandProcessingResult commandProcessingResult = this.writePlatformService.deleteDatatableEntry(command.entityName(), command.entityId(), command.subentityId()); return new CommandProcessingResultBuilder() // diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteOneToOneDatatableEntryCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteOneToOneDatatableEntryCommandHandler.java index 301e29bbb..24dc94c39 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteOneToOneDatatableEntryCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/DeleteOneToOneDatatableEntryCommandHandler.java @@ -28,7 +28,7 @@ public class DeleteOneToOneDatatableEntryCommandHandler implements NewCommandSou @Override public CommandProcessingResult processCommand(final JsonCommand command) { - CommandProcessingResult commandProcessingResult = this.writePlatformService.deleteDatatableEntries(command.entityName(), + final CommandProcessingResult commandProcessingResult = this.writePlatformService.deleteDatatableEntries(command.entityName(), command.entityId()); return new CommandProcessingResultBuilder() // diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/UpdateDatatableCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/UpdateDatatableCommandHandler.java index b96a8bfc5..0fa4d7709 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/UpdateDatatableCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/handler/UpdateDatatableCommandHandler.java @@ -27,14 +27,11 @@ public class UpdateDatatableCommandHandler implements NewCommandSourceHandler { @Transactional @Override public CommandProcessingResult processCommand(final JsonCommand command) { - - final String datatableName = command.getUrl().replaceAll("/datatables/", ""); - + + final String datatableName = command.getUrl().replaceAll("/datatables/", ""); + this.writePlatformService.updateDatatable(datatableName, command); - return new CommandProcessingResultBuilder() - .withCommandId(command.commandId()) - .withResourceIdAsString(datatableName) - .build(); + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withResourceIdAsString(datatableName).build(); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/serialization/ReportCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/serialization/ReportCommandFromApiJsonDeserializer.java index b74f6b6eb..3e9d3bd0c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/serialization/ReportCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/serialization/ReportCommandFromApiJsonDeserializer.java @@ -40,6 +40,6 @@ public final class ReportCommandFromApiJsonDeserializer { final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/GenericDataServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/GenericDataServiceImpl.java index ce3cd7874..eddc31168 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/GenericDataServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/GenericDataServiceImpl.java @@ -76,7 +76,7 @@ public class GenericDataServiceImpl implements GenericDataService { // apache one to be about the same then this can be removed. int s = 0; int e = 0; - StringBuffer result = new StringBuffer(); + final StringBuffer result = new StringBuffer(); while ((e = str.indexOf(pattern, s)) >= 0) { result.append(str.substring(s, e)); @@ -101,17 +101,17 @@ public class GenericDataServiceImpl implements GenericDataService { @Override public String generateJsonFromGenericResultsetData(final GenericResultsetData grs) { - StringBuffer writer = new StringBuffer(); + final StringBuffer writer = new StringBuffer(); writer.append("["); final List columnHeaders = grs.getColumnHeaders(); - List data = grs.getData(); + final List data = grs.getData(); List row; Integer rSize; - String doubleQuote = "\""; - String slashDoubleQuote = "\\\""; + final String doubleQuote = "\""; + final String slashDoubleQuote = "\\\""; String currColType; String currVal; @@ -140,7 +140,7 @@ public class GenericDataServiceImpl implements GenericDataService { writer.append(currVal); } else { if (currColType.equals("DATE")) { - LocalDate localDate = new LocalDate(currVal); + final LocalDate localDate = new LocalDate(currVal); writer.append("[" + localDate.getYear() + ", " + localDate.getMonthOfYear() + ", " + localDate.getDayOfMonth() + "]"); } else { @@ -151,7 +151,9 @@ public class GenericDataServiceImpl implements GenericDataService { } else { writer.append("null"); } - if (j < (rSize - 1)) writer.append(",\n"); + if (j < (rSize - 1)) { + writer.append(",\n"); + } } if (i < (data.size() - 1)) { @@ -181,26 +183,26 @@ public class GenericDataServiceImpl implements GenericDataService { final String columnType = columnDefinitions.getString("DATA_TYPE"); final Long columnLength = columnDefinitions.getLong("CHARACTER_MAXIMUM_LENGTH"); - boolean columnNullable = "YES".equalsIgnoreCase(isNullable); - boolean columnIsPrimaryKey = "PRI".equalsIgnoreCase(isPrimaryKey); + final boolean columnNullable = "YES".equalsIgnoreCase(isNullable); + final boolean columnIsPrimaryKey = "PRI".equalsIgnoreCase(isPrimaryKey); List columnValues = new ArrayList(); String codeName = null; if ("varchar".equalsIgnoreCase(columnType)) { - int codePosition = columnName.indexOf("_cv"); + final int codePosition = columnName.indexOf("_cv"); if (codePosition > 0) { codeName = columnName.substring(0, codePosition); columnValues = retreiveColumnValues(codeName); } - + } else if ("int".equalsIgnoreCase(columnType)) { - int codePosition = columnName.indexOf("_cd"); + final int codePosition = columnName.indexOf("_cd"); if (codePosition > 0) { codeName = columnName.substring(0, codePosition); columnValues = retreiveColumnValues(codeName); } } - if(codeName == null){ + if (codeName == null) { final SqlRowSet rsValues = getDatatableCodeData(datatable, columnName); Integer codeId = null; while (rsValues.next()) { @@ -212,7 +214,7 @@ public class GenericDataServiceImpl implements GenericDataService { } final ResultsetColumnHeaderData rsch = ResultsetColumnHeaderData.detailed(columnName, columnType, columnLength, columnNullable, - columnIsPrimaryKey, columnValues,codeName); + columnIsPrimaryKey, columnValues, codeName); columnHeaders.add(rsch); } @@ -228,22 +230,22 @@ public class GenericDataServiceImpl implements GenericDataService { final List columnValues = new ArrayList(); - final String sql = "select v.id, v.code_value from m_code m " + " join m_code_value v on v.code_id = m.id " - + " where m.code_name = '" + codeName + "' order by v.order_position, v.id"; + final String sql = "select v.id, v.code_value from m_code m " + " join m_code_value v on v.code_id = m.id " + + " where m.code_name = '" + codeName + "' order by v.order_position, v.id"; - final SqlRowSet rsValues = this.jdbcTemplate.queryForRowSet(sql); + final SqlRowSet rsValues = this.jdbcTemplate.queryForRowSet(sql); - rsValues.beforeFirst(); - while (rsValues.next()) { - final Integer id = rsValues.getInt("id"); - final String codeValue = rsValues.getString("code_value"); + rsValues.beforeFirst(); + while (rsValues.next()) { + final Integer id = rsValues.getInt("id"); + final String codeValue = rsValues.getString("code_value"); - columnValues.add(new ResultsetColumnValueData(id, codeValue)); - } + columnValues.add(new ResultsetColumnValueData(id, codeValue)); + } return columnValues; } - + private List retreiveColumnValues(final Integer codeId) { final List columnValues = new ArrayList(); @@ -274,7 +276,7 @@ public class GenericDataServiceImpl implements GenericDataService { throw new DatatableNotFoundException(datatable); } - private SqlRowSet getDatatableCodeData(final String datatable, String columnName) { + private SqlRowSet getDatatableCodeData(final String datatable, final String columnName) { final String sql = "select mc.id,mc.code_name from m_code mc join x_table_cloumn_code_mappings xcc on xcc.code_id = mc.id where xcc.column_alias_name='" + datatable.toLowerCase().replaceAll("\\s", "_") + "_" + columnName + "'"; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadReportingServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadReportingServiceImpl.java index 025af12e3..8c04afc36 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadReportingServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadReportingServiceImpl.java @@ -84,7 +84,7 @@ public class ReadReportingServiceImpl implements ReadReportingService { final GenericDataService genericDataService) { // kick off pentaho reports server ClassicEngineBoot.getInstance().start(); - noPentaho = false; + this.noPentaho = false; this.context = context; this.dataSource = dataSource; @@ -101,12 +101,12 @@ public class ReadReportingServiceImpl implements ReadReportingService { public void write(final OutputStream out) { try { - GenericResultsetData result = retrieveGenericResultset(name, type, queryParams); - StringBuffer sb = generateCsvFileBuffer(result); + final GenericResultsetData result = retrieveGenericResultset(name, type, queryParams); + final StringBuffer sb = generateCsvFileBuffer(result); - InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8")); + final InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8")); - byte[] outputByte = new byte[4096]; + final byte[] outputByte = new byte[4096]; Integer readLen = in.read(outputByte, 0, 4096); while (readLen != -1) { @@ -116,7 +116,7 @@ public class ReadReportingServiceImpl implements ReadReportingService { // in.close(); // out.flush(); // out.close(); - } catch (Exception e) { + } catch (final Exception e) { throw new PlatformDataIntegrityException("error.msg.exception.error", e.getMessage()); } } @@ -125,25 +125,27 @@ public class ReadReportingServiceImpl implements ReadReportingService { } private StringBuffer generateCsvFileBuffer(final GenericResultsetData result) { - StringBuffer writer = new StringBuffer(); + final StringBuffer writer = new StringBuffer(); - List columnHeaders = result.getColumnHeaders(); + final List columnHeaders = result.getColumnHeaders(); logger.info("NO. of Columns: " + columnHeaders.size()); - Integer chSize = columnHeaders.size(); + final Integer chSize = columnHeaders.size(); for (int i = 0; i < chSize; i++) { writer.append('"' + columnHeaders.get(i).getColumnName() + '"'); - if (i < (chSize - 1)) writer.append(","); + if (i < (chSize - 1)) { + writer.append(","); + } } writer.append('\n'); - List data = result.getData(); + final List data = result.getData(); List row; Integer rSize; // String currCol; String currColType; String currVal; - String doubleQuote = "\""; - String twoDoubleQuotes = doubleQuote + doubleQuote; + final String doubleQuote = "\""; + final String twoDoubleQuotes = doubleQuote + doubleQuote; logger.info("NO. of Rows: " + data.size()); for (int i = 0; i < data.size(); i++) { row = data.get(i).getRow(); @@ -154,13 +156,16 @@ public class ReadReportingServiceImpl implements ReadReportingService { currVal = row.get(j); if (currVal != null) { if (currColType.equals("DECIMAL") || currColType.equals("DOUBLE") || currColType.equals("BIGINT") - || currColType.equals("SMALLINT") || currColType.equals("INT")) + || currColType.equals("SMALLINT") || currColType.equals("INT")) { writer.append(currVal); - else - writer.append('"' + genericDataService.replace(currVal, doubleQuote, twoDoubleQuotes) + '"'); + } else { + writer.append('"' + this.genericDataService.replace(currVal, doubleQuote, twoDoubleQuotes) + '"'); + } } - if (j < (rSize - 1)) writer.append(","); + if (j < (rSize - 1)) { + writer.append(","); + } } writer.append('\n'); } @@ -171,14 +176,14 @@ public class ReadReportingServiceImpl implements ReadReportingService { @Override public GenericResultsetData retrieveGenericResultset(final String name, final String type, final Map queryParams) { - long startTime = System.currentTimeMillis(); + final long startTime = System.currentTimeMillis(); logger.info("STARTING REPORT: " + name + " Type: " + type); - String sql = getSQLtoRun(name, type, queryParams); + final String sql = getSQLtoRun(name, type, queryParams); - GenericResultsetData result = genericDataService.fillGenericResultSet(sql); + final GenericResultsetData result = this.genericDataService.fillGenericResultSet(sql); - long elapsed = System.currentTimeMillis() - startTime; + final long elapsed = System.currentTimeMillis() - startTime; logger.info("FINISHING Report/Request Name: " + name + " - " + type + " Elapsed Time: " + elapsed); return result; } @@ -187,22 +192,22 @@ public class ReadReportingServiceImpl implements ReadReportingService { String sql = getSql(name, type); - Set keys = queryParams.keySet(); - for (String key : keys) { - String pValue = queryParams.get(key); + final Set keys = queryParams.keySet(); + for (final String key : keys) { + final String pValue = queryParams.get(key); // logger.info("(" + key + " : " + pValue + ")"); - sql = genericDataService.replace(sql, key, pValue); + sql = this.genericDataService.replace(sql, key, pValue); } - AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); // Allows sql query to restrict data by office hierarchy if required - sql = genericDataService.replace(sql, "${currentUserHierarchy}", currentUser.getOffice().getHierarchy()); + sql = this.genericDataService.replace(sql, "${currentUserHierarchy}", currentUser.getOffice().getHierarchy()); // Allows sql query to restrict data by current user Id if required // (typically used to return report lists containing only reports // permitted to be run by the user - sql = genericDataService.replace(sql, "${currentUserId}", currentUser.getId().toString()); + sql = this.genericDataService.replace(sql, "${currentUserId}", currentUser.getId().toString()); - sql = genericDataService.wrapSQL(sql); + sql = this.genericDataService.wrapSQL(sql); return sql; @@ -211,7 +216,7 @@ public class ReadReportingServiceImpl implements ReadReportingService { private String getSql(final String name, final String type) { final String inputSql = "select " + type + "_sql as the_sql from stretchy_" + type + " where " + type + "_name = '" + name + "'"; - final String inputSqlWrapped = genericDataService.wrapSQL(inputSql); + final String inputSqlWrapped = this.genericDataService.wrapSQL(inputSql); final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(inputSqlWrapped); @@ -224,7 +229,7 @@ public class ReadReportingServiceImpl implements ReadReportingService { final String sql = "SELECT ifnull(report_type,'') as report_type FROM `stretchy_report` where report_name = '" + reportName + "'"; - final String sqlWrapped = genericDataService.wrapSQL(sql); + final String sqlWrapped = this.genericDataService.wrapSQL(sql); final SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sqlWrapped); @@ -237,13 +242,15 @@ public class ReadReportingServiceImpl implements ReadReportingService { final Locale locale) { String outputType = "HTML"; - if (StringUtils.isNotBlank(outputTypeParam)) outputType = outputTypeParam; + if (StringUtils.isNotBlank(outputTypeParam)) { + outputType = outputTypeParam; + } if (!(outputType.equalsIgnoreCase("HTML") || outputType.equalsIgnoreCase("PDF") || outputType.equalsIgnoreCase("XLS") || outputType - .equalsIgnoreCase("CSV"))) - throw new PlatformDataIntegrityException("error.msg.invalid.outputType", "No matching Output Type: " + outputType); + .equalsIgnoreCase("CSV"))) { throw new PlatformDataIntegrityException("error.msg.invalid.outputType", + "No matching Output Type: " + outputType); } - if (noPentaho) { throw new PlatformDataIntegrityException("error.msg.no.pentaho", "Pentaho is not enabled", + if (this.noPentaho) { throw new PlatformDataIntegrityException("error.msg.no.pentaho", "Pentaho is not enabled", "Pentaho is not enabled"); } final String reportPath = FileSystemContentRepository.MIFOSX_BASE_DIR + File.separator + "pentahoReports" + File.separator @@ -251,20 +258,20 @@ public class ReadReportingServiceImpl implements ReadReportingService { logger.info("Report path: " + reportPath); // load report definition - ResourceManager manager = new ResourceManager(); + final ResourceManager manager = new ResourceManager(); manager.registerDefaults(); Resource res; try { res = manager.createDirectly(reportPath, MasterReport.class); - MasterReport masterReport = (MasterReport) res.getResource(); - DefaultReportEnvironment reportEnvironment = (DefaultReportEnvironment) masterReport.getReportEnvironment(); + final MasterReport masterReport = (MasterReport) res.getResource(); + final DefaultReportEnvironment reportEnvironment = (DefaultReportEnvironment) masterReport.getReportEnvironment(); if (locale != null) { reportEnvironment.setLocale(locale); } addParametersToReport(masterReport, queryParams); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); if ("PDF".equalsIgnoreCase(outputType)) { PdfReportUtil.createPDF(masterReport, baos); @@ -287,11 +294,11 @@ public class ReadReportingServiceImpl implements ReadReportingService { HtmlReportUtil.createStreamHTML(masterReport, baos); return Response.ok().entity(baos.toByteArray()).type("text/html").build(); } - } catch (ResourceException e) { + } catch (final ResourceException e) { throw new PlatformDataIntegrityException("error.msg.reporting.error", e.getMessage()); - } catch (ReportProcessingException e) { + } catch (final ReportProcessingException e) { throw new PlatformDataIntegrityException("error.msg.reporting.error", e.getMessage()); - } catch (IOException e) { + } catch (final IOException e) { throw new PlatformDataIntegrityException("error.msg.reporting.error", e.getMessage()); } @@ -300,12 +307,12 @@ public class ReadReportingServiceImpl implements ReadReportingService { private void addParametersToReport(final MasterReport report, final Map queryParams) { - AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); try { - ReportParameterValues rptParamValues = report.getParameterValues(); - ReportParameterDefinition paramsDefinition = report.getParameterDefinition(); + final ReportParameterValues rptParamValues = report.getParameterValues(); + final ReportParameterDefinition paramsDefinition = report.getParameterDefinition(); /* * only allow integer, long, date and string parameter types and @@ -314,25 +321,25 @@ public class ReadReportingServiceImpl implements ReadReportingService { * better... currently assuming they come in ok... and if not an * error */ - for (ParameterDefinitionEntry paramDefEntry : paramsDefinition.getParameterDefinitions()) { - String paramName = paramDefEntry.getName(); + for (final ParameterDefinitionEntry paramDefEntry : paramsDefinition.getParameterDefinitions()) { + final String paramName = paramDefEntry.getName(); if (!((paramName.equals("tenantdb")) || (paramName.equals("userhierarchy")))) { logger.info("paramName:" + paramName); - String pValue = queryParams.get(paramName); - if (StringUtils.isBlank(pValue)) - throw new PlatformDataIntegrityException("error.msg.reporting.error", "Pentaho Parameter: " + paramName - + " - not Provided"); + final String pValue = queryParams.get(paramName); + if (StringUtils.isBlank(pValue)) { throw new PlatformDataIntegrityException("error.msg.reporting.error", + "Pentaho Parameter: " + paramName + " - not Provided"); } - Class clazz = paramDefEntry.getValueType(); + final Class clazz = paramDefEntry.getValueType(); logger.info("addParametersToReport(" + paramName + " : " + pValue + " : " + clazz.getCanonicalName() + ")"); - if (clazz.getCanonicalName().equalsIgnoreCase("java.lang.Integer")) + if (clazz.getCanonicalName().equalsIgnoreCase("java.lang.Integer")) { rptParamValues.put(paramName, Integer.parseInt(pValue)); - else if (clazz.getCanonicalName().equalsIgnoreCase("java.lang.Long")) + } else if (clazz.getCanonicalName().equalsIgnoreCase("java.lang.Long")) { rptParamValues.put(paramName, Long.parseLong(pValue)); - else if (clazz.getCanonicalName().equalsIgnoreCase("java.sql.Date")) + } else if (clazz.getCanonicalName().equalsIgnoreCase("java.sql.Date")) { rptParamValues.put(paramName, Date.valueOf(pValue)); - else + } else { rptParamValues.put(paramName, pValue); + } } } @@ -341,18 +348,18 @@ public class ReadReportingServiceImpl implements ReadReportingService { // passed as parameters to allow multitenant penaho reporting // and // data scoping - Connection connection = dataSource.getConnection(); + final Connection connection = this.dataSource.getConnection(); String tenantdb; try { tenantdb = connection.getCatalog(); } finally { connection.close(); } - String userhierarchy = currentUser.getOffice().getHierarchy(); + final String userhierarchy = currentUser.getOffice().getHierarchy(); logger.info("db name:" + tenantdb + " userhierarchy:" + userhierarchy); rptParamValues.put("tenantdb", tenantdb); rptParamValues.put("userhierarchy", userhierarchy); - } catch (Exception e) { + } catch (final Exception e) { logger.error("error.msg.reporting.error:" + e.getMessage()); throw new PlatformDataIntegrityException("error.msg.reporting.error", e.getMessage()); } @@ -361,29 +368,29 @@ public class ReadReportingServiceImpl implements ReadReportingService { @Override public String retrieveReportPDF(final String reportName, final String type, final Map queryParams) { - String fileLocation = FileSystemContentRepository.MIFOSX_BASE_DIR + File.separator + ""; + final String fileLocation = FileSystemContentRepository.MIFOSX_BASE_DIR + File.separator + ""; if (!new File(fileLocation).isDirectory()) { new File(fileLocation).mkdirs(); } - String genaratePdf = fileLocation + File.separator + reportName + ".pdf"; + final String genaratePdf = fileLocation + File.separator + reportName + ".pdf"; try { - GenericResultsetData result = retrieveGenericResultset(reportName, type, queryParams); + final GenericResultsetData result = retrieveGenericResultset(reportName, type, queryParams); - List columnHeaders = result.getColumnHeaders(); - List data = result.getData(); + final List columnHeaders = result.getColumnHeaders(); + final List data = result.getData(); List row; logger.info("NO. of Columns: " + columnHeaders.size()); - Integer chSize = columnHeaders.size(); + final Integer chSize = columnHeaders.size(); - Document document = new Document(PageSize.B0.rotate()); + final Document document = new Document(PageSize.B0.rotate()); PdfWriter.getInstance(document, new FileOutputStream(new File(fileLocation + reportName + ".pdf"))); document.open(); - PdfPTable table = new PdfPTable(chSize); + final PdfPTable table = new PdfPTable(chSize); table.setWidthPercentage(100); for (int i = 0; i < chSize; i++) { @@ -418,7 +425,7 @@ public class ReadReportingServiceImpl implements ReadReportingService { document.add(table); document.close(); return genaratePdf; - } catch (Exception e) { + } catch (final Exception e) { logger.error("error.msg.reporting.error:" + e.getMessage()); throw new PlatformDataIntegrityException("error.msg.exception.error", e.getMessage()); } @@ -426,9 +433,9 @@ public class ReadReportingServiceImpl implements ReadReportingService { @Override public ReportData retrieveReport(final Long id) { - Collection reports = retrieveReports(id); + final Collection reports = retrieveReports(id); - for (ReportData report : reports) { + for (final ReportData report : reports) { return report; } return null; @@ -441,14 +448,14 @@ public class ReadReportingServiceImpl implements ReadReportingService { private Collection retrieveReports(final Long id) { - ReportParameterJoinMapper rm = new ReportParameterJoinMapper(); + final ReportParameterJoinMapper rm = new ReportParameterJoinMapper(); - String sql = rm.schema(id); + final String sql = rm.schema(id); - Collection rpJoins = this.jdbcTemplate.query(sql, rm, new Object[] {}); + final Collection rpJoins = this.jdbcTemplate.query(sql, rm, new Object[] {}); - Collection reportList = new ArrayList(); - if (rpJoins == null || rpJoins.size() == 0) return reportList; + final Collection reportList = new ArrayList(); + if (rpJoins == null || rpJoins.size() == 0) { return reportList; } Collection reportParameters = null; @@ -464,7 +471,7 @@ public class ReadReportingServiceImpl implements ReadReportingService { Long prevReportId = (long) -1234; Boolean firstReport = true; - for (ReportParameterJoinData rpJoin : rpJoins) { + for (final ReportParameterJoinData rpJoin : rpJoins) { if (rpJoin.getReportId().equals(prevReportId)) { // more than one parameter for report @@ -516,9 +523,9 @@ public class ReadReportingServiceImpl implements ReadReportingService { @Override public Collection getAllowedParameters() { - ReportParameterMapper rm = new ReportParameterMapper(); - String sql = rm.schema(); - Collection parameters = this.jdbcTemplate.query(sql, rm, new Object[] {}); + final ReportParameterMapper rm = new ReportParameterMapper(); + final String sql = rm.schema(); + final Collection parameters = this.jdbcTemplate.query(sql, rm, new Object[] {}); return parameters; } @@ -530,14 +537,17 @@ public class ReadReportingServiceImpl implements ReadReportingService { + " r.report_subtype as reportSubType, r.report_category as reportCategory, r.description, r.core_report as coreReport, r.use_report as useReport, " + " rp.id as reportParameterId, rp.parameter_id as parameterId, rp.report_parameter_name as reportParameterName, p.parameter_name as parameterName"; - if (reportId != null) sql += ", r.report_sql as reportSql "; + if (reportId != null) { + sql += ", r.report_sql as reportSql "; + } sql += " from stretchy_report r" + " left join stretchy_report_parameter rp on rp.report_id = r.id" + " left join stretchy_parameter p on p.id = rp.parameter_id"; - if (reportId != null) + if (reportId != null) { sql += " where r.id = " + reportId; - else + } else { sql += " order by r.id, rp.parameter_id"; + } return sql; @@ -571,7 +581,7 @@ public class ReadReportingServiceImpl implements ReadReportingService { // reportSql might not be on the select list of columns try { reportSql = rs.getString("reportSql"); - } catch (SQLException e) { + } catch (final SQLException e) { reportSql = null; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java index 5f67f4768..e50a41cb1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataService.java @@ -16,9 +16,9 @@ import org.springframework.security.access.prepost.PreAuthorize; public interface ReadWriteNonCoreDataService { List retrieveDatatableNames(String appTable); - + DatatableData retrieveDatatable(String datatable); - + @PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'REGISTER_DATATABLE')") void registerDatatable(String datatable, String appTable); @@ -28,7 +28,7 @@ public interface ReadWriteNonCoreDataService { GenericResultsetData retrieveDataTableGenericResultSet(String datatable, Long appTableId, String order, Long id); CommandProcessingResult createDatatable(JsonCommand command); - + void updateDatatable(String datatableName, JsonCommand command); void deleteDatatable(String datatableName); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java index 06517b50f..a5fd1dd6c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java @@ -120,7 +120,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final String sql = "select application_table_name, registered_table_name" + " from x_registered_table " + " where exists" + " (select 'f'" + " from m_appuser_role ur " + " join m_role r on r.id = ur.role_id" + " left join m_role_permission rp on rp.role_id = r.id" + " left join m_permission p on p.id = rp.permission_id" - + " where ur.appuser_id = " + context.authenticatedUser().getId() + + " where ur.appuser_id = " + this.context.authenticatedUser().getId() + " and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) " + andClause + " order by application_table_name, registered_table_name"; @@ -146,7 +146,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final String sql = "select application_table_name, registered_table_name" + " from x_registered_table " + " where exists" + " (select 'f'" + " from m_appuser_role ur " + " join m_role r on r.id = ur.role_id" + " left join m_role_permission rp on rp.role_id = r.id" + " left join m_permission p on p.id = rp.permission_id" - + " where ur.appuser_id = " + context.authenticatedUser().getId() + " and registered_table_name='" + datatable + "'" + + " where ur.appuser_id = " + this.context.authenticatedUser().getId() + " and registered_table_name='" + datatable + "'" + " and (p.code in ('ALL_FUNCTIONS', 'ALL_FUNCTIONS_READ') or p.code = concat('READ_', registered_table_name))) " + " order by application_table_name, registered_table_name"; @@ -224,22 +224,22 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ + dataTableName + "', false)"; try { - String[] sqlArray = { registerDatatableSql, permissionsSql }; + final String[] sqlArray = { registerDatatableSql, permissionsSql }; this.jdbcTemplate.batchUpdate(sqlArray); } - /*** + final /*** * Strangely, a Hibernate contraint violation exception is thrown ****/ catch (ConstraintViolationException cve) { - Throwable realCause = cve.getCause(); + final Throwable realCause = cve.getCause(); // even if duplicate is only due to permission duplicate, okay to // show duplicate datatable error msg if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( "error.msg.datatable.registered", "Datatable `" + dataTableName + "` is already registered against an application table.", "dataTableName", dataTableName); } - } catch (DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + } catch (final DataIntegrityViolationException dve) { + final Throwable realCause = dve.getMostSpecificCause(); // even if duplicate is only due to permission duplicate, okay to // show duplicate datatable error msg if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( @@ -266,7 +266,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final String deleteRegisteredDatatableSql = "delete from x_registered_table where registered_table_name = '" + datatable + "'"; String[] sqlArray = null; - if (configurationDomainService.isConstraintApproachEnabledForDatatables()) { + if (this.configurationDomainService.isConstraintApproachEnabledForDatatables()) { final String deleteColumnCodeSql = "delete from x_table_cloumn_code_mappings where column_alias_name like'" + datatable.toLowerCase().replaceAll("\\s", "_") + "%'"; sqlArray = new String[4]; @@ -287,7 +287,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ try { final String appTable = queryForApplicationTableName(dataTableName); - CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); + final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); final List columnHeaders = this.genericDataService.fillResultsetColumnHeaders(dataTableName); @@ -300,11 +300,11 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ return commandProcessingResult; // - } catch (ConstraintViolationException dve) { + } catch (final ConstraintViolationException dve) { // NOTE: jdbctemplate throws a // org.hibernate.exception.ConstraintViolationException even though // it should be a DataAccessException? - Throwable realCause = dve.getCause(); + final Throwable realCause = dve.getCause(); if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName + "` and application table with identifier `" + appTableId + "`.", "dataTableName", dataTableName, appTableId); } @@ -312,8 +312,8 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ logAsErrorUnexpectedDataIntegrityException(dve); throw new PlatformDataIntegrityException("error.msg.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); - } catch (DataAccessException dve) { - Throwable realCause = dve.getMostSpecificCause(); + } catch (final DataAccessException dve) { + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("Duplicate entry")) { throw new PlatformDataIntegrityException( "error.msg.datatable.entry.duplicate", "An entry already exists for datatable `" + dataTableName + "` and application table with identifier `" + appTableId + "`.", "dataTableName", dataTableName, appTableId); } @@ -331,7 +331,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ return new Boolean(isRegisteredDataTable); } - private void assertDataTableExists(String datatableName) { + private void assertDataTableExists(final String datatableName) { final String sql = "select if((exists (select 1 from information_schema.tables where table_schema = schema() and table_name = ?)) = 1, 'true', 'false')"; final String dataTableExistsString = this.jdbcTemplate.queryForObject(sql, String.class, new Object[] { datatableName }); final boolean dataTableExists = new Boolean(dataTableExistsString); @@ -357,18 +357,19 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ "Validation errors exist.", dataValidationErrors); } } - private void parseDatatableColumnObjectForCreate(final JsonObject column, StringBuilder sqlBuilder, StringBuilder constrainBuilder, - String dataTableNameAlias, Map codeMappings, boolean isConstraintApproach) { + private void parseDatatableColumnObjectForCreate(final JsonObject column, StringBuilder sqlBuilder, + final StringBuilder constrainBuilder, final String dataTableNameAlias, final Map codeMappings, + final boolean isConstraintApproach) { String name = (column.has("name")) ? column.get("name").getAsString() : null; - String type = (column.has("type")) ? column.get("type").getAsString() : null; - Integer length = (column.has("length")) ? column.get("length").getAsInt() : null; - Boolean mandatory = (column.has("mandatory")) ? column.get("mandatory").getAsBoolean() : false; - String code = (column.has("code")) ? column.get("code").getAsString() : null; + final String type = (column.has("type")) ? column.get("type").getAsString() : null; + final Integer length = (column.has("length")) ? column.get("length").getAsInt() : null; + final Boolean mandatory = (column.has("mandatory")) ? column.get("mandatory").getAsBoolean() : false; + final String code = (column.has("code")) ? column.get("code").getAsString() : null; if (StringUtils.isNotBlank(code)) { if (isConstraintApproach) { - codeMappings.put(dataTableNameAlias + "_" + name, codeReadPlatformService.retriveCode(code).getCodeId()); + codeMappings.put(dataTableNameAlias + "_" + name, this.codeReadPlatformService.retriveCode(code).getCodeId()); constrainBuilder.append(", CONSTRAINT `fk_").append(dataTableNameAlias).append("_").append(name).append("` ") .append("FOREIGN KEY (`" + name + "`) ").append("REFERENCES `").append(CODE_VALUES_TABLE).append("` (`id`)"); } else { @@ -376,7 +377,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } - String mysqlType = apiTypeToMySQL.get(type); + final String mysqlType = apiTypeToMySQL.get(type); sqlBuilder = sqlBuilder.append("`" + name + "` " + mysqlType); if (type != null) { @@ -406,13 +407,13 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ String datatableName = null; try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); - JsonElement element = this.fromJsonHelper.parse(command.json()); - JsonArray columns = this.fromJsonHelper.extractJsonArrayNamed("columns", element); + final JsonElement element = this.fromJsonHelper.parse(command.json()); + final JsonArray columns = this.fromJsonHelper.extractJsonArrayNamed("columns", element); datatableName = this.fromJsonHelper.extractStringNamed("datatableName", element); - String apptableName = this.fromJsonHelper.extractStringNamed("apptableName", element); + final String apptableName = this.fromJsonHelper.extractStringNamed("apptableName", element); Boolean multiRow = this.fromJsonHelper.extractBooleanNamed("multiRow", element); /*** @@ -422,7 +423,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ * Ex: Centers are a specific type of group, add abstractions for * the same ***/ - String actualAppTableName = mapToActualAppTable(apptableName); + final String actualAppTableName = mapToActualAppTable(apptableName); if (multiRow == null) { multiRow = false; @@ -430,13 +431,13 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ validateDatatableName(datatableName); validateAppTable(apptableName); - boolean isConstraintApproach = configurationDomainService.isConstraintApproachEnabledForDatatables(); - String fkColumnName = apptableName.substring(2) + "_id"; + final boolean isConstraintApproach = this.configurationDomainService.isConstraintApproachEnabledForDatatables(); + final String fkColumnName = apptableName.substring(2) + "_id"; final String dataTableNameAlias = datatableName.toLowerCase().replaceAll("\\s", "_"); - String fkName = dataTableNameAlias + "_" + fkColumnName; + final String fkName = dataTableNameAlias + "_" + fkColumnName; StringBuilder sqlBuilder = new StringBuilder(); - StringBuilder constrainBuilder = new StringBuilder(); - Map codeMappings = new HashMap(); + final StringBuilder constrainBuilder = new StringBuilder(); + final Map codeMappings = new HashMap(); sqlBuilder = sqlBuilder.append("CREATE TABLE `" + datatableName + "` ("); if (multiRow) { @@ -446,7 +447,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ sqlBuilder = sqlBuilder.append("`" + fkColumnName + "` BIGINT(20) NOT NULL, "); } - for (JsonElement column : columns) { + for (final JsonElement column : columns) { parseDatatableColumnObjectForCreate(column.getAsJsonObject(), sqlBuilder, constrainBuilder, dataTableNameAlias, codeMappings, isConstraintApproach); } @@ -471,9 +472,9 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ registerDatatable(datatableName, apptableName); registerColumnCodeMapping(codeMappings); - } catch (SQLGrammarException e) { - Throwable realCause = e.getCause(); - List dataValidationErrors = new ArrayList(); + } catch (final SQLGrammarException e) { + final Throwable realCause = e.getCause(); + final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable"); if (realCause.getMessage().toLowerCase().contains("duplicate column name")) { @@ -493,25 +494,26 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } private void parseDatatableColumnForUpdate(final JsonObject column, - final Map mapColumnNameDefinition, StringBuilder sqlBuilder, String datatableName, - StringBuilder constrainBuilder, Map codeMappings, List removeMappings, boolean isConstraintApproach) { + final Map mapColumnNameDefinition, StringBuilder sqlBuilder, final String datatableName, + final StringBuilder constrainBuilder, final Map codeMappings, final List removeMappings, + final boolean isConstraintApproach) { String name = (column.has("name")) ? column.get("name").getAsString() : null; - String lengthStr = (column.has("length")) ? column.get("length").getAsString() : null; + final String lengthStr = (column.has("length")) ? column.get("length").getAsString() : null; Integer length = (StringUtils.isNotBlank(lengthStr)) ? Integer.parseInt(lengthStr) : null; String newName = (column.has("newName")) ? column.get("newName").getAsString() : name; - Boolean mandatory = (column.has("mandatory")) ? column.get("mandatory").getAsBoolean() : false; - String after = (column.has("after")) ? column.get("after").getAsString() : null; - String code = (column.has("code")) ? column.get("code").getAsString() : null; - String newCode = (column.has("newCode")) ? column.get("newCode").getAsString() : null; - String dataTableNameAlias = datatableName.toLowerCase().replaceAll("\\s", "_"); + final Boolean mandatory = (column.has("mandatory")) ? column.get("mandatory").getAsBoolean() : false; + final String after = (column.has("after")) ? column.get("after").getAsString() : null; + final String code = (column.has("code")) ? column.get("code").getAsString() : null; + final String newCode = (column.has("newCode")) ? column.get("newCode").getAsString() : null; + final String dataTableNameAlias = datatableName.toLowerCase().replaceAll("\\s", "_"); if (isConstraintApproach) { if (StringUtils.isBlank(newName)) { newName = name; } if (!StringUtils.equalsIgnoreCase(code, newCode) || !StringUtils.equalsIgnoreCase(name, newName)) { if (StringUtils.equalsIgnoreCase(code, newCode)) { - int codeId = getCodeIdForColumn(dataTableNameAlias, name); + final int codeId = getCodeIdForColumn(dataTableNameAlias, name); if (codeId > 0) { removeMappings.add(dataTableNameAlias + "_" + name); constrainBuilder.append(", DROP FOREIGN KEY `fk_").append(dataTableNameAlias).append("_").append(name).append("` "); @@ -530,7 +532,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } if (newCode != null) { - codeMappings.put(dataTableNameAlias + "_" + newName, codeReadPlatformService.retriveCode(newCode).getCodeId()); + codeMappings.put(dataTableNameAlias + "_" + newName, this.codeReadPlatformService.retriveCode(newCode).getCodeId()); if (code == null) { constrainBuilder.append(",ADD CONSTRAINT `fk_").append(dataTableNameAlias).append("_").append(newName) .append("` ").append("FOREIGN KEY (`" + newName + "`) ").append("REFERENCES `") @@ -551,7 +553,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } if (!mapColumnNameDefinition.containsKey(name)) { throw new PlatformDataIntegrityException( "error.msg.datatable.column.missing.update.parse", "Column " + name + " does not exist.", name); } - String type = mapColumnNameDefinition.get(name).getColumnType(); + final String type = mapColumnNameDefinition.get(name).getColumnType(); if (length == null && type.toLowerCase().equals("varchar")) { length = mapColumnNameDefinition.get(name).getColumnLength().intValue(); } @@ -577,33 +579,32 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } - private int getCodeIdForColumn(String dataTableNameAlias, String name) { - StringBuilder checkColumnCodeMapping = new StringBuilder(); + private int getCodeIdForColumn(final String dataTableNameAlias, final String name) { + final StringBuilder checkColumnCodeMapping = new StringBuilder(); checkColumnCodeMapping.append("select ccm.code_id from x_table_cloumn_code_mappings ccm where ccm.column_alias_name='") .append(dataTableNameAlias).append("_").append(name).append("'"); int codeId = 0; try { codeId = this.jdbcTemplate.queryForInt(checkColumnCodeMapping.toString()); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { logger.info(e.getMessage()); } return codeId; } - - private void parseDatatableColumnForAdd(final JsonObject column, StringBuilder sqlBuilder, String dataTableNameAlias, - StringBuilder constrainBuilder, Map codeMappings, boolean isConstraintApproach) { + private void parseDatatableColumnForAdd(final JsonObject column, StringBuilder sqlBuilder, final String dataTableNameAlias, + final StringBuilder constrainBuilder, final Map codeMappings, final boolean isConstraintApproach) { String name = (column.has("name")) ? column.get("name").getAsString() : null; - String type = (column.has("type")) ? column.get("type").getAsString() : null; - Integer length = (column.has("length")) ? column.get("length").getAsInt() : null; - Boolean mandatory = (column.has("mandatory")) ? column.get("mandatory").getAsBoolean() : false; - String after = (column.has("after")) ? column.get("after").getAsString() : null; - String code = (column.has("code")) ? column.get("code").getAsString() : null; + final String type = (column.has("type")) ? column.get("type").getAsString() : null; + final Integer length = (column.has("length")) ? column.get("length").getAsInt() : null; + final Boolean mandatory = (column.has("mandatory")) ? column.get("mandatory").getAsBoolean() : false; + final String after = (column.has("after")) ? column.get("after").getAsString() : null; + final String code = (column.has("code")) ? column.get("code").getAsString() : null; if (StringUtils.isNotBlank(code)) { if (isConstraintApproach) { - codeMappings.put(dataTableNameAlias + "_" + name, codeReadPlatformService.retriveCode(code).getCodeId()); + codeMappings.put(dataTableNameAlias + "_" + name, this.codeReadPlatformService.retriveCode(code).getCodeId()); constrainBuilder.append(",ADD CONSTRAINT `fk_").append(dataTableNameAlias).append("_").append(name).append("` ") .append("FOREIGN KEY (`" + name + "`) ").append("REFERENCES `").append(CODE_VALUES_TABLE).append("` (`id`)"); } else { @@ -611,7 +612,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } - String mysqlType = apiTypeToMySQL.get(type); + final String mysqlType = apiTypeToMySQL.get(type); sqlBuilder = sqlBuilder.append(", ADD `" + name + "` " + mysqlType); if (type != null) { @@ -635,28 +636,28 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } - private void parseDatatableColumnForDrop(final JsonObject column, StringBuilder sqlBuilder, String datatableName, - StringBuilder constrainBuilder, List codeMappings) { - String datatableAlias = datatableName.toLowerCase().replaceAll("\\s", "_"); - String name = (column.has("name")) ? column.get("name").getAsString() : null; + private void parseDatatableColumnForDrop(final JsonObject column, StringBuilder sqlBuilder, final String datatableName, + final StringBuilder constrainBuilder, final List codeMappings) { + final String datatableAlias = datatableName.toLowerCase().replaceAll("\\s", "_"); + final String name = (column.has("name")) ? column.get("name").getAsString() : null; sqlBuilder = sqlBuilder.append(", DROP COLUMN `" + name + "`"); - StringBuilder findFKSql = new StringBuilder(); + final StringBuilder findFKSql = new StringBuilder(); findFKSql.append("SELECT count(*)").append("FROM information_schema.TABLE_CONSTRAINTS i") .append(" WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY'").append(" AND i.TABLE_SCHEMA = DATABASE()") .append(" AND i.TABLE_NAME = '").append(datatableName).append("' AND i.CONSTRAINT_NAME = 'fk_").append(datatableAlias) .append("_").append(name).append("' "); - int count = this.jdbcTemplate.queryForInt(findFKSql.toString()); + final int count = this.jdbcTemplate.queryForInt(findFKSql.toString()); if (count > 0) { codeMappings.add(datatableAlias + "_" + name); constrainBuilder.append(", DROP FOREIGN KEY `fk_").append(datatableAlias).append("_").append(name).append("` "); } } - private void registerColumnCodeMapping(Map codeMappings) { + private void registerColumnCodeMapping(final Map codeMappings) { if (codeMappings != null && !codeMappings.isEmpty()) { - String[] addSqlList = new String[codeMappings.size()]; + final String[] addSqlList = new String[codeMappings.size()]; int i = 0; - for (Map.Entry mapEntry : codeMappings.entrySet()) { + for (final Map.Entry mapEntry : codeMappings.entrySet()) { addSqlList[i++] = "insert into x_table_cloumn_code_mappings (column_alias_name, code_id) values ('" + mapEntry.getKey() + "'," + mapEntry.getValue() + ");"; } @@ -665,11 +666,11 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } - private void deleteColumnCodeMapping(List columnNames) { + private void deleteColumnCodeMapping(final List columnNames) { if (columnNames != null && !columnNames.isEmpty()) { - String[] deleteSqlList = new String[columnNames.size()]; + final String[] deleteSqlList = new String[columnNames.size()]; int i = 0; - for (String columnName : columnNames) { + for (final String columnName : columnNames) { deleteSqlList[i++] = "DELETE FROM x_table_cloumn_code_mappings WHERE column_alias_name='" + columnName + "';"; } @@ -683,35 +684,35 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ public void updateDatatable(final String datatableName, final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); - JsonElement element = this.fromJsonHelper.parse(command.json()); - JsonArray changeColumns = this.fromJsonHelper.extractJsonArrayNamed("changeColumns", element); - JsonArray addColumns = this.fromJsonHelper.extractJsonArrayNamed("addColumns", element); - JsonArray dropColumns = this.fromJsonHelper.extractJsonArrayNamed("dropColumns", element); - String apptableName = this.fromJsonHelper.extractStringNamed("apptableName", element); + final JsonElement element = this.fromJsonHelper.parse(command.json()); + final JsonArray changeColumns = this.fromJsonHelper.extractJsonArrayNamed("changeColumns", element); + final JsonArray addColumns = this.fromJsonHelper.extractJsonArrayNamed("addColumns", element); + final JsonArray dropColumns = this.fromJsonHelper.extractJsonArrayNamed("dropColumns", element); + final String apptableName = this.fromJsonHelper.extractStringNamed("apptableName", element); validateDatatableName(datatableName); - List columnHeaderData = this.genericDataService.fillResultsetColumnHeaders(datatableName); - Map mapColumnNameDefinition = new HashMap(); - for (ResultsetColumnHeaderData columnHeader : columnHeaderData) { + final List columnHeaderData = this.genericDataService.fillResultsetColumnHeaders(datatableName); + final Map mapColumnNameDefinition = new HashMap(); + for (final ResultsetColumnHeaderData columnHeader : columnHeaderData) { mapColumnNameDefinition.put(columnHeader.getColumnName(), columnHeader); } - boolean isConstraintApproach = configurationDomainService.isConstraintApproachEnabledForDatatables(); + final boolean isConstraintApproach = this.configurationDomainService.isConstraintApproachEnabledForDatatables(); if (!StringUtils.isBlank(apptableName)) { validateAppTable(apptableName); - String oldApptableName = this.queryForApplicationTableName(datatableName); + final String oldApptableName = queryForApplicationTableName(datatableName); if (!StringUtils.equals(oldApptableName, apptableName)) { - String oldFKName = oldApptableName.substring(2) + "_id"; - String newFKName = apptableName.substring(2) + "_id"; - String actualAppTableName = mapToActualAppTable(apptableName); - String oldConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + oldFKName; - String newConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + newFKName; + final String oldFKName = oldApptableName.substring(2) + "_id"; + final String newFKName = apptableName.substring(2) + "_id"; + final String actualAppTableName = mapToActualAppTable(apptableName); + final String oldConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + oldFKName; + final String newConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + newFKName; StringBuilder sqlBuilder = new StringBuilder(); if (mapColumnNameDefinition.containsKey("id")) { @@ -741,14 +742,14 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (dropColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); - StringBuilder constrainBuilder = new StringBuilder(); - List codeMappings = new ArrayList(); - for (JsonElement column : dropColumns) { + final StringBuilder constrainBuilder = new StringBuilder(); + final List codeMappings = new ArrayList(); + for (final JsonElement column : dropColumns) { parseDatatableColumnForDrop(column.getAsJsonObject(), sqlBuilder, datatableName, constrainBuilder, codeMappings); } // Remove the first comma, right after ALTER TABLE `datatable` - int indexOfFirstComma = sqlBuilder.indexOf(","); + final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } @@ -759,15 +760,15 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (addColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); - StringBuilder constrainBuilder = new StringBuilder(); - Map codeMappings = new HashMap(); - for (JsonElement column : addColumns) { + final StringBuilder constrainBuilder = new StringBuilder(); + final Map codeMappings = new HashMap(); + for (final JsonElement column : addColumns) { parseDatatableColumnForAdd(column.getAsJsonObject(), sqlBuilder, datatableName.toLowerCase().replaceAll("\\s", "_"), constrainBuilder, codeMappings, isConstraintApproach); } // Remove the first comma, right after ALTER TABLE `datatable` - int indexOfFirstComma = sqlBuilder.indexOf(","); + final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } @@ -778,16 +779,16 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (changeColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); - StringBuilder constrainBuilder = new StringBuilder(); - Map codeMappings = new HashMap(); - List removeMappings = new ArrayList(); - for (JsonElement column : changeColumns) { + final StringBuilder constrainBuilder = new StringBuilder(); + final Map codeMappings = new HashMap(); + final List removeMappings = new ArrayList(); + for (final JsonElement column : changeColumns) { parseDatatableColumnForUpdate(column.getAsJsonObject(), mapColumnNameDefinition, sqlBuilder, datatableName, constrainBuilder, codeMappings, removeMappings, isConstraintApproach); } // Remove the first comma, right after ALTER TABLE `datatable` - int indexOfFirstComma = sqlBuilder.indexOf(","); + final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } @@ -796,14 +797,14 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ this.jdbcTemplate.execute(sqlBuilder.toString()); deleteColumnCodeMapping(removeMappings); registerColumnCodeMapping(codeMappings); - } catch (GenericJDBCException e) { + } catch (final GenericJDBCException e) { if (e.getMessage().contains("Error on rename")) { throw new PlatformServiceUnavailableException( "error.msg.datatable.column.update.not.allowed", "One of the column name modification not allowed"); } } } - } catch (SQLGrammarException e) { - Throwable realCause = e.getCause(); - List dataValidationErrors = new ArrayList(); + } catch (final SQLGrammarException e) { + final Throwable realCause = e.getCause(); + final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable"); if (realCause.getMessage().toLowerCase().contains("unknown column")) { @@ -823,15 +824,15 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ public void deleteDatatable(final String datatableName) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); if (!isRegisteredDataTable(datatableName)) { throw new DatatableNotFoundException(datatableName); } validateDatatableName(datatableName); deregisterDatatable(datatableName); - String sql = "DROP TABLE `" + datatableName + "`"; + final String sql = "DROP TABLE `" + datatableName + "`"; this.jdbcTemplate.execute(sql); - } catch (SQLGrammarException e) { - Throwable realCause = e.getCause(); - List dataValidationErrors = new ArrayList(); + } catch (final SQLGrammarException e) { + final Throwable realCause = e.getCause(); + final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("datatable"); if (realCause.getMessage().contains("Unknown table")) { baseDataValidator.reset().parameter("datatableName").failWithCode("does.not.exist"); @@ -860,7 +861,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ final JsonCommand command) { final String appTable = queryForApplicationTableName(dataTableName); - CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); + final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); final GenericResultsetData grs = retrieveDataTableGenericResultSetForUpdate(appTable, dataTableName, appTableId, datatableId); @@ -870,7 +871,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ "Application table: " + dataTableName + " Foreign key id: " + appTableId); } final Type typeOfMap = new TypeToken>() {}.getType(); - Map dataParams = this.fromJsonHelper.extractDataMap(typeOfMap, command.json()); + final Map dataParams = this.fromJsonHelper.extractDataMap(typeOfMap, command.json()); String pkName = "id"; // 1:M datatable if (datatableId == null) { @@ -910,11 +911,11 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ public CommandProcessingResult deleteDatatableEntries(final String dataTableName, final Long appTableId) { final String appTable = queryForApplicationTableName(dataTableName); - CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); + final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); final String deleteOneToOneEntrySql = getDeleteEntriesSql(dataTableName, getFKField(appTable), appTableId); - int rowsDeleted = this.jdbcTemplate.update(deleteOneToOneEntrySql); + final int rowsDeleted = this.jdbcTemplate.update(deleteOneToOneEntrySql); if (rowsDeleted < 1) { throw new DatatableNotFoundException(dataTableName, appTableId); } return commandProcessingResult; @@ -925,7 +926,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ public CommandProcessingResult deleteDatatableEntry(final String dataTableName, final Long appTableId, final Long datatableId) { final String appTable = queryForApplicationTableName(dataTableName); - CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); + final CommandProcessingResult commandProcessingResult = checkMainResourceExistsWithinScope(appTable, appTableId); final String sql = getDeleteEntrySql(dataTableName, datatableId); @@ -990,12 +991,12 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (!rs.next()) { throw new DatatableNotFoundException(appTable, appTableId); } - Long officeId = getLongSqlRowSet(rs, "officeId"); - Long groupId = getLongSqlRowSet(rs, "groupId"); - Long clientId = getLongSqlRowSet(rs, "clientId"); - Long savingsId = getLongSqlRowSet(rs, "savingsId"); - Long LoanId = getLongSqlRowSet(rs, "loanId"); - Long entityId = getLongSqlRowSet(rs, "entityId"); + final Long officeId = getLongSqlRowSet(rs, "officeId"); + final Long groupId = getLongSqlRowSet(rs, "groupId"); + final Long clientId = getLongSqlRowSet(rs, "clientId"); + final Long savingsId = getLongSqlRowSet(rs, "savingsId"); + final Long LoanId = getLongSqlRowSet(rs, "loanId"); + final Long entityId = getLongSqlRowSet(rs, "entityId"); if (rs.next()) { throw new DatatableSystemErrorException("System Error: More than one row returned from data scoping query"); } @@ -1010,7 +1011,9 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ private Long getLongSqlRowSet(final SqlRowSet rs, final String column) { Long val = rs.getLong(column); - if (val == 0) val = null; + if (val == 0) { + val = null; + } return val; } @@ -1022,7 +1025,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ * applies */ - AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); String scopedSQL = null; /* * m_loan and m_savings_account are connected to an m_office thru either @@ -1092,14 +1095,14 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ private void validateAppTable(final String appTable) { - if (appTable.equalsIgnoreCase("m_loan")) return; - if (appTable.equalsIgnoreCase("m_savings_account")) return; - if (appTable.equalsIgnoreCase("m_client")) return; - if (appTable.equalsIgnoreCase("m_group")) return; - if (appTable.equalsIgnoreCase("m_center")) return; - if (appTable.equalsIgnoreCase("m_office")) return; - if (appTable.equalsIgnoreCase("m_product_loan")) return; - if (appTable.equalsIgnoreCase("m_savings_product")) return; + if (appTable.equalsIgnoreCase("m_loan")) { return; } + if (appTable.equalsIgnoreCase("m_savings_account")) { return; } + if (appTable.equalsIgnoreCase("m_client")) { return; } + if (appTable.equalsIgnoreCase("m_group")) { return; } + if (appTable.equalsIgnoreCase("m_center")) { return; } + if (appTable.equalsIgnoreCase("m_office")) { return; } + if (appTable.equalsIgnoreCase("m_product_loan")) { return; } + if (appTable.equalsIgnoreCase("m_savings_product")) { return; } throw new PlatformDataIntegrityException("error.msg.invalid.application.table", "Invalid Application Table: " + appTable, "name", appTable); @@ -1160,19 +1163,19 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ String pValueWrite = ""; String addSql = ""; - String singleQuote = "'"; + final String singleQuote = "'"; String insertColumns = ""; String selectColumns = ""; String columnName = ""; String pValue = null; - for (String key : affectedColumns.keySet()) { + for (final String key : affectedColumns.keySet()) { pValue = affectedColumns.get(key); if (StringUtils.isEmpty(pValue)) { pValueWrite = "null"; } else { - pValueWrite = singleQuote + genericDataService.replace(pValue, singleQuote, singleQuote + singleQuote) + singleQuote; + pValueWrite = singleQuote + this.genericDataService.replace(pValue, singleQuote, singleQuote + singleQuote) + singleQuote; } columnName = "`" + key + "`"; insertColumns += ", " + columnName; @@ -1195,15 +1198,15 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ // completeness but its okay to take this risk with additional fields // data - if (changedColumns.size() == 0) return null; + if (changedColumns.size() == 0) { return null; } String pValue = null; String pValueWrite = ""; - String singleQuote = "'"; + final String singleQuote = "'"; boolean firstColumn = true; String sql = "update `" + datatable + "` "; - for (String key : changedColumns.keySet()) { + for (final String key : changedColumns.keySet()) { if (firstColumn) { sql += " set "; firstColumn = false; @@ -1215,7 +1218,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ if (StringUtils.isEmpty(pValue)) { pValueWrite = "null"; } else { - pValueWrite = singleQuote + genericDataService.replace(pValue, singleQuote, singleQuote + singleQuote) + singleQuote; + pValueWrite = singleQuote + this.genericDataService.replace(pValue, singleQuote, singleQuote + singleQuote) + singleQuote; } sql += "`" + key + "` = " + pValueWrite; } @@ -1244,7 +1247,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ private boolean columnChanged(final String key, final String keyValue, final String colType, final GenericResultsetData grs) { - List columnValues = grs.getData().get(0).getRow(); + final List columnValues = grs.getData().get(0).getRow(); String columnValue = null; for (int i = 0; i < grs.getColumnHeaders().size(); i++) { @@ -1263,21 +1266,23 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ private Map getAffectedColumns(final List columnHeaders, final Map queryParams, final String keyFieldName) { - String dateFormat = queryParams.get("dateFormat"); + final String dateFormat = queryParams.get("dateFormat"); Locale clientApplicationLocale = null; - String localeQueryParam = queryParams.get("locale"); - if (!(StringUtils.isBlank(localeQueryParam))) clientApplicationLocale = new Locale(queryParams.get("locale")); + final String localeQueryParam = queryParams.get("locale"); + if (!(StringUtils.isBlank(localeQueryParam))) { + clientApplicationLocale = new Locale(queryParams.get("locale")); + } - String underscore = "_"; - String space = " "; + final String underscore = "_"; + final String space = " "; String pValue = null; String queryParamColumnUnderscored; String columnHeaderUnderscored; boolean notFound; - Map affectedColumns = new HashMap(); - Set keys = queryParams.keySet(); - for (String key : keys) { + final Map affectedColumns = new HashMap(); + final Set keys = queryParams.keySet(); + for (final String key : keys) { // ignores id and foreign key fields // also ignores locale and dateformat fields that are used for // validating numeric and date data @@ -1286,10 +1291,10 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ notFound = true; // matches incoming fields with and without underscores (spaces // and underscores considered the same) - queryParamColumnUnderscored = genericDataService.replace(key, space, underscore); - for (ResultsetColumnHeaderData columnHeader : columnHeaders) { + queryParamColumnUnderscored = this.genericDataService.replace(key, space, underscore); + for (final ResultsetColumnHeaderData columnHeader : columnHeaders) { if (notFound) { - columnHeaderUnderscored = genericDataService.replace(columnHeader.getColumnName(), space, underscore); + columnHeaderUnderscored = this.genericDataService.replace(columnHeader.getColumnName(), space, underscore); if (queryParamColumnUnderscored.equalsIgnoreCase(columnHeaderUnderscored)) { pValue = queryParams.get(key); pValue = validateColumn(columnHeader, pValue, dateFormat, clientApplicationLocale); @@ -1366,14 +1371,14 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ paramValue = tmpDate.toString(); } } else if (columnHeader.isIntegerDisplayType()) { - Integer tmpInt = helper.convertToInteger(paramValue, columnHeader.getColumnName(), clientApplicationLocale); + final Integer tmpInt = this.helper.convertToInteger(paramValue, columnHeader.getColumnName(), clientApplicationLocale); if (tmpInt == null) { paramValue = null; } else { paramValue = tmpInt.toString(); } } else if (columnHeader.isDecimalDisplayType()) { - BigDecimal tmpDecimal = helper.convertFrom(paramValue, columnHeader.getColumnName(), clientApplicationLocale); + final BigDecimal tmpDecimal = this.helper.convertFrom(paramValue, columnHeader.getColumnName(), clientApplicationLocale); if (tmpDecimal == null) { paramValue = null; } else { @@ -1381,10 +1386,10 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } } else if (columnHeader.isString()) { if (paramValue.length() > columnHeader.getColumnLength()) { - ApiParameterError error = ApiParameterError.parameterError("validation.msg.datatable.entry.column.exceeds.maxlength", - "The column `" + columnHeader.getColumnName() + "` exceeds its defined max-length ", - columnHeader.getColumnName(), paramValue); - List dataValidationErrors = new ArrayList(); + final ApiParameterError error = ApiParameterError.parameterError( + "validation.msg.datatable.entry.column.exceeds.maxlength", "The column `" + columnHeader.getColumnName() + + "` exceeds its defined max-length ", columnHeader.getColumnName(), paramValue); + final List dataValidationErrors = new ArrayList(); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); @@ -1408,11 +1413,11 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ } private boolean notTheSame(final String currValue, final String pValue, final String colType) { - if (StringUtils.isEmpty(currValue) && StringUtils.isEmpty(pValue)) return false; + if (StringUtils.isEmpty(currValue) && StringUtils.isEmpty(pValue)) { return false; } - if (StringUtils.isEmpty(currValue)) return true; + if (StringUtils.isEmpty(currValue)) { return true; } - if (StringUtils.isEmpty(pValue)) return true; + if (StringUtils.isEmpty(pValue)) { return true; } if ("DECIMAL".equalsIgnoreCase(colType)) { final BigDecimal currentDecimal = BigDecimal.valueOf(Double.valueOf(currValue)); @@ -1421,7 +1426,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ return currentDecimal.compareTo(newDecimal) != 0; } - if (currValue.equals(pValue)) return false; + if (currValue.equals(pValue)) { return false; } return true; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReportWritePlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReportWritePlatformServiceImpl.java index 48beb0304..4cb2c2bf1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReportWritePlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReportWritePlatformServiceImpl.java @@ -67,7 +67,7 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic public CommandProcessingResult createReport(final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validate(command.json()); @@ -84,7 +84,7 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic .withCommandId(command.commandId()) // .withEntityId(report.getId()) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleReportDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -95,7 +95,7 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic public CommandProcessingResult updateReport(final Long reportId, final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validate(command.json()); @@ -106,7 +106,7 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic if (changes.containsKey("reportParameters")) { final Set reportParameterUsages = assembleSetOfReportParameterUsages(report, command); - boolean updated = report.update(reportParameterUsages); + final boolean updated = report.update(reportParameterUsages); if (!updated) { changes.remove("reportParameters"); } @@ -121,7 +121,7 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic .withEntityId(report.getId()) // .with(changes) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleReportDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -156,7 +156,7 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic */ private void handleReportDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("unq_report_name")) { final String name = command.stringValueOfParameterNamed("reportName"); throw new PlatformDataIntegrityException("error.msg.report.duplicate.name", "A report with name '" + name + "' already exists", @@ -173,7 +173,7 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic Set reportParameterUsages = null; if (command.parameterExists("reportParameters")) { - JsonArray reportParametersArray = command.arrayOfParameterNamed("reportParameters"); + final JsonArray reportParametersArray = command.arrayOfParameterNamed("reportParameters"); if (reportParametersArray != null) { reportParameterUsages = new HashSet(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/api/ImagesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/api/ImagesApiResource.java index dbd576106..21453b29a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/api/ImagesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/api/ImagesApiResource.java @@ -108,7 +108,7 @@ public class ImagesApiResource { @Produces({ MediaType.TEXT_PLAIN }) public String retrieveClientImage(@PathParam("clientId") final Long clientId) { - context.authenticatedUser().validateHasReadPermission("CLIENTIMAGE"); + this.context.authenticatedUser().validateHasReadPermission("CLIENTIMAGE"); final ImageData imageData = this.imageReadPlatformService.retrieveClientImage(clientId); @@ -120,7 +120,7 @@ public class ImagesApiResource { imageDataURISuffix = ContentRepositoryUtils.IMAGE_DATA_URI_SUFFIX.PNG.getValue(); } - String clientImageAsBase64Text = imageDataURISuffix + Base64.encodeBytes(imageData.getContent()); + final String clientImageAsBase64Text = imageDataURISuffix + Base64.encodeBytes(imageData.getContent()); return clientImageAsBase64Text; } @@ -129,10 +129,10 @@ public class ImagesApiResource { @Produces({ MediaType.APPLICATION_OCTET_STREAM }) public Response downloadClientImage(@PathParam("clientId") final Long clientId) { - context.authenticatedUser().validateHasReadPermission("CLIENTIMAGE"); + this.context.authenticatedUser().validateHasReadPermission("CLIENTIMAGE"); final ImageData imageData = this.imageReadPlatformService.retrieveClientImage(clientId); - ResponseBuilder response = Response.ok(imageData.getContent()); + final ResponseBuilder response = Response.ok(imageData.getContent()); response.header("Content-Disposition", "attachment; filename=\"" + imageData.getEntityDisplayName() + IMAGE_FILE_EXTENSION.JPEG + "\""); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/command/DocumentCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/command/DocumentCommand.java index 1706f7f8e..7802d1a06 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/command/DocumentCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/command/DocumentCommand.java @@ -100,7 +100,7 @@ public class DocumentCommand { return this.storageType; } - public void setStorageType(Integer storageType) { + public void setStorageType(final Integer storageType) { this.storageType = storageType; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/ContentRepositoryFactory.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/ContentRepositoryFactory.java index 837ad7dfc..932ebb0be 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/ContentRepositoryFactory.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/ContentRepositoryFactory.java @@ -11,8 +11,8 @@ import org.springframework.stereotype.Component; @Component public class ContentRepositoryFactory { - private ApplicationContext applicationContext; - private ExternalServicesReadPlatformService externalServicesReadPlatformService; + private final ApplicationContext applicationContext; + private final ExternalServicesReadPlatformService externalServicesReadPlatformService; @Autowired public ContentRepositoryFactory(final ApplicationContext applicationContext, @@ -22,19 +22,19 @@ public class ContentRepositoryFactory { } public ContentRepository getRepository() { - ConfigurationDomainService configurationDomainServiceJpa = applicationContext.getBean("configurationDomainServiceJpa", + final ConfigurationDomainService configurationDomainServiceJpa = this.applicationContext.getBean("configurationDomainServiceJpa", ConfigurationDomainService.class); if (configurationDomainServiceJpa.isAmazonS3Enabled()) { return createS3DocumentStore(); } return new FileSystemContentRepository(); } - public ContentRepository getRepository(StorageType documentStoreType) { + public ContentRepository getRepository(final StorageType documentStoreType) { if (documentStoreType == StorageType.FILE_SYSTEM) { return new FileSystemContentRepository(); } return createS3DocumentStore(); } private ContentRepository createS3DocumentStore() { - S3CredentialsData s3CredentialsData = externalServicesReadPlatformService.getS3Credentials(); + final S3CredentialsData s3CredentialsData = this.externalServicesReadPlatformService.getS3Credentials(); return new S3ContentRepository(s3CredentialsData.getBucketName(), s3CredentialsData.getSecretKey(), s3CredentialsData.getAccessKey()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/ContentRepositoryUtils.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/ContentRepositoryUtils.java index 730bf9986..a938c95d5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/ContentRepositoryUtils.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/ContentRepositoryUtils.java @@ -64,7 +64,7 @@ public class ContentRepositoryUtils { * * @param mimeType */ - public static void validateImageMimeType(String mimeType) { + public static void validateImageMimeType(final String mimeType) { if (!(mimeType.equalsIgnoreCase(IMAGE_MIME_TYPE.GIF.getValue()) || mimeType.equalsIgnoreCase(IMAGE_MIME_TYPE.JPEG.getValue()) || mimeType .equalsIgnoreCase(IMAGE_MIME_TYPE.PNG.getValue()))) { throw new ImageUploadException(); } } @@ -74,7 +74,7 @@ public class ContentRepositoryUtils { * * @param mimeType */ - public static Base64EncodedImage extractImageFromDataURL(String dataURL) { + public static Base64EncodedImage extractImageFromDataURL(final String dataURL) { String fileExtension = ""; String base64EncodedString = null; if (StringUtils.startsWith(dataURL, IMAGE_DATA_URI_SUFFIX.GIF.getValue())) { @@ -93,7 +93,7 @@ public class ContentRepositoryUtils { return new Base64EncodedImage(base64EncodedString, fileExtension); } - public static void validateFileSizeWithinPermissibleRange(Long fileSize, String name) { + public static void validateFileSizeWithinPermissibleRange(final Long fileSize, final String name) { /** * Using Content-Length gives me size of the entire request, which is * good enough for now for a fast fail as the length of the rest of the @@ -104,13 +104,13 @@ public class ContentRepositoryUtils { name, fileSize, ContentRepository.MAX_FILE_UPLOAD_SIZE_IN_MB); } } - public static void validateClientImageNotEmpty(String imageFileName) { - List dataValidationErrors = new ArrayList(); + public static void validateClientImageNotEmpty(final String imageFileName) { + final List dataValidationErrors = new ArrayList(); if (imageFileName == null) { - StringBuilder validationErrorCode = new StringBuilder("validation.msg.clientImage.cannot.be.blank"); - StringBuilder defaultEnglishMessage = new StringBuilder("The parameter image cannot be blank."); - ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), defaultEnglishMessage.toString(), - "image"); + final StringBuilder validationErrorCode = new StringBuilder("validation.msg.clientImage.cannot.be.blank"); + final StringBuilder defaultEnglishMessage = new StringBuilder("The parameter image cannot be blank."); + final ApiParameterError error = ApiParameterError.parameterError(validationErrorCode.toString(), + defaultEnglishMessage.toString(), "image"); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); @@ -123,9 +123,9 @@ public class ContentRepositoryUtils { * @return */ public static String generateRandomString() { - String characters = "abcdefghijklmnopqrstuvwxyz123456789"; - int length = generateRandomNumber(); - char[] text = new char[length]; + final String characters = "abcdefghijklmnopqrstuvwxyz123456789"; + final int length = generateRandomNumber(); + final char[] text = new char[length]; for (int i = 0; i < length; i++) { text[i] = characters.charAt(random.nextInt(characters.length())); } @@ -138,7 +138,7 @@ public class ContentRepositoryUtils { * @return */ public static int generateRandomNumber() { - Random randomGenerator = new Random(); + final Random randomGenerator = new Random(); return randomGenerator.nextInt(11) + 5; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/FileSystemContentRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/FileSystemContentRepository.java index 0f065d925..476b6ef82 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/FileSystemContentRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/FileSystemContentRepository.java @@ -31,47 +31,47 @@ public class FileSystemContentRepository implements ContentRepository { public static final String MIFOSX_BASE_DIR = System.getProperty("user.home") + File.separator + ".mifosx"; @Override - public String saveFile(InputStream uploadedInputStream, DocumentCommand documentCommand) { - String fileName = documentCommand.getFileName(); - String uploadDocumentLocation = generateFileParentDirectory(documentCommand.getParentEntityType(), + public String saveFile(final InputStream uploadedInputStream, final DocumentCommand documentCommand) { + final String fileName = documentCommand.getFileName(); + final String uploadDocumentLocation = generateFileParentDirectory(documentCommand.getParentEntityType(), documentCommand.getParentEntityId()); ContentRepositoryUtils.validateFileSizeWithinPermissibleRange(documentCommand.getSize(), fileName); makeDirectories(uploadDocumentLocation); - String fileLocation = uploadDocumentLocation + File.separator + fileName; + final String fileLocation = uploadDocumentLocation + File.separator + fileName; writeFileToFileSystem(fileName, uploadedInputStream, fileLocation); return fileLocation; } @Override - public String saveImage(InputStream uploadedInputStream, Long resourceId, String imageName, Long fileSize) { - String uploadImageLocation = generateClientImageParentDirectory(resourceId); + public String saveImage(final InputStream uploadedInputStream, final Long resourceId, final String imageName, final Long fileSize) { + final String uploadImageLocation = generateClientImageParentDirectory(resourceId); ContentRepositoryUtils.validateFileSizeWithinPermissibleRange(fileSize, imageName); makeDirectories(uploadImageLocation); - String fileLocation = uploadImageLocation + File.separator + imageName; + final String fileLocation = uploadImageLocation + File.separator + imageName; writeFileToFileSystem(imageName, uploadedInputStream, fileLocation); return fileLocation; } @Override - public String saveImage(Base64EncodedImage base64EncodedImage, Long resourceId, String imageName) { - String uploadImageLocation = generateClientImageParentDirectory(resourceId); + public String saveImage(final Base64EncodedImage base64EncodedImage, final Long resourceId, final String imageName) { + final String uploadImageLocation = generateClientImageParentDirectory(resourceId); makeDirectories(uploadImageLocation); - String fileLocation = uploadImageLocation + File.separator + imageName + base64EncodedImage.getFileExtension(); + final String fileLocation = uploadImageLocation + File.separator + imageName + base64EncodedImage.getFileExtension(); try { - OutputStream out = new FileOutputStream(new File(fileLocation)); - byte[] imgBytes = Base64.decode(base64EncodedImage.getBase64EncodedString()); + final OutputStream out = new FileOutputStream(new File(fileLocation)); + final byte[] imgBytes = Base64.decode(base64EncodedImage.getBase64EncodedString()); out.write(imgBytes); out.flush(); out.close(); - } catch (IOException ioe) { + } catch (final IOException ioe) { throw new ContentManagementException(imageName, ioe.getMessage()); } return fileLocation; @@ -87,12 +87,12 @@ public class FileSystemContentRepository implements ContentRepository { } @Override - public void deleteFile(String fileName, String documentPath) { + public void deleteFile(final String fileName, final String documentPath) { final boolean fileDeleted = deleteFile(documentPath); if (!fileDeleted) { throw new ContentManagementException(fileName, null); } } - private boolean deleteFile(String documentPath) { + private boolean deleteFile(final String documentPath) { final File fileToBeDeleted = new File(documentPath); return fileToBeDeleted.delete(); } @@ -103,14 +103,14 @@ public class FileSystemContentRepository implements ContentRepository { } @Override - public FileData fetchFile(DocumentData documentData) { - File file = new File(documentData.fileLocation()); + public FileData fetchFile(final DocumentData documentData) { + final File file = new File(documentData.fileLocation()); return new FileData(file, documentData.fileName(), documentData.contentType()); } @Override - public ImageData fetchImage(ImageData imageData) { - File file = new File(imageData.location()); + public ImageData fetchImage(final ImageData imageData) { + final File file = new File(imageData.location()); imageData.updateContent(file); return imageData; } @@ -122,7 +122,7 @@ public class FileSystemContentRepository implements ContentRepository { * @param entityId * @return */ - private String generateFileParentDirectory(String entityType, Long entityId) { + private String generateFileParentDirectory(final String entityType, final Long entityId) { return FileSystemContentRepository.MIFOSX_BASE_DIR + File.separator + ThreadLocalContextUtil.getTenant().getName().replaceAll(" ", "").trim() + File.separator + "documents" + File.separator + entityType + File.separator + entityId + File.separator + ContentRepositoryUtils.generateRandomString(); @@ -140,24 +140,24 @@ public class FileSystemContentRepository implements ContentRepository { /** * Recursively create the directory if it does not exist * */ - private void makeDirectories(String uploadDocumentLocation) { + private void makeDirectories(final String uploadDocumentLocation) { if (!new File(uploadDocumentLocation).isDirectory()) { new File(uploadDocumentLocation).mkdirs(); } } - private void writeFileToFileSystem(String fileName, InputStream uploadedInputStream, String fileLocation) { + private void writeFileToFileSystem(final String fileName, final InputStream uploadedInputStream, final String fileLocation) { try { - OutputStream out = new FileOutputStream(new File(fileLocation)); + final OutputStream out = new FileOutputStream(new File(fileLocation)); int read = 0; - byte[] bytes = new byte[1024]; + final byte[] bytes = new byte[1024]; while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); - } catch (IOException ioException) { + } catch (final IOException ioException) { throw new ContentManagementException(fileName, ioException.getMessage()); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/S3ContentRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/S3ContentRepository.java index fb80d9784..4d8d3410f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/S3ContentRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/contentrepository/S3ContentRepository.java @@ -32,62 +32,63 @@ public class S3ContentRepository implements ContentRepository { private final static Logger logger = LoggerFactory.getLogger(S3ContentRepository.class); private final String s3BucketName; - private AmazonS3 s3Client; + private final AmazonS3 s3Client; - public S3ContentRepository(String bucketName, String secretKey, String accessKey) { + public S3ContentRepository(final String bucketName, final String secretKey, final String accessKey) { this.s3BucketName = bucketName; this.s3Client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey)); } @Override - public String saveFile(InputStream toUpload, DocumentCommand documentCommand) { - String fileName = documentCommand.getFileName(); + public String saveFile(final InputStream toUpload, final DocumentCommand documentCommand) { + final String fileName = documentCommand.getFileName(); ContentRepositoryUtils.validateFileSizeWithinPermissibleRange(documentCommand.getSize(), fileName); - String uploadDocFolder = generateFileParentDirectory(documentCommand.getParentEntityType(), documentCommand.getParentEntityId()); - String uploadDocFullPath = uploadDocFolder + File.separator + fileName; + final String uploadDocFolder = generateFileParentDirectory(documentCommand.getParentEntityType(), + documentCommand.getParentEntityId()); + final String uploadDocFullPath = uploadDocFolder + File.separator + fileName; uploadDocument(fileName, toUpload, uploadDocFullPath); return uploadDocFullPath; } @Override - public void deleteFile(String documentName, String documentPath) { + public void deleteFile(final String documentName, final String documentPath) { try { deleteObjectFromS3(documentPath); - } catch (AmazonClientException ace) { + } catch (final AmazonClientException ace) { throw new ContentManagementException(documentName, ace.getMessage()); } } @Override - public String saveImage(InputStream toUploadInputStream, Long resourceId, String imageName, Long fileSize) { + public String saveImage(final InputStream toUploadInputStream, final Long resourceId, final String imageName, final Long fileSize) { ContentRepositoryUtils.validateFileSizeWithinPermissibleRange(fileSize, imageName); - String uploadImageLocation = generateClientImageParentDirectory(resourceId); - String fileLocation = uploadImageLocation + File.separator + imageName; + final String uploadImageLocation = generateClientImageParentDirectory(resourceId); + final String fileLocation = uploadImageLocation + File.separator + imageName; uploadDocument(imageName, toUploadInputStream, fileLocation); return fileLocation; } @Override - public String saveImage(Base64EncodedImage base64EncodedImage, Long resourceId, String imageName) { - String uploadImageLocation = generateClientImageParentDirectory(resourceId); - String fileLocation = uploadImageLocation + File.separator + imageName + base64EncodedImage.getFileExtension(); - InputStream toUploadInputStream = new ByteArrayInputStream(Base64.decode(base64EncodedImage.getBase64EncodedString())); + public String saveImage(final Base64EncodedImage base64EncodedImage, final Long resourceId, final String imageName) { + final String uploadImageLocation = generateClientImageParentDirectory(resourceId); + final String fileLocation = uploadImageLocation + File.separator + imageName + base64EncodedImage.getFileExtension(); + final InputStream toUploadInputStream = new ByteArrayInputStream(Base64.decode(base64EncodedImage.getBase64EncodedString())); uploadDocument(imageName, toUploadInputStream, fileLocation); return fileLocation; } @Override - public void deleteImage(Long resourceId, String location) { + public void deleteImage(final Long resourceId, final String location) { try { deleteObjectFromS3(location); - } catch (AmazonServiceException ase) { + } catch (final AmazonServiceException ase) { deleteObjectAmazonServiceExceptionMessage(ase); logger.warn("Unable to delete image associated with clients with Id " + resourceId); - } catch (AmazonClientException ace) { + } catch (final AmazonClientException ace) { deleteObjectAmazonClientExceptionMessage(ace); logger.warn("Unable to delete image associated with clients with Id " + resourceId); } @@ -99,14 +100,14 @@ public class S3ContentRepository implements ContentRepository { } @Override - public FileData fetchFile(DocumentData documentData) throws DocumentNotFoundException { + public FileData fetchFile(final DocumentData documentData) throws DocumentNotFoundException { FileData fileData = null; - String fileName = documentData.fileName(); + final String fileName = documentData.fileName(); try { logger.info("Downloading an object"); - S3Object s3object = s3Client.getObject(new GetObjectRequest(s3BucketName, documentData.fileLocation())); + final S3Object s3object = this.s3Client.getObject(new GetObjectRequest(this.s3BucketName, documentData.fileLocation())); fileData = new FileData(s3object.getObjectContent(), fileName, documentData.contentType()); - } catch (AmazonClientException ace) { + } catch (final AmazonClientException ace) { logger.error(ace.getMessage()); throw new DocumentNotFoundException(documentData.getParentEntityType(), documentData.getParentEntityId(), documentData.getId()); } @@ -114,43 +115,44 @@ public class S3ContentRepository implements ContentRepository { } @Override - public ImageData fetchImage(ImageData imageData) { - S3Object s3object = s3Client.getObject(new GetObjectRequest(s3BucketName, imageData.location())); + public ImageData fetchImage(final ImageData imageData) { + final S3Object s3object = this.s3Client.getObject(new GetObjectRequest(this.s3BucketName, imageData.location())); imageData.updateContent(s3object.getObjectContent()); return imageData; } - private void deleteObjectAmazonClientExceptionMessage(AmazonClientException ace) { - String message = "Caught an AmazonClientException." + "Error Message: " + ace.getMessage(); + private void deleteObjectAmazonClientExceptionMessage(final AmazonClientException ace) { + final String message = "Caught an AmazonClientException." + "Error Message: " + ace.getMessage(); logger.error(message); } - private void deleteObjectAmazonServiceExceptionMessage(AmazonServiceException ase) { - String message = "Caught an AmazonServiceException." + "Error Message: " + ase.getMessage() + "HTTP Status Code: " + private void deleteObjectAmazonServiceExceptionMessage(final AmazonServiceException ase) { + final String message = "Caught an AmazonServiceException." + "Error Message: " + ase.getMessage() + "HTTP Status Code: " + ase.getStatusCode() + "AWS Error Code: " + ase.getErrorCode() + "Error Type: " + ase.getErrorType() + "Request ID: " + ase.getRequestId(); logger.error(message); } - private String generateFileParentDirectory(String entityType, Long entityId) { + private String generateFileParentDirectory(final String entityType, final Long entityId) { return "documents" + File.separator + entityType + File.separator + entityId + File.separator + ContentRepositoryUtils.generateRandomString(); } - private String generateClientImageParentDirectory(Long resourceId) { + private String generateClientImageParentDirectory(final Long resourceId) { return "images" + File.separator + "clients" + File.separator + resourceId; } - private void deleteObjectFromS3(String location) { - s3Client.deleteObject(new DeleteObjectRequest(s3BucketName, location)); + private void deleteObjectFromS3(final String location) { + this.s3Client.deleteObject(new DeleteObjectRequest(this.s3BucketName, location)); } - private void uploadDocument(String filename, InputStream inputStream, String s3UploadLocation) throws ContentManagementException { + private void uploadDocument(final String filename, final InputStream inputStream, final String s3UploadLocation) + throws ContentManagementException { try { logger.info("Uploading a new object to S3 from a file to " + s3UploadLocation); - s3Client.putObject(new PutObjectRequest(this.s3BucketName, s3UploadLocation, inputStream, new ObjectMetadata())); - } catch (AmazonClientException ace) { - String message = ace.getMessage(); + this.s3Client.putObject(new PutObjectRequest(this.s3BucketName, s3UploadLocation, inputStream, new ObjectMetadata())); + } catch (final AmazonClientException ace) { + final String message = ace.getMessage(); throw new ContentManagementException(filename, message); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/DocumentData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/DocumentData.java index 25d155473..f553fb179 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/DocumentData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/DocumentData.java @@ -27,7 +27,7 @@ public class DocumentData { private final Integer storageType; public DocumentData(final Long id, final String parentEntityType, final Long parentEntityId, final String name, final String fileName, - final Long size, final String type, final String description, final String location, Integer storageType) { + final Long size, final String type, final String description, final String location, final Integer storageType) { this.id = id; this.parentEntityType = parentEntityType; this.parentEntityId = parentEntityId; @@ -53,7 +53,7 @@ public class DocumentData { } public StorageType storageType() { - return StorageType.fromInt(storageType); + return StorageType.fromInt(this.storageType); } public String getParentEntityType() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/FileData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/FileData.java index 984ee35e0..f61274b36 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/FileData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/FileData.java @@ -17,14 +17,14 @@ public class FileData { private final String contentType; private final InputStream inputStream; - public FileData(File file, String fileName, String contentType) { + public FileData(final File file, final String fileName, final String contentType) { this.file = file; this.fileName = fileName; this.contentType = contentType; this.inputStream = null; } - public FileData(InputStream inputStream, String fileName, String contentType) { + public FileData(final InputStream inputStream, final String fileName, final String contentType) { this.file = null; this.inputStream = inputStream; this.fileName = fileName; @@ -32,18 +32,18 @@ public class FileData { } public String contentType() { - return contentType; + return this.contentType; } public String name() { - return fileName; + return this.fileName; } public InputStream file() { try { - if (inputStream == null) { return new FileInputStream(file); } - return inputStream; - } catch (FileNotFoundException e) { + if (this.inputStream == null) { return new FileInputStream(this.file); } + return this.inputStream; + } catch (final FileNotFoundException e) { logger.error(e.toString()); return null; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/ImageData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/ImageData.java index 7a25e895d..8990eacf8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/ImageData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/data/ImageData.java @@ -22,7 +22,7 @@ public class ImageData { private String contentType; private InputStream inputStream; - public ImageData(Long imageId, String location, Integer storageType, String entityDisplayName) { + public ImageData(final Long imageId, final String location, final Integer storageType, final String entityDisplayName) { this.imageId = imageId; this.location = location; this.storageType = storageType; @@ -32,13 +32,13 @@ public class ImageData { public byte[] getContent() { // TODO Vishwas Fix error handling try { - if (inputStream == null) { - FileInputStream fileInputStream = new FileInputStream(file); + if (this.inputStream == null) { + final FileInputStream fileInputStream = new FileInputStream(this.file); return IOUtils.toByteArray(fileInputStream); } - return IOUtils.toByteArray(inputStream); - } catch (IOException e) { + return IOUtils.toByteArray(this.inputStream); + } catch (final IOException e) { return null; } } @@ -46,8 +46,8 @@ public class ImageData { private String setImageContentType() { String contentType = ContentRepositoryUtils.IMAGE_MIME_TYPE.JPEG.getValue(); - if (file != null) { - String fileName = file.getName(); + if (this.file != null) { + final String fileName = this.file.getName(); if (StringUtils.endsWith(fileName, ContentRepositoryUtils.IMAGE_FILE_EXTENSION.GIF.getValue())) { contentType = ContentRepositoryUtils.IMAGE_MIME_TYPE.GIF.getValue(); @@ -63,7 +63,7 @@ public class ImageData { } public StorageType storageType() { - return StorageType.fromInt(storageType); + return StorageType.fromInt(this.storageType); } public String name() { @@ -74,11 +74,11 @@ public class ImageData { return this.location; } - public void updateContent(InputStream objectContent) { + public void updateContent(final InputStream objectContent) { this.inputStream = objectContent; } - public void updateContent(File file) { + public void updateContent(final File file) { this.file = file; setImageContentType(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/domain/Image.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/domain/Image.java index c4b21c373..5e033e7ee 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/domain/Image.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/domain/Image.java @@ -21,7 +21,7 @@ public final class Image extends AbstractPersistable { @Column(name = "storage_type_enum") private Integer storageType; - public Image(String location, StorageType storageType) { + public Image(final String location, final StorageType storageType) { this.location = location; this.storageType = storageType.getValue(); } @@ -38,11 +38,11 @@ public final class Image extends AbstractPersistable { return this.storageType; } - public void setLocation(String location) { + public void setLocation(final String location) { this.location = location; } - public void setStorageType(Integer storageType) { + public void setStorageType(final Integer storageType) { this.storageType = storageType; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/domain/StorageType.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/domain/StorageType.java index 2cd78d59f..152189114 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/domain/StorageType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/domain/StorageType.java @@ -8,12 +8,12 @@ public enum StorageType { private Integer value; - StorageType(Integer value) { + StorageType(final Integer value) { this.value = value; } public Integer getValue() { - return value; + return this.value; } private static final Map intToEnumMap = new HashMap(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/DocumentReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/DocumentReadPlatformServiceImpl.java index 16d53d686..3c71d4920 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/DocumentReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/DocumentReadPlatformServiceImpl.java @@ -55,8 +55,8 @@ public class DocumentReadPlatformServiceImpl implements DocumentReadPlatformServ public FileData retrieveFileData(final String entityType, final Long entityId, final Long documentId) { try { final DocumentMapper mapper = new DocumentMapper(false, false); - DocumentData documentData = fetchDocumentDetails(entityType, entityId, documentId, mapper); - ContentRepository contentRepository = contentRepositoryFactory.getRepository(documentData.storageType()); + final DocumentData documentData = fetchDocumentDetails(entityType, entityId, documentId, mapper); + final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(documentData.storageType()); return contentRepository.fetchFile(documentData); } catch (final EmptyResultDataAccessException e) { throw new DocumentNotFoundException(entityType, entityId, documentId); @@ -64,7 +64,7 @@ public class DocumentReadPlatformServiceImpl implements DocumentReadPlatformServ } @Override - public DocumentData retrieveDocument(String entityType, Long entityId, Long documentId) { + public DocumentData retrieveDocument(final String entityType, final Long entityId, final Long documentId) { try { final DocumentMapper mapper = new DocumentMapper(true, true); return fetchDocumentDetails(entityType, entityId, documentId, mapper); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/DocumentWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/DocumentWritePlatformServiceJpaRepositoryImpl.java index e7734dc9e..4dca5d076 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/DocumentWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/DocumentWritePlatformServiceJpaRepositoryImpl.java @@ -56,7 +56,7 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr validator.validateForCreate(); - ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(); + final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(); final String fileLocation = contentRepository.saveFile(inputStream, documentCommand); @@ -89,10 +89,10 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr if (documentForUpdate == null) { throw new DocumentNotFoundException(documentCommand.getParentEntityType(), documentCommand.getParentEntityId(), documentCommand.getId()); } - StorageType documentStoreType = documentForUpdate.storageType(); + final StorageType documentStoreType = documentForUpdate.storageType(); oldLocation = documentForUpdate.getLocation(); if (inputStream != null && documentCommand.isFileNameChanged()) { - ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(); + final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(); documentCommand.setLocation(contentRepository.saveFile(inputStream, documentCommand)); documentCommand.setStorageType(contentRepository.getStorageType().getValue()); } @@ -100,7 +100,7 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr documentForUpdate.update(documentCommand); if (inputStream != null && documentCommand.isFileNameChanged()) { - ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(documentStoreType); + final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(documentStoreType); contentRepository.deleteFile(documentCommand.getName(), oldLocation); } @@ -129,7 +129,7 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr documentCommand.getParentEntityId(), documentCommand.getId()); } this.documentRepository.delete(document); - ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(document.storageType()); + final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(document.storageType()); contentRepository.deleteFile(document.getName(), document.getLocation()); return new CommandProcessingResult(document.getId()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/ImageReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/ImageReadPlatformServiceImpl.java index 173d11a83..1d260c46c 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/ImageReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/ImageReadPlatformServiceImpl.java @@ -56,23 +56,23 @@ public class ImageReadPlatformServiceImpl implements ImageReadPlatformService { final Long id = JdbcSupport.getLong(rs, "id"); final String location = rs.getString("location"); final Integer storageType = JdbcSupport.getInteger(rs, "storageType"); - return new ImageData(id, location, storageType, entityDisplayName); + return new ImageData(id, location, storageType, this.entityDisplayName); } } @Override - public ImageData retrieveClientImage(Long clientId) { + public ImageData retrieveClientImage(final Long clientId) { try { - Client client = clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); + final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); final ImageMapper imageMapper = new ImageMapper(client.getDisplayName()); final String sql = "select " + imageMapper.schema(); - ImageData imageData = this.jdbcTemplate.queryForObject(sql, imageMapper, new Object[] { clientId }); - ContentRepository contentRepository = contentRepositoryFactory.getRepository(imageData.storageType()); + final ImageData imageData = this.jdbcTemplate.queryForObject(sql, imageMapper, new Object[] { clientId }); + final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(imageData.storageType()); return contentRepository.fetchImage(imageData); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new ImageNotFoundException("clients", clientId); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/ImageWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/ImageWritePlatformServiceJpaRepositoryImpl.java index cb5a1b3ce..6d4ccc426 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/ImageWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/documentmanagement/service/ImageWritePlatformServiceJpaRepositoryImpl.java @@ -38,12 +38,12 @@ public class ImageWritePlatformServiceJpaRepositoryImpl implements ImageWritePla @Transactional @Override public CommandProcessingResult saveOrUpdateClientImage(final Long clientId, final String imageName, final InputStream inputStream, - Long fileSize) { + final Long fileSize) { final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); deletePreviousClientImage(client); - ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(); - String imageLocation = contentRepository.saveImage(inputStream, clientId, imageName, fileSize); + final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(); + final String imageLocation = contentRepository.saveImage(inputStream, clientId, imageName, fileSize); return updateClientImage(client, imageLocation, contentRepository.getStorageType()); } @@ -53,7 +53,7 @@ public class ImageWritePlatformServiceJpaRepositoryImpl implements ImageWritePla final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); deletePreviousClientImage(client); - ContentRepository contenRepository = this.contentRepositoryFactory.getRepository(); + final ContentRepository contenRepository = this.contentRepositoryFactory.getRepository(); final String imageLocation = contenRepository.saveImage(encodedImage, clientId, "image"); return updateClientImage(client, imageLocation, contenRepository.getStorageType()); @@ -65,10 +65,11 @@ public class ImageWritePlatformServiceJpaRepositoryImpl implements ImageWritePla final Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId); - Image image = client.getImage(); + final Image image = client.getImage(); // delete image from the file system if (image != null) { - ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(StorageType.fromInt(image.getStorageType())); + final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(StorageType.fromInt(image + .getStorageType())); contentRepository.deleteImage(clientId, image.getLocation()); client.setImage(null); this.imageRepository.delete(image); @@ -79,9 +80,10 @@ public class ImageWritePlatformServiceJpaRepositoryImpl implements ImageWritePla } private void deletePreviousClientImage(final Client client) { - Image image = client.getImage(); + final Image image = client.getImage(); if (image != null) { - ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(StorageType.fromInt(image.getStorageType())); + final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(StorageType.fromInt(image + .getStorageType())); contentRepository.deleteImage(client.getId(), image.getLocation()); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/annotation/CronMethodParser.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/annotation/CronMethodParser.java index da3219f53..ba44331d0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/annotation/CronMethodParser.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/annotation/CronMethodParser.java @@ -39,7 +39,7 @@ public class CronMethodParser { public static final int METHOD_INDEX = 1; - public static String[] findTargetMethodDetails(String attributeValue) throws IOException { + public static String[] findTargetMethodDetails(final String attributeValue) throws IOException { if (!targetMethosMap.containsKey(attributeValue)) { findAnnotationMethods(CronTarget.class, CRON_ANNOTATION_ATTRIBUTE_NAME); } @@ -50,21 +50,23 @@ public class CronMethodParser { * method adds all the method names to map with annotation attribute value * as key */ - private static void findAnnotationMethods(Class annotationClass, String attributeName) throws IOException { - String basePackagePath = ClassUtils.convertClassNameToResourcePath(new StandardEnvironment() + private static void findAnnotationMethods(final Class annotationClass, final String attributeName) + throws IOException { + final String basePackagePath = ClassUtils.convertClassNameToResourcePath(new StandardEnvironment() .resolveRequiredPlaceholders(SEARCH_PACKAGE)); - String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + basePackagePath + "/" + RESOURCE_PATTERN; - Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); - for (Resource resource : resources) { + final String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + basePackagePath + "/" + RESOURCE_PATTERN; + final Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); + for (final Resource resource : resources) { if (resource.isReadable()) { - MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); - Set metadataSet = metadataReader.getAnnotationMetadata().getAnnotatedMethods(annotationClass.getName()); + final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); + final Set metadataSet = metadataReader.getAnnotationMetadata().getAnnotatedMethods( + annotationClass.getName()); if (metadataSet != null && metadataSet.size() > 0) { - for (MethodMetadata metadata : metadataSet) { - Map attributes = metadata.getAnnotationAttributes(annotationClass.getName()); - JobName attributeValue = (JobName) attributes.get(attributeName); - String className = metadata.getDeclaringClassName(); - String[] mapVal = { className, metadata.getMethodName() }; + for (final MethodMetadata metadata : metadataSet) { + final Map attributes = metadata.getAnnotationAttributes(annotationClass.getName()); + final JobName attributeValue = (JobName) attributes.get(attributeName); + final String className = metadata.getDeclaringClassName(); + final String[] mapVal = { className, metadata.getMethodName() }; targetMethosMap.put(attributeValue.toString(), mapVal); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/api/SchedulerApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/api/SchedulerApiResource.java index 159dadedb..6d197d0c5 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/api/SchedulerApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/api/SchedulerApiResource.java @@ -41,9 +41,9 @@ public class SchedulerApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveStatus(@Context final UriInfo uriInfo) { - boolean isSchedulerRunning = jobRegisterService.isSchedulerRunning(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - SchedulerDetailData schedulerDetailData = new SchedulerDetailData(isSchedulerRunning); + final boolean isSchedulerRunning = this.jobRegisterService.isSchedulerRunning(); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final SchedulerDetailData schedulerDetailData = new SchedulerDetailData(isSchedulerRunning); return this.toApiJsonSerializer.serialize(settings, schedulerDetailData, SchedulerJobApiConstants.SCHEDULER_DETAIL_RESPONSE_DATA_PARAMETERS); } @@ -54,10 +54,10 @@ public class SchedulerApiResource { public Response changeSchedulerStatus(@QueryParam(SchedulerJobApiConstants.COMMAND) final String commandParam) { Response response = Response.status(400).build(); if (is(commandParam, SchedulerJobApiConstants.COMMAND_START_SCHEDULER)) { - jobRegisterService.startScheduler(); + this.jobRegisterService.startScheduler(); response = Response.status(202).build(); } else if (is(commandParam, SchedulerJobApiConstants.COMMAND_STOP_SCHEDULER)) { - jobRegisterService.pauseScheduler(); + this.jobRegisterService.pauseScheduler(); response = Response.status(202).build(); } else { throw new UnrecognizedQueryParamException(SchedulerJobApiConstants.COMMAND, commandParam); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/api/SchedulerJobApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/api/SchedulerJobApiResource.java index f978bdf89..b7e4f816d 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/api/SchedulerJobApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/api/SchedulerJobApiResource.java @@ -62,7 +62,7 @@ public class SchedulerJobApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAll(@Context final UriInfo uriInfo) { - List jobDetailDatas = this.schedulerJobRunnerReadService.findAllJobDeatils(); + final List jobDetailDatas = this.schedulerJobRunnerReadService.findAllJobDeatils(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, jobDetailDatas, SchedulerJobApiConstants.JOB_DETAIL_RESPONSE_DATA_PARAMETERS); } @@ -72,7 +72,7 @@ public class SchedulerJobApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveOne(@PathParam(SchedulerJobApiConstants.JOB_ID) final Long jobId, @Context final UriInfo uriInfo) { - JobDetailData jobDetailData = this.schedulerJobRunnerReadService.retrieveOne(jobId); + final JobDetailData jobDetailData = this.schedulerJobRunnerReadService.retrieveOne(jobId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, jobDetailData, SchedulerJobApiConstants.JOB_DETAIL_RESPONSE_DATA_PARAMETERS); } @@ -85,7 +85,8 @@ public class SchedulerJobApiResource { @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, @QueryParam("orderBy") final String orderBy, @QueryParam("sortOrder") final String sortOrder) { final SearchParameters searchParameters = SearchParameters.forPagination(offset, limit, orderBy, sortOrder); - Page jobhistoryDetailData = this.schedulerJobRunnerReadService.retrieveJobHistory(jobId, searchParameters); + final Page jobhistoryDetailData = this.schedulerJobRunnerReadService.retrieveJobHistory(jobId, + searchParameters); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.jobHistoryToApiJsonSerializer.serialize(settings, jobhistoryDetailData, SchedulerJobApiConstants.JOB_HISTORY_RESPONSE_DATA_PARAMETERS); @@ -121,7 +122,7 @@ public class SchedulerJobApiResource { if (result.getChanges() != null && (result.getChanges().containsKey(SchedulerJobApiConstants.jobActiveStatusParamName) || result.getChanges().containsKey( SchedulerJobApiConstants.cronExpressionParamName))) { - jobRegisterService.rescheduleJob(jobId); + this.jobRegisterService.rescheduleJob(jobId); } return this.toApiJsonSerializer.serialize(result); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/data/JobDetailData.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/data/JobDetailData.java index 2b7575a08..6de8aa288 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/data/JobDetailData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/data/JobDetailData.java @@ -15,7 +15,7 @@ public class JobDetailData { @SuppressWarnings("unused") private final String initializingError; - + @SuppressWarnings("unused") private final String cronExpression; @@ -29,7 +29,7 @@ public class JobDetailData { private final JobDetailHistoryData lastRunHistory; public JobDetailData(final Long jobId, final String displayName, final Date nextRunTime, final String initializingError, - final String cronExpression,final boolean active, final boolean currentlyRunning, final JobDetailHistoryData lastRunHistory) { + final String cronExpression, final boolean active, final boolean currentlyRunning, final JobDetailHistoryData lastRunHistory) { this.jobId = jobId; this.displayName = displayName; this.nextRunTime = nextRunTime; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/domain/ScheduledJobDetailRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/domain/ScheduledJobDetailRepository.java index 50cb0dc5f..dc2320aaf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/domain/ScheduledJobDetailRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/domain/ScheduledJobDetailRepository.java @@ -8,17 +8,15 @@ import org.springframework.data.jpa.repository.Lock; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface ScheduledJobDetailRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface ScheduledJobDetailRepository extends JpaRepository, JpaSpecificationExecutor { @Query("from ScheduledJobDetail jobDetail where jobDetail.jobKey = :jobKey") ScheduledJobDetail findByJobKey(@Param("jobKey") String jobKey); - + @Query("from ScheduledJobDetail jobDetail where jobDetail.id=:jobId") ScheduledJobDetail findByJobId(@Param("jobId") Long jobId); - - @Lock(value=LockModeType.PESSIMISTIC_WRITE) + @Lock(value = LockModeType.PESSIMISTIC_WRITE) @Query("from ScheduledJobDetail jobDetail where jobDetail.jobKey = :jobKey") ScheduledJobDetail findByJobKeyWithLock(@Param("jobKey") String jobKey); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/domain/SchedulerDetail.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/domain/SchedulerDetail.java index 3cb68eee3..13800f29f 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/domain/SchedulerDetail.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/domain/SchedulerDetail.java @@ -27,7 +27,7 @@ public class SchedulerDetail extends AbstractPersistable { return this.executeInstructionForMisfiredJobs; } - public void updateExecuteInstructionForMisfiredJobs(boolean executeInstructionForMisfiredJobs) { + public void updateExecuteInstructionForMisfiredJobs(final boolean executeInstructionForMisfiredJobs) { this.executeInstructionForMisfiredJobs = executeInstructionForMisfiredJobs; } @@ -35,7 +35,7 @@ public class SchedulerDetail extends AbstractPersistable { return this.suspended; } - public void updateSuspendedState(boolean suspended) { + public void updateSuspendedState(final boolean suspended) { this.suspended = suspended; } @@ -43,7 +43,7 @@ public class SchedulerDetail extends AbstractPersistable { return this.resetSchedulerOnBootup; } - public void updateResetSchedulerOnBootup(boolean resetSchedulerOnBootup) { + public void updateResetSchedulerOnBootup(final boolean resetSchedulerOnBootup) { this.resetSchedulerOnBootup = resetSchedulerOnBootup; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/exception/JobExecutionException.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/exception/JobExecutionException.java index 32e105907..8f12f2a9a 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/exception/JobExecutionException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/exception/JobExecutionException.java @@ -1,9 +1,8 @@ package org.mifosplatform.infrastructure.jobs.exception; +public class JobExecutionException extends Exception { -public class JobExecutionException extends Exception{ - - public JobExecutionException(String msg) { + public JobExecutionException(final String msg) { super(msg); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/exception/JobInProcessExecution.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/exception/JobInProcessExecution.java index a9ac9ea7a..16d744663 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/exception/JobInProcessExecution.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/exception/JobInProcessExecution.java @@ -2,11 +2,10 @@ package org.mifosplatform.infrastructure.jobs.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; - public class JobInProcessExecution extends AbstractPlatformResourceNotFoundException { - public JobInProcessExecution(String identifier) { - super("error.msg.sheduler.job.inprogress", "job execution is in process for "+identifier, identifier); + public JobInProcessExecution(final String identifier) { + super("error.msg.sheduler.job.inprogress", "job execution is in process for " + identifier, identifier); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/handler/UpdateJobDetailCommandhandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/handler/UpdateJobDetailCommandhandler.java index 18630346a..b1333a2bb 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/handler/UpdateJobDetailCommandhandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/handler/UpdateJobDetailCommandhandler.java @@ -18,7 +18,7 @@ public class UpdateJobDetailCommandhandler implements NewCommandSourceHandler { } @Override - public CommandProcessingResult processCommand(JsonCommand command) { + public CommandProcessingResult processCommand(final JsonCommand command) { return this.schedularWritePlatformService.updateJobDetail(command.entityId(), command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobName.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobName.java index 1bf267f4c..57fc53e28 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobName.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobName.java @@ -15,6 +15,6 @@ public enum JobName { @Override public String toString() { - return name; + return this.name; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobRegisterService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobRegisterService.java index 7006d8d5d..8c001589e 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobRegisterService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobRegisterService.java @@ -1,6 +1,5 @@ package org.mifosplatform.infrastructure.jobs.service; - public interface JobRegisterService { public void executeJob(Long jobId); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobRegisterServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobRegisterServiceImpl.java index 405e8d156..d03fb4154 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobRegisterServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/JobRegisterServiceImpl.java @@ -63,16 +63,16 @@ public class JobRegisterServiceImpl implements JobRegisterService { @PostConstruct public void loadAllJobs() { - List allTenants = this.tenantDetailsService.findAllTenants(); - for (MifosPlatformTenant tenant : allTenants) { + final List allTenants = this.tenantDetailsService.findAllTenants(); + for (final MifosPlatformTenant tenant : allTenants) { ThreadLocalContextUtil.setTenant(tenant); - List scheduledJobDetails = this.schedularWritePlatformService.retrieveAllJobs(); - for (ScheduledJobDetail jobDetails : scheduledJobDetails) { + final List scheduledJobDetails = this.schedularWritePlatformService.retrieveAllJobs(); + for (final ScheduledJobDetail jobDetails : scheduledJobDetails) { scheduleJob(jobDetails); jobDetails.updateTriggerMisfired(false); this.schedularWritePlatformService.saveOrUpdate(jobDetails); } - SchedulerDetail schedulerDetail = this.schedularWritePlatformService.retriveSchedulerDetail(); + final SchedulerDetail schedulerDetail = this.schedularWritePlatformService.retriveSchedulerDetail(); if (schedulerDetail.isResetSchedulerOnBootup()) { schedulerDetail.updateSuspendedState(false); this.schedularWritePlatformService.updateSchedulerDetail(schedulerDetail); @@ -88,17 +88,17 @@ public class JobRegisterServiceImpl implements JobRegisterService { } jobDataMap.put(SchedulerServiceConstants.TRIGGER_TYPE_REFERENCE, triggerType); jobDataMap.put(SchedulerServiceConstants.TENANT_IDENTIFIER, ThreadLocalContextUtil.getTenant().getTenantIdentifier()); - String key = scheduledJobDetail.getJobKey(); - JobKey jobKey = constructJobKey(key); - String schedulerName = getSchedulerName(scheduledJobDetail); - Scheduler scheduler = schedulers.get(schedulerName); + final String key = scheduledJobDetail.getJobKey(); + final JobKey jobKey = constructJobKey(key); + final String schedulerName = getSchedulerName(scheduledJobDetail); + final Scheduler scheduler = this.schedulers.get(schedulerName); if (scheduler == null || !scheduler.checkExists(jobKey)) { - JobDetail jobDetail = createJobDetail(scheduledJobDetail); - String tempSchedulerName = "temp" + scheduledJobDetail.getId(); - List> listenerClasses = new ArrayList>(2); + final JobDetail jobDetail = createJobDetail(scheduledJobDetail); + final String tempSchedulerName = "temp" + scheduledJobDetail.getId(); + final List> listenerClasses = new ArrayList>(2); listenerClasses.add(SchedulerJobListener.class); listenerClasses.add(SchedulerStopListener.class); - Scheduler tempScheduler = createScheduler(tempSchedulerName, 1, listenerClasses); + final Scheduler tempScheduler = createScheduler(tempSchedulerName, 1, listenerClasses); tempScheduler.addJob(jobDetail, true); jobDataMap.put(SchedulerServiceConstants.SCHEDULER_NAME, tempSchedulerName); this.schedulers.put(tempSchedulerName, tempScheduler); @@ -107,7 +107,7 @@ public class JobRegisterServiceImpl implements JobRegisterService { scheduler.triggerJob(jobKey, jobDataMap); } - } catch (Exception e) { + } catch (final Exception e) { throw new PlatformInternalServerException("error.msg.sheduler.job.execution.failed", "Job execution failed for job with id:" + scheduledJobDetail.getId(), scheduledJobDetail.getId()); } @@ -116,17 +116,17 @@ public class JobRegisterServiceImpl implements JobRegisterService { public void rescheduleJob(final ScheduledJobDetail scheduledJobDetail) { try { - String jobIdentity = scheduledJobDetail.getJobKey(); - JobKey jobKey = constructJobKey(jobIdentity); - String schedulername = getSchedulerName(scheduledJobDetail); - Scheduler scheduler = schedulers.get(schedulername); + final String jobIdentity = scheduledJobDetail.getJobKey(); + final JobKey jobKey = constructJobKey(jobIdentity); + final String schedulername = getSchedulerName(scheduledJobDetail); + final Scheduler scheduler = this.schedulers.get(schedulername); if (scheduler != null) { scheduler.deleteJob(jobKey); } scheduleJob(scheduledJobDetail); this.schedularWritePlatformService.saveOrUpdate(scheduledJobDetail); - } catch (Throwable throwable) { - String stackTrace = getStackTraceAsString(throwable); + } catch (final Throwable throwable) { + final String stackTrace = getStackTraceAsString(throwable); scheduledJobDetail.updateErrorLog(stackTrace); this.schedularWritePlatformService.saveOrUpdate(scheduledJobDetail); } @@ -134,7 +134,7 @@ public class JobRegisterServiceImpl implements JobRegisterService { @Override public void pauseScheduler() { - SchedulerDetail schedulerDetail = this.schedularWritePlatformService.retriveSchedulerDetail(); + final SchedulerDetail schedulerDetail = this.schedularWritePlatformService.retriveSchedulerDetail(); if (!schedulerDetail.isSuspended()) { schedulerDetail.updateSuspendedState(true); this.schedularWritePlatformService.updateSchedulerDetail(schedulerDetail); @@ -143,30 +143,30 @@ public class JobRegisterServiceImpl implements JobRegisterService { @Override public void startScheduler() { - SchedulerDetail schedulerDetail = this.schedularWritePlatformService.retriveSchedulerDetail(); + final SchedulerDetail schedulerDetail = this.schedularWritePlatformService.retriveSchedulerDetail(); if (schedulerDetail.isSuspended()) { schedulerDetail.updateSuspendedState(false); this.schedularWritePlatformService.updateSchedulerDetail(schedulerDetail); if (schedulerDetail.isExecuteInstructionForMisfiredJobs()) { - List scheduledJobDetails = this.schedularWritePlatformService.retrieveAllJobs(); - for (ScheduledJobDetail jobDetail : scheduledJobDetails) { + final List scheduledJobDetails = this.schedularWritePlatformService.retrieveAllJobs(); + for (final ScheduledJobDetail jobDetail : scheduledJobDetails) { if (jobDetail.isTriggerMisfired()) { if (jobDetail.isActiveSchedular()) { executeJob(jobDetail, SchedulerServiceConstants.TRIGGER_TYPE_CRON); } - String schedulerName = getSchedulerName(jobDetail); - Scheduler scheduler = schedulers.get(schedulerName); + final String schedulerName = getSchedulerName(jobDetail); + final Scheduler scheduler = this.schedulers.get(schedulerName); if (scheduler != null) { - String key = jobDetail.getJobKey(); - JobKey jobKey = constructJobKey(key); + final String key = jobDetail.getJobKey(); + final JobKey jobKey = constructJobKey(key); try { - List triggers = scheduler.getTriggersOfJob(jobKey); - for (Trigger trigger : triggers) { + final List triggers = scheduler.getTriggersOfJob(jobKey); + for (final Trigger trigger : triggers) { if (trigger.getNextFireTime() != null && trigger.getNextFireTime().after(jobDetail.getNextRunTime())) { jobDetail.updateNextRunTime(trigger.getNextFireTime()); } } - } catch (SchedulerException e) { + } catch (final SchedulerException e) { logger.error(e.getMessage(), e); } } @@ -180,13 +180,13 @@ public class JobRegisterServiceImpl implements JobRegisterService { @Override public void rescheduleJob(final Long jobId) { - ScheduledJobDetail scheduledJobDetail = this.schedularWritePlatformService.findByJobId(jobId); + final ScheduledJobDetail scheduledJobDetail = this.schedularWritePlatformService.findByJobId(jobId); rescheduleJob(scheduledJobDetail); } @Override public void executeJob(final Long jobId) { - ScheduledJobDetail scheduledJobDetail = this.schedularWritePlatformService.findByJobId(jobId); + final ScheduledJobDetail scheduledJobDetail = this.schedularWritePlatformService.findByJobId(jobId); if (scheduledJobDetail == null) { throw new JobNotFoundException(String.valueOf(jobId)); } executeJob(scheduledJobDetail, null); } @@ -203,23 +203,23 @@ public class JobRegisterServiceImpl implements JobRegisterService { return; } try { - JobDetail jobDetail = createJobDetail(scheduledJobDetails); - Trigger trigger = createTrigger(scheduledJobDetails, jobDetail); - Scheduler scheduler = getScheduler(scheduledJobDetails); + final JobDetail jobDetail = createJobDetail(scheduledJobDetails); + final Trigger trigger = createTrigger(scheduledJobDetails, jobDetail); + final Scheduler scheduler = getScheduler(scheduledJobDetails); scheduler.scheduleJob(jobDetail, trigger); scheduledJobDetails.updateJobKey(getJobKeyAsString(jobDetail.getKey())); scheduledJobDetails.updateNextRunTime(trigger.getNextFireTime()); scheduledJobDetails.updateErrorLog(null); - } catch (Throwable throwable) { + } catch (final Throwable throwable) { scheduledJobDetails.updateNextRunTime(null); - String stackTrace = getStackTraceAsString(throwable); + final String stackTrace = getStackTraceAsString(throwable); scheduledJobDetails.updateErrorLog(stackTrace); } scheduledJobDetails.updateCurrentlyRunningStatus(false); } private Scheduler getScheduler(final ScheduledJobDetail scheduledJobDetail) throws Exception { - String schedulername = getSchedulerName(scheduledJobDetail); + final String schedulername = getSchedulerName(scheduledJobDetail); Scheduler scheduler = this.schedulers.get(schedulername); if (scheduler == null) { int noOfThreads = SchedulerServiceConstants.DEFAULT_THREAD_COUNT; @@ -233,18 +233,18 @@ public class JobRegisterServiceImpl implements JobRegisterService { } @Override - public void stopScheduler(String name) { - Scheduler scheduler = this.schedulers.remove(name); + public void stopScheduler(final String name) { + final Scheduler scheduler = this.schedulers.remove(name); try { scheduler.shutdown(); - } catch (SchedulerException e) { + } catch (final SchedulerException e) { logger.error(e.getMessage(), e); } } private String getSchedulerName(final ScheduledJobDetail scheduledJobDetail) { - StringBuilder sb = new StringBuilder(20); - MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); + final StringBuilder sb = new StringBuilder(20); + final MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); sb.append(SchedulerServiceConstants.SCHEDULER).append(tenant.getId()); if (scheduledJobDetail.getSchedulerGroup() > 0) { sb.append(SchedulerServiceConstants.SCHEDULER_GROUP).append(scheduledJobDetail.getSchedulerGroup()); @@ -254,17 +254,17 @@ public class JobRegisterServiceImpl implements JobRegisterService { private Scheduler createScheduler(final String name, final int noOfThreads, List> listenerClasses) throws Exception { - SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); + final SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); schedulerFactoryBean.setSchedulerName(name); if (listenerClasses == null) { listenerClasses = new ArrayList>(1); listenerClasses.add(SchedulerJobListener.class); } schedulerFactoryBean.setGlobalJobListeners(getGlobalListener(listenerClasses)); - TriggerListener globalTriggerListener = applicationContext.getBean("schedulerTriggerListener", TriggerListener.class); - TriggerListener[] globalTriggerListeners = { globalTriggerListener }; + final TriggerListener globalTriggerListener = this.applicationContext.getBean("schedulerTriggerListener", TriggerListener.class); + final TriggerListener[] globalTriggerListeners = { globalTriggerListener }; schedulerFactoryBean.setGlobalTriggerListeners(globalTriggerListeners); - Properties quartzProperties = new Properties(); + final Properties quartzProperties = new Properties(); quartzProperties.put(SchedulerFactoryBean.PROP_THREAD_COUNT, Integer.toString(noOfThreads)); schedulerFactoryBean.setQuartzProperties(quartzProperties); schedulerFactoryBean.afterPropertiesSet(); @@ -272,21 +272,21 @@ public class JobRegisterServiceImpl implements JobRegisterService { return schedulerFactoryBean.getScheduler(); } - private JobListener[] getGlobalListener(List> listenerClasses) throws ClassNotFoundException { - List listeners = new ArrayList(listenerClasses.size()); - for (Class listenerClass : listenerClasses) { - JobListener listener = (JobListener) getBeanObject(listenerClass); + private JobListener[] getGlobalListener(final List> listenerClasses) throws ClassNotFoundException { + final List listeners = new ArrayList(listenerClasses.size()); + for (final Class listenerClass : listenerClasses) { + final JobListener listener = (JobListener) getBeanObject(listenerClass); listeners.add(listener); } - JobListener[] listenerArray = new JobListener[listeners.size()]; + final JobListener[] listenerArray = new JobListener[listeners.size()]; return listeners.toArray(listenerArray); } private JobDetail createJobDetail(final ScheduledJobDetail scheduledJobDetail) throws Exception { - MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); - String[] jobDetails = CronMethodParser.findTargetMethodDetails(scheduledJobDetail.getJobName()); - Object targetObject = getBeanObject(Class.forName(jobDetails[CronMethodParser.CLASS_INDEX])); - MethodInvokingJobDetailFactoryBean jobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean(); + final MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); + final String[] jobDetails = CronMethodParser.findTargetMethodDetails(scheduledJobDetail.getJobName()); + final Object targetObject = getBeanObject(Class.forName(jobDetails[CronMethodParser.CLASS_INDEX])); + final MethodInvokingJobDetailFactoryBean jobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean(); jobDetailFactoryBean.setName(scheduledJobDetail.getJobName() + "JobDetail" + tenant.getId()); jobDetailFactoryBean.setTargetObject(targetObject); jobDetailFactoryBean.setTargetMethod(jobDetails[CronMethodParser.METHOD_INDEX]); @@ -301,9 +301,9 @@ public class JobRegisterServiceImpl implements JobRegisterService { * @return * @throws ClassNotFoundException */ - private Object getBeanObject(Class classType) throws ClassNotFoundException { - List> typesList = new ArrayList>(); - Class[] interfaceType = classType.getInterfaces(); + private Object getBeanObject(final Class classType) throws ClassNotFoundException { + final List> typesList = new ArrayList>(); + final Class[] interfaceType = classType.getInterfaces(); if (interfaceType.length > 0) { typesList.addAll(Arrays.asList(interfaceType)); } else { @@ -313,13 +313,13 @@ public class JobRegisterServiceImpl implements JobRegisterService { } typesList.add(superclassType); } - List beanNames = new ArrayList(); - for (Class clazz : typesList) { + final List beanNames = new ArrayList(); + for (final Class clazz : typesList) { beanNames.addAll(Arrays.asList(this.applicationContext.getBeanNamesForType(clazz))); } Object targetObject = null; - for (String beanName : beanNames) { - Object nextObject = this.applicationContext.getBean(beanName); + for (final String beanName : beanNames) { + final Object nextObject = this.applicationContext.getBean(beanName); String targetObjName = nextObject.toString(); targetObjName = targetObjName.substring(0, targetObjName.lastIndexOf("@")); if (classType.getName().equals(targetObjName)) { @@ -335,14 +335,14 @@ public class JobRegisterServiceImpl implements JobRegisterService { * @return */ private Trigger createTrigger(final ScheduledJobDetail scheduledJobDetails, final JobDetail jobDetail) { - MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); - CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean(); + final MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); + final CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean(); cronTriggerFactoryBean.setName(scheduledJobDetails.getJobName() + "Trigger" + tenant.getId()); cronTriggerFactoryBean.setJobDetail(jobDetail); - JobDataMap jobDataMap = new JobDataMap(); + final JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put(SchedulerServiceConstants.TENANT_IDENTIFIER, tenant.getTenantIdentifier()); cronTriggerFactoryBean.setJobDataMap(jobDataMap); - TimeZone timeZone = TimeZone.getTimeZone(tenant.getTimezoneId()); + final TimeZone timeZone = TimeZone.getTimeZone(tenant.getTimezoneId()); cronTriggerFactoryBean.setTimeZone(timeZone); cronTriggerFactoryBean.setGroup(scheduledJobDetails.getGroupName()); cronTriggerFactoryBean.setCronExpression(scheduledJobDetails.getCronExpression()); @@ -355,10 +355,10 @@ public class JobRegisterServiceImpl implements JobRegisterService { * @param throwable * @return */ - private String getStackTraceAsString(Throwable throwable) { - StackTraceElement[] stackTraceElements = throwable.getStackTrace(); - StringBuffer sb = new StringBuffer(throwable.toString()); - for (StackTraceElement element : stackTraceElements) { + private String getStackTraceAsString(final Throwable throwable) { + final StackTraceElement[] stackTraceElements = throwable.getStackTrace(); + final StringBuffer sb = new StringBuffer(throwable.toString()); + for (final StackTraceElement element : stackTraceElements) { sb.append("\n \t at ").append(element.getClassName()).append(".").append(element.getMethodName()).append("(") .append(element.getLineNumber()).append(")"); } @@ -370,8 +370,8 @@ public class JobRegisterServiceImpl implements JobRegisterService { } private JobKey constructJobKey(final String Key) { - String[] keyParams = Key.split(SchedulerServiceConstants.JOB_KEY_SEPERATOR); - JobKey JobKey = new JobKey(keyParams[0], keyParams[1]); + final String[] keyParams = Key.split(SchedulerServiceConstants.JOB_KEY_SEPERATOR); + final JobKey JobKey = new JobKey(keyParams[0], keyParams[1]); return JobKey; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedularWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedularWritePlatformServiceJpaRepositoryImpl.java index b686ef849..ca2dda372 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedularWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedularWritePlatformServiceJpaRepositoryImpl.java @@ -42,12 +42,12 @@ public class SchedularWritePlatformServiceJpaRepositoryImpl implements Schedular @Override public List retrieveAllJobs() { - return scheduledJobDetailsRepository.findAll(); + return this.scheduledJobDetailsRepository.findAll(); } @Override public ScheduledJobDetail findByJobKey(final String jobKey) { - return scheduledJobDetailsRepository.findByJobKey(jobKey); + return this.scheduledJobDetailsRepository.findByJobKey(jobKey); } @Transactional @@ -66,7 +66,7 @@ public class SchedularWritePlatformServiceJpaRepositoryImpl implements Schedular @Override public Long fetchMaxVersionBy(final String jobKey) { Long version = 0L; - Long versionFromDB = this.scheduledJobRunHistoryRepository.findMaxVersionByJobKey(jobKey); + final Long versionFromDB = this.scheduledJobRunHistoryRepository.findMaxVersionByJobKey(jobKey); if (versionFromDB != null) { version = versionFromDB; } @@ -74,7 +74,7 @@ public class SchedularWritePlatformServiceJpaRepositoryImpl implements Schedular } @Override - public ScheduledJobDetail findByJobId(Long jobId) { + public ScheduledJobDetail findByJobId(final Long jobId) { return this.scheduledJobDetailsRepository.findByJobId(jobId); } @@ -87,7 +87,7 @@ public class SchedularWritePlatformServiceJpaRepositoryImpl implements Schedular @Override public SchedulerDetail retriveSchedulerDetail() { SchedulerDetail schedulerDetail = null; - List schedulerDetailList = schedulerDetailRepository.findAll(); + final List schedulerDetailList = this.schedulerDetailRepository.findAll(); if (schedulerDetailList != null) { schedulerDetail = schedulerDetailList.get(0); } @@ -97,7 +97,7 @@ public class SchedularWritePlatformServiceJpaRepositoryImpl implements Schedular @Transactional @Override public CommandProcessingResult updateJobDetail(final Long jobId, final JsonCommand command) { - dataValidator.validateForUpdate(command.json()); + this.dataValidator.validateForUpdate(command.json()); final ScheduledJobDetail scheduledJobDetail = findByJobId(jobId); if (scheduledJobDetail == null) { throw new JobNotFoundException(String.valueOf(jobId)); } final Map changes = scheduledJobDetail.update(command); @@ -114,9 +114,9 @@ public class SchedularWritePlatformServiceJpaRepositoryImpl implements Schedular @Transactional @Override - public boolean processJobDetailForExecution(String jobKey, String triggerType) { + public boolean processJobDetailForExecution(final String jobKey, final String triggerType) { boolean isStopExecution = false; - final ScheduledJobDetail scheduledJobDetail = scheduledJobDetailsRepository.findByJobKeyWithLock(jobKey); + final ScheduledJobDetail scheduledJobDetail = this.scheduledJobDetailsRepository.findByJobKeyWithLock(jobKey); if (scheduledJobDetail.isCurrentlyRunning() || (triggerType == SchedulerServiceConstants.TRIGGER_TYPE_CRON && (scheduledJobDetail.getNextRunTime().after(new Date())))) { isStopExecution = true; @@ -128,7 +128,7 @@ public class SchedularWritePlatformServiceJpaRepositoryImpl implements Schedular } else if (!isStopExecution) { scheduledJobDetail.updateCurrentlyRunningStatus(true); } - scheduledJobDetailsRepository.save(scheduledJobDetail); + this.scheduledJobDetailsRepository.save(scheduledJobDetail); return isStopExecution; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerJobListener.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerJobListener.java index 542397498..a341e6c87 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerJobListener.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerJobListener.java @@ -50,24 +50,24 @@ public class SchedulerJobListener implements JobListener { @Override public void jobWasExecuted(final JobExecutionContext context, final JobExecutionException jobException) { - Trigger trigger = context.getTrigger(); - JobKey key = context.getJobDetail().getKey(); - String jobKey = key.getName() + SchedulerServiceConstants.JOB_KEY_SEPERATOR + key.getGroup(); - final ScheduledJobDetail scheduledJobDetails = schedularService.findByJobKey(jobKey); - Long version = schedularService.fetchMaxVersionBy(jobKey) + 1; + final Trigger trigger = context.getTrigger(); + final JobKey key = context.getJobDetail().getKey(); + final String jobKey = key.getName() + SchedulerServiceConstants.JOB_KEY_SEPERATOR + key.getGroup(); + final ScheduledJobDetail scheduledJobDetails = this.schedularService.findByJobKey(jobKey); + final Long version = this.schedularService.fetchMaxVersionBy(jobKey) + 1; String status = SchedulerServiceConstants.STATUS_SUCCESS; String errorMessage = null; String errorLog = null; if (jobException != null) { status = SchedulerServiceConstants.STATUS_FAILED; - stackTraceLevel = 0; - Throwable throwable = getCauseFromException(jobException); - stackTraceLevel = 0; + this.stackTraceLevel = 0; + final Throwable throwable = getCauseFromException(jobException); + this.stackTraceLevel = 0; StackTraceElement[] stackTraceElements = null; errorMessage = throwable.getMessage(); stackTraceElements = throwable.getStackTrace(); - StringBuffer sb = new StringBuffer(throwable.toString()); - for (StackTraceElement element : stackTraceElements) { + final StringBuffer sb = new StringBuffer(throwable.toString()); + for (final StackTraceElement element : stackTraceElements) { sb.append("\n \t at ").append(element.getClassName()).append(".").append(element.getMethodName()).append("(") .append(element.getLineNumber()).append(")"); } @@ -86,21 +86,21 @@ public class SchedulerJobListener implements JobListener { scheduledJobDetails.updatePreviousRunStartTime(context.getFireTime()); scheduledJobDetails.updateCurrentlyRunningStatus(false); - ScheduledJobRunHistory runHistory = new ScheduledJobRunHistory(scheduledJobDetails, version, context.getFireTime(), new Date(), - status, errorMessage, triggerType, errorLog); + final ScheduledJobRunHistory runHistory = new ScheduledJobRunHistory(scheduledJobDetails, version, context.getFireTime(), + new Date(), status, errorMessage, triggerType, errorLog); // scheduledJobDetails.addRunHistory(runHistory); - schedularService.saveOrUpdate(scheduledJobDetails, runHistory); + this.schedularService.saveOrUpdate(scheduledJobDetails, runHistory); } private Throwable getCauseFromException(final Throwable exception) { - if (stackTraceLevel <= SchedulerServiceConstants.STACK_TRACE_LEVEL + if (this.stackTraceLevel <= SchedulerServiceConstants.STACK_TRACE_LEVEL && exception.getCause() != null && (exception.getCause().toString().contains(SchedulerServiceConstants.SCHEDULER_EXCEPTION) || exception.getCause().toString().contains(SchedulerServiceConstants.JOB_EXECUTION_EXCEPTION) || exception .getCause().toString().contains(SchedulerServiceConstants.JOB_METHOD_INVOCATION_FAILED_EXCEPTION))) { - stackTraceLevel++; + this.stackTraceLevel++; return getCauseFromException(exception.getCause()); } else if (exception.getCause() != null) { return exception.getCause(); } return exception; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerJobRunnerReadServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerJobRunnerReadServiceImpl.java index ecefa9471..d64b75b0e 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerJobRunnerReadServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerJobRunnerReadServiceImpl.java @@ -28,34 +28,34 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead @Autowired public SchedulerJobRunnerReadServiceImpl(final RoutingDataSource dataSource) { - jdbcTemplate = new JdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override public List findAllJobDeatils() { - JobDetailMapper detailMapper = new JobDetailMapper(); - String sql = detailMapper.schema(); - List JobDeatils = jdbcTemplate.query(sql, detailMapper, new Object[] {}); + final JobDetailMapper detailMapper = new JobDetailMapper(); + final String sql = detailMapper.schema(); + final List JobDeatils = this.jdbcTemplate.query(sql, detailMapper, new Object[] {}); return JobDeatils; } @Override - public JobDetailData retrieveOne(Long jobId) { + public JobDetailData retrieveOne(final Long jobId) { try { - JobDetailMapper detailMapper = new JobDetailMapper(); - String sql = detailMapper.schema() + " where job.id=?"; - return jdbcTemplate.queryForObject(sql, detailMapper, new Object[] { jobId }); - } catch (EmptyResultDataAccessException e) { + final JobDetailMapper detailMapper = new JobDetailMapper(); + final String sql = detailMapper.schema() + " where job.id=?"; + return this.jdbcTemplate.queryForObject(sql, detailMapper, new Object[] { jobId }); + } catch (final EmptyResultDataAccessException e) { throw new JobNotFoundException(String.valueOf(jobId)); } } @Override - public Page retrieveJobHistory(Long jobId, SearchParameters searchParameters) { + public Page retrieveJobHistory(final Long jobId, final SearchParameters searchParameters) { if (!isJobExist(jobId)) { throw new JobNotFoundException(String.valueOf(jobId)); } - JobHistoryMapper jobHistoryMapper = new JobHistoryMapper(); - StringBuilder sqlBuilder = new StringBuilder(200); + final JobHistoryMapper jobHistoryMapper = new JobHistoryMapper(); + final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append(jobHistoryMapper.schema()); sqlBuilder.append(" where job.id=?"); @@ -75,25 +75,26 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead } final String sqlCountRows = "SELECT FOUND_ROWS()"; - return paginationHelper.fetchPage(jdbcTemplate, sqlCountRows, sqlBuilder.toString(), new Object[] { jobId }, jobHistoryMapper); + return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), new Object[] { jobId }, + jobHistoryMapper); } @Override public boolean isUpdatesAllowed() { - String sql = "select job.display_name from job job where job.currently_running=true and job.updates_allowed=false"; - List names = jdbcTemplate.queryForList(sql, String.class); + final String sql = "select job.display_name from job job where job.currently_running=true and job.updates_allowed=false"; + final List names = this.jdbcTemplate.queryForList(sql, String.class); if (names != null && names.size() > 0) { - String listVals = names.toString(); - String jobNames = listVals.substring(listVals.indexOf("[") + 1, listVals.indexOf("]")); + final String listVals = names.toString(); + final String jobNames = listVals.substring(listVals.indexOf("[") + 1, listVals.indexOf("]")); throw new OperationNotAllowedException(jobNames); } return true; } - private boolean isJobExist(Long jobId) { + private boolean isJobExist(final Long jobId) { boolean isJobPresent = false; - String sql = "select count(*) from job job where job.id=" + jobId; - int count = jdbcTemplate.queryForInt(sql); + final String sql = "select count(*) from job job where job.id=" + jobId; + final int count = this.jdbcTemplate.queryForInt(sql); if (count == 1) { isJobPresent = true; } @@ -102,39 +103,39 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead private static final class JobDetailMapper implements RowMapper { - private StringBuilder sqlBuilder = new StringBuilder("select") + private final StringBuilder sqlBuilder = new StringBuilder("select") .append(" job.id,job.display_name as displayName,job.next_run_time as nextRunTime,job.initializing_errorlog as initializingError,job.cron_expression as cronExpression,job.is_active as active,job.currently_running as currentlyRunning,") .append(" runHistory.version,runHistory.start_time as lastRunStartTime,runHistory.end_time as lastRunEndTime,runHistory.`status`,runHistory.error_message as jobRunErrorMessage,runHistory.trigger_type as triggerType,runHistory.error_log as jobRunErrorLog ") .append(" from job job left join job_run_history runHistory ON job.id=runHistory.job_id and job.previous_run_start_time=runHistory.start_time "); public String schema() { - return sqlBuilder.toString(); + return this.sqlBuilder.toString(); } @Override - public JobDetailData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { - Long id = rs.getLong("id"); - String displayName = rs.getString("displayName"); - Date nextRunTime = rs.getTimestamp("nextRunTime"); - String initializingError = rs.getString("initializingError"); - String cronExpression = rs.getString("cronExpression"); - boolean active = rs.getBoolean("active"); - boolean currentlyRunning = rs.getBoolean("currentlyRunning"); + public JobDetailData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + final Long id = rs.getLong("id"); + final String displayName = rs.getString("displayName"); + final Date nextRunTime = rs.getTimestamp("nextRunTime"); + final String initializingError = rs.getString("initializingError"); + final String cronExpression = rs.getString("cronExpression"); + final boolean active = rs.getBoolean("active"); + final boolean currentlyRunning = rs.getBoolean("currentlyRunning"); - Long version = rs.getLong("version"); - Date jobRunStartTime = rs.getTimestamp("lastRunStartTime"); - Date jobRunEndTime = rs.getTimestamp("lastRunEndTime"); - String status = rs.getString("status"); - String jobRunErrorMessage = rs.getString("jobRunErrorMessage"); - String triggerType = rs.getString("triggerType"); - String jobRunErrorLog = rs.getString("jobRunErrorLog"); + final Long version = rs.getLong("version"); + final Date jobRunStartTime = rs.getTimestamp("lastRunStartTime"); + final Date jobRunEndTime = rs.getTimestamp("lastRunEndTime"); + final String status = rs.getString("status"); + final String jobRunErrorMessage = rs.getString("jobRunErrorMessage"); + final String triggerType = rs.getString("triggerType"); + final String jobRunErrorLog = rs.getString("jobRunErrorLog"); JobDetailHistoryData lastRunHistory = null; if (version > 0) { lastRunHistory = new JobDetailHistoryData(version, jobRunStartTime, jobRunEndTime, status, jobRunErrorMessage, triggerType, jobRunErrorLog); } - JobDetailData jobDetail = new JobDetailData(id, displayName, nextRunTime, initializingError, cronExpression, active, + final JobDetailData jobDetail = new JobDetailData(id, displayName, nextRunTime, initializingError, cronExpression, active, currentlyRunning, lastRunHistory); return jobDetail; } @@ -143,24 +144,24 @@ public class SchedulerJobRunnerReadServiceImpl implements SchedulerJobRunnerRead private static final class JobHistoryMapper implements RowMapper { - private StringBuilder sqlBuilder = new StringBuilder(200) + private final StringBuilder sqlBuilder = new StringBuilder(200) .append(" runHistory.version,runHistory.start_time as runStartTime,runHistory.end_time as runEndTime,runHistory.`status`,runHistory.error_message as jobRunErrorMessage,runHistory.trigger_type as triggerType,runHistory.error_log as jobRunErrorLog ") .append(" from job job join job_run_history runHistory ON job.id=runHistory.job_id"); public String schema() { - return sqlBuilder.toString(); + return this.sqlBuilder.toString(); } @Override - public JobDetailHistoryData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { - Long version = rs.getLong("version"); - Date jobRunStartTime = rs.getTimestamp("runStartTime"); - Date jobRunEndTime = rs.getTimestamp("runEndTime"); - String status = rs.getString("status"); - String jobRunErrorMessage = rs.getString("jobRunErrorMessage"); - String triggerType = rs.getString("triggerType"); - String jobRunErrorLog = rs.getString("jobRunErrorLog"); - JobDetailHistoryData jobDetailHistory = new JobDetailHistoryData(version, jobRunStartTime, jobRunEndTime, status, + public JobDetailHistoryData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { + final Long version = rs.getLong("version"); + final Date jobRunStartTime = rs.getTimestamp("runStartTime"); + final Date jobRunEndTime = rs.getTimestamp("runEndTime"); + final String status = rs.getString("status"); + final String jobRunErrorMessage = rs.getString("jobRunErrorMessage"); + final String triggerType = rs.getString("triggerType"); + final String jobRunErrorLog = rs.getString("jobRunErrorLog"); + final JobDetailHistoryData jobDetailHistory = new JobDetailHistoryData(version, jobRunStartTime, jobRunEndTime, status, jobRunErrorMessage, triggerType, jobRunErrorLog); return jobDetailHistory; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerServiceConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerServiceConstants.java index f95c21ce8..8a6d9396f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerServiceConstants.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerServiceConstants.java @@ -19,5 +19,5 @@ public interface SchedulerServiceConstants { public static final int DEFAULT_THREAD_COUNT = 7; public static final int GROUP_THREAD_COUNT = 1; public static final String SCHEDULER_NAME = "schedulerName"; - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerStopListener.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerStopListener.java index cb7ab74d1..1b3a80135 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerStopListener.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerStopListener.java @@ -41,11 +41,11 @@ public class SchedulerStopListener implements JobListener { public void jobWasExecuted(final JobExecutionContext context, @SuppressWarnings("unused") final JobExecutionException jobException) { final String schedulerName = context.getTrigger().getJobDataMap().getString(SchedulerServiceConstants.SCHEDULER_NAME); if (schedulerName != null) { - Thread newThread = new Thread(new Runnable() { + final Thread newThread = new Thread(new Runnable() { @Override public void run() { - jobRegisterService.stopScheduler(schedulerName); + SchedulerStopListener.this.jobRegisterService.stopScheduler(schedulerName); } }); newThread.run(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerTriggerListener.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerTriggerListener.java index b33daeeae..2977dd7af 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerTriggerListener.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/jobs/service/SchedulerTriggerListener.java @@ -33,33 +33,35 @@ public class SchedulerTriggerListener implements TriggerListener { } @Override - public void triggerFired(@SuppressWarnings("unused") Trigger trigger, @SuppressWarnings("unused") JobExecutionContext context) { + public void triggerFired(@SuppressWarnings("unused") final Trigger trigger, + @SuppressWarnings("unused") final JobExecutionContext context) { } @Override - public boolean vetoJobExecution(Trigger trigger, JobExecutionContext context) { + public boolean vetoJobExecution(final Trigger trigger, final JobExecutionContext context) { - String tenantIdentifier = trigger.getJobDataMap().getString(SchedulerServiceConstants.TENANT_IDENTIFIER); - MifosPlatformTenant tenant = this.tenantDetailsService.loadTenantById(tenantIdentifier); + final String tenantIdentifier = trigger.getJobDataMap().getString(SchedulerServiceConstants.TENANT_IDENTIFIER); + final MifosPlatformTenant tenant = this.tenantDetailsService.loadTenantById(tenantIdentifier); ThreadLocalContextUtil.setTenant(tenant); - JobKey key = trigger.getJobKey(); - String jobKey = key.getName() + SchedulerServiceConstants.JOB_KEY_SEPERATOR + key.getGroup(); + final JobKey key = trigger.getJobKey(); + final String jobKey = key.getName() + SchedulerServiceConstants.JOB_KEY_SEPERATOR + key.getGroup(); String triggerType = SchedulerServiceConstants.TRIGGER_TYPE_CRON; if (context.getMergedJobDataMap().containsKey(SchedulerServiceConstants.TRIGGER_TYPE_REFERENCE)) { triggerType = context.getMergedJobDataMap().getString(SchedulerServiceConstants.TRIGGER_TYPE_REFERENCE); } - return schedularService.processJobDetailForExecution(jobKey, triggerType); + return this.schedularService.processJobDetailForExecution(jobKey, triggerType); } @Override - public void triggerMisfired(@SuppressWarnings("unused") Trigger trigger) { + public void triggerMisfired(@SuppressWarnings("unused") final Trigger trigger) { } @Override - public void triggerComplete(@SuppressWarnings("unused") Trigger trigger, @SuppressWarnings("unused") JobExecutionContext context, - @SuppressWarnings("unused") CompletedExecutionInstruction triggerInstructionCode) { + public void triggerComplete(@SuppressWarnings("unused") final Trigger trigger, + @SuppressWarnings("unused") final JobExecutionContext context, + @SuppressWarnings("unused") final CompletedExecutionInstruction triggerInstructionCode) { } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/api/AuthenticationApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/api/AuthenticationApiResource.java index e2a56432e..16ab3d59c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/api/AuthenticationApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/api/AuthenticationApiResource.java @@ -52,23 +52,23 @@ public class AuthenticationApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String authenticate(@QueryParam("username") final String username, @QueryParam("password") final String password) { - Authentication authentication = new UsernamePasswordAuthenticationToken(username, password); - Authentication authenticationCheck = customAuthenticationProvider.authenticate(authentication); + final Authentication authentication = new UsernamePasswordAuthenticationToken(username, password); + final Authentication authenticationCheck = this.customAuthenticationProvider.authenticate(authentication); - Collection permissions = new ArrayList(); + final Collection permissions = new ArrayList(); AuthenticatedUserData authenticatedUserData = new AuthenticatedUserData(username, permissions); if (authenticationCheck.isAuthenticated()) { - Collection authorities = new ArrayList(authenticationCheck.getAuthorities()); - for (GrantedAuthority grantedAuthority : authorities) { + final Collection authorities = new ArrayList(authenticationCheck.getAuthorities()); + for (final GrantedAuthority grantedAuthority : authorities) { permissions.add(grantedAuthority.getAuthority()); } - AppUser principal = (AppUser) authenticationCheck.getPrincipal(); - byte[] base64EncodedAuthenticationKey = Base64.encode(username + ":" + password); + final AppUser principal = (AppUser) authenticationCheck.getPrincipal(); + final byte[] base64EncodedAuthenticationKey = Base64.encode(username + ":" + password); - Collection roles = new ArrayList(); - Set userRoles = principal.getRoles(); - for (Role role : userRoles) { + final Collection roles = new ArrayList(); + final Set userRoles = principal.getRoles(); + for (final Role role : userRoles) { roles.add(role.toData()); } @@ -81,8 +81,7 @@ public class AuthenticationApiResource { final EnumOptionData organisationalRole = principal.organisationalRoleData(); authenticatedUserData = new AuthenticatedUserData(username, officeId, officeName, staffId, staffDisplayName, - organisationalRole, roles, permissions, - principal.getId(), new String(base64EncodedAuthenticationKey)); + organisationalRole, roles, permissions, principal.getId(), new String(base64EncodedAuthenticationKey)); } return this.apiJsonSerializerService.serialize(authenticatedUserData); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/data/PlatformRequestLog.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/data/PlatformRequestLog.java index 291a51395..11fa7c07e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/data/PlatformRequestLog.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/data/PlatformRequestLog.java @@ -20,22 +20,22 @@ import org.apache.commons.lang.time.StopWatch; public class PlatformRequestLog { @SuppressWarnings("unused") - private long startTime; + private final long startTime; @SuppressWarnings("unused") - private long totalTime; + private final long totalTime; @SuppressWarnings("unused") private final String method; @SuppressWarnings("unused") - private String url; + private final String url; @SuppressWarnings("unused") - private Map parameters; + private final Map parameters; public static PlatformRequestLog from(final StopWatch task, final HttpServletRequest request) throws IOException { final String requestUrl = request.getRequestURL().toString(); @SuppressWarnings("unchecked") - Map parameters = new HashMap(request.getParameterMap()); + final Map parameters = new HashMap(request.getParameterMap()); parameters.remove("password"); parameters.remove("_"); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/domain/PlatformUserRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/domain/PlatformUserRepository.java index 4951b8454..14448ec16 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/domain/PlatformUserRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/domain/PlatformUserRepository.java @@ -5,7 +5,6 @@ */ package org.mifosplatform.infrastructure.security.domain; - public interface PlatformUserRepository { PlatformUser findByUsername(String username); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/filter/TenantAwareBasicAuthenticationFilter.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/filter/TenantAwareBasicAuthenticationFilter.java index 10c0ef4e3..9283f1044 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/filter/TenantAwareBasicAuthenticationFilter.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/filter/TenantAwareBasicAuthenticationFilter.java @@ -35,16 +35,16 @@ import org.springframework.stereotype.Service; /** * A customised version of spring security's {@link BasicAuthenticationFilter}. - * + * * This filter is responsible for extracting multi-tenant and basic auth * credentials from the request and checking that the details provided are * valid. - * + * * If multi-tenant and basic auth credentials are valid, the details of the * tenant are stored in {@link MifosPlatformTenant} and stored in a * {@link ThreadLocal} variable for this request using * {@link ThreadLocalContextUtil}. - * + * * If multi-tenant and basic auth credentials are invalid, a http error response * is returned. */ @@ -64,10 +64,9 @@ public class TenantAwareBasicAuthenticationFilter extends BasicAuthenticationFil @Autowired public TenantAwareBasicAuthenticationFilter(final AuthenticationManager authenticationManager, - final AuthenticationEntryPoint authenticationEntryPoint, - final BasicAuthTenantDetailsService basicAuthTenantDetailsService, - final ToApiJsonSerializer toApiJsonSerializer, - final ConfigurationDomainService configurationDomainService, final CacheWritePlatformService cacheWritePlatformService) { + final AuthenticationEntryPoint authenticationEntryPoint, final BasicAuthTenantDetailsService basicAuthTenantDetailsService, + final ToApiJsonSerializer toApiJsonSerializer, final ConfigurationDomainService configurationDomainService, + final CacheWritePlatformService cacheWritePlatformService) { super(authenticationManager, authenticationEntryPoint); this.basicAuthTenantDetailsService = basicAuthTenantDetailsService; this.toApiJsonSerializer = toApiJsonSerializer; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/CustomAuthenticationFailureHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/CustomAuthenticationFailureHandler.java index 198f13f5b..5772fde54 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/CustomAuthenticationFailureHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/CustomAuthenticationFailureHandler.java @@ -23,7 +23,7 @@ import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { - + protected final Log logger = LogFactory.getLog(getClass()); private String defaultFailureUrl; @@ -31,38 +31,37 @@ public class CustomAuthenticationFailureHandler implements AuthenticationFailure private boolean allowSessionCreation = true; private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - public CustomAuthenticationFailureHandler() { - } + public CustomAuthenticationFailureHandler() {} /** - * Performs the redirect or forward to the {@code defaultFailureUrl} if set, otherwise returns a 401 error code. + * Performs the redirect or forward to the {@code defaultFailureUrl} if set, + * otherwise returns a 401 error code. *

- * If redirecting or forwarding, {@code saveException} will be called to cache the exception for use in - * the target view. + * If redirecting or forwarding, {@code saveException} will be called to + * cache the exception for use in the target view. */ @Override - public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, - AuthenticationException exception) throws IOException, ServletException { + public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, + final AuthenticationException exception) throws IOException, ServletException { - if (defaultFailureUrl == null) { - logger.debug("No failure URL set, sending 401 Unauthorized error"); + if (this.defaultFailureUrl == null) { + this.logger.debug("No failure URL set, sending 401 Unauthorized error"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed: " + exception.getMessage()); } else { saveException(request, exception); - if (forwardToDestination) { - logger.debug("Forwarding to " + defaultFailureUrl); + if (this.forwardToDestination) { + this.logger.debug("Forwarding to " + this.defaultFailureUrl); - request.getRequestDispatcher(defaultFailureUrl).forward(request, response); + request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response); } else { - logger.debug("Redirecting to " + defaultFailureUrl); - - - String oauthToken = request.getParameter("oauth_token"); + this.logger.debug("Redirecting to " + this.defaultFailureUrl); + + final String oauthToken = request.getParameter("oauth_token"); request.setAttribute("oauth_token", oauthToken); - String url = defaultFailureUrl + "?oauth_token=" + oauthToken; - redirectStrategy.sendRedirect(request, response, url); + final String url = this.defaultFailureUrl + "?oauth_token=" + oauthToken; + this.redirectStrategy.sendRedirect(request, response, url); } } } @@ -70,17 +69,18 @@ public class CustomAuthenticationFailureHandler implements AuthenticationFailure /** * Caches the {@code AuthenticationException} for use in view rendering. *

- * If {@code forwardToDestination} is set to true, request scope will be used, otherwise it will attempt to store - * the exception in the session. If there is no session and {@code allowSessionCreation} is {@code true} a session - * will be created. Otherwise the exception will not be stored. + * If {@code forwardToDestination} is set to true, request scope will be + * used, otherwise it will attempt to store the exception in the session. If + * there is no session and {@code allowSessionCreation} is {@code true} a + * session will be created. Otherwise the exception will not be stored. */ - protected final void saveException(HttpServletRequest request, AuthenticationException exception) { - if (forwardToDestination) { + protected final void saveException(final HttpServletRequest request, final AuthenticationException exception) { + if (this.forwardToDestination) { request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); } else { - HttpSession session = request.getSession(false); + final HttpSession session = request.getSession(false); - if (session != null || allowSessionCreation) { + if (session != null || this.allowSessionCreation) { request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception); } } @@ -88,43 +88,43 @@ public class CustomAuthenticationFailureHandler implements AuthenticationFailure /** * The URL which will be used as the failure destination. - * - * @param defaultFailureUrl the failure URL, for example "/loginFailed.jsp". + * + * @param defaultFailureUrl + * the failure URL, for example "/loginFailed.jsp". */ - public void setDefaultFailureUrl(String defaultFailureUrl) { - Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl), - "'" + defaultFailureUrl + "' is not a valid redirect URL"); + public void setDefaultFailureUrl(final String defaultFailureUrl) { + Assert.isTrue(UrlUtils.isValidRedirectUrl(defaultFailureUrl), "'" + defaultFailureUrl + "' is not a valid redirect URL"); this.defaultFailureUrl = defaultFailureUrl; } protected boolean isUseForward() { - return forwardToDestination; + return this.forwardToDestination; } /** - * If set to true, performs a forward to the failure destination URL instead of a redirect. Defaults to - * false. + * If set to true, performs a forward to the failure destination + * URL instead of a redirect. Defaults to false. */ - public void setUseForward(boolean forwardToDestination) { + public void setUseForward(final boolean forwardToDestination) { this.forwardToDestination = forwardToDestination; } /** * Allows overriding of the behaviour when redirecting to a target URL. */ - public void setRedirectStrategy(RedirectStrategy redirectStrategy) { + public void setRedirectStrategy(final RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } protected RedirectStrategy getRedirectStrategy() { - return redirectStrategy; + return this.redirectStrategy; } protected boolean isAllowSessionCreation() { - return allowSessionCreation; + return this.allowSessionCreation; } - public void setAllowSessionCreation(boolean allowSessionCreation) { + public void setAllowSessionCreation(final boolean allowSessionCreation) { this.allowSessionCreation = allowSessionCreation; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/JdbcTenantDetailsService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/JdbcTenantDetailsService.java index 4282fa597..9396bb23d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/JdbcTenantDetailsService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/JdbcTenantDetailsService.java @@ -60,8 +60,8 @@ public class JdbcTenantDetailsService implements TenantDetailsService { final String timezoneId = rs.getString("timezoneId"); final boolean autoUpdateEnabled = rs.getBoolean("autoUpdate"); - return new MifosPlatformTenant(id, tenantIdentifier,name, schemaName, schemaServer, schemaServerPort, schemaUsername, schemaPassword, - timezoneId, autoUpdateEnabled); + return new MifosPlatformTenant(id, tenantIdentifier, name, schemaName, schemaServer, schemaServerPort, schemaUsername, + schemaPassword, timezoneId, autoUpdateEnabled); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/PlatformSecurityContext.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/PlatformSecurityContext.java index 56d9907d3..9c99fb8e0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/PlatformSecurityContext.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/PlatformSecurityContext.java @@ -10,6 +10,6 @@ import org.mifosplatform.useradministration.domain.AppUser; public interface PlatformSecurityContext { AppUser authenticatedUser(); - + void validateAccessRights(String resourceOfficeHierarchy); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/PlatformUserDetailsService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/PlatformUserDetailsService.java index f7bce1651..352475692 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/PlatformUserDetailsService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/PlatformUserDetailsService.java @@ -11,5 +11,5 @@ import org.springframework.security.core.userdetails.UserDetailsService; * Interface to hide implementation detail of spring security. */ public interface PlatformUserDetailsService extends UserDetailsService { - // no added behaviour + // no added behaviour } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/RandomPasswordGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/RandomPasswordGenerator.java index 6395f4029..d187f0cbb 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/RandomPasswordGenerator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/RandomPasswordGenerator.java @@ -15,7 +15,7 @@ public class RandomPasswordGenerator { public String generate() { - StringBuilder passwordBuilder = new StringBuilder(this.numberOfCharactersInPassword); + final StringBuilder passwordBuilder = new StringBuilder(this.numberOfCharactersInPassword); for (int i = 0; i < this.numberOfCharactersInPassword; i++) { passwordBuilder.append((char) ((int) (Math.random() * 26) + 97)); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/SpringSecurityPlatformSecurityContext.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/SpringSecurityPlatformSecurityContext.java index d9308ab88..2096725de 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/SpringSecurityPlatformSecurityContext.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/SpringSecurityPlatformSecurityContext.java @@ -42,9 +42,8 @@ public class SpringSecurityPlatformSecurityContext implements PlatformSecurityCo final AppUser user = authenticatedUser(); final String userOfficeHierarchy = user.getOffice().getHierarchy(); - if (!resourceOfficeHierarchy.startsWith(userOfficeHierarchy)) { - throw new NoAuthorizationException("The user doesn't have enough permissions to access the resource."); - } + if (!resourceOfficeHierarchy.startsWith(userOfficeHierarchy)) { throw new NoAuthorizationException( + "The user doesn't have enough permissions to access the resource."); } } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/TenantAwareJpaPlatformUserDetailsService.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/TenantAwareJpaPlatformUserDetailsService.java index 49343456e..f0ca9479e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/TenantAwareJpaPlatformUserDetailsService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/security/service/TenantAwareJpaPlatformUserDetailsService.java @@ -16,9 +16,10 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; /** - * Used in securityContext.xml as implementation of spring security's {@link UserDetailsService}. + * Used in securityContext.xml as implementation of spring security's + * {@link UserDetailsService}. */ -@Service(value="userDetailsService") +@Service(value = "userDetailsService") public class TenantAwareJpaPlatformUserDetailsService implements PlatformUserDetailsService { @Autowired diff --git a/mifosng-provider/src/main/java/org/mifosplatform/mix/api/MixTaxonomyMappingApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/mix/api/MixTaxonomyMappingApiResource.java index 3c4d9cd3d..ef25bf378 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/mix/api/MixTaxonomyMappingApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/mix/api/MixTaxonomyMappingApiResource.java @@ -41,10 +41,11 @@ public class MixTaxonomyMappingApiResource { private final ApiRequestParameterHelper apiRequestParameterHelper; @Autowired - public MixTaxonomyMappingApiResource(PlatformSecurityContext context, ToApiJsonSerializer toApiJsonSerializer, - MixTaxonomyMappingReadPlatformService readTaxonomyMappingService, - PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - ApiRequestParameterHelper apiRequestParameterHelper) { + public MixTaxonomyMappingApiResource(final PlatformSecurityContext context, + final ToApiJsonSerializer toApiJsonSerializer, + final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, + final ApiRequestParameterHelper apiRequestParameterHelper) { this.context = context; this.toApiJsonSerializer = toApiJsonSerializer; @@ -57,10 +58,10 @@ public class MixTaxonomyMappingApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveTaxonomyMapping(@Context final UriInfo uriInfo) { - context.authenticatedUser(); - MixTaxonomyMappingData mappingData = this.readTaxonomyMappingService.retrieveTaxonomyMapping(); + this.context.authenticatedUser(); + final MixTaxonomyMappingData mappingData = this.readTaxonomyMappingService.retrieveTaxonomyMapping(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, mappingData, RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, mappingData, this.RESPONSE_DATA_PARAMETERS); } @PUT diff --git a/mifosng-provider/src/main/java/org/mifosplatform/mix/data/MixTaxonomyData.java b/mifosng-provider/src/main/java/org/mifosplatform/mix/data/MixTaxonomyData.java index 1a6d3c7b7..11b7dda96 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/mix/data/MixTaxonomyData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/mix/data/MixTaxonomyData.java @@ -16,7 +16,8 @@ public class MixTaxonomyData { @SuppressWarnings("unused") private final String description; - public MixTaxonomyData(final Long id, final String name, final String namespace, final String dimension, final Integer type, final String description) { + public MixTaxonomyData(final Long id, final String name, final String namespace, final String dimension, final Integer type, + final String description) { this.id = id; this.name = name; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/mix/exception/XBRLMappingInvalidException.java b/mifosng-provider/src/main/java/org/mifosplatform/mix/exception/XBRLMappingInvalidException.java index 500e3a93d..7de700699 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/mix/exception/XBRLMappingInvalidException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/mix/exception/XBRLMappingInvalidException.java @@ -4,7 +4,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul public class XBRLMappingInvalidException extends AbstractPlatformDomainRuleException { - public XBRLMappingInvalidException(String msg) { + public XBRLMappingInvalidException(final String msg) { super("error.msg.xbrl.report.mapping.invalid.id", "Mapping does not exist", msg); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/mix/handler/UpdateTaxonomyMappingCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/mix/handler/UpdateTaxonomyMappingCommandHandler.java index b6e6124ef..20bf29da4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/mix/handler/UpdateTaxonomyMappingCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/mix/handler/UpdateTaxonomyMappingCommandHandler.java @@ -14,13 +14,13 @@ public class UpdateTaxonomyMappingCommandHandler implements NewCommandSourceHand private final MixTaxonomyMappingWritePlatformService writeTaxonomyService; @Autowired - public UpdateTaxonomyMappingCommandHandler(MixTaxonomyMappingWritePlatformService writeTaxonomyService) { + public UpdateTaxonomyMappingCommandHandler(final MixTaxonomyMappingWritePlatformService writeTaxonomyService) { this.writeTaxonomyService = writeTaxonomyService; } @Transactional @Override - public CommandProcessingResult processCommand(JsonCommand command) { + public CommandProcessingResult processCommand(final JsonCommand command) { return this.writeTaxonomyService.updateMapping(command.entityId(), command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/mix/service/XBRLBuilder.java b/mifosng-provider/src/main/java/org/mifosplatform/mix/service/XBRLBuilder.java index 45479f1a7..f49b6aed9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/mix/service/XBRLBuilder.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/mix/service/XBRLBuilder.java @@ -36,67 +36,68 @@ public class XBRLBuilder { @Autowired private NamespaceReadPlatformService readNamespaceService; - public String build(XBRLData xbrlData) { + public String build(final XBRLData xbrlData) { return this.build(xbrlData.getResultMap(), xbrlData.getStartDate(), xbrlData.getEndDate(), xbrlData.getCurrency()); } - public String build(Map map, Date startDate, Date endDate, String currency) { - instantScenarioCounter = 1; - durationScenarioCounter = 1; - contextMap = new HashMap(); - Document doc = DocumentHelper.createDocument(); - root = doc.addElement("xbrl"); + public String build(final Map map, final Date startDate, final Date endDate, final String currency) { + this.instantScenarioCounter = 1; + this.durationScenarioCounter = 1; + this.contextMap = new HashMap(); + final Document doc = DocumentHelper.createDocument(); + this.root = doc.addElement("xbrl"); - root.addElement("schemaRef").addNamespace("link", + this.root.addElement("schemaRef").addNamespace("link", "http://www.themix.org/sites/default/files/Taxonomy2010/dct/dc-all_2010-08-31.xsd"); this.startDate = startDate; this.endDate = endDate; - for (Entry entry : map.entrySet()) { - MixTaxonomyData taxonomy = entry.getKey(); - BigDecimal value = entry.getValue(); - this.addTaxonomy(root, taxonomy, value); + for (final Entry entry : map.entrySet()) { + final MixTaxonomyData taxonomy = entry.getKey(); + final BigDecimal value = entry.getValue(); + addTaxonomy(this.root, taxonomy, value); } - this.addContexts(); - this.addCurrencyUnit(currency); - this.addNumberUnit(); + addContexts(); + addCurrencyUnit(currency); + addNumberUnit(); doc.setXMLEncoding("UTF-8"); return doc.asXML(); } - Element addTaxonomy(Element rootElement, MixTaxonomyData taxonomy, BigDecimal value) { + Element addTaxonomy(final Element rootElement, final MixTaxonomyData taxonomy, final BigDecimal value) { // throw an error is start / endate is null - if (startDate == null || endDate == null) { throw new XBRLMappingInvalidException("start date and end date should not be null"); } + if (this.startDate == null || this.endDate == null) { throw new XBRLMappingInvalidException( + "start date and end date should not be null"); } - String prefix = taxonomy.getNamespace(); + final String prefix = taxonomy.getNamespace(); String qname = taxonomy.getName(); if (prefix != null && (!prefix.isEmpty())) { - NamespaceData ns = readNamespaceService.retrieveNamespaceByPrefix(prefix); + final NamespaceData ns = this.readNamespaceService.retrieveNamespaceByPrefix(prefix); if (ns != null) { - root.addNamespace(prefix, ns.url()); + this.root.addNamespace(prefix, ns.url()); } qname = prefix + ":" + taxonomy.getName(); } - Element xmlElement = rootElement.addElement(qname); + final Element xmlElement = rootElement.addElement(qname); - String dimension = taxonomy.getDimension(); - SimpleDateFormat timeFormat = new SimpleDateFormat("MM_dd_yyyy"); + final String dimension = taxonomy.getDimension(); + final SimpleDateFormat timeFormat = new SimpleDateFormat("MM_dd_yyyy"); ContextData context = null; if (dimension != null) { - String[] dims = dimension.split(":"); + final String[] dims = dimension.split(":"); if (dims.length == 2) { context = new ContextData(dims[0], dims[1], taxonomy.getType()); - if (contextMap.containsKey(context)) { + if (this.contextMap.containsKey(context)) { } else { @@ -108,18 +109,18 @@ public class XBRLBuilder { context = new ContextData(null, null, taxonomy.getType()); } - if (!contextMap.containsKey(context)) { + if (!this.contextMap.containsKey(context)) { - String startDateStr = timeFormat.format(startDate); - String endDateStr = timeFormat.format(endDate); + final String startDateStr = timeFormat.format(this.startDate); + final String endDateStr = timeFormat.format(this.endDate); - String contextRefID = (context.getPeriodType() == 0) ? ("As_Of_" + endDateStr + (instantScenarioCounter++)) : ("Duration_" - + startDateStr + "_To_" + endDateStr + (durationScenarioCounter++)); + final String contextRefID = (context.getPeriodType() == 0) ? ("As_Of_" + endDateStr + (this.instantScenarioCounter++)) + : ("Duration_" + startDateStr + "_To_" + endDateStr + (this.durationScenarioCounter++)); - contextMap.put(context, contextRefID); + this.contextMap.put(context, contextRefID); } - xmlElement.addAttribute("contextRef", contextMap.get(context)); + xmlElement.addAttribute("contextRef", this.contextMap.get(context)); xmlElement.addAttribute("unitRef", getUnitRef(taxonomy)); xmlElement.addAttribute("decimals", getNumberOfDecimalPlaces(value).toString()); @@ -129,7 +130,7 @@ public class XBRLBuilder { return xmlElement; } - private String getUnitRef(MixTaxonomyData tx) { + private String getUnitRef(final MixTaxonomyData tx) { return tx.isPortfolio() ? UNITID_PURE : UNITID_CUR; } @@ -137,9 +138,9 @@ public class XBRLBuilder { * Adds the generic number unit */ void addNumberUnit() { - Element numerUnit = root.addElement("unit"); + final Element numerUnit = this.root.addElement("unit"); numerUnit.addAttribute("id", UNITID_PURE); - Element measure = numerUnit.addElement("measure"); + final Element measure = numerUnit.addElement("measure"); measure.addText("xbrli:pure"); } @@ -149,33 +150,33 @@ public class XBRLBuilder { * * @param currencyCode */ - public void addCurrencyUnit(String currencyCode) { - Element currencyUnitElement = root.addElement("unit"); + public void addCurrencyUnit(final String currencyCode) { + final Element currencyUnitElement = this.root.addElement("unit"); currencyUnitElement.addAttribute("id", UNITID_CUR); - Element measure = currencyUnitElement.addElement("measure"); + final Element measure = currencyUnitElement.addElement("measure"); measure.addText("iso4217:" + currencyCode); } public void addContexts() { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - for (Entry entry : contextMap.entrySet()) { - ContextData context = entry.getKey(); - Element contextElement = root.addElement("context"); + final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + for (final Entry entry : this.contextMap.entrySet()) { + final ContextData context = entry.getKey(); + final Element contextElement = this.root.addElement("context"); contextElement.addAttribute("id", entry.getValue()); contextElement.addElement("entity").addElement("identifier").addAttribute("scheme", SCHEME_URL).addText(IDENTIFIER); - Element periodElement = contextElement.addElement("period"); + final Element periodElement = contextElement.addElement("period"); if (context.getPeriodType() == 0) { - periodElement.addElement("instant").addText(format.format(endDate)); + periodElement.addElement("instant").addText(format.format(this.endDate)); } else { - periodElement.addElement("startDate").addText(format.format(startDate)); - periodElement.addElement("endDate").addText(format.format(endDate)); + periodElement.addElement("startDate").addText(format.format(this.startDate)); + periodElement.addElement("endDate").addText(format.format(this.endDate)); } - String dimension = context.getDimension(); - String dimType = context.getDimensionType(); + final String dimension = context.getDimension(); + final String dimType = context.getDimensionType(); if (dimType != null && dimension != null) { contextElement.addElement("scenario").addElement("explicitMember").addAttribute("dimension", dimType).addText(dimension); } @@ -183,9 +184,9 @@ public class XBRLBuilder { } - private Integer getNumberOfDecimalPlaces(BigDecimal bigDecimal) { - String string = bigDecimal.stripTrailingZeros().toPlainString(); - int index = string.indexOf("."); + private Integer getNumberOfDecimalPlaces(final BigDecimal bigDecimal) { + final String string = bigDecimal.stripTrailingZeros().toPlainString(); + final int index = string.indexOf("."); return index < 0 ? 0 : string.length() - index - 1; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/mix/service/XBRLResultServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/mix/service/XBRLResultServiceImpl.java index 8e8056287..69a297020 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/mix/service/XBRLResultServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/mix/service/XBRLResultServiceImpl.java @@ -35,8 +35,8 @@ public class XBRLResultServiceImpl implements XBRLResultService { private HashMap accountBalanceMap; @Autowired - public XBRLResultServiceImpl(final RoutingDataSource dataSource, final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService, - final MixTaxonomyReadPlatformService readTaxonomyService) { + public XBRLResultServiceImpl(final RoutingDataSource dataSource, + final MixTaxonomyMappingReadPlatformService readTaxonomyMappingService, final MixTaxonomyReadPlatformService readTaxonomyService) { this.readTaxonomyMappingService = readTaxonomyMappingService; this.readTaxonomyService = readTaxonomyService; this.jdbcTemplate = new JdbcTemplate(dataSource); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/api/HolidayApiConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/api/HolidayApiConstants.java index 89d228f7b..580e8038c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/api/HolidayApiConstants.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/api/HolidayApiConstants.java @@ -6,13 +6,13 @@ import java.util.Set; public class HolidayApiConstants { - public static final String HOLIDAY_RESOURCE_NAME = "holiday"; - - // general + public static final String HOLIDAY_RESOURCE_NAME = "holiday"; + + // general public static final String localeParamName = "locale"; public static final String dateFormatParamName = "dateFormat"; - - //request parameters + + // request parameters public static final String name = "name"; public static final String fromDate = "fromDate"; public static final String toDate = "toDate"; @@ -21,10 +21,10 @@ public class HolidayApiConstants { public static final String officeId = "officeId"; public static final String repaymentsRescheduledTo = "repaymentsRescheduledTo"; public static final String processed = "processed"; - + public static final Set HOLIDAY_CREATE_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, dateFormatParamName, name, fromDate, toDate, description, offices, repaymentsRescheduledTo)); - + public static final Set HOLIDAY_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, dateFormatParamName, name, fromDate, toDate, repaymentsRescheduledTo)); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/api/HolidaysApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/api/HolidaysApiResource.java index 84cca551d..58ed77d4f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/api/HolidaysApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/api/HolidaysApiResource.java @@ -34,14 +34,14 @@ import org.springframework.stereotype.Component; public class HolidaysApiResource { private final String resourceNameForPermissions = "HOLIDAY"; - + private final DefaultToApiJsonSerializer toApiJsonSerializer; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; private final PlatformSecurityContext context; private final ApiRequestParameterHelper apiRequestParameterHelper; - + private final HolidayReadPlatformService holidayReadPlatformService; - + @Autowired public HolidaysApiResource(final DefaultToApiJsonSerializer toApiJsonSerializer, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final PlatformSecurityContext context, @@ -52,7 +52,7 @@ public class HolidaysApiResource { this.apiRequestParameterHelper = apiRequestParameterHelper; this.holidayReadPlatformService = holidayReadPlatformService; } - + @POST @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @@ -64,7 +64,7 @@ public class HolidaysApiResource { return this.toApiJsonSerializer.serialize(result); } - + @GET @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @@ -72,7 +72,7 @@ public class HolidaysApiResource { @QueryParam("fromDate") final DateParam fromDateParam, @QueryParam("toDate") final DateParam toDateParam, @QueryParam("locale") final String locale, @QueryParam("dateFormat") final String dateFormat) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); Date fromDate = null; if (fromDateParam != null) { @@ -83,9 +83,10 @@ public class HolidaysApiResource { toDate = toDateParam.getDate("toDate", dateFormat, locale); } - Collection holidays = this.holidayReadPlatformService.retrieveAllHolidaysBySearchParamerters(officeId, fromDate, toDate); + final Collection holidays = this.holidayReadPlatformService.retrieveAllHolidaysBySearchParamerters(officeId, fromDate, + toDate); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, holidays, HolidayApiConstants.HOLIDAY_REQUEST_DATA_PARAMETERS); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/data/HolidayData.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/data/HolidayData.java index 2b3de32c5..82e73c9c7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/data/HolidayData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/data/HolidayData.java @@ -2,9 +2,8 @@ package org.mifosplatform.organisation.holiday.data; import org.joda.time.LocalDate; - public class HolidayData { - + @SuppressWarnings("unused") private final Long id; @SuppressWarnings("unused") @@ -17,7 +16,7 @@ public class HolidayData { private final LocalDate repaymentsScheduleTO; @SuppressWarnings("unused") private final Long officeId; - + public HolidayData(final Long id, final String name, final LocalDate fromDate, final LocalDate toDate, final LocalDate repaymentsScheduleTO) { this.id = id; @@ -26,6 +25,6 @@ public class HolidayData { this.toDate = toDate; this.repaymentsScheduleTO = repaymentsScheduleTO; this.officeId = null; - + } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/data/HolidayDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/data/HolidayDataValidator.java index 413dec54f..c815aab89 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/data/HolidayDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/data/HolidayDataValidator.java @@ -38,8 +38,8 @@ public class HolidayDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, HolidayApiConstants.HOLIDAY_CREATE_REQUEST_DATA_PARAMETERS); - final JsonElement element = fromApiJsonHelper.parse(json); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, HolidayApiConstants.HOLIDAY_CREATE_REQUEST_DATA_PARAMETERS); + final JsonElement element = this.fromApiJsonHelper.parse(json); final List dataValidationErrors = new ArrayList(); @@ -54,8 +54,9 @@ public class HolidayDataValidator { final LocalDate toDate = this.fromApiJsonHelper.extractLocalDateNamed(HolidayApiConstants.toDate, element); baseDataValidator.reset().parameter(HolidayApiConstants.toDate).value(toDate).notNull(); - - final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper.extractLocalDateNamed(HolidayApiConstants.repaymentsRescheduledTo, element); + + final LocalDate repaymentsRescheduledTo = this.fromApiJsonHelper.extractLocalDateNamed(HolidayApiConstants.repaymentsRescheduledTo, + element); baseDataValidator.reset().parameter(HolidayApiConstants.repaymentsRescheduledTo).value(repaymentsRescheduledTo).notNull(); Set offices = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/domain/Holiday.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/domain/Holiday.java index b1eba52b1..f041ef38e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/domain/Holiday.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/domain/Holiday.java @@ -44,7 +44,7 @@ public class Holiday extends AbstractPersistable { @Column(name = "repayments_rescheduled_to", nullable = false) @Temporal(TemporalType.DATE) private Date repaymentsRescheduledTo; - + @Column(name = "processed", nullable = false) private boolean processed; @@ -60,12 +60,14 @@ public class Holiday extends AbstractPersistable { final LocalDate fromDate = command.localDateValueOfParameterNamed(HolidayApiConstants.fromDate); final LocalDate toDate = command.localDateValueOfParameterNamed(HolidayApiConstants.toDate); final LocalDate repaymentsRescheduledTo = command.localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledTo); - final boolean processed = false;//default it to false. Only batch job should update this field. + final boolean processed = false;// default it to false. Only batch job + // should update this field. final String description = command.stringValueOfParameterNamed(HolidayApiConstants.description); return new Holiday(name, fromDate, toDate, repaymentsRescheduledTo, processed, description, offices); } - private Holiday(final String name, final LocalDate fromDate, final LocalDate toDate, final LocalDate repaymentsRescheduledTo, final boolean processed, final String description, final Set offices) { + private Holiday(final String name, final LocalDate fromDate, final LocalDate toDate, final LocalDate repaymentsRescheduledTo, + final boolean processed, final String description, final Set offices) { if (StringUtils.isNotBlank(name)) { this.name = name.trim(); } @@ -77,13 +79,13 @@ public class Holiday extends AbstractPersistable { if (toDate != null) { this.toDate = toDate.toDate(); } - + if (repaymentsRescheduledTo != null) { this.repaymentsRescheduledTo = repaymentsRescheduledTo.toDate(); } this.processed = processed; - + if (StringUtils.isNotBlank(name)) { this.description = description.trim(); } else { @@ -94,7 +96,7 @@ public class Holiday extends AbstractPersistable { this.offices = offices; } } - + protected Holiday() {} public LocalDate getRepaymentsRescheduledToLocalDate() { @@ -112,7 +114,7 @@ public class Holiday extends AbstractPersistable { public Set getOffices() { return this.offices; } - + public LocalDate getFromDateLocalDate() { LocalDate fromDate = null; if (this.fromDate != null) { @@ -120,16 +122,16 @@ public class Holiday extends AbstractPersistable { } return fromDate; } - + public LocalDate getToDateLocalDate() { LocalDate toDate = null; if (this.toDate != null) { toDate = new LocalDate(this.toDate); } return toDate; - } + } - public void processed(){ + public void processed() { this.processed = true; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/domain/HolidayRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/domain/HolidayRepository.java index 11a0b84c7..cc2500b2f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/domain/HolidayRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/domain/HolidayRepository.java @@ -13,12 +13,11 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface HolidayRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface HolidayRepository extends JpaRepository, JpaSpecificationExecutor { + @Query("select holiday from Holiday holiday, IN(holiday.offices) office where (holiday.fromDate >= :date OR :date <= holiday.toDate) and office.id = :officeId") List findByOfficeIdAndGreaterThanDate(@Param("officeId") Long officeId, @Param("date") Date date); - + @Query("from Holiday holiday where holiday.processed = false") List findUnprocessed(); } - diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/exception/HolidayDateException.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/exception/HolidayDateException.java index d5e577b80..6826eb9ed 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/exception/HolidayDateException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/exception/HolidayDateException.java @@ -9,8 +9,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul public class HolidayDateException extends AbstractPlatformDomainRuleException { - public HolidayDateException(String postFix, String defaultUserMessage, - Object... defaultUserMessageArgs) { + public HolidayDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.holiday." + postFix, defaultUserMessage, defaultUserMessageArgs); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/handler/CreateHolidayCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/handler/CreateHolidayCommandHandler.java index bbbc93e5f..4072d654d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/handler/CreateHolidayCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/handler/CreateHolidayCommandHandler.java @@ -11,14 +11,14 @@ import org.springframework.transaction.annotation.Transactional; @Service public class CreateHolidayCommandHandler implements NewCommandSourceHandler { - private final HolidayWritePlatformService holidayWritePlatformService; - - @Autowired + private final HolidayWritePlatformService holidayWritePlatformService; + + @Autowired public CreateHolidayCommandHandler(final HolidayWritePlatformService holidayWritePlatformService) { this.holidayWritePlatformService = holidayWritePlatformService; } - - @Transactional + + @Transactional @Override public CommandProcessingResult processCommand(final JsonCommand command) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayReadPlatformService.java index 9fa4fa7d1..f71b3f0a3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayReadPlatformService.java @@ -5,7 +5,6 @@ import java.util.Date; import org.mifosplatform.organisation.holiday.data.HolidayData; - public interface HolidayReadPlatformService { Collection retrieveAllHolidaysBySearchParamerters(final Long officeId, Date fromDate, Date toDate); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayReadPlatformServiceImpl.java index 0713521fb..ea1f89b05 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayReadPlatformServiceImpl.java @@ -23,13 +23,13 @@ public class HolidayReadPlatformServiceImpl implements HolidayReadPlatformServic private final PlatformSecurityContext context; private final JdbcTemplate jdbcTemplate; - + @Autowired public HolidayReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); } - + private static final class HolidayMapper implements RowMapper { private final String schema; @@ -39,28 +39,28 @@ public class HolidayReadPlatformServiceImpl implements HolidayReadPlatformServic sqlBuilder.append("h.id as id, h.name as name, h.from_date as fromDate, h.to_date as toDate, "); sqlBuilder.append("h.repayments_rescheduled_to as repaymentsScheduleTO "); sqlBuilder.append("from m_holiday h join m_holiday_office hf on h.id = hf.holiday_id and "); - schema = sqlBuilder.toString(); + this.schema = sqlBuilder.toString(); } - + public String schema() { return this.schema; } - + @Override - public HolidayData mapRow(ResultSet rs, @SuppressWarnings("unused") int rowNum) throws SQLException { + public HolidayData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { final Long id = rs.getLong("id"); final String name = rs.getString("name"); final LocalDate fromDate = JdbcSupport.getLocalDate(rs, "fromDate"); final LocalDate toDate = JdbcSupport.getLocalDate(rs, "toDate"); final LocalDate repaymentsScheduleTO = JdbcSupport.getLocalDate(rs, "repaymentsScheduleTO"); - + return new HolidayData(id, name, fromDate, toDate, repaymentsScheduleTO); } - + } - + @Override - public Collection retrieveAllHolidaysBySearchParamerters(Long officeId, Date fromDate, Date toDate) { + public Collection retrieveAllHolidaysBySearchParamerters(final Long officeId, final Date fromDate, final Date toDate) { this.context.authenticatedUser(); final DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); @@ -68,7 +68,7 @@ public class HolidayReadPlatformServiceImpl implements HolidayReadPlatformServic final Object[] objectArray = new Object[3]; int arrayPos = 0; - HolidayMapper rm = new HolidayMapper(); + final HolidayMapper rm = new HolidayMapper(); String sql = "select " + rm.schema() + " hf.office_id = ? "; objectArray[arrayPos] = officeId; @@ -91,7 +91,7 @@ public class HolidayReadPlatformServiceImpl implements HolidayReadPlatformServic arrayPos = arrayPos + 1; } } - + final Object[] finalObjectArray = Arrays.copyOf(objectArray, arrayPos); return this.jdbcTemplate.query(sql, rm, finalObjectArray); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayUtil.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayUtil.java index df5526119..d597d267a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayUtil.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayUtil.java @@ -17,14 +17,13 @@ public class HolidayUtil { } return repaymentDate; } - - public static boolean isHoliday(final LocalDate date, final List holidays){ - for (Holiday holiday : holidays) { - if (date.isEqual(holiday.getFromDateLocalDate()) || date.isEqual(holiday.getToDateLocalDate()) || (date.isAfter(holiday.getFromDateLocalDate()) && date.isBefore(holiday.getToDateLocalDate()))) { - return true; - } + + public static boolean isHoliday(final LocalDate date, final List holidays) { + for (final Holiday holiday : holidays) { + if (date.isEqual(holiday.getFromDateLocalDate()) || date.isEqual(holiday.getToDateLocalDate()) + || (date.isAfter(holiday.getFromDateLocalDate()) && date.isBefore(holiday.getToDateLocalDate()))) { return true; } } - + return false; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayWritePlatformService.java index 8becdc951..593cf6523 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayWritePlatformService.java @@ -5,5 +5,5 @@ import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; public interface HolidayWritePlatformService { - CommandProcessingResult createHoliday(JsonCommand command); + CommandProcessingResult createHoliday(JsonCommand command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayWritePlatformServiceJpaRepositoryImpl.java index 3d028aa4b..68c8a8b05 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/holiday/service/HolidayWritePlatformServiceJpaRepositoryImpl.java @@ -39,7 +39,7 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit private final HolidayDataValidator fromApiJsonDeserializer; private final HolidayRepository holidayRepository; private final WorkingDaysRepositoryWrapper daysRepositoryWrapper; - + private final PlatformSecurityContext context; private final OfficeRepository officeRepository; private final FromJsonHelper fromApiJsonHelper; @@ -65,7 +65,7 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit this.fromApiJsonDeserializer.validateForCreate(command.json()); validateInputDates(command); - + final Set offices = getSelectedOffices(command); final Holiday holiday = Holiday.createNew(offices, command); @@ -115,12 +115,12 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit final LocalDate toDate = command.localDateValueOfParameterNamed(HolidayApiConstants.toDate); final LocalDate repaymentsRescheduledTo = command.localDateValueOfParameterNamed(HolidayApiConstants.repaymentsRescheduledTo); String defaultUserMessage = ""; - + if (toDate.isBefore(fromDate)) { defaultUserMessage = "To Date date cannot be before the From Date."; throw new HolidayDateException("to.date.cannot.be.before.from.date", defaultUserMessage, fromDate.toString(), toDate.toString()); } - + if (repaymentsRescheduledTo.isEqual(fromDate) || repaymentsRescheduledTo.isEqual(toDate) || (repaymentsRescheduledTo.isAfter(fromDate) && repaymentsRescheduledTo.isBefore(toDate))) { @@ -129,24 +129,27 @@ public class HolidayWritePlatformServiceJpaRepositoryImpl implements HolidayWrit repaymentsRescheduledTo.toString()); } - WorkingDays workingDays = this.daysRepositoryWrapper.findOne(); - Boolean isRepaymentOnWorkingDay = WorkingDaysUtil.isWorkingDay(workingDays, repaymentsRescheduledTo); + final WorkingDays workingDays = this.daysRepositoryWrapper.findOne(); + final Boolean isRepaymentOnWorkingDay = WorkingDaysUtil.isWorkingDay(workingDays, repaymentsRescheduledTo); if (!isRepaymentOnWorkingDay) { defaultUserMessage = "Repayments rescheduled date should not fall on non working days"; throw new HolidayDateException("repayments.rescheduled.date.should.not.fall.on.non.working.day", defaultUserMessage, repaymentsRescheduledTo.toString()); } - - //validate repaymentsRescheduledTo date - //1. should be within a 7 days date range. - //2. Alternative date should not be an exist holiday.//TBD - //3. Holiday should not be on an repaymentsRescheduledTo date of another holiday.//TBD - - //restricting repaymentsRescheduledTo date to be within 7 days range before or after from date and to date. - if(repaymentsRescheduledTo.isBefore(fromDate.minusDays(7)) || repaymentsRescheduledTo.isAfter(toDate.plusDays(7))){ + + // validate repaymentsRescheduledTo date + // 1. should be within a 7 days date range. + // 2. Alternative date should not be an exist holiday.//TBD + // 3. Holiday should not be on an repaymentsRescheduledTo date of + // another holiday.//TBD + + // restricting repaymentsRescheduledTo date to be within 7 days range + // before or after from date and to date. + if (repaymentsRescheduledTo.isBefore(fromDate.minusDays(7)) || repaymentsRescheduledTo.isAfter(toDate.plusDays(7))) { defaultUserMessage = "Repayments Rescheduled to date must be within 7 days before or after from and to dates"; - throw new HolidayDateException("repayments.rescheduled.to.must.be.within.range", defaultUserMessage, fromDate.toString(), toDate.toString(), repaymentsRescheduledTo.toString()); + throw new HolidayDateException("repayments.rescheduled.to.must.be.within.range", defaultUserMessage, fromDate.toString(), + toDate.toString(), repaymentsRescheduledTo.toString()); } } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/api/CurrenciesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/api/CurrenciesApiResource.java index 8d4360f39..1129033da 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/api/CurrenciesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/api/CurrenciesApiResource.java @@ -64,12 +64,12 @@ public class CurrenciesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveCurrencies(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final ApplicationCurrencyConfigurationData configurationData = this.readPlatformService.retrieveCurrencyConfiguration(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, configurationData, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, configurationData, this.RESPONSE_DATA_PARAMETERS); } @PUT diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/data/ApplicationCurrencyConfigurationData.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/data/ApplicationCurrencyConfigurationData.java index d3d833110..e0814874f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/data/ApplicationCurrencyConfigurationData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/data/ApplicationCurrencyConfigurationData.java @@ -17,7 +17,8 @@ public class ApplicationCurrencyConfigurationData { @SuppressWarnings("unused") private final Collection currencyOptions; - public ApplicationCurrencyConfigurationData(final Collection currencyOptions, final Collection selectedCurrencyOptions) { + public ApplicationCurrencyConfigurationData(final Collection currencyOptions, + final Collection selectedCurrencyOptions) { this.currencyOptions = currencyOptions; this.selectedCurrencyOptions = selectedCurrencyOptions; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/data/CurrencyData.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/data/CurrencyData.java index 52730b434..871fcac81 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/data/CurrencyData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/data/CurrencyData.java @@ -21,10 +21,11 @@ public class CurrencyData { private final String displayLabel; public static CurrencyData blank() { - return new CurrencyData("", "", 0,0, "", ""); + return new CurrencyData("", "", 0, 0, "", ""); } - public CurrencyData(final String code, final String name, final int decimalPlaces,final Integer inMultiplesOf, final String displaySymbol, final String nameCode) { + public CurrencyData(final String code, final String name, final int decimalPlaces, final Integer inMultiplesOf, + final String displaySymbol, final String nameCode) { this.code = code; this.name = name; this.decimalPlaces = decimalPlaces; @@ -41,14 +42,14 @@ public class CurrencyData { public int decimalPlaces() { return this.decimalPlaces; } - + public Integer currencyInMultiplesOf() { return this.inMultiplesOf; } - + @Override - public boolean equals(Object obj) { - CurrencyData currencyData = (CurrencyData) obj; + public boolean equals(final Object obj) { + final CurrencyData currencyData = (CurrencyData) obj; return currencyData.code.equals(this.code); } @@ -59,9 +60,9 @@ public class CurrencyData { private String generateDisplayLabel() { - StringBuilder builder = new StringBuilder(this.name).append(' '); + final StringBuilder builder = new StringBuilder(this.name).append(' '); - if (this.displaySymbol != null && !"".equalsIgnoreCase(displaySymbol.trim())) { + if (this.displaySymbol != null && !"".equalsIgnoreCase(this.displaySymbol.trim())) { builder.append('(').append(this.displaySymbol).append(')'); } else { builder.append('[').append(this.code).append(']'); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/ApplicationCurrency.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/ApplicationCurrency.java index e7441e151..028e9f887 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/ApplicationCurrency.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/ApplicationCurrency.java @@ -76,11 +76,11 @@ public class ApplicationCurrency extends AbstractPersistable { } public String getNameCode() { - return nameCode; + return this.nameCode; } public String getDisplaySymbol() { - return displaySymbol; + return this.displaySymbol; } public CurrencyData toData() { @@ -92,6 +92,6 @@ public class ApplicationCurrency extends AbstractPersistable { } public OrganisationCurrency toOrganisationCurrency() { - return new OrganisationCurrency(this.code, this.name, this.decimalPlaces,this.inMultiplesOf, this.nameCode, this.displaySymbol); + return new OrganisationCurrency(this.code, this.name, this.decimalPlaces, this.inMultiplesOf, this.nameCode, this.displaySymbol); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/ApplicationCurrencyRepositoryWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/ApplicationCurrencyRepositoryWrapper.java index 009cf6ee9..4b7eedbaf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/ApplicationCurrencyRepositoryWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/ApplicationCurrencyRepositoryWrapper.java @@ -38,7 +38,7 @@ public class ApplicationCurrencyRepositoryWrapper { if (defaultApplicationCurrency == null) { throw new CurrencyNotFoundException(currency.getCode()); } final ApplicationCurrency applicationCurrency = ApplicationCurrency.from(defaultApplicationCurrency, - currency.getDigitsAfterDecimal(),currency.getCurrencyInMultiplesOf()); + currency.getDigitsAfterDecimal(), currency.getCurrencyInMultiplesOf()); return applicationCurrency; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/MonetaryCurrency.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/MonetaryCurrency.java index a34e45b46..eba559b31 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/MonetaryCurrency.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/MonetaryCurrency.java @@ -26,25 +26,25 @@ public class MonetaryCurrency { this.inMultiplesOf = 0; } - public MonetaryCurrency(final String code, final int digitsAfterDecimal,final Integer inMultiplesOf) { + public MonetaryCurrency(final String code, final int digitsAfterDecimal, final Integer inMultiplesOf) { this.code = code; this.digitsAfterDecimal = digitsAfterDecimal; this.inMultiplesOf = inMultiplesOf; } public MonetaryCurrency copy() { - return new MonetaryCurrency(this.code, this.digitsAfterDecimal,this.inMultiplesOf); + return new MonetaryCurrency(this.code, this.digitsAfterDecimal, this.inMultiplesOf); } public String getCode() { - return code; + return this.code; } public int getDigitsAfterDecimal() { - return digitsAfterDecimal; + return this.digitsAfterDecimal; } - + public Integer getCurrencyInMultiplesOf() { - return inMultiplesOf; + return this.inMultiplesOf; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/Money.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/Money.java index 7bf69e277..14d0147f0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/Money.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/domain/Money.java @@ -37,7 +37,7 @@ public class Money implements Comparable { } public static Money total(final Iterable monies) { - Iterator it = monies.iterator(); + final Iterator it = monies.iterator(); if (it.hasNext() == false) { throw new IllegalArgumentException("Money iterator must not be empty"); } Money total = it.next(); while (it.hasNext()) { @@ -72,13 +72,13 @@ public class Money implements Comparable { final BigDecimal amountScaled = amountStripped.setScale(this.currencyDigitsAfterDecimal, RoundingMode.HALF_EVEN); // round monetary amounts into multiplesof say 20/50. - if (inMultiplesOf!= null && this.currencyDigitsAfterDecimal == 0 && inMultiplesOf>0 && amountScaled.doubleValue()>0) { - double existingVal = amountScaled.doubleValue(); - double ceilingOfValue = ceiling(existingVal, inMultiplesOf); - double floorOfValue = floor(existingVal, inMultiplesOf); + if (inMultiplesOf != null && this.currencyDigitsAfterDecimal == 0 && inMultiplesOf > 0 && amountScaled.doubleValue() > 0) { + final double existingVal = amountScaled.doubleValue(); + final double ceilingOfValue = ceiling(existingVal, inMultiplesOf); + final double floorOfValue = floor(existingVal, inMultiplesOf); - double floorDiff = existingVal - floorOfValue; - double ceilDiff = ceilingOfValue - existingVal; + final double floorDiff = existingVal - floorOfValue; + final double ceilDiff = ceilingOfValue - existingVal; if (ceilDiff > floorDiff) { this.amount = BigDecimal.valueOf(floorOfValue); @@ -128,15 +128,15 @@ public class Money implements Comparable { public Money plus(final Iterable moniesToAdd) { BigDecimal total = this.amount; - for (Money moneyProvider : moniesToAdd) { - Money money = this.checkCurrencyEqual(moneyProvider); + for (final Money moneyProvider : moniesToAdd) { + final Money money = checkCurrencyEqual(moneyProvider); total = total.add(money.amount); } return Money.of(monetaryCurrency(), total); } public Money plus(final Money moneyToAdd) { - Money toAdd = this.checkCurrencyEqual(moneyToAdd); + final Money toAdd = checkCurrencyEqual(moneyToAdd); return this.plus(toAdd.getAmount()); } @@ -148,12 +148,12 @@ public class Money implements Comparable { public Money plus(final double amountToAdd) { if (amountToAdd == 0) { return this; } - BigDecimal newAmount = this.amount.add(BigDecimal.valueOf(amountToAdd)); + final BigDecimal newAmount = this.amount.add(BigDecimal.valueOf(amountToAdd)); return Money.of(monetaryCurrency(), newAmount); } public Money minus(final Money moneyToSubtract) { - Money toSubtract = this.checkCurrencyEqual(moneyToSubtract); + final Money toSubtract = checkCurrencyEqual(moneyToSubtract); return this.minus(toSubtract.getAmount()); } @@ -164,7 +164,7 @@ public class Money implements Comparable { } private Money checkCurrencyEqual(final Money money) { - if (this.isSameCurrency(money) == false) { throw new UnsupportedOperationException("currencies are different."); } + if (isSameCurrency(money) == false) { throw new UnsupportedOperationException("currencies are different."); } return money; } @@ -174,37 +174,37 @@ public class Money implements Comparable { public Money dividedBy(final BigDecimal valueToDivideBy, final RoundingMode roundingMode) { if (valueToDivideBy.compareTo(BigDecimal.ONE) == 0) { return this; } - BigDecimal newAmount = this.amount.divide(valueToDivideBy, roundingMode); + final BigDecimal newAmount = this.amount.divide(valueToDivideBy, roundingMode); return Money.of(monetaryCurrency(), newAmount); } public Money dividedBy(final double valueToDivideBy, final RoundingMode roundingMode) { if (valueToDivideBy == 1) { return this; } - BigDecimal newAmount = this.amount.divide(BigDecimal.valueOf(valueToDivideBy), roundingMode); + final BigDecimal newAmount = this.amount.divide(BigDecimal.valueOf(valueToDivideBy), roundingMode); return Money.of(monetaryCurrency(), newAmount); } public Money dividedBy(final long valueToDivideBy, final RoundingMode roundingMode) { if (valueToDivideBy == 1) { return this; } - BigDecimal newAmount = this.amount.divide(BigDecimal.valueOf(valueToDivideBy), roundingMode); + final BigDecimal newAmount = this.amount.divide(BigDecimal.valueOf(valueToDivideBy), roundingMode); return Money.of(monetaryCurrency(), newAmount); } public Money multipliedBy(final BigDecimal valueToMultiplyBy) { if (valueToMultiplyBy.compareTo(BigDecimal.ONE) == 0) { return this; } - BigDecimal newAmount = this.amount.multiply(valueToMultiplyBy); + final BigDecimal newAmount = this.amount.multiply(valueToMultiplyBy); return Money.of(monetaryCurrency(), newAmount); } public Money multipliedBy(final double valueToMultiplyBy) { if (valueToMultiplyBy == 1) { return this; } - BigDecimal newAmount = this.amount.multiply(BigDecimal.valueOf(valueToMultiplyBy)); + final BigDecimal newAmount = this.amount.multiply(BigDecimal.valueOf(valueToMultiplyBy)); return Money.of(monetaryCurrency(), newAmount); } public Money multipliedBy(final long valueToMultiplyBy) { if (valueToMultiplyBy == 1) { return this; } - BigDecimal newAmount = this.amount.multiply(BigDecimal.valueOf(valueToMultiplyBy)); + final BigDecimal newAmount = this.amount.multiply(BigDecimal.valueOf(valueToMultiplyBy)); return Money.of(monetaryCurrency(), newAmount); } @@ -221,18 +221,18 @@ public class Money implements Comparable { @Override public int compareTo(final Money other) { - Money otherMoney = other; + final Money otherMoney = other; if (this.currencyCode.equals(otherMoney.currencyCode) == false) { throw new UnsupportedOperationException( "currencies arent different"); } return this.amount.compareTo(otherMoney.amount); } public boolean isZero() { - return this.isEqualTo(Money.zero(this.getCurrency())); + return isEqualTo(Money.zero(getCurrency())); } public boolean isEqualTo(final Money other) { - return this.compareTo(other) == 0; + return compareTo(other) == 0; } public boolean isNotEqualTo(final Money other) { @@ -240,23 +240,23 @@ public class Money implements Comparable { } public boolean isGreaterThanOrEqualTo(final Money other) { - return this.isGreaterThan(other) || this.isEqualTo(other); + return isGreaterThan(other) || isEqualTo(other); } public boolean isGreaterThan(final Money other) { - return this.compareTo(other) > 0; + return compareTo(other) > 0; } public boolean isGreaterThanZero() { - return this.isGreaterThan(Money.zero(this.getCurrency())); + return isGreaterThan(Money.zero(getCurrency())); } public boolean isLessThan(final Money other) { - return this.compareTo(other) < 0; + return compareTo(other) < 0; } public boolean isLessThanZero() { - return this.isLessThan(Money.zero(this.getCurrency())); + return isLessThan(Money.zero(getCurrency())); } public String getCurrencyCode() { @@ -293,12 +293,12 @@ public class Money implements Comparable { } public Money negated() { - if (this.isZero()) { return this; } + if (isZero()) { return this; } return Money.of(monetaryCurrency(), this.amount.negate()); } public Money abs() { - return this.isLessThanZero() ? this.negated() : this; + return isLessThanZero() ? negated() : this; } public MonetaryCurrency getCurrency() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/exception/CurrencyNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/exception/CurrencyNotFoundException.java index 689051b94..40c71d9b5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/exception/CurrencyNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/exception/CurrencyNotFoundException.java @@ -12,7 +12,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN */ public class CurrencyNotFoundException extends AbstractPlatformResourceNotFoundException { - public CurrencyNotFoundException(final String currencyCode) { - super("error.msg.currency.currencyCode.invalid", "Currency with identifier " + currencyCode + " does not exist", currencyCode); - } + public CurrencyNotFoundException(final String currencyCode) { + super("error.msg.currency.currencyCode.invalid", "Currency with identifier " + currencyCode + " does not exist", currencyCode); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/serialization/CurrencyCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/serialization/CurrencyCommandFromApiJsonDeserializer.java index 14255b736..89a4475d2 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/serialization/CurrencyCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/serialization/CurrencyCommandFromApiJsonDeserializer.java @@ -45,13 +45,13 @@ public final class CurrencyCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("currencies"); - final JsonElement element = fromApiJsonHelper.parse(json); - final String[] currencies = fromApiJsonHelper.extractArrayNamed("currencies", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final String[] currencies = this.fromApiJsonHelper.extractArrayNamed("currencies", element); baseDataValidator.reset().parameter("currencies").value(currencies).arrayNotEmpty(); throwExceptionIfValidationWarningsExist(dataValidationErrors); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/service/CurrencyReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/service/CurrencyReadPlatformServiceImpl.java index b594d8358..3a7ca3aaf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/service/CurrencyReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/service/CurrencyReadPlatformServiceImpl.java @@ -35,19 +35,19 @@ public class CurrencyReadPlatformServiceImpl implements CurrencyReadPlatformServ @Override public Collection retrieveAllowedCurrencies() { - context.authenticatedUser(); + this.context.authenticatedUser(); - final String sql = "select " + currencyRowMapper.schema() + " from m_organisation_currency c order by c.name"; + final String sql = "select " + this.currencyRowMapper.schema() + " from m_organisation_currency c order by c.name"; - return this.jdbcTemplate.query(sql, currencyRowMapper, new Object[] {}); + return this.jdbcTemplate.query(sql, this.currencyRowMapper, new Object[] {}); } @Override public Collection retrieveAllPlatformCurrencies() { - final String sql = "select " + currencyRowMapper.schema() + " from m_currency c order by c.name"; + final String sql = "select " + this.currencyRowMapper.schema() + " from m_currency c order by c.name"; - return this.jdbcTemplate.query(sql, currencyRowMapper, new Object[] {}); + return this.jdbcTemplate.query(sql, this.currencyRowMapper, new Object[] {}); } private static final class CurrencyMapper implements RowMapper { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java index 3360609cf..71a5e0ce4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/monetary/service/CurrencyWritePlatformServiceJpaRepositoryImpl.java @@ -48,7 +48,7 @@ public class CurrencyWritePlatformServiceJpaRepositoryImpl implements CurrencyWr @Override public CommandProcessingResult updateAllowedCurrencies(final JsonCommand command) { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/api/OfficeTransactionsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/api/OfficeTransactionsApiResource.java index 7bfffb2e6..fb5032fa5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/api/OfficeTransactionsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/api/OfficeTransactionsApiResource.java @@ -41,8 +41,8 @@ import org.springframework.stereotype.Component; public class OfficeTransactionsApiResource { private static final Set RESPONSE_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "transactionDate", "fromOfficeId", - "fromOfficeName", "toOfficeId", "toOfficeIdName", "currencyCode", "digitsAfterDecimal","inMultiplesOf", "transactionAmount", "description", - "allowedOffices", "currencyOptions")); + "fromOfficeName", "toOfficeId", "toOfficeIdName", "currencyCode", "digitsAfterDecimal", "inMultiplesOf", "transactionAmount", + "description", "allowedOffices", "currencyOptions")); private final String resourceNameForReadPermissions = "OFFICE"; @@ -69,11 +69,11 @@ public class OfficeTransactionsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveOfficeTransactions(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForReadPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForReadPermissions); final Collection officeTransactions = this.readPlatformService.retrieveAllOfficeTransactions(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, officeTransactions, RESPONSE_DATA_PARAMETERS); } @@ -83,11 +83,11 @@ public class OfficeTransactionsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String newOfficeTransactionDetails(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForReadPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForReadPermissions); final OfficeTransactionData officeTransactionData = this.readPlatformService.retrieveNewOfficeTransactionDetails(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, officeTransactionData, RESPONSE_DATA_PARAMETERS); } @@ -102,7 +102,7 @@ public class OfficeTransactionsApiResource { return this.toApiJsonSerializer.serialize(result); } - + @DELETE @Path("{transactionId}") @Consumes({ MediaType.APPLICATION_JSON }) diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/data/OfficeTransactionData.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/data/OfficeTransactionData.java index bc5e26534..8dead5d99 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/data/OfficeTransactionData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/data/OfficeTransactionData.java @@ -29,7 +29,7 @@ public class OfficeTransactionData { @SuppressWarnings("unused") private final String toOfficeName; @SuppressWarnings("unused") - private CurrencyData currency; + private final CurrencyData currency; @SuppressWarnings("unused") private final BigDecimal transactionAmount; @SuppressWarnings("unused") diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/Office.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/Office.java index 5994bedb2..208d59988 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/Office.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/Office.java @@ -161,7 +161,7 @@ public class Office extends AbstractPersistable { if (this.parent == null) { throw new RootOfficeParentCannotBeUpdated(); } - if (this.identifiedBy(newParent.getId())) { throw new CannotUpdateOfficeWithParentOfficeSameAsSelf(this.getId(), newParent.getId()); } + if (identifiedBy(newParent.getId())) { throw new CannotUpdateOfficeWithParentOfficeSameAsSelf(getId(), newParent.getId()); } this.parent = newParent; generateHierarchy(); @@ -173,8 +173,8 @@ public class Office extends AbstractPersistable { public void generateHierarchy() { - if (parent != null) { - this.hierarchy = this.parent.hierarchyOf(this.getId()); + if (this.parent != null) { + this.hierarchy = this.parent.hierarchyOf(getId()); } else { this.hierarchy = "."; } @@ -189,7 +189,7 @@ public class Office extends AbstractPersistable { } public String getHierarchy() { - return hierarchy; + return this.hierarchy; } public boolean hasParentOf(final Office office) { @@ -201,7 +201,7 @@ public class Office extends AbstractPersistable { } public boolean doesNotHaveAnOfficeInHierarchyWithId(final Long officeId) { - return !this.hasAnOfficeInHierarchyWithId(officeId); + return !hasAnOfficeInHierarchyWithId(officeId); } private boolean hasAnOfficeInHierarchyWithId(final Long officeId) { @@ -213,8 +213,8 @@ public class Office extends AbstractPersistable { } if (!match) { - for (Office child : this.children) { - boolean result = child.hasAnOfficeInHierarchyWithId(officeId); + for (final Office child : this.children) { + final boolean result = child.hasAnOfficeInHierarchyWithId(officeId); if (result) { match = result; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/OfficeRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/OfficeRepository.java index 72d3ef93c..403c47dd3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/OfficeRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/OfficeRepository.java @@ -8,7 +8,6 @@ package org.mifosplatform.organisation.office.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface OfficeRepository extends JpaRepository, - JpaSpecificationExecutor { +public interface OfficeRepository extends JpaRepository, JpaSpecificationExecutor { // no added behaviour } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/OfficeTransactionRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/OfficeTransactionRepository.java index 672e69153..8b9848ed9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/OfficeTransactionRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/domain/OfficeTransactionRepository.java @@ -8,8 +8,6 @@ package org.mifosplatform.organisation.office.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface OfficeTransactionRepository extends - JpaRepository, - JpaSpecificationExecutor { - // no added behaviour +public interface OfficeTransactionRepository extends JpaRepository, JpaSpecificationExecutor { + // no added behaviour } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/exception/InvalidOfficeException.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/exception/InvalidOfficeException.java index e6646ff89..fa570a180 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/exception/InvalidOfficeException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/exception/InvalidOfficeException.java @@ -8,11 +8,13 @@ package org.mifosplatform.organisation.office.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown when office mismatch occurs + * {@link AbstractPlatformDomainRuleException} thrown when office mismatch + * occurs */ public class InvalidOfficeException extends AbstractPlatformDomainRuleException { - public InvalidOfficeException(final String entity, final String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg."+entity+"."+postFix+".invalid.office", defaultUserMessage, defaultUserMessageArgs); + public InvalidOfficeException(final String entity, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { + super("error.msg." + entity + "." + postFix + ".invalid.office", defaultUserMessage, defaultUserMessageArgs); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/exception/OfficeTransactionNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/exception/OfficeTransactionNotFoundException.java index d6406a3b7..47cff8710 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/exception/OfficeTransactionNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/exception/OfficeTransactionNotFoundException.java @@ -8,7 +8,8 @@ package org.mifosplatform.organisation.office.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when office transaction resources are not found. + * A {@link RuntimeException} thrown when office transaction resources are not + * found. */ public class OfficeTransactionNotFoundException extends AbstractPlatformResourceNotFoundException { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/serialization/OfficeCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/serialization/OfficeCommandFromApiJsonDeserializer.java index c5477f913..3de26be1a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/serialization/OfficeCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/serialization/OfficeCommandFromApiJsonDeserializer.java @@ -49,26 +49,26 @@ public final class OfficeCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("office"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); - final LocalDate openingDate = fromApiJsonHelper.extractLocalDateNamed("openingDate", element); + final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed("openingDate", element); baseDataValidator.reset().parameter("openingDate").value(openingDate).notNull(); - if (fromApiJsonHelper.parameterExists("externalId", element)) { - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); + if (this.fromApiJsonHelper.parameterExists("externalId", element)) { + final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element); baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("parentId", element)) { - final Long parentId = fromApiJsonHelper.extractLongNamed("parentId", element); + if (this.fromApiJsonHelper.parameterExists("parentId", element)) { + final Long parentId = this.fromApiJsonHelper.extractLongNamed("parentId", element); baseDataValidator.reset().parameter("parentId").value(parentId).notNull().integerGreaterThanZero(); } @@ -84,30 +84,30 @@ public final class OfficeCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("office"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - if (fromApiJsonHelper.parameterExists("name", element)) { - final String name = fromApiJsonHelper.extractStringNamed("name", element); + if (this.fromApiJsonHelper.parameterExists("name", element)) { + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("openingDate", element)) { - final LocalDate openingDate = fromApiJsonHelper.extractLocalDateNamed("openingDate", element); + if (this.fromApiJsonHelper.parameterExists("openingDate", element)) { + final LocalDate openingDate = this.fromApiJsonHelper.extractLocalDateNamed("openingDate", element); baseDataValidator.reset().parameter("openingDate").value(openingDate).notNull(); } - if (fromApiJsonHelper.parameterExists("externalId", element)) { - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); + if (this.fromApiJsonHelper.parameterExists("externalId", element)) { + final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element); baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("parentId", element)) { - final Long parentId = fromApiJsonHelper.extractLongNamed("parentId", element); + if (this.fromApiJsonHelper.parameterExists("parentId", element)) { + final Long parentId = this.fromApiJsonHelper.extractLongNamed("parentId", element); baseDataValidator.reset().parameter("parentId").value(parentId).notNull().integerGreaterThanZero(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/serialization/OfficeTransactionCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/serialization/OfficeTransactionCommandFromApiJsonDeserializer.java index d65865045..fbf2de335 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/serialization/OfficeTransactionCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/serialization/OfficeTransactionCommandFromApiJsonDeserializer.java @@ -47,16 +47,16 @@ public final class OfficeTransactionCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("officeTransaction"); - final JsonElement element = fromApiJsonHelper.parse(json); - final Long fromOfficeId = fromApiJsonHelper.extractLongNamed("fromOfficeId", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final Long fromOfficeId = this.fromApiJsonHelper.extractLongNamed("fromOfficeId", element); baseDataValidator.reset().parameter("fromOfficeId").value(fromOfficeId).ignoreIfNull().integerGreaterThanZero(); - final Long toOfficeId = fromApiJsonHelper.extractLongNamed("toOfficeId", element); + final Long toOfficeId = this.fromApiJsonHelper.extractLongNamed("toOfficeId", element); baseDataValidator.reset().parameter("toOfficeId").value(toOfficeId).ignoreIfNull().integerGreaterThanZero(); if (fromOfficeId == null && toOfficeId == null) { @@ -67,16 +67,16 @@ public final class OfficeTransactionCommandFromApiJsonDeserializer { baseDataValidator.reset().parameter("fromOfficeId").value(fromOfficeId).notSameAsParameter("toOfficeId", toOfficeId); } - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); baseDataValidator.reset().parameter("transactionDate").value(transactionDate).notNull(); - final String currencyCode = fromApiJsonHelper.extractStringNamed("currencyCode", element); + final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element); baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3); - final BigDecimal transactionAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("transactionAmount", element); + final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("transactionAmount", element); baseDataValidator.reset().parameter("transactionAmount").value(transactionAmount).notNull().positiveAmount(); - final String description = fromApiJsonHelper.extractStringNamed("description", element); + final String description = this.fromApiJsonHelper.extractStringNamed("description", element); baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(100); throwExceptionIfValidationWarningsExist(dataValidationErrors); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/service/OfficeReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/service/OfficeReadPlatformServiceImpl.java index cf32cd041..ef6864819 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/service/OfficeReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/service/OfficeReadPlatformServiceImpl.java @@ -137,7 +137,7 @@ public class OfficeReadPlatformServiceImpl implements OfficeReadPlatformService /** TODO: Vishwas This change breaks caching, need to have a relook **/ @Override @Cacheable(value = "offices", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy()+'of')") - public Collection retrieveAllOffices(boolean includeAllOffices) { + public Collection retrieveAllOffices(final boolean includeAllOffices) { final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); String hierarchySearchString = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java index 9de32df83..75d0e9e01 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/office/service/OfficeWritePlatformServiceJpaRepositoryImpl.java @@ -68,7 +68,7 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP public CommandProcessingResult createOffice(final JsonCommand command) { try { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); @@ -92,7 +92,7 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP .withEntityId(office.getId()) // .withOfficeId(office.getId()) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleOfficeDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -103,11 +103,11 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP @Caching(evict = { @CacheEvict(value = "offices", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy()+'of')"), @CacheEvict(value = "officesForDropdown", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy()+'ofd')"), - @CacheEvict(value = "officesById", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#officeId)")}) + @CacheEvict(value = "officesById", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#officeId)") }) public CommandProcessingResult updateOffice(final Long officeId, final JsonCommand command) { try { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); @@ -135,7 +135,7 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP .withOfficeId(office.getId()) // .with(changes) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleOfficeDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -145,7 +145,7 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP @Override public CommandProcessingResult officeTransaction(final JsonCommand command) { - context.authenticatedUser(); + this.context.authenticatedUser(); this.moneyTransferCommandFromApiJsonDeserializer.validateOfficeTransfer(command.json()); @@ -168,7 +168,8 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP final String currencyCode = command.stringValueOfParameterNamed("currencyCode"); final ApplicationCurrency appCurrency = this.applicationCurrencyRepository.findOneWithNotFoundDetection(currencyCode); - final MonetaryCurrency currency = new MonetaryCurrency(appCurrency.getCode(), appCurrency.getDecimalPlaces(),appCurrency.getCurrencyInMultiplesOf()); + final MonetaryCurrency currency = new MonetaryCurrency(appCurrency.getCode(), appCurrency.getDecimalPlaces(), + appCurrency.getCurrencyInMultiplesOf()); final Money amount = Money.of(currency, command.bigDecimalValueOfParameterNamed("transactionAmount")); final OfficeTransaction entity = OfficeTransaction.fromJson(fromOffice, toOffice, amount, command); @@ -186,7 +187,7 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP @Override public CommandProcessingResult deleteOfficeTransaction(final Long transactionId, final JsonCommand command) { - context.authenticatedUser(); + this.context.authenticatedUser(); this.officeTransactionRepository.delete(transactionId); @@ -202,7 +203,7 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP */ private void handleOfficeDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("externalid_org")) { final String externalId = command.stringValueOfParameterNamed("externalId"); throw new PlatformDataIntegrityException("error.msg.office.duplicate.externalId", "Office with externalId `" + externalId diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/api/StaffApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/api/StaffApiResource.java index 61e40044f..b28cc638b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/api/StaffApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/api/StaffApiResource.java @@ -80,7 +80,7 @@ public class StaffApiResource { @QueryParam("officeId") final Long officeId, @DefaultValue("false") @QueryParam("staffInOfficeHierarchy") final boolean staffInOfficeHierarchy) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Collection staff; if (staffInOfficeHierarchy) { @@ -90,8 +90,8 @@ public class StaffApiResource { staff = this.readPlatformService.retrieveAllStaff(sqlSearch, officeId); } - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, staff, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, staff, this.RESPONSE_DATA_PARAMETERS); } @POST @@ -112,17 +112,17 @@ public class StaffApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retreiveStaff(@PathParam("staffId") final Long staffId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); StaffData staff = this.readPlatformService.retrieveStaff(staffId); if (settings.isTemplate()) { - final Collection allowedOffices = officeReadPlatformService.retrieveAllOfficesForDropdown(); + final Collection allowedOffices = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); staff = StaffData.templateData(staff, allowedOffices); } - return this.toApiJsonSerializer.serialize(settings, staff, RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, staff, this.RESPONSE_DATA_PARAMETERS); } @PUT diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/data/StaffAccountSummaryCollectionData.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/data/StaffAccountSummaryCollectionData.java index 0fd820705..28f673a36 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/data/StaffAccountSummaryCollectionData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/data/StaffAccountSummaryCollectionData.java @@ -32,24 +32,24 @@ public class StaffAccountSummaryCollectionData { private Collection loans; - public LoanAccountSummary(Long id, String displayName) { + public LoanAccountSummary(final Long id, final String displayName) { this.id = id; this.displayName = displayName; } public Long getId() { - return id; + return this.id; } public String getDisplayName() { - return displayName; + return this.displayName; } public Collection getLoans() { - return loans; + return this.loans; } - public void setLoans(Collection loans) { + public void setLoans(final Collection loans) { this.loans = loans; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/Staff.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/Staff.java index d4c9d7b36..f8bf51002 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/Staff.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/Staff.java @@ -22,8 +22,8 @@ import org.mifosplatform.organisation.office.domain.Office; import org.springframework.data.jpa.domain.AbstractPersistable; @Entity -@Table(name = "m_staff", uniqueConstraints = { @UniqueConstraint(columnNames = { "display_name" }, name = "display_name") , -@UniqueConstraint(columnNames = { "external_id" }, name = "external_id_UNIQUE") }) +@Table(name = "m_staff", uniqueConstraints = { @UniqueConstraint(columnNames = { "display_name" }, name = "display_name"), + @UniqueConstraint(columnNames = { "external_id" }, name = "external_id_UNIQUE") }) public class Staff extends AbstractPersistable { @Column(name = "firstname", length = 50) @@ -61,7 +61,7 @@ public class Staff extends AbstractPersistable { final String lastnameParamName = "lastname"; final String lastname = command.stringValueOfParameterNamed(lastnameParamName); - + final String externalIdParamName = "externalId"; final String externalId = command.stringValueOfParameterNamedAllowingNull(externalIdParamName); @@ -71,7 +71,8 @@ public class Staff extends AbstractPersistable { return new Staff(staffOffice, firstname, lastname, externalId, isLoanOfficer); } - public static Staff createNew(final Office staffOffice, final String firstname, final String lastname, final String externalId, final boolean isLoanOfficer) { + public static Staff createNew(final Office staffOffice, final String firstname, final String lastname, final String externalId, + final boolean isLoanOfficer) { return new Staff(staffOffice, firstname, lastname, externalId, isLoanOfficer); } @@ -79,7 +80,8 @@ public class Staff extends AbstractPersistable { // } - private Staff(final Office staffOffice, final String firstname, final String lastname, final String externalId, final boolean isLoanOfficer) { + private Staff(final Office staffOffice, final String firstname, final String lastname, final String externalId, + final boolean isLoanOfficer) { this.office = staffOffice; this.firstname = StringUtils.defaultIfEmpty(firstname, null); this.lastname = StringUtils.defaultIfEmpty(lastname, null); @@ -138,7 +140,7 @@ public class Staff extends AbstractPersistable { actualChanges.put(externalIdParamName, newValue); this.externalId = newValue; } - + final String isLoanOfficerParamName = "isLoanOfficer"; if (command.isChangeInBooleanParameterNamed(isLoanOfficerParamName, this.loanOfficer)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(isLoanOfficerParamName); @@ -176,7 +178,7 @@ public class Staff extends AbstractPersistable { public String displayName() { return this.displayName; } - + public Office office() { return this.office; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffOrganisationalRoleType.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffOrganisationalRoleType.java index 14382496c..bbe6855a1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffOrganisationalRoleType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffOrganisationalRoleType.java @@ -22,11 +22,11 @@ public enum StaffOrganisationalRoleType { } public Integer getValue() { - return value; + return this.value; } public String getCode() { - return code; + return this.code; } public static StaffOrganisationalRoleType fromInt(final Integer chargeCalculation) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffRepository.java index 39fbbc5b6..6fdea9b4b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffRepository.java @@ -10,9 +10,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -public interface StaffRepository extends JpaRepository, - JpaSpecificationExecutor { - +public interface StaffRepository extends JpaRepository, JpaSpecificationExecutor { + public final static String FIND_BY_OFFICE_QUERY = "select s from Staff s where s.id = :id AND s.office.id = :officeId"; /** @@ -20,5 +19,5 @@ public interface StaffRepository extends JpaRepository, */ @Query(FIND_BY_OFFICE_QUERY) public Staff findByOffice(@Param("id") Long id, @Param("officeId") Long officeId); - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffRepositoryWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffRepositoryWrapper.java index acc3ff8f1..168522eff 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffRepositoryWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/domain/StaffRepositoryWrapper.java @@ -36,14 +36,12 @@ public class StaffRepositoryWrapper { if (staff == null) { throw new StaffNotFoundException(staffId); } return staff; } - + public Staff findByOfficeHierarchyWithNotFoundDetection(final Long staffId, final String hierarchy) { final Staff staff = this.repository.findOne(staffId); if (staff == null) { throw new StaffNotFoundException(staffId); } final String staffhierarchy = staff.office().getHierarchy(); - if (!hierarchy.startsWith(staffhierarchy)) { - throw new StaffNotFoundException(staffId); - } + if (!hierarchy.startsWith(staffhierarchy)) { throw new StaffNotFoundException(staffId); } return staff; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/exception/StaffNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/exception/StaffNotFoundException.java index 8b98a6820..9bf476414 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/exception/StaffNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/exception/StaffNotFoundException.java @@ -10,11 +10,9 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN /** * A {@link RuntimeException} thrown when staff resources are not found. */ -public class StaffNotFoundException extends - AbstractPlatformResourceNotFoundException { +public class StaffNotFoundException extends AbstractPlatformResourceNotFoundException { - public StaffNotFoundException(final Long id) { - super("error.msg.staff.id.invalid", "Staff with identifier " + id - + " does not exist", id); - } + public StaffNotFoundException(final Long id) { + super("error.msg.staff.id.invalid", "Staff with identifier " + id + " does not exist", id); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/exception/StaffRoleException.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/exception/StaffRoleException.java index 19001566a..1ea7ddfa6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/exception/StaffRoleException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/exception/StaffRoleException.java @@ -10,19 +10,18 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN /** * A {@link RuntimeException} thrown when staff resources are not found. */ -public class StaffRoleException extends - AbstractPlatformResourceNotFoundException { +public class StaffRoleException extends AbstractPlatformResourceNotFoundException { - public static enum STAFF_ROLE { - LOAN_OFFICER, BRANCH_MANAGER; - @Override - public String toString() { - return name().toString().replaceAll("-", " ").toLowerCase(); - } - } + public static enum STAFF_ROLE { + LOAN_OFFICER, BRANCH_MANAGER; - public StaffRoleException(final Long id, STAFF_ROLE role) { - super("error.msg.staff.id.invalid.role", "Staff with identifier " + id - + " is not a " + role.toString(), id); - } + @Override + public String toString() { + return name().toString().replaceAll("-", " ").toLowerCase(); + } + } + + public StaffRoleException(final Long id, final STAFF_ROLE role) { + super("error.msg.staff.id.invalid.role", "Staff with identifier " + id + " is not a " + role.toString(), id); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/serialization/StaffCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/serialization/StaffCommandFromApiJsonDeserializer.java index c1562e58a..15837b578 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/serialization/StaffCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/serialization/StaffCommandFromApiJsonDeserializer.java @@ -31,7 +31,8 @@ public final class StaffCommandFromApiJsonDeserializer { /** * The parameters supported for this command. */ - private final Set supportedParameters = new HashSet(Arrays.asList("firstname", "lastname", "officeId", "externalId", "isLoanOfficer")); + private final Set supportedParameters = new HashSet(Arrays.asList("firstname", "lastname", "officeId", "externalId", + "isLoanOfficer")); private final FromJsonHelper fromApiJsonHelper; @@ -44,24 +45,24 @@ public final class StaffCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("staff"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final Long officeId = fromApiJsonHelper.extractLongNamed("officeId", element); + final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element); baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero(); - - final String firstname = fromApiJsonHelper.extractStringNamed("firstname", element); + + final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element); baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(50); - final String lastname = fromApiJsonHelper.extractStringNamed("lastname", element); + final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element); baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(50); - if (fromApiJsonHelper.parameterExists("isLoanOfficer", element)) { - final Boolean loanOfficerFlag = fromApiJsonHelper.extractBooleanNamed("isLoanOfficer", element); + if (this.fromApiJsonHelper.parameterExists("isLoanOfficer", element)) { + final Boolean loanOfficerFlag = this.fromApiJsonHelper.extractBooleanNamed("isLoanOfficer", element); baseDataValidator.reset().parameter("isLoanOfficer").value(loanOfficerFlag).notNull(); } @@ -72,29 +73,29 @@ public final class StaffCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("staff"); - - final JsonElement element = fromApiJsonHelper.parse(json); - if (fromApiJsonHelper.parameterExists("officeId", element)) { - final Long officeId = fromApiJsonHelper.extractLongNamed("officeId", element); + + final JsonElement element = this.fromApiJsonHelper.parse(json); + if (this.fromApiJsonHelper.parameterExists("officeId", element)) { + final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element); baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero(); } - - if (fromApiJsonHelper.parameterExists("firstname", element)) { - final String firstname = fromApiJsonHelper.extractStringNamed("firstname", element); + + if (this.fromApiJsonHelper.parameterExists("firstname", element)) { + final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element); baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(50); } - if (fromApiJsonHelper.parameterExists("lastname", element)) { - final String lastname = fromApiJsonHelper.extractStringNamed("lastname", element); + if (this.fromApiJsonHelper.parameterExists("lastname", element)) { + final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element); baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(50); } - if (fromApiJsonHelper.parameterExists("isLoanOfficer", element)) { - final Boolean loanOfficerFlag = fromApiJsonHelper.extractBooleanNamed("isLoanOfficer", element); + if (this.fromApiJsonHelper.parameterExists("isLoanOfficer", element)) { + final Boolean loanOfficerFlag = this.fromApiJsonHelper.extractBooleanNamed("isLoanOfficer", element); baseDataValidator.reset().parameter("isLoanOfficer").value(loanOfficerFlag).notNull(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/service/StaffReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/service/StaffReadPlatformServiceImpl.java index 3d7c8808a..9c41a9dca 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/service/StaffReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/service/StaffReadPlatformServiceImpl.java @@ -62,7 +62,7 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { public String schema(final boolean loanOfficersOnly) { - StringBuilder sqlBuilder = new StringBuilder(200); + final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("s.id as id, s.office_id as officeId, ohierarchy.name as officeName,"); sqlBuilder.append("s.firstname as firstname, s.lastname as lastname,"); sqlBuilder.append("s.display_name as displayName, s.is_loan_officer as isLoanOfficer, s.external_id as externalId "); @@ -149,13 +149,13 @@ public class StaffReadPlatformServiceImpl implements StaffReadPlatformService { public StaffData retrieveStaff(final Long staffId) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); final StaffMapper rm = new StaffMapper(); final String sql = "select " + rm.schema() + " where s.id = ?"; return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { staffId }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new StaffNotFoundException(staffId); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java index ad66f77c6..d46504561 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/staff/service/StaffWritePlatformServiceJpaRepositoryImpl.java @@ -52,7 +52,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla public CommandProcessingResult createStaff(final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); @@ -69,7 +69,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla .withCommandId(command.commandId()) // .withEntityId(staff.getId()).withOfficeId(officeId) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleStaffDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -80,7 +80,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla public CommandProcessingResult updateStaff(final Long staffId, final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); @@ -103,7 +103,7 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(staffId) .withOfficeId(staffForUpdate.officeId()).with(changesOnly).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleStaffDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -114,15 +114,14 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla * is. */ private void handleStaffDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("external_id")) { final String externalId = command.stringValueOfParameterNamed("externalId"); throw new PlatformDataIntegrityException("error.msg.staff.duplicate.externalId", "Staff with externalId `" + externalId + "` already exists", "externalId", externalId); - } - else if (realCause.getMessage().contains("display_name")) { + } else if (realCause.getMessage().contains("display_name")) { final String lastname = command.stringValueOfParameterNamed("lastname"); String displayName = lastname; if (!StringUtils.isBlank(displayName)) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/domain/RepaymentRescheduleType.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/domain/RepaymentRescheduleType.java index 2a992312c..7c4eea891 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/domain/RepaymentRescheduleType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/domain/RepaymentRescheduleType.java @@ -10,11 +10,10 @@ import java.util.Map; public enum RepaymentRescheduleType { - INVALID(0, "RepaymentRescheduleType.invalid"), - SAME_DAY(1, "RepaymentRescheduleType.same.day"), - MOVE_TO_NEXT_WORKING_DAY(2,"RepaymentRescheduleType.move.to.next.working.day"), - MOVE_TO_NEXT_REPAYMENT_MEETING_DAY(3,"RepaymentRescheduleType.move.to.next.repayment.meeting.day"), - MOVE_TO_PREVIOUS_WORKING_DAY(4,"RepaymentRescheduleType.move.to.previous.working.day"); + INVALID(0, "RepaymentRescheduleType.invalid"), SAME_DAY(1, "RepaymentRescheduleType.same.day"), MOVE_TO_NEXT_WORKING_DAY(2, + "RepaymentRescheduleType.move.to.next.working.day"), MOVE_TO_NEXT_REPAYMENT_MEETING_DAY(3, + "RepaymentRescheduleType.move.to.next.repayment.meeting.day"), MOVE_TO_PREVIOUS_WORKING_DAY(4, + "RepaymentRescheduleType.move.to.previous.working.day"); private final Integer value; private final String code; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/domain/WorkingDays.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/domain/WorkingDays.java index e7225f9df..664d1f79a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/domain/WorkingDays.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/domain/WorkingDays.java @@ -15,23 +15,22 @@ import org.springframework.data.jpa.domain.AbstractPersistable; @Entity @Table(name = "m_working_days") public class WorkingDays extends AbstractPersistable { - + @Column(name = "recurrence", length = 100, nullable = true) private String recurrence; - + @Column(name = "repayment_rescheduling_enum", nullable = false) private Integer repaymentReschedulingType; protected WorkingDays() { - + } - protected WorkingDays(String recurrence, Integer repaymentReschedulingType) { + protected WorkingDays(final String recurrence, final Integer repaymentReschedulingType) { this.recurrence = recurrence; this.repaymentReschedulingType = repaymentReschedulingType; } - /** * @return the recurrence */ @@ -39,12 +38,11 @@ public class WorkingDays extends AbstractPersistable { return this.recurrence; } - /** * @return the repaymentReschedulingType */ public Integer getRepaymentReschedulingType() { return this.repaymentReschedulingType; } - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/service/WorkingDaysUtil.java b/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/service/WorkingDaysUtil.java index 4fb1dc9f0..e802e8d65 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/service/WorkingDaysUtil.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/organisation/workingdays/service/WorkingDaysUtil.java @@ -13,13 +13,13 @@ import org.mifosplatform.portfolio.calendar.service.CalendarUtils; public class WorkingDaysUtil { - public static LocalDate getOffSetDateIfNonWorkingDay(final LocalDate date, final LocalDate nextMeetingDate, final WorkingDays workingDays) { + public static LocalDate getOffSetDateIfNonWorkingDay(final LocalDate date, final LocalDate nextMeetingDate, + final WorkingDays workingDays) { - //If date is not a non working day then return date. + // If date is not a non working day then return date. if (isWorkingDay(workingDays, date)) { return date; } - final RepaymentRescheduleType rescheduleType = RepaymentRescheduleType.fromInt(workingDays - .getRepaymentReschedulingType()); + final RepaymentRescheduleType rescheduleType = RepaymentRescheduleType.fromInt(workingDays.getRepaymentReschedulingType()); switch (rescheduleType) { case INVALID: @@ -37,7 +37,7 @@ public class WorkingDaysUtil { } } - public static boolean isWorkingDay(WorkingDays workingDays, final LocalDate date){ + public static boolean isWorkingDay(final WorkingDays workingDays, final LocalDate date) { return CalendarUtils.isValidRedurringDate(workingDays.getRecurrence(), date, date); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/PortfolioAccountType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/PortfolioAccountType.java index ad65f8bfb..8e75a7534 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/PortfolioAccountType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/PortfolioAccountType.java @@ -48,10 +48,10 @@ public enum PortfolioAccountType { switch (type) { case 1: enumType = LOAN; - break; + break; case 2: enumType = SAVINGS; - break; + break; } } return enumType; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/api/AccountTransfersApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/api/AccountTransfersApiResource.java index 01f551d83..ed09fc841 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/api/AccountTransfersApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/api/AccountTransfersApiResource.java @@ -67,12 +67,12 @@ public class AccountTransfersApiResource { @QueryParam("toAccountId") final Long toAccountId, @QueryParam("toAccountType") final Integer toAccountType, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); - AccountTransferData transferData = this.accountTransfersReadPlatformService.retrieveTemplate(fromOfficeId, fromClientId, + final AccountTransferData transferData = this.accountTransfersReadPlatformService.retrieveTemplate(fromOfficeId, fromClientId, fromAccountId, fromAccountType, toOfficeId, toClientId, toAccountId, toAccountType); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, transferData, AccountTransfersApiConstants.RESPONSE_DATA_PARAMETERS); } @@ -96,13 +96,13 @@ public class AccountTransfersApiResource { @QueryParam("limit") final Integer limit, @QueryParam("orderBy") final String orderBy, @QueryParam("sortOrder") final String sortOrder) { - context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); final SearchParameters searchParameters = SearchParameters.forLoans(sqlSearch, externalId, offset, limit, orderBy, sortOrder); final Page transfers = this.accountTransfersReadPlatformService.retrieveAll(searchParameters); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, transfers, AccountTransfersApiConstants.RESPONSE_DATA_PARAMETERS); } @@ -112,11 +112,11 @@ public class AccountTransfersApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveOne(@PathParam("transferId") final Long transferId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(AccountTransfersApiConstants.ACCOUNT_TRANSFER_RESOURCE_NAME); - AccountTransferData transfer = this.accountTransfersReadPlatformService.retrieveOne(transferId); + final AccountTransferData transfer = this.accountTransfersReadPlatformService.retrieveOne(transferId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, transfer, AccountTransfersApiConstants.RESPONSE_DATA_PARAMETERS); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransferDTO.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransferDTO.java index f9fb6b889..fd835b15e 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransferDTO.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransferDTO.java @@ -10,19 +10,19 @@ import org.mifosplatform.portfolio.paymentdetail.domain.PaymentDetail; public class AccountTransferDTO { - private LocalDate transactionDate; - private BigDecimal transactionAmount; - private PortfolioAccountType fromAccountType; - private PortfolioAccountType toAccountType; - private Long fromAccountId; - private Long toAccountId; - private String description; - private Locale locale; - private DateTimeFormatter fmt; - private PaymentDetail paymentDetail; - private Integer fromTransferType; - private Integer toTransferType; - private Long chargeId; + private final LocalDate transactionDate; + private final BigDecimal transactionAmount; + private final PortfolioAccountType fromAccountType; + private final PortfolioAccountType toAccountType; + private final Long fromAccountId; + private final Long toAccountId; + private final String description; + private final Locale locale; + private final DateTimeFormatter fmt; + private final PaymentDetail paymentDetail; + private final Integer fromTransferType; + private final Integer toTransferType; + private final Long chargeId; public AccountTransferDTO(final LocalDate transactionDate, final BigDecimal transactionAmount, final PortfolioAccountType fromAccountType, final PortfolioAccountType toAccountType, final Long fromAccountId, @@ -91,7 +91,6 @@ public class AccountTransferDTO { return this.toTransferType; } - public Long getChargeId() { return this.chargeId; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransferData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransferData.java index 93d6612f6..f4a191a38 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransferData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransferData.java @@ -57,7 +57,7 @@ public class AccountTransferData { BigDecimal transferAmount = BigDecimal.ZERO; if (fromAccount != null) { currency = fromAccount.currency(); - if(fromAccount.getAmtForTransfer() != null){ + if (fromAccount.getAmtForTransfer() != null) { transferAmount = fromAccount.getAmtForTransfer(); } } @@ -74,8 +74,8 @@ public class AccountTransferData { final PortfolioAccountData fromAccount, final EnumOptionData toAccountType, final PortfolioAccountData toAccount) { return new AccountTransferData(id, reversed, fromOffice, fromClient, fromAccountType, fromAccount, currency, transferAmount, - transferDate, transferDescription, toOffice, toClient, toAccountType, toAccount, null, null, null, null, null, null, - null, null); + transferDate, transferDescription, toOffice, toClient, toAccountType, toAccount, null, null, null, null, null, null, null, + null); } public static AccountTransferData transferBasicDetails(final Long id, final CurrencyData currency, final BigDecimal transferAmount, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransfersDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransfersDataValidator.java index 1d49518d8..aec86eae7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransfersDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/AccountTransfersDataValidator.java @@ -56,7 +56,7 @@ public class AccountTransfersDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) @@ -64,40 +64,41 @@ public class AccountTransfersDataValidator { final JsonElement element = command.parsedJson(); - final Long fromOfficeId = fromApiJsonHelper.extractLongNamed(fromOfficeIdParamName, element); + final Long fromOfficeId = this.fromApiJsonHelper.extractLongNamed(fromOfficeIdParamName, element); baseDataValidator.reset().parameter(fromOfficeIdParamName).value(fromOfficeId).notNull().integerGreaterThanZero(); - final Long fromClientId = fromApiJsonHelper.extractLongNamed(fromClientIdParamName, element); + final Long fromClientId = this.fromApiJsonHelper.extractLongNamed(fromClientIdParamName, element); baseDataValidator.reset().parameter(fromClientIdParamName).value(fromClientId).notNull().integerGreaterThanZero(); - final Long fromAccountId = fromApiJsonHelper.extractLongNamed(fromAccountIdParamName, element); + final Long fromAccountId = this.fromApiJsonHelper.extractLongNamed(fromAccountIdParamName, element); baseDataValidator.reset().parameter(fromAccountIdParamName).value(fromAccountId).notNull().integerGreaterThanZero(); - final Integer fromAccountType = fromApiJsonHelper.extractIntegerSansLocaleNamed(fromAccountTypeParamName, element); + final Integer fromAccountType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(fromAccountTypeParamName, element); baseDataValidator.reset().parameter(fromAccountTypeParamName).value(fromAccountType) .isOneOfTheseValues(Integer.valueOf(1), Integer.valueOf(2)); - final Long toOfficeId = fromApiJsonHelper.extractLongNamed(toOfficeIdParamName, element); + final Long toOfficeId = this.fromApiJsonHelper.extractLongNamed(toOfficeIdParamName, element); baseDataValidator.reset().parameter(toOfficeIdParamName).value(toOfficeId).notNull().integerGreaterThanZero(); - final Long toClientId = fromApiJsonHelper.extractLongNamed(toClientIdParamName, element); + final Long toClientId = this.fromApiJsonHelper.extractLongNamed(toClientIdParamName, element); baseDataValidator.reset().parameter(toClientIdParamName).value(toClientId).notNull().integerGreaterThanZero(); - final Long toAccountId = fromApiJsonHelper.extractLongNamed(toAccountIdParamName, element); + final Long toAccountId = this.fromApiJsonHelper.extractLongNamed(toAccountIdParamName, element); baseDataValidator.reset().parameter(toAccountIdParamName).value(toAccountId).notNull().integerGreaterThanZero(); - final Integer toAccountType = fromApiJsonHelper.extractIntegerSansLocaleNamed(toAccountTypeParamName, element); + final Integer toAccountType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(toAccountTypeParamName, element); baseDataValidator.reset().parameter(toAccountTypeParamName).value(toAccountType) .isOneOfTheseValues(Integer.valueOf(1), Integer.valueOf(2)); - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed(transferDateParamName, element); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(transferDateParamName, element); baseDataValidator.reset().parameter(transferDateParamName).value(transactionDate).notNull(); - final BigDecimal transactionAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(transferAmountParamName, element); + final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(transferAmountParamName, element); baseDataValidator.reset().parameter(transferAmountParamName).value(transactionAmount).notNull().positiveAmount(); - final String transactionDescription = fromApiJsonHelper.extractStringNamed(transferDescriptionParamName, element); - baseDataValidator.reset().parameter(transferDescriptionParamName).value(transactionDescription).notBlank().notExceedingLengthOf(200); + final String transactionDescription = this.fromApiJsonHelper.extractStringNamed(transferDescriptionParamName, element); + baseDataValidator.reset().parameter(transferDescriptionParamName).value(transactionDescription).notBlank() + .notExceedingLengthOf(200); throwExceptionIfValidationWarningsExist(dataValidationErrors); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/PortfolioAccountData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/PortfolioAccountData.java index 1f9c45c46..1f2af4da8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/PortfolioAccountData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/data/PortfolioAccountData.java @@ -103,8 +103,8 @@ public class PortfolioAccountData { public BigDecimal getAmtForTransfer() { return this.amtForTransfer; } - - public Long accountId(){ + + public Long accountId() { return this.id; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountAssociations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountAssociations.java index 8adbaa7bd..ff5299ef8 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountAssociations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountAssociations.java @@ -39,7 +39,7 @@ public class AccountAssociations extends AbstractPersistable { this.linkedSavingsAccount = linkedSavingsAccount; } - public static AccountAssociations associateSavingsAccount(Loan loan, SavingsAccount savingsAccount) { + public static AccountAssociations associateSavingsAccount(final Loan loan, final SavingsAccount savingsAccount) { return new AccountAssociations(loan, null, null, savingsAccount); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountAssociationsRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountAssociationsRepository.java index 364c7f5dd..f63612a17 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountAssociationsRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountAssociationsRepository.java @@ -10,5 +10,5 @@ public interface AccountAssociationsRepository extends JpaRepository { public static AccountTransfer LoanTosavingsTransfer(final Office fromOffice, final Client fromClient, final Loan fromLoanAccount, final Office toOffice, final Client toClient, final SavingsAccount toSavingsAccount, final SavingsAccountTransaction deposit, - final LoanTransaction loanRefundTransaction, final LocalDate transactionDate, final Money transactionAmount, final String description) { + final LoanTransaction loanRefundTransaction, final LocalDate transactionDate, final Money transactionAmount, + final String description) { return new AccountTransfer(fromOffice, fromClient, null, fromLoanAccount, toOffice, toClient, toSavingsAccount, null, null, deposit, null, loanRefundTransaction, transactionDate, transactionAmount, description); } @@ -127,7 +128,7 @@ public class AccountTransfer extends AbstractPersistable { private AccountTransfer(final Office fromOffice, final Client fromClient, final SavingsAccount fromSavingsAccount, final Loan fromLoanAccount, final Office toOffice, final Client toClient, final SavingsAccount toSavingsAccount, final Loan toLoanAccount, final SavingsAccountTransaction withdrawal, final SavingsAccountTransaction deposit, - final LoanTransaction loanRepaymentTransaction, LoanTransaction loanRefundTransaction, final LocalDate transactionDate, + final LoanTransaction loanRepaymentTransaction, final LoanTransaction loanRefundTransaction, final LocalDate transactionDate, final Money transactionAmount, final String description) { this.fromOffice = fromOffice; this.fromClient = fromClient; @@ -147,22 +148,18 @@ public class AccountTransfer extends AbstractPersistable { this.description = description; } - public LoanTransaction getFromLoanTransaction() { return this.fromLoanTransaction; } - public SavingsAccountTransaction getFromTransaction() { return this.fromTransaction; } - public LoanTransaction getToLoanTransaction() { return this.toLoanTransaction; } - public SavingsAccountTransaction getToSavingsTransaction() { return this.toSavingsTransaction; } @@ -171,12 +168,10 @@ public class AccountTransfer extends AbstractPersistable { this.reversed = true; } - public SavingsAccount getToSavingsAccount() { return this.toSavingsAccount; } - public SavingsAccount getFromAccount() { return this.fromAccount; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountTransferRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountTransferRepository.java index 34e866ca4..fa04fc9cc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountTransferRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/domain/AccountTransferRepository.java @@ -16,7 +16,7 @@ public interface AccountTransferRepository extends JpaRepository findByFromLoanId(@Param("accountNumber") Long accountNumber); - + @Query("from AccountTransfer at where (at.fromLoanAccount.id= :accountNumber or at.toLoanAccount.id=:accountNumber) and at.reversed=false") List findAllByLoanId(@Param("accountNumber") Long accountNumber); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/handler/CreateAccountTransferCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/handler/CreateAccountTransferCommandHandler.java index 106de2e3e..0845ebad3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/handler/CreateAccountTransferCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/handler/CreateAccountTransferCommandHandler.java @@ -27,6 +27,6 @@ public class CreateAccountTransferCommandHandler implements NewCommandSourceHand @Override public CommandProcessingResult processCommand(final JsonCommand command) { - return writePlatformService.create(command); + return this.writePlatformService.create(command); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformService.java index e2f361331..8a148b41e 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformService.java @@ -2,7 +2,6 @@ package org.mifosplatform.portfolio.account.service; import org.mifosplatform.portfolio.account.data.PortfolioAccountData; - public interface AccountAssociationsReadPlatformService { public PortfolioAccountData retriveLoanAssociation(final Long loanId); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java index 886191dd2..f958013f6 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountAssociationsReadPlatformServiceImpl.java @@ -47,17 +47,16 @@ public class AccountAssociationsReadPlatformServiceImpl implements AccountAssoci @Override public boolean isLinkedWithAnyActiveLoan(final Long savingsId) { boolean hasActiveLoan = false; - final String sql = "select loanAccount.loan_status_id as status from m_portfolio_account_associations aa " + - "left join m_loan loanAccount on loanAccount.id = aa.loan_account_id " + - "where aa.linked_savings_account_id = ?"; + final String sql = "select loanAccount.loan_status_id as status from m_portfolio_account_associations aa " + + "left join m_loan loanAccount on loanAccount.id = aa.loan_account_id " + "where aa.linked_savings_account_id = ?"; - final List statusList= this.jdbcTemplate.queryForList(sql,Integer.class, savingsId); - for(final Integer status:statusList){ - final LoanStatus loanStatus= LoanStatus.fromInt(status); - if(loanStatus.isActiveOrAwaitingApprovalOrDisbursal() || loanStatus.isUnderTransfer()){ - hasActiveLoan = true; - break; - } + final List statusList = this.jdbcTemplate.queryForList(sql, Integer.class, savingsId); + for (final Integer status : statusList) { + final LoanStatus loanStatus = LoanStatus.fromInt(status); + if (loanStatus.isActiveOrAwaitingApprovalOrDisbursal() || loanStatus.isUnderTransfer()) { + hasActiveLoan = true; + break; + } } return hasActiveLoan; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransferEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransferEnumerations.java index 99fdf7335..5aac38d38 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransferEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransferEnumerations.java @@ -21,15 +21,15 @@ public class AccountTransferEnumerations { if (type != null) { switch (type) { case INVALID: - break; + break; case LOAN: optionData = new EnumOptionData(PortfolioAccountType.LOAN.getValue().longValue(), PortfolioAccountType.LOAN.getCode(), "Loan Account"); - break; + break; case SAVINGS: optionData = new EnumOptionData(PortfolioAccountType.SAVINGS.getValue().longValue(), PortfolioAccountType.SAVINGS.getCode(), "Savings Account"); - break; + break; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersReadPlatformService.java index 2967fa1a6..0a5908546 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersReadPlatformService.java @@ -18,6 +18,6 @@ public interface AccountTransfersReadPlatformService { Page retrieveAll(SearchParameters searchParameters); AccountTransferData retrieveOne(Long transferId); - - boolean isAccountTransfer(Long transactionId,PortfolioAccountType accountType); + + boolean isAccountTransfer(Long transactionId, PortfolioAccountType accountType); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersReadPlatformServiceImpl.java index 8146af0ba..0982c70d7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersReadPlatformServiceImpl.java @@ -69,7 +69,7 @@ public class AccountTransfersReadPlatformServiceImpl implements AccountTransfers final EnumOptionData loanAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN); final EnumOptionData savingsAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS); - Integer mostRelevantFromAccountType = fromAccountType; + final Integer mostRelevantFromAccountType = fromAccountType; final Collection fromAccountTypeOptions = Arrays.asList(savingsAccountType, loanAccountType); final Collection toAccountTypeOptions; if (mostRelevantFromAccountType == 1) { @@ -309,17 +309,16 @@ public class AccountTransfersReadPlatformServiceImpl implements AccountTransfers final String toClientName = rs.getString("toClientName"); final ClientData toClient = ClientData.lookup(toClientId, toClientName, toOfficeId, toOfficeName); - final Long fromSavingsAccountId = JdbcSupport.getLong(rs, "fromSavingsAccountId"); final String fromSavingsAccountNo = rs.getString("fromSavingsAccountNo"); final Long fromLoanAccountId = JdbcSupport.getLong(rs, "fromLoanAccountId"); final String fromLoanAccountNo = rs.getString("fromLoanAccountNo"); PortfolioAccountData fromAccount = null; EnumOptionData fromAccountType = null; - if(fromSavingsAccountId != null){ + if (fromSavingsAccountId != null) { fromAccount = PortfolioAccountData.lookup(fromSavingsAccountId, fromSavingsAccountNo); fromAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.SAVINGS); - }else if(fromLoanAccountId != null){ + } else if (fromLoanAccountId != null) { fromAccount = PortfolioAccountData.lookup(fromLoanAccountId, fromLoanAccountNo); fromAccountType = AccountTransferEnumerations.accountType(PortfolioAccountType.LOAN); } @@ -345,15 +344,16 @@ public class AccountTransfersReadPlatformServiceImpl implements AccountTransfers } @Override - public boolean isAccountTransfer(Long transactionId, PortfolioAccountType accountType) { - StringBuilder sql = new StringBuilder("select count(*) from m_savings_account_transfer at where "); + public boolean isAccountTransfer(final Long transactionId, final PortfolioAccountType accountType) { + final StringBuilder sql = new StringBuilder("select count(*) from m_savings_account_transfer at where "); if (accountType.isLoanAccount()) { sql.append("at.from_loan_transaction_id=").append(transactionId).append(" or at.to_loan_transaction_id=").append(transactionId); } else { - sql.append("at.from_savings_transaction_id=").append(transactionId).append(" or at.to_savings_transaction_id=").append(transactionId); + sql.append("at.from_savings_transaction_id=").append(transactionId).append(" or at.to_savings_transaction_id=") + .append(transactionId); } - int count = this.jdbcTemplate.queryForInt(sql.toString()); + final int count = this.jdbcTemplate.queryForInt(sql.toString()); return count > 0; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersWritePlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersWritePlatformServiceImpl.java index d1c5e7f93..3c23a7fc5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersWritePlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/AccountTransfersWritePlatformServiceImpl.java @@ -167,7 +167,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer @Override @Transactional - public void reverseTransfersWithFromAccountType(Long accountNumber, PortfolioAccountType accountTypeId) { + public void reverseTransfersWithFromAccountType(final Long accountNumber, final PortfolioAccountType accountTypeId) { List acccountTransfers = null; if (accountTypeId.isLoanAccount()) { acccountTransfers = this.accountTransferRepository.findByFromLoanId(accountNumber); @@ -180,7 +180,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer @Override @Transactional - public void reverseAllTransactions(Long accountId, PortfolioAccountType accountTypeId) { + public void reverseAllTransactions(final Long accountId, final PortfolioAccountType accountTypeId) { List acccountTransfers = null; if (accountTypeId.isLoanAccount()) { acccountTransfers = this.accountTransferRepository.findAllByLoanId(accountId); @@ -193,8 +193,8 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer /** * @param acccountTransfers */ - private void undoTransactions(List acccountTransfers) { - for (AccountTransfer accountTransfer : acccountTransfers) { + private void undoTransactions(final List acccountTransfers) { + for (final AccountTransfer accountTransfer : acccountTransfers) { if (accountTransfer.getFromLoanTransaction() != null) { this.loanAccountDomainService.reverseTransfer(accountTransfer.getFromLoanTransaction()); } else if (accountTransfer.getToLoanTransaction() != null) { @@ -215,7 +215,7 @@ public class AccountTransfersWritePlatformServiceImpl implements AccountTransfer @Override @Transactional - public Long transferFunds(AccountTransferDTO accountTransferDTO) { + public Long transferFunds(final AccountTransferDTO accountTransferDTO) { Long transferTransactionId = null; if (isSavingsToLoanAccountTransfer(accountTransferDTO.getFromAccountType(), accountTransferDTO.getToAccountType())) { // diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/PortfolioAccountReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/PortfolioAccountReadPlatformServiceImpl.java index 02a0a6c50..46de1ad64 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/PortfolioAccountReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/account/service/PortfolioAccountReadPlatformServiceImpl.java @@ -68,7 +68,7 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount sql = "select " + this.savingsAccountMapper.schema() + " where sa.id = ?"; if (currencyCode != null) { sql += " and sa.currency_code = ?"; - sqlParams = new Object[] {accountId, currencyCode}; + sqlParams = new Object[] { accountId, currencyCode }; } accountData = this.jdbcTemplate.queryForObject(sql, this.savingsAccountMapper, sqlParams); @@ -84,23 +84,24 @@ public class PortfolioAccountReadPlatformServiceImpl implements PortfolioAccount } @Override - public Collection retrieveAllForLookup(final Integer accountTypeId, final Long clientId, long[] accountStatus) { + public Collection retrieveAllForLookup(final Integer accountTypeId, final Long clientId, + final long[] accountStatus) { return retrieveAllForLookup(accountTypeId, clientId, null, accountStatus); } @Override public Collection retrieveAllForLookup(final Integer accountTypeId, final Long clientId, - final String currencyCode, long[] accountStatus) { + final String currencyCode, final long[] accountStatus) { Object[] sqlParams = new Object[] { clientId }; Collection accounts = null; String sql = null; String defaultAccountStatus = "300"; if (accountStatus != null) { - for (long status : accountStatus) { + for (final long status : accountStatus) { defaultAccountStatus += ", " + status; } - defaultAccountStatus = defaultAccountStatus.substring(defaultAccountStatus.indexOf(",")+1); + defaultAccountStatus = defaultAccountStatus.substring(defaultAccountStatus.indexOf(",") + 1); } final PortfolioAccountType accountType = PortfolioAccountType.fromInt(accountTypeId); switch (accountType) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/data/AccountSummaryCollectionData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/data/AccountSummaryCollectionData.java index dd4b59650..e9247b733 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/data/AccountSummaryCollectionData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/data/AccountSummaryCollectionData.java @@ -31,7 +31,7 @@ public class AccountSummaryCollectionData { public AccountSummaryCollectionData(final Collection loanAccounts, final Collection savingsAccounts, final Collection memberLoanAccounts, - Collection memberSavingsAccounts) { + final Collection memberSavingsAccounts) { this.loanAccounts = defaultLoanAccountsIfEmpty(loanAccounts); this.savingsAccounts = defaultSavingsAccountsIfEmpty(savingsAccounts); this.memberLoanAccounts = defaultLoanAccountsIfEmpty(memberLoanAccounts); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/domain/AccountType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/domain/AccountType.java index 02ba6955e..e1c801485 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/domain/AccountType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/domain/AccountType.java @@ -13,7 +13,7 @@ public enum AccountType { INVALID(0, "accountType.invalid"), // INDIVIDUAL(1, "accountType.individual"), // GROUP(2, "accountType.group"), // - JLG(3, "accountType.jlg");//JLG account given in group context + JLG(3, "accountType.jlg");// JLG account given in group context private final Integer value; private final String code; @@ -40,42 +40,42 @@ public enum AccountType { return enumeration; } - public static AccountType fromName(final String name){ + public static AccountType fromName(final String name) { AccountType accountType = AccountType.INVALID; - for (AccountType type : AccountType.values()) { - if(type.getName().equals(name)) { + for (final AccountType type : AccountType.values()) { + if (type.getName().equals(name)) { accountType = type; break; } } return accountType; } - + public Integer getValue() { return this.value; } public String getCode() { - return code; + return this.code; } - - public String getName(){ + + public String getName() { return name().toLowerCase(); } - - public boolean isInvalid(){ + + public boolean isInvalid() { return this.value.equals(AccountType.INVALID.getValue()); } - - public boolean isIndividualAccount(){ + + public boolean isIndividualAccount() { return this.value.equals(AccountType.INDIVIDUAL.getValue()); } - - public boolean isGroupAccount(){ + + public boolean isGroupAccount() { return this.value.equals(AccountType.GROUP.getValue()); } - - public boolean isJLGAccount(){ + + public boolean isJLGAccount() { return this.value.equals(AccountType.JLG.getValue()); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountDetailsReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountDetailsReadPlatformService.java index ad918f046..b752f5244 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountDetailsReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountDetailsReadPlatformService.java @@ -5,14 +5,13 @@ import java.util.Collection; import org.mifosplatform.portfolio.accountdetails.data.AccountSummaryCollectionData; import org.mifosplatform.portfolio.accountdetails.data.LoanAccountSummaryData; - public interface AccountDetailsReadPlatformService { public AccountSummaryCollectionData retrieveClientAccountDetails(final Long clientId); - + public AccountSummaryCollectionData retrieveGroupAccountDetails(final Long groupId); public Collection retrieveClientLoanAccountsByLoanOfficerId(final Long clientId, final Long loanOfficerId); - public Collection retrieveGroupLoanAccountsByLoanOfficerId(final Long groupId,final Long loanOfficerId); + public Collection retrieveGroupLoanAccountsByLoanOfficerId(final Long groupId, final Long loanOfficerId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountDetailsReadPlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountDetailsReadPlatformServiceJpaRepositoryImpl.java index 4952e81d8..6921b41c9 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountDetailsReadPlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountDetailsReadPlatformServiceJpaRepositoryImpl.java @@ -40,28 +40,30 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou } @Override - public AccountSummaryCollectionData retrieveClientAccountDetails(Long clientId) { + public AccountSummaryCollectionData retrieveClientAccountDetails(final Long clientId) { // Check if client exists - clientReadPlatformService.retrieveOne(clientId); - String loanwhereClause = " where l.client_id = ?"; - String savingswhereClause = " where sa.client_id = ? order by sa.status_enum ASC, sa.account_no ASC"; - List loanAccounts = retrieveLoanAccountDetails(loanwhereClause, new Object[] { clientId }); - List savingsAccounts = retrieveAccountDetails(savingswhereClause, new Object[] { clientId }); + this.clientReadPlatformService.retrieveOne(clientId); + final String loanwhereClause = " where l.client_id = ?"; + final String savingswhereClause = " where sa.client_id = ? order by sa.status_enum ASC, sa.account_no ASC"; + final List loanAccounts = retrieveLoanAccountDetails(loanwhereClause, new Object[] { clientId }); + final List savingsAccounts = retrieveAccountDetails(savingswhereClause, new Object[] { clientId }); return new AccountSummaryCollectionData(loanAccounts, savingsAccounts); } @Override - public AccountSummaryCollectionData retrieveGroupAccountDetails(Long groupId) { + public AccountSummaryCollectionData retrieveGroupAccountDetails(final Long groupId) { // Check if group exists - groupReadPlatformService.retrieveOne(groupId); - String loanWhereClauseForGroup = " where l.group_id = ? and l.client_id is null"; - String loanWhereClauseForMembers = " where l.group_id = ? and l.client_id is not null"; - String savingswhereClauseForGroup = " where sa.group_id = ? and sa.client_id is null order by sa.status_enum ASC, sa.account_no ASC"; - String savingswhereClauseForMembers = " where sa.group_id = ? and sa.client_id is not null order by sa.status_enum ASC, sa.account_no ASC"; - List groupLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroup, new Object[] { groupId }); - List groupSavingsAccounts = retrieveAccountDetails(savingswhereClauseForGroup, new Object[] { groupId }); - List memberLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForMembers, new Object[] { groupId }); - List memberSavingsAccounts = retrieveAccountDetails(savingswhereClauseForMembers, + this.groupReadPlatformService.retrieveOne(groupId); + final String loanWhereClauseForGroup = " where l.group_id = ? and l.client_id is null"; + final String loanWhereClauseForMembers = " where l.group_id = ? and l.client_id is not null"; + final String savingswhereClauseForGroup = " where sa.group_id = ? and sa.client_id is null order by sa.status_enum ASC, sa.account_no ASC"; + final String savingswhereClauseForMembers = " where sa.group_id = ? and sa.client_id is not null order by sa.status_enum ASC, sa.account_no ASC"; + final List groupLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForGroup, new Object[] { groupId }); + final List groupSavingsAccounts = retrieveAccountDetails(savingswhereClauseForGroup, + new Object[] { groupId }); + final List memberLoanAccounts = retrieveLoanAccountDetails(loanWhereClauseForMembers, + new Object[] { groupId }); + final List memberSavingsAccounts = retrieveAccountDetails(savingswhereClauseForMembers, new Object[] { groupId }); return new AccountSummaryCollectionData(groupLoanAccounts, groupSavingsAccounts, memberLoanAccounts, memberSavingsAccounts); } @@ -69,22 +71,22 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou @Override public Collection retrieveClientLoanAccountsByLoanOfficerId(final Long clientId, final Long loanOfficerId) { // Check if client exists - clientReadPlatformService.retrieveOne(clientId); - String loanWhereClause = " where l.client_id = ? and l.loan_officer_id = ?"; + this.clientReadPlatformService.retrieveOne(clientId); + final String loanWhereClause = " where l.client_id = ? and l.loan_officer_id = ?"; return retrieveLoanAccountDetails(loanWhereClause, new Object[] { clientId, loanOfficerId }); } @Override public Collection retrieveGroupLoanAccountsByLoanOfficerId(final Long groupId, final Long loanOfficerId) { // Check if group exists - groupReadPlatformService.retrieveOne(groupId); - String loanWhereClause = " where l.group_id = ? and l.client_id is null and l.loan_officer_id = ?"; + this.groupReadPlatformService.retrieveOne(groupId); + final String loanWhereClause = " where l.group_id = ? and l.client_id is null and l.loan_officer_id = ?"; return retrieveLoanAccountDetails(loanWhereClause, new Object[] { groupId, loanOfficerId }); } - private List retrieveLoanAccountDetails(String loanwhereClause, Object[] inputs) { - LoanAccountSummaryDataMapper rm = new LoanAccountSummaryDataMapper(); - String sql = "select " + rm.loanAccountSummarySchema() + loanwhereClause; + private List retrieveLoanAccountDetails(final String loanwhereClause, final Object[] inputs) { + final LoanAccountSummaryDataMapper rm = new LoanAccountSummaryDataMapper(); + final String sql = "select " + rm.loanAccountSummarySchema() + loanwhereClause; return this.jdbcTemplate.query(sql, rm, inputs); } @@ -92,8 +94,8 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou * @param entityId * @return */ - private List retrieveAccountDetails(String savingswhereClause, Object[] inputs) { - SavingsAccountSummaryDataMapper savingsAccountSummaryDataMapper = new SavingsAccountSummaryDataMapper(); + private List retrieveAccountDetails(final String savingswhereClause, final Object[] inputs) { + final SavingsAccountSummaryDataMapper savingsAccountSummaryDataMapper = new SavingsAccountSummaryDataMapper(); final String savingsSql = "select " + savingsAccountSummaryDataMapper.schema() + savingswhereClause; return this.jdbcTemplate.query(savingsSql, savingsAccountSummaryDataMapper, inputs); } @@ -103,7 +105,7 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou final String schemaSql; public SavingsAccountSummaryDataMapper() { - StringBuilder accountsSummary = new StringBuilder(); + final StringBuilder accountsSummary = new StringBuilder(); accountsSummary.append("sa.id as id, sa.account_no as accountNo, sa.external_id as externalId, sa.status_enum as statusEnum, "); accountsSummary.append("sa.account_type_enum as accountType, "); accountsSummary.append("sa.account_balance_derived as accountBalance, "); @@ -155,7 +157,7 @@ public class AccountDetailsReadPlatformServiceJpaRepositoryImpl implements Accou public String loanAccountSummarySchema() { - StringBuilder accountsSummary = new StringBuilder("l.id as id, l.account_no as accountNo, l.external_id as externalId,"); + final StringBuilder accountsSummary = new StringBuilder("l.id as id, l.account_no as accountNo, l.external_id as externalId,"); accountsSummary.append("l.product_id as productId, lp.name as productName,") .append("l.loan_status_id as statusId, l.loan_type_enum as loanType, ").append("l.loan_product_counter as loanCycle ") .append(" from m_loan l ").append("LEFT JOIN m_product_loan AS lp ON lp.id = l.product_id"); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountEnumerations.java index 119d3c8a4..78d11dd73 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/accountdetails/service/AccountEnumerations.java @@ -3,9 +3,8 @@ package org.mifosplatform.portfolio.accountdetails.service; import org.mifosplatform.infrastructure.core.data.EnumOptionData; import org.mifosplatform.portfolio.accountdetails.domain.AccountType; - public class AccountEnumerations { - + public static EnumOptionData loanType(final Integer loanTypeId) { return loanType(AccountType.fromInt(loanTypeId)); } @@ -21,7 +20,8 @@ public class AccountEnumerations { optionData = new EnumOptionData(AccountType.INVALID.getValue().longValue(), AccountType.INVALID.getCode(), "Invalid"); break; case INDIVIDUAL: - optionData = new EnumOptionData(AccountType.INDIVIDUAL.getValue().longValue(), AccountType.INDIVIDUAL.getCode(), "Individual"); + optionData = new EnumOptionData(AccountType.INDIVIDUAL.getValue().longValue(), AccountType.INDIVIDUAL.getCode(), + "Individual"); break; case GROUP: optionData = new EnumOptionData(AccountType.GROUP.getValue().longValue(), AccountType.GROUP.getCode(), "Group"); @@ -34,5 +34,4 @@ public class AccountEnumerations { return optionData; } - } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/CalendarConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/CalendarConstants.java index 0164bed95..358b85006 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/CalendarConstants.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/CalendarConstants.java @@ -14,8 +14,8 @@ public class CalendarConstants { CALENDAR_ID("id"), ENTITY_TYPE("entityType"), ENTITY_ID("entityId"), TITLE("title"), DESCRIPTION("description"), LOCATION( "location"), START_DATE("startDate"), END_DATE("endDate"), CREATED_DATE("createdDate"), DURATION("duration"), TYPE_ID( "typeId"), REPEATING("repeating"), REMIND_BY_ID("remindById"), FIRST_REMINDER("firstReminder"), SECOND_REMINDER( - "secondReminder"), LOCALE("locale"), DATE_FORMAT("dateFormat"), REPEATS("repeats"), REPEATS_EVERY("repeatsEvery"), - REPEATS_ON_DAY("repeatsOnDay"); + "secondReminder"), LOCALE("locale"), DATE_FORMAT("dateFormat"), REPEATS("repeats"), REPEATS_EVERY("repeatsEvery"), REPEATS_ON_DAY( + "repeatsOnDay"); private final String value; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/data/CalendarData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/data/CalendarData.java index 8bdcf2071..ba9e0423a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/data/CalendarData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/data/CalendarData.java @@ -54,8 +54,9 @@ public class CalendarData { public CalendarData(final Long id, final Long entityId, final EnumOptionData entityType, final String title, final String description, final String location, final LocalDate startDate, final LocalDate endDate, final Integer duration, final EnumOptionData type, final boolean repeating, final String recurrence, final EnumOptionData remindBy, final Integer firstReminder, - final Integer secondReminder, final String humanReadable, final LocalDate recentEligibleMeetingDate, final LocalDate createdDate, final LocalDate lastUpdatedDate, - final Long createdByUserId, final String createdByUsername, final Long lastUpdatedByUserId, final String lastUpdatedByUsername) { + final Integer secondReminder, final String humanReadable, final LocalDate recentEligibleMeetingDate, + final LocalDate createdDate, final LocalDate lastUpdatedDate, final Long createdByUserId, final String createdByUsername, + final Long lastUpdatedByUserId, final String lastUpdatedByUsername) { this.id = id; this.entityId = entityId; @@ -120,7 +121,8 @@ public class CalendarData { this.lastUpdatedByUsername = calendarData.lastUpdatedByUsername; } - public CalendarData(final CalendarData calendarData, final Collection recurringDates, final Collection nextTenRecurringDates, final LocalDate recentEligibleMeetingDate) { + public CalendarData(final CalendarData calendarData, final Collection recurringDates, + final Collection nextTenRecurringDates, final LocalDate recentEligibleMeetingDate) { this.id = calendarData.id; this.entityId = calendarData.entityId; this.entityType = calendarData.entityType; @@ -170,7 +172,7 @@ public class CalendarData { final Integer secondReminder = new Integer(0); final String humanReadable = null; final LocalDate recentEligibleMeetingDate = null; - + final LocalDate createdDate = null; final LocalDate lastUpdatedDate = null; final Long createdByUserId = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/Calendar.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/Calendar.java index cb50d666d..b63c594a4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/Calendar.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/Calendar.java @@ -73,8 +73,8 @@ public class Calendar extends AbstractAuditableCustom { } public Calendar(final String title, final String description, final String location, final LocalDate startDate, - final LocalDate endDate, final Integer duration, final Integer typeId, final boolean repeating, - final String recurrence, final Integer remindById, final Integer firstReminder, final Integer secondReminder) { + final LocalDate endDate, final Integer duration, final Integer typeId, final boolean repeating, final String recurrence, + final Integer remindById, final Integer firstReminder, final Integer secondReminder) { this.title = StringUtils.defaultIfEmpty(title, null); this.description = StringUtils.defaultIfEmpty(description, null); this.location = StringUtils.defaultIfEmpty(location, null); @@ -120,8 +120,8 @@ public class Calendar extends AbstractAuditableCustom { .getValue()); final String recurrence = Calendar.constructRecurrence(command, null); - return new Calendar(title, description, location, startDate, endDate, duration, typeId, repeating, recurrence, - remindById, firstReminder, secondReminder); + return new Calendar(title, description, location, startDate, endDate, duration, typeId, repeating, recurrence, remindById, + firstReminder, secondReminder); } public Map update(final JsonCommand command) { @@ -153,15 +153,17 @@ public class Calendar extends AbstractAuditableCustom { final String valueAsInput = command.stringValueOfParameterNamed(startDateParamName); final LocalDate newValue = command.localDateValueOfParameterNamed(startDateParamName); - if(isStartDateBefore(newValue)){ + if (isStartDateBefore(newValue)) { actualChanges.put(startDateParamName, valueAsInput); actualChanges.put("dateFormat", dateFormatAsInput); actualChanges.put("locale", localeAsInput); this.startDate = newValue.toDate(); - }else{ - //new meeting start date should be greater than existing meeting start date + } else { + // new meeting start date should be greater than existing + // meeting start date final String defaultUserMessage = "New meeting start on or after date cannot be a date before existing meeting start date"; - throw new CalendarDateException("new.start.date.before.existing.date", defaultUserMessage, newValue, getStartDateLocalDate()); + throw new CalendarDateException("new.start.date.before.existing.date", defaultUserMessage, newValue, + getStartDateLocalDate()); } } @@ -183,21 +185,25 @@ public class Calendar extends AbstractAuditableCustom { this.duration = newValue; } - //Do not allow to change calendar type - //TODO: AA Instead of throwing an exception, do not allow meeting calendar type to update. + // Do not allow to change calendar type + // TODO: AA Instead of throwing an exception, do not allow meeting + // calendar type to update. final String typeParamName = CALENDAR_SUPPORTED_PARAMETERS.TYPE_ID.getValue(); if (command.isChangeInIntegerSansLocaleParameterNamed(typeParamName, this.typeId)) { final Integer newValue = command.integerValueSansLocaleOfParameterNamed(typeParamName); final String defaultUserMessage = "Meeting calendar type update is not supported"; final String oldMeeingType = CalendarType.fromInt(this.typeId).name(); final String newMeetingType = CalendarType.fromInt(newValue).name(); - + throw new CalendarParameterUpdateNotSupportedException("meeting.type", defaultUserMessage, newMeetingType, oldMeeingType); - /*final Integer newValue = command.integerValueSansLocaleOfParameterNamed(typeParamName); - actualChanges.put(typeParamName, newValue); - this.typeId = newValue;*/ + /* + * final Integer newValue = + * command.integerValueSansLocaleOfParameterNamed(typeParamName); + * actualChanges.put(typeParamName, newValue); this.typeId = + * newValue; + */ } - + final String repeatingParamName = CALENDAR_SUPPORTED_PARAMETERS.REPEATING.getValue(); if (command.isChangeInBooleanParameterNamed(repeatingParamName, this.repeating)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(repeatingParamName); @@ -208,16 +214,17 @@ public class Calendar extends AbstractAuditableCustom { final String newRecurrence = Calendar.constructRecurrence(command, this); if (this.recurrence != null && !newRecurrence.equalsIgnoreCase(this.recurrence)) { - //FIXME: AA - Is this restriction required only for collection type meetings or for all?. - //Do not allow to change meeting frequency - - if(!CalendarUtils.isFrequencySame(this.recurrence, newRecurrence)){ + // FIXME: AA - Is this restriction required only for collection type + // meetings or for all?. + // Do not allow to change meeting frequency + + if (!CalendarUtils.isFrequencySame(this.recurrence, newRecurrence)) { final String defaultUserMessage = "Update of meeting frequency is not supported"; throw new CalendarParameterUpdateNotSupportedException("meeting.frequency", defaultUserMessage); } - - //Do not allow to change meeting interval - if(!CalendarUtils.isIntervalSame(this.recurrence, newRecurrence)){ + + // Do not allow to change meeting interval + if (!CalendarUtils.isIntervalSame(this.recurrence, newRecurrence)) { final String defaultUserMessage = "Update of meeting interval is not supported"; throw new CalendarParameterUpdateNotSupportedException("meeting.interval", defaultUserMessage); } @@ -329,7 +336,7 @@ public class Calendar extends AbstractAuditableCustom { } if (repeating) { - StringBuilder recurrenceBuilder = new StringBuilder(200); + final StringBuilder recurrenceBuilder = new StringBuilder(200); final String repeats = command.stringValueOfParameterNamed(CALENDAR_SUPPORTED_PARAMETERS.REPEATS.getValue()); recurrenceBuilder.append("FREQ="); recurrenceBuilder.append(repeats.toUpperCase()); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarEntityType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarEntityType.java index 95cf5329d..931504dae 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarEntityType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarEntityType.java @@ -66,19 +66,19 @@ public enum CalendarEntityType { public String toString() { return name().toString(); } - + public static boolean isGroup(final Integer value) { return CalendarEntityType.GROUPS.value.equals(value) ? true : false; } - + public static boolean isGroup(final String name) { return CalendarEntityType.GROUPS.name().equalsIgnoreCase(name) ? true : false; } - + public static boolean isCenter(final Integer value) { return CalendarEntityType.CENTERS.value.equals(value) ? true : false; } - + public static boolean isCenter(final String name) { return CalendarEntityType.CENTERS.name().equalsIgnoreCase(name) ? true : false; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarInstance.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarInstance.java index 2d2d03207..ac9cacbb8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarInstance.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarInstance.java @@ -21,20 +21,20 @@ public class CalendarInstance extends AbstractPersistable { @ManyToOne @JoinColumn(name = "calendar_id", nullable = false) private Calendar calendar; - + @Column(name = "entity_id", nullable = false) private Long entityId; - + @Column(name = "entity_type_enum", nullable = false) private Integer entityTypeId; - public CalendarInstance(Calendar calendar, Long entityId, Integer entityTypeId) { + public CalendarInstance(final Calendar calendar, final Long entityId, final Integer entityTypeId) { this.calendar = calendar; this.entityId = entityId; this.entityTypeId = entityTypeId; } - protected CalendarInstance(){ + protected CalendarInstance() { } @@ -43,8 +43,8 @@ public class CalendarInstance extends AbstractPersistable { final Integer entityTypeId = CalendarEntityType.valueOf(command.getSupportedEntityType().toUpperCase()).getValue(); return new CalendarInstance(calendar, entityId, entityTypeId); } - - public void updateCalendar(final Calendar calendar){ + + public void updateCalendar(final Calendar calendar) { this.calendar = calendar; } @@ -52,14 +52,12 @@ public class CalendarInstance extends AbstractPersistable { return this.calendar; } - public Long getEntityId() { return this.entityId; } - public Integer getEntityTypeId() { return this.entityTypeId; } - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarInstanceRepositoryWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarInstanceRepositoryWrapper.java index ce94b7088..d15ae3bea 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarInstanceRepositoryWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarInstanceRepositoryWrapper.java @@ -11,9 +11,10 @@ import org.springframework.stereotype.Service; /** *

- * Wrapper for {@link CalendarInstanceRepository} that is responsible for checking - * if {@link CalendarInstance} is returned when using findOne - * repository method and throwing an appropriate not found exception. + * Wrapper for {@link CalendarInstanceRepository} that is responsible for + * checking if {@link CalendarInstance} is returned when using + * findOne repository method and throwing an appropriate not found + * exception. *

* *

diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarRepositoryWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarRepositoryWrapper.java index 4356292fb..a81ac5cba 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarRepositoryWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/domain/CalendarRepositoryWrapper.java @@ -11,9 +11,9 @@ import org.springframework.stereotype.Service; /** *

- * Wrapper for {@link CalendarRepository} that is responsible for checking - * if {@link Calendar} is returned when using findOne - * repository method and throwing an appropriate not found exception. + * Wrapper for {@link CalendarRepository} that is responsible for checking if + * {@link Calendar} is returned when using findOne repository + * method and throwing an appropriate not found exception. *

* *

diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarDateException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarDateException.java index f87c2c43c..5691b842b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarDateException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarDateException.java @@ -12,7 +12,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class CalendarDateException extends AbstractPlatformDomainRuleException { - public CalendarDateException(String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg.calendar." + postFix , defaultUserMessage, defaultUserMessageArgs); + public CalendarDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { + super("error.msg.calendar." + postFix, defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarInstanceNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarInstanceNotFoundException.java index 13042f555..1853862dc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarInstanceNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarInstanceNotFoundException.java @@ -8,14 +8,15 @@ package org.mifosplatform.portfolio.calendar.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when CalendarInstance resources are not found. + * A {@link RuntimeException} thrown when CalendarInstance resources are not + * found. */ public class CalendarInstanceNotFoundException extends AbstractPlatformResourceNotFoundException { public CalendarInstanceNotFoundException(final Long id) { super("error.msg.calendar.instance.id.invalid", "Calendar Instance with identifier " + id + " does not exist", id); } - + public CalendarInstanceNotFoundException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.calendar.instance." + postFix, defaultUserMessage, defaultUserMessageArgs); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarParameterUpdateNotSupportedException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarParameterUpdateNotSupportedException.java index 21bca5984..da9fe670d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarParameterUpdateNotSupportedException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/CalendarParameterUpdateNotSupportedException.java @@ -12,7 +12,8 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class CalendarParameterUpdateNotSupportedException extends AbstractPlatformDomainRuleException { - public CalendarParameterUpdateNotSupportedException(String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { + public CalendarParameterUpdateNotSupportedException(final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg.calendar.update.of." + postFix + ".is.not.supported", defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/MeetingFrequencyMismatchException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/MeetingFrequencyMismatchException.java index 36dd1fde0..abd9794dc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/MeetingFrequencyMismatchException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/MeetingFrequencyMismatchException.java @@ -12,7 +12,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class MeetingFrequencyMismatchException extends AbstractPlatformDomainRuleException { - public MeetingFrequencyMismatchException(String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { + public MeetingFrequencyMismatchException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.calendar." + postFix + ".not.the.same.as.meeting.frequency", defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/NotValidRecurringDateException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/NotValidRecurringDateException.java index 6600feefa..cffba2548 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/NotValidRecurringDateException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/exception/NotValidRecurringDateException.java @@ -12,7 +12,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class NotValidRecurringDateException extends AbstractPlatformDomainRuleException { - public NotValidRecurringDateException(String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { + public NotValidRecurringDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.calendar." + postFix + ".not.valid.recurring.date", defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/serialization/CalendarCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/serialization/CalendarCommandFromApiJsonDeserializer.java index f8198f49d..ecc57aced 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/serialization/CalendarCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/serialization/CalendarCommandFromApiJsonDeserializer.java @@ -108,15 +108,16 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD final String startDateStr = this.fromApiJsonHelper.extractStringNamed(CALENDAR_SUPPORTED_PARAMETERS.START_DATE.getValue(), element); baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.START_DATE.getValue()).value(startDateStr).notBlank(); - if(!StringUtils.isBlank(startDateStr)){ - final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed(CALENDAR_SUPPORTED_PARAMETERS.START_DATE.getValue(), element); + if (!StringUtils.isBlank(startDateStr)) { + final LocalDate startDate = this.fromApiJsonHelper.extractLocalDateNamed(CALENDAR_SUPPORTED_PARAMETERS.START_DATE.getValue(), + element); baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.START_DATE.getValue()).value(startDate).notNull(); } if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.END_DATE.getValue(), element)) { final String endDateStr = this.fromApiJsonHelper.extractStringNamed(CALENDAR_SUPPORTED_PARAMETERS.END_DATE.getValue(), element); baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.END_DATE.getValue()).value(endDateStr).notBlank(); - + final LocalDate endDate = this.fromApiJsonHelper.extractLocalDateNamed(CALENDAR_SUPPORTED_PARAMETERS.END_DATE.getValue(), element); baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.END_DATE.getValue()).value(endDate).notNull(); @@ -170,13 +171,15 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.FIRST_REMINDER.getValue(), element)) { final Integer firstReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( CALENDAR_SUPPORTED_PARAMETERS.FIRST_REMINDER.getValue(), element); - baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.FIRST_REMINDER.getValue()).value(firstReminder).ignoreIfNull().integerGreaterThanZero(); + baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.FIRST_REMINDER.getValue()).value(firstReminder) + .ignoreIfNull().integerGreaterThanZero(); } if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.SECOND_REMINDER.getValue(), element)) { final Integer secondReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( CALENDAR_SUPPORTED_PARAMETERS.SECOND_REMINDER.getValue(), element); - baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.SECOND_REMINDER.getValue()).value(secondReminder).ignoreIfNull().integerGreaterThanZero(); + baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.SECOND_REMINDER.getValue()).value(secondReminder) + .ignoreIfNull().integerGreaterThanZero(); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", @@ -234,7 +237,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD CALENDAR_SUPPORTED_PARAMETERS.DURATION.getValue(), element); baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.DURATION.getValue()).value(duration).ignoreIfNull(); } - //TODO: AA do not allow to change calendar type. + // TODO: AA do not allow to change calendar type. if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.TYPE_ID.getValue(), element)) { final Integer typeId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(CALENDAR_SUPPORTED_PARAMETERS.TYPE_ID.getValue(), element); @@ -246,7 +249,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD final boolean repeating = this.fromApiJsonHelper.extractBooleanNamed(CALENDAR_SUPPORTED_PARAMETERS.REPEATING.getValue(), element); baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.REPEATING.getValue()).value(repeating).notNull(); - + if (repeating) { final String repeats = this.fromApiJsonHelper.extractStringNamed(CALENDAR_SUPPORTED_PARAMETERS.REPEATS.getValue(), element); baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.REPEATS.getValue()).value(repeats).ignoreIfNull() @@ -267,7 +270,7 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD } } } - + if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.REMIND_BY_ID.getValue(), element)) { final Integer remindById = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( CALENDAR_SUPPORTED_PARAMETERS.REMIND_BY_ID.getValue(), element); @@ -278,13 +281,15 @@ public class CalendarCommandFromApiJsonDeserializer extends AbstractFromApiJsonD if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.FIRST_REMINDER.getValue(), element)) { final Integer firstReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( CALENDAR_SUPPORTED_PARAMETERS.FIRST_REMINDER.getValue(), element); - baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.FIRST_REMINDER.getValue()).value(firstReminder).ignoreIfNull(); + baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.FIRST_REMINDER.getValue()).value(firstReminder) + .ignoreIfNull(); } if (this.fromApiJsonHelper.parameterExists(CALENDAR_SUPPORTED_PARAMETERS.SECOND_REMINDER.getValue(), element)) { final Integer secondReminder = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( CALENDAR_SUPPORTED_PARAMETERS.SECOND_REMINDER.getValue(), element); - baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.SECOND_REMINDER.getValue()).value(secondReminder).ignoreIfNull(); + baseDataValidator.reset().parameter(CALENDAR_SUPPORTED_PARAMETERS.SECOND_REMINDER.getValue()).value(secondReminder) + .ignoreIfNull(); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarReadPlatformServiceImpl.java index 126a07962..0ffaffa36 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarReadPlatformServiceImpl.java @@ -69,11 +69,15 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ final String recurrence = rs.getString("recurrence"); final Integer remindById = rs.getInt("remindById"); EnumOptionData remindBy = null; - if (remindById != null && remindById != 0) remindBy = CalendarEnumerations.calendarRemindBy(remindById); + if (remindById != null && remindById != 0) { + remindBy = CalendarEnumerations.calendarRemindBy(remindById); + } final Integer firstReminder = rs.getInt("firstReminder"); final Integer secondReminder = rs.getInt("secondReminder"); String humanReadable = null; - if (startDate != null && recurrence != null) humanReadable = CalendarUtils.getRRuleReadable(startDate, recurrence); + if (startDate != null && recurrence != null) { + humanReadable = CalendarUtils.getRRuleReadable(startDate, recurrence); + } final LocalDate createdDate = JdbcSupport.getLocalDate(rs, "createdDate"); final LocalDate lastUpdatedDate = JdbcSupport.getLocalDate(rs, "updatedDate"); @@ -81,12 +85,12 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ final String createdByUserName = rs.getString("creatingUserName"); final Long lastUpdatedByUserId = rs.getLong("updatingUserId"); final String lastUpdatedByUserName = rs.getString("updatingUserName"); - + final LocalDate recentEligibleMeetingDate = null; return new CalendarData(id, entityId, entityType, title, description, location, startDate, endDate, duration, type, repeating, - recurrence, remindBy, firstReminder, secondReminder, humanReadable, recentEligibleMeetingDate, createdDate, lastUpdatedDate, createdByUserId, - createdByUserName, lastUpdatedByUserId, lastUpdatedByUserName); + recurrence, remindBy, firstReminder, secondReminder, humanReadable, recentEligibleMeetingDate, createdDate, + lastUpdatedDate, createdByUserId, createdByUserName, lastUpdatedByUserId, lastUpdatedByUserName); } } @@ -117,25 +121,25 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ sql = rm.schema() + " and ci.entity_id = ? and ci.entity_type_enum = ? order by c.start_date "; result = this.jdbcTemplate.query(sql, rm, new Object[] { entityId, entityTypeId }); } else if (!calendarTypeOptions.isEmpty()) { - String sqlCalendarTypeOptions = CalendarUtils.getSqlCalendarTypeOptionsInString(calendarTypeOptions); + final String sqlCalendarTypeOptions = CalendarUtils.getSqlCalendarTypeOptionsInString(calendarTypeOptions); sql = rm.schema() + " and ci.entity_id = ? and ci.entity_type_enum = ? and c.calendar_type_enum in ( " + sqlCalendarTypeOptions + " ) order by c.start_date "; result = this.jdbcTemplate.query(sql, rm, new Object[] { entityId, entityTypeId }); } return result; } - + @Override public CalendarData retrieveCollctionCalendarByEntity(final Long entityId, final Integer entityTypeId) { final CalendarDataMapper rm = new CalendarDataMapper(); - String sql = rm.schema() + " and ci.entity_id = ? and ci.entity_type_enum = ? and calendar_type_enum = ? order by c.start_date "; - List result = this.jdbcTemplate.query(sql, rm, new Object[] { entityId, entityTypeId, CalendarType.COLLECTION.getValue() }); + final String sql = rm.schema() + + " and ci.entity_id = ? and ci.entity_type_enum = ? and calendar_type_enum = ? order by c.start_date "; + final List result = this.jdbcTemplate.query(sql, rm, + new Object[] { entityId, entityTypeId, CalendarType.COLLECTION.getValue() }); + + if (!result.isEmpty() && result.size() > 0) { return result.get(0); } - if(!result.isEmpty() && result.size() > 0){ - return result.get(0); - } - return null; } @@ -146,8 +150,8 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ final CalendarDataMapper rm = new CalendarDataMapper(); Collection result = null; String sql = ""; - CalendarEntityType ceType = CalendarEntityType.fromInt(entityTypeId); - String parentHeirarchyCondition = getParentHierarchyCondition(ceType); + final CalendarEntityType ceType = CalendarEntityType.fromInt(entityTypeId); + final String parentHeirarchyCondition = getParentHierarchyCondition(ceType); // FIXME :AA center is the parent entity of group, change this code to // support more parent entity types. @@ -155,7 +159,7 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ sql = rm.schema() + " " + parentHeirarchyCondition + " and ci.entity_type_enum = ? order by c.start_date "; result = this.jdbcTemplate.query(sql, rm, new Object[] { entityId, CalendarEntityType.CENTERS.getValue() }); } else { - String sqlCalendarTypeOptions = CalendarUtils.getSqlCalendarTypeOptionsInString(calendarTypeOptions); + final String sqlCalendarTypeOptions = CalendarUtils.getSqlCalendarTypeOptionsInString(calendarTypeOptions); sql = rm.schema() + " " + parentHeirarchyCondition + " and ci.entity_type_enum = ? and c.calendar_type_enum in (" + sqlCalendarTypeOptions + ") order by c.start_date "; result = this.jdbcTemplate.query(sql, rm, new Object[] { entityId, CalendarEntityType.CENTERS.getValue() }); @@ -182,31 +186,33 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ public CalendarData generateRecurringDate(final CalendarData calendarData) { return generateRecurringDate(calendarData, null); } - + @Override - public CalendarData generateRecurringDate(CalendarData calendarData, LocalDate tillDate) { - if (!calendarData.isRepeating()) return calendarData; + public CalendarData generateRecurringDate(final CalendarData calendarData, final LocalDate tillDate) { + if (!calendarData.isRepeating()) { return calendarData; } final String rrule = calendarData.getRecurrence(); final LocalDate currentDate = DateUtils.getLocalDateOfTenant(); - LocalDate seedDate = calendarData.getStartDate(); + final LocalDate seedDate = calendarData.getStartDate(); LocalDate endDate = calendarData.getEndDate(); LocalDate startDate = calendarData.getStartDate(); if (seedDate.isBefore(currentDate.minusYears(1))) { startDate = currentDate.minusYears(1); } - if(tillDate != null){ - if(endDate != null){ - if(endDate.isAfter(tillDate)){ - endDate = tillDate;//to retrieve meeting dates till specified date (tillDate) - } - }else{ - endDate = tillDate;//end date is null then fetch meeting dates tillDate + if (tillDate != null) { + if (endDate != null) { + if (endDate.isAfter(tillDate)) { + endDate = tillDate;// to retrieve meeting dates till + // specified date (tillDate) + } + } else { + endDate = tillDate;// end date is null then fetch meeting dates + // tillDate } - }else if (endDate == null || endDate.isAfter(currentDate.plusYears(1))) { + } else if (endDate == null || endDate.isAfter(currentDate.plusYears(1))) { endDate = currentDate.plusYears(1); } - + final Collection recurringDates = CalendarUtils.getRecurringDates(rrule, seedDate, startDate, endDate, -1); final Collection nextTenRecurringDates = CalendarUtils.getRecurringDates(rrule, seedDate, endDate); final LocalDate recentEligibleMeetingDate = CalendarUtils.getRecentEligibleMeetingDate(rrule, seedDate); @@ -216,9 +222,9 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ @Override public Collection generateRecurringDates(final Collection calendarsData) { - Collection recuCalendarsData = new ArrayList(); + final Collection recuCalendarsData = new ArrayList(); - for (CalendarData calendarData : calendarsData) { + for (final CalendarData calendarData : calendarsData) { recuCalendarsData.add(generateRecurringDate(calendarData)); } @@ -235,7 +241,7 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ new Object[] { loanId, CalendarEntityType.LOANS.getValue() }); if (!CollectionUtils.isEmpty(calendars)) { - for (CalendarData calendar : calendars) { + for (final CalendarData calendar : calendars) { calendarData = calendar; break;// Loans are associated with only one calendar } @@ -271,5 +277,5 @@ public class CalendarReadPlatformServiceImpl implements CalendarReadPlatformServ return conditionSql; } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarUtils.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarUtils.java index a3b27ee19..685da4f19 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarUtils.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarUtils.java @@ -48,15 +48,15 @@ public class CalendarUtils { final Date nextRecDate = recur.getNextDate(seed, periodStart); return nextRecDate == null ? null : new LocalDate(nextRecDate); } - - private static Date convertToiCal4JCompatibleDate(final LocalDate inputDate){ - // Date format in iCal4J is hard coded + + private static Date convertToiCal4JCompatibleDate(final LocalDate inputDate) { + // Date format in iCal4J is hard coded Date formattedDate = null; final DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); final String seedDateStr = df.format(inputDate.toDateTimeAtStartOfDay().toDate()); try { formattedDate = new Date(seedDateStr, "yyyy-MM-dd"); - } catch (ParseException e) { + } catch (final ParseException e) { e.printStackTrace(); } return formattedDate; @@ -68,8 +68,9 @@ public class CalendarUtils { final LocalDate periodEndDate = (endDate == null) ? DateUtils.getLocalDateOfTenant().plusYears(5) : endDate; return getRecurringDates(recurringRule, seedDate, periodStartDate, periodEndDate); } - - public static Collection getRecurringDatesFrom(final String recurringRule, final LocalDate seedDate, final LocalDate startDate) { + + public static Collection getRecurringDatesFrom(final String recurringRule, final LocalDate seedDate, + final LocalDate startDate) { final LocalDate periodStartDate = (startDate == null) ? DateUtils.getLocalDateOfTenant() : startDate; final LocalDate periodEndDate = DateUtils.getLocalDateOfTenant().plusYears(5); return getRecurringDates(recurringRule, seedDate, periodStartDate, periodEndDate); @@ -86,8 +87,7 @@ public class CalendarUtils { final Recur recur = CalendarUtils.getICalRecur(recurringRule); - return getRecurringDates(recur, seedDate, periodStartDate, - periodEndDate, maxCount); + return getRecurringDates(recur, seedDate, periodStartDate, periodEndDate, maxCount); } private static Collection getRecurringDates(final Recur recur, final LocalDate seedDate, final LocalDate periodStartDate, @@ -209,196 +209,207 @@ public class CalendarUtils { return humanReadable; } - - public static boolean isValidRedurringDate(final String recurringRule, final LocalDate seedDate, final LocalDate date){ - - final Recur recur = CalendarUtils.getICalRecur(recurringRule); - if (recur == null) { return false; } - - return isValidRecurringDate(recur, seedDate, date); + + public static boolean isValidRedurringDate(final String recurringRule, final LocalDate seedDate, final LocalDate date) { + + final Recur recur = CalendarUtils.getICalRecur(recurringRule); + if (recur == null) { return false; } + + return isValidRecurringDate(recur, seedDate, date); } - - public static boolean isValidRecurringDate(final Recur recur, final LocalDate seedDate, final LocalDate date){ - + + public static boolean isValidRecurringDate(final Recur recur, final LocalDate seedDate, final LocalDate date) { + final Collection recurDate = getRecurringDates(recur, seedDate, date, date.plusDays(1), 1); return (recurDate == null || recurDate.isEmpty()) ? false : true; } - - public static enum DayNameEnum{ + + public static enum DayNameEnum { MO(1, "Monday"), TU(2, "Tuesday"), WE(3, "Wednesday"), TH(4, "Thursday"), FR(5, "Friday"), SA(6, "Saturday"), SU(7, "Sunday"); + private final String code; private final Integer value; - private DayNameEnum(final Integer value, final String code){ + + private DayNameEnum(final Integer value, final String code) { this.value = value; this.code = code; } - - public String getCode(){ + + public String getCode() { return this.code; } - + public int getValue() { return this.value; } - public static DayNameEnum from(String name){ - for (DayNameEnum dayName : DayNameEnum.values()){ - if(dayName.toString().equals(name)) return dayName; + public static DayNameEnum from(final String name) { + for (final DayNameEnum dayName : DayNameEnum.values()) { + if (dayName.toString().equals(name)) { return dayName; } } - return DayNameEnum.MO;//Default it to Monday + return DayNameEnum.MO;// Default it to Monday } } - - public static PeriodFrequencyType getMeetingPeriodFrequencyType(final String recurringRule){ - final Recur recur = CalendarUtils.getICalRecur(recurringRule); - PeriodFrequencyType meetingFrequencyType = PeriodFrequencyType.INVALID; - if(recur.getFrequency().equals(Recur.DAILY)){ - meetingFrequencyType = PeriodFrequencyType.DAYS; - }else if(recur.getFrequency().equals(Recur.WEEKLY)){ - meetingFrequencyType = PeriodFrequencyType.WEEKS; - }else if(recur.getFrequency().equals(Recur.MONTHLY)){ - meetingFrequencyType = PeriodFrequencyType.MONTHS; - }else if(recur.getFrequency().equals(Recur.YEARLY)){ - meetingFrequencyType = PeriodFrequencyType.YEARS; - } - return meetingFrequencyType; + + public static PeriodFrequencyType getMeetingPeriodFrequencyType(final String recurringRule) { + final Recur recur = CalendarUtils.getICalRecur(recurringRule); + PeriodFrequencyType meetingFrequencyType = PeriodFrequencyType.INVALID; + if (recur.getFrequency().equals(Recur.DAILY)) { + meetingFrequencyType = PeriodFrequencyType.DAYS; + } else if (recur.getFrequency().equals(Recur.WEEKLY)) { + meetingFrequencyType = PeriodFrequencyType.WEEKS; + } else if (recur.getFrequency().equals(Recur.MONTHLY)) { + meetingFrequencyType = PeriodFrequencyType.MONTHS; + } else if (recur.getFrequency().equals(Recur.YEARLY)) { + meetingFrequencyType = PeriodFrequencyType.YEARS; + } + return meetingFrequencyType; } - - public static String getMeetingFrequencyFromPeriodFrequencyType(final PeriodFrequencyType periodFrequency){ - String frequency = null; - if(periodFrequency.equals(PeriodFrequencyType.DAYS)){ - frequency = Recur.DAILY; - }else if(periodFrequency.equals(PeriodFrequencyType.WEEKS)){ - frequency = Recur.WEEKLY; - }else if(periodFrequency.equals(PeriodFrequencyType.MONTHS)){ - frequency = Recur.MONTHLY; - }else if(periodFrequency.equals(PeriodFrequencyType.YEARS)){ - frequency = Recur.YEARLY; - } - return frequency; + + public static String getMeetingFrequencyFromPeriodFrequencyType(final PeriodFrequencyType periodFrequency) { + String frequency = null; + if (periodFrequency.equals(PeriodFrequencyType.DAYS)) { + frequency = Recur.DAILY; + } else if (periodFrequency.equals(PeriodFrequencyType.WEEKS)) { + frequency = Recur.WEEKLY; + } else if (periodFrequency.equals(PeriodFrequencyType.MONTHS)) { + frequency = Recur.MONTHLY; + } else if (periodFrequency.equals(PeriodFrequencyType.YEARS)) { + frequency = Recur.YEARLY; + } + return frequency; } - - public static int getInterval(final String recurringRule){ - final Recur recur = CalendarUtils.getICalRecur(recurringRule); - return recur.getInterval(); + + public static int getInterval(final String recurringRule) { + final Recur recur = CalendarUtils.getICalRecur(recurringRule); + return recur.getInterval(); } - - public static LocalDate getFirstRepaymentMeetingDate(final Calendar calendar, final LocalDate disbursementDate, final Integer loanRepaymentInterval, final String frequency){ - final Recur recur = CalendarUtils.getICalRecur(calendar.getRecurrence()); - if (recur == null) { return null; } - LocalDate startDate = disbursementDate; - final LocalDate seedDate = calendar.getStartDateLocalDate(); - if(isValidRedurringDate(calendar.getRecurrence(), seedDate, startDate)){ - startDate = startDate.plusDays(1); - } - //Recurring dates should follow loanRepaymentInterval. - //e.g. - // for weekly meeting interval is 1 - //where as for loan product with fortnightly frequency interval is 2 - //to generate currect set of meeting dates reset interval same as loan repayment interval. - recur.setInterval(loanRepaymentInterval); - - //Recurring dates should follow loanRepayment frequency. - //e.g. - // daily meeting frequency should support all loan products with any frequency type. - //to generate currect set of meeting dates reset frequency same as loan repayment frequency. - if(recur.getFrequency().equals(Recur.DAILY)){ - recur.setFrequency(frequency); - } - - final LocalDate firstRepaymentDate = getNextRecurringDate(recur, seedDate, startDate); - - return firstRepaymentDate; + + public static LocalDate getFirstRepaymentMeetingDate(final Calendar calendar, final LocalDate disbursementDate, + final Integer loanRepaymentInterval, final String frequency) { + final Recur recur = CalendarUtils.getICalRecur(calendar.getRecurrence()); + if (recur == null) { return null; } + LocalDate startDate = disbursementDate; + final LocalDate seedDate = calendar.getStartDateLocalDate(); + if (isValidRedurringDate(calendar.getRecurrence(), seedDate, startDate)) { + startDate = startDate.plusDays(1); + } + // Recurring dates should follow loanRepaymentInterval. + // e.g. + // for weekly meeting interval is 1 + // where as for loan product with fortnightly frequency interval is 2 + // to generate currect set of meeting dates reset interval same as loan + // repayment interval. + recur.setInterval(loanRepaymentInterval); + + // Recurring dates should follow loanRepayment frequency. + // e.g. + // daily meeting frequency should support all loan products with any + // frequency type. + // to generate currect set of meeting dates reset frequency same as loan + // repayment frequency. + if (recur.getFrequency().equals(Recur.DAILY)) { + recur.setFrequency(frequency); + } + + final LocalDate firstRepaymentDate = getNextRecurringDate(recur, seedDate, startDate); + + return firstRepaymentDate; } - - public static LocalDate getNewRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, final LocalDate oldRepaymentDate, final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays){ + + public static LocalDate getNewRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, + final LocalDate oldRepaymentDate, final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays) { final Recur recur = CalendarUtils.getICalRecur(recurringRule); if (recur == null) { return null; } - if(isValidRecurringDate(recur, seedDate, oldRepaymentDate)){ - return oldRepaymentDate; - } - return getNextRepaymentMeetingDate(recurringRule, seedDate, oldRepaymentDate, loanRepaymentInterval, frequency, workingDays); + if (isValidRecurringDate(recur, seedDate, oldRepaymentDate)) { return oldRepaymentDate; } + return getNextRepaymentMeetingDate(recurringRule, seedDate, oldRepaymentDate, loanRepaymentInterval, frequency, workingDays); } - - public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, final LocalDate repaymentDate, final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays){ - + + public static LocalDate getNextRepaymentMeetingDate(final String recurringRule, final LocalDate seedDate, + final LocalDate repaymentDate, final Integer loanRepaymentInterval, final String frequency, final WorkingDays workingDays) { + final Recur recur = CalendarUtils.getICalRecur(recurringRule); if (recur == null) { return null; } LocalDate tmpDate = repaymentDate; - if(isValidRecurringDate(recur, seedDate, repaymentDate)){ + if (isValidRecurringDate(recur, seedDate, repaymentDate)) { tmpDate = repaymentDate.plusDays(1); } - /* Recurring dates should follow loanRepaymentInterval. + /* + * Recurring dates should follow loanRepaymentInterval. * - e.g. The weekly meeting will have interval of 1, if the loan product with fortnightly frequency will have interval of 2, - to generate right set of meeting dates reset interval same as loan repayment interval. - */ + * e.g. The weekly meeting will have interval of 1, if the loan product + * with fortnightly frequency will have interval of 2, to generate right + * set of meeting dates reset interval same as loan repayment interval. + */ recur.setInterval(loanRepaymentInterval); - - /*Recurring dates should follow loanRepayment frequency. - //e.g. daily meeting frequency should support all loan products with any type of frequency. - to generate right set of meeting dates reset frequency same as loan repayment frequency. - */ - if(recur.getFrequency().equals(Recur.DAILY)){ - recur.setFrequency(frequency); + + /* + * Recurring dates should follow loanRepayment frequency. //e.g. daily + * meeting frequency should support all loan products with any type of + * frequency. to generate right set of meeting dates reset frequency + * same as loan repayment frequency. + */ + if (recur.getFrequency().equals(Recur.DAILY)) { + recur.setFrequency(frequency); } - + LocalDate newRepaymentDate = getNextRecurringDate(recur, seedDate, tmpDate); - LocalDate nextRepaymentDate = getNextRecurringDate(recur, seedDate, newRepaymentDate); - + final LocalDate nextRepaymentDate = getNextRecurringDate(recur, seedDate, newRepaymentDate); + newRepaymentDate = WorkingDaysUtil.getOffSetDateIfNonWorkingDay(newRepaymentDate, nextRepaymentDate, workingDays); - + return newRepaymentDate; } - + public static boolean isFrequencySame(final String oldRRule, final String newRRule) { - Recur oldRecur = getICalRecur(oldRRule); - Recur newRecur = getICalRecur(newRRule); + final Recur oldRecur = getICalRecur(oldRRule); + final Recur newRecur = getICalRecur(newRRule); if (oldRecur == null || oldRecur.getFrequency() == null || newRecur == null || newRecur.getFrequency() == null) { return false; } return oldRecur.getFrequency().equals(newRecur.getFrequency()); } - + public static boolean isIntervalSame(final String oldRRule, final String newRRule) { - Recur oldRecur = getICalRecur(oldRRule); - Recur newRecur = getICalRecur(newRRule); + final Recur oldRecur = getICalRecur(oldRRule); + final Recur newRecur = getICalRecur(newRRule); if (oldRecur == null || oldRecur.getFrequency() == null || newRecur == null || newRecur.getFrequency() == null) { return false; } return (oldRecur.getInterval() == newRecur.getInterval()); } - - public static List createIntegerListFromQueryParameter(String calendarTypeQuery) { - List calendarTypeOptions = new ArrayList(); + + public static List createIntegerListFromQueryParameter(final String calendarTypeQuery) { + final List calendarTypeOptions = new ArrayList(); // adding all calendar Types if query parameter is "all" - if(calendarTypeQuery.equalsIgnoreCase("all")){ + if (calendarTypeQuery.equalsIgnoreCase("all")) { calendarTypeOptions.add(1); calendarTypeOptions.add(2); calendarTypeOptions.add(3); calendarTypeOptions.add(4); return calendarTypeOptions; } - // creating a list of calendar type options from the comma separated query parameter. - List calendarTypeOptionsInQuery = new ArrayList(); - StringTokenizer st = new StringTokenizer(calendarTypeQuery, ","); + // creating a list of calendar type options from the comma separated + // query parameter. + final List calendarTypeOptionsInQuery = new ArrayList(); + final StringTokenizer st = new StringTokenizer(calendarTypeQuery, ","); while (st.hasMoreElements()) { calendarTypeOptionsInQuery.add(st.nextElement().toString()); } - for(String calType : calendarTypeOptionsInQuery){ - if(calType.equalsIgnoreCase("collection")) { + for (final String calType : calendarTypeOptionsInQuery) { + if (calType.equalsIgnoreCase("collection")) { calendarTypeOptions.add(1); - } else if(calType.equalsIgnoreCase("training")) { + } else if (calType.equalsIgnoreCase("training")) { calendarTypeOptions.add(2); - } else if(calType.equalsIgnoreCase("audit")) { + } else if (calType.equalsIgnoreCase("audit")) { calendarTypeOptions.add(3); - } else if(calType.equalsIgnoreCase("general")) { + } else if (calType.equalsIgnoreCase("general")) { calendarTypeOptions.add(4); } } return calendarTypeOptions; } - + /** * function returns a comma separated list of calendar_type_enum values ex. * 1,2,3,4 @@ -408,33 +419,31 @@ public class CalendarUtils { */ public static String getSqlCalendarTypeOptionsInString(final List calendarTypeOptions) { String sqlCalendarTypeOptions = ""; - int size = calendarTypeOptions.size(); + final int size = calendarTypeOptions.size(); for (int i = 0; i < size - 1; i++) { sqlCalendarTypeOptions += calendarTypeOptions.get(i).toString() + ","; } sqlCalendarTypeOptions += calendarTypeOptions.get(size - 1).toString(); return sqlCalendarTypeOptions; } - - public static LocalDate getRecentEligibleMeetingDate(final String recurringRule, final LocalDate seedDate){ + + public static LocalDate getRecentEligibleMeetingDate(final String recurringRule, final LocalDate seedDate) { LocalDate currentDate = DateUtils.getLocalDateOfTenant(); final Recur recur = CalendarUtils.getICalRecur(recurringRule); if (recur == null) { return null; } - - if(isValidRecurringDate(recur, seedDate, currentDate)){ - return currentDate; - } - - if(recur.getFrequency().equals(Recur.DAILY)){ + + if (isValidRecurringDate(recur, seedDate, currentDate)) { return currentDate; } + + if (recur.getFrequency().equals(Recur.DAILY)) { currentDate = currentDate.plusDays(recur.getInterval()); - }else if(recur.getFrequency().equals(Recur.WEEKLY)){ + } else if (recur.getFrequency().equals(Recur.WEEKLY)) { currentDate = currentDate.plusWeeks(recur.getInterval()); - }else if(recur.getFrequency().equals(Recur.MONTHLY)){ + } else if (recur.getFrequency().equals(Recur.MONTHLY)) { currentDate = currentDate.plusMonths(recur.getInterval()); - }else if(recur.getFrequency().equals(Recur.YEARLY)){ + } else if (recur.getFrequency().equals(Recur.YEARLY)) { currentDate = currentDate.plusYears(recur.getInterval()); } - + return getNextRecurringDate(recur, seedDate, currentDate); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarWritePlatformService.java index d5d3c0c0b..c0dd74baa 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarWritePlatformService.java @@ -15,8 +15,8 @@ public interface CalendarWritePlatformService { CommandProcessingResult updateCalendar(JsonCommand command); CommandProcessingResult deleteCalendar(Long calendarId); - + CommandProcessingResult createCalendarInstance(Long calendarId, Long entityId, Integer entityTypeId); - + CommandProcessingResult updateCalendarInstance(Long calendarId, Long entityId, Integer entityTypeId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarWritePlatformServiceJpaRepositoryImpl.java index a329a15b1..fbbee1587 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/calendar/service/CalendarWritePlatformServiceJpaRepositoryImpl.java @@ -36,7 +36,8 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr @Autowired public CalendarWritePlatformServiceJpaRepositoryImpl(final CalendarRepository calendarRepository, final CalendarCommandFromApiJsonDeserializer fromApiJsonDeserializer, - final CalendarInstanceRepository calendarInstanceRepository, final LoanWritePlatformService loanWritePlatformService, final ConfigurationDomainService configurationDomainService) { + final CalendarInstanceRepository calendarInstanceRepository, final LoanWritePlatformService loanWritePlatformService, + final ConfigurationDomainService configurationDomainService) { this.calendarRepository = calendarRepository; this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.calendarInstanceRepository = calendarInstanceRepository; @@ -75,14 +76,18 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr if (!changes.isEmpty()) { this.calendarRepository.saveAndFlush(calendarForUpdate); - - if(this.configurationDomainService.isRescheduleFutureRepaymentsEnabled()){ - //In this approach loans following this meeting calendar will be affected immediately. - //get all calendar instances following this meeting calendar and calendar entity type is loan - final Collection loanCalendarInstances = this.calendarInstanceRepository.findByCalendarIdAndEntityTypeId(calendarId, CalendarEntityType.LOANS.getValue()); - + + if (this.configurationDomainService.isRescheduleFutureRepaymentsEnabled()) { + // In this approach loans following this meeting calendar will + // be affected immediately. + // get all calendar instances following this meeting calendar + // and calendar entity type is loan + final Collection loanCalendarInstances = this.calendarInstanceRepository.findByCalendarIdAndEntityTypeId( + calendarId, CalendarEntityType.LOANS.getValue()); + if (!CollectionUtils.isEmpty(loanCalendarInstances)) { - // update all loans which are following this meeting calendar + // update all loans which are following this meeting + // calendar this.loanWritePlatformService.applyMeetingDateChanges(calendarForUpdate, loanCalendarInstances); // } @@ -113,26 +118,27 @@ public class CalendarWritePlatformServiceJpaRepositoryImpl implements CalendarWr final Calendar calendarForUpdate = this.calendarRepository.findOne(calendarId); if (calendarForUpdate == null) { throw new CalendarNotFoundException(calendarId); } - + final CalendarInstance newCalendarInstance = new CalendarInstance(calendarForUpdate, entityId, entityTypeId); this.calendarInstanceRepository.save(newCalendarInstance); - + return new CommandProcessingResultBuilder() // - .withCommandId(null) // - .withEntityId(calendarForUpdate.getId()) // - .build(); + .withCommandId(null) // + .withEntityId(calendarForUpdate.getId()) // + .build(); } @Override - public CommandProcessingResult updateCalendarInstance(Long calendarId, Long entityId, Integer entityTypeId) { + public CommandProcessingResult updateCalendarInstance(final Long calendarId, final Long entityId, final Integer entityTypeId) { final Calendar calendarForUpdate = this.calendarRepository.findOne(calendarId); if (calendarForUpdate == null) { throw new CalendarNotFoundException(calendarId); } - - final CalendarInstance calendarInstanceForUpdate = this.calendarInstanceRepository.findByCalendarIdAndEntityIdAndEntityTypeId(calendarId, entityId, entityTypeId); + + final CalendarInstance calendarInstanceForUpdate = this.calendarInstanceRepository.findByCalendarIdAndEntityIdAndEntityTypeId( + calendarId, entityId, entityTypeId); this.calendarInstanceRepository.saveAndFlush(calendarInstanceForUpdate); return new CommandProcessingResultBuilder() // - .withCommandId(null) // - .withEntityId(calendarForUpdate.getId()) // - .build(); + .withCommandId(null) // + .withEntityId(calendarForUpdate.getId()) // + .build(); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/api/ChargesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/api/ChargesApiResource.java index bbc9b8c6d..b5d8e2261 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/api/ChargesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/api/ChargesApiResource.java @@ -69,12 +69,12 @@ public class ChargesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllCharges(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Collection charges = this.readPlatformService.retrieveAllCharges(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, charges, CHARGES_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, charges, this.CHARGES_DATA_PARAMETERS); } @GET @@ -83,17 +83,17 @@ public class ChargesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveCharge(@PathParam("chargeId") final Long chargeId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); ChargeData charge = this.readPlatformService.retrieveCharge(chargeId); if (settings.isTemplate()) { - ChargeData templateData = this.readPlatformService.retrieveNewChargeDetails(); + final ChargeData templateData = this.readPlatformService.retrieveNewChargeDetails(); charge = ChargeData.withTemplate(charge, templateData); } - return this.toApiJsonSerializer.serialize(settings, charge, CHARGES_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, charge, this.CHARGES_DATA_PARAMETERS); } @GET @@ -102,12 +102,12 @@ public class ChargesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveNewChargeDetails(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final ChargeData charge = this.readPlatformService.retrieveNewChargeDetails(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, charge, CHARGES_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, charge, this.CHARGES_DATA_PARAMETERS); } @POST diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/data/ChargeData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/data/ChargeData.java index cfba9aecc..7ad450aa7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/data/ChargeData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/data/ChargeData.java @@ -40,48 +40,50 @@ public class ChargeData implements Comparable, Serializable { public static ChargeData template(final Collection currencyOptions, final List chargeCalculationTypeOptions, final List chargeAppliesToOptions, - final List chargeTimeTypeOptions, List chargePaymentModeOptions) { - return new ChargeData(null, null, null, null, null, null, null, null, false, false, currencyOptions, - chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, chargePaymentModeOptions); + final List chargeTimeTypeOptions, final List chargePaymentModeOptions) { + return new ChargeData(null, null, null, null, null, null, null, null, false, false, currencyOptions, chargeCalculationTypeOptions, + chargeAppliesToOptions, chargeTimeTypeOptions, chargePaymentModeOptions); } public static ChargeData withTemplate(final ChargeData charge, final ChargeData template) { return new ChargeData(charge.id, charge.name, charge.amount, charge.currency, charge.chargeTimeType, charge.chargeAppliesTo, - charge.chargeCalculationType, charge.chargePaymentMode, charge.penalty, charge.active, - template.currencyOptions, template.chargeCalculationTypeOptions, template.chargeAppliesToOptions, template.chargeTimeTypeOptions, + charge.chargeCalculationType, charge.chargePaymentMode, charge.penalty, charge.active, template.currencyOptions, + template.chargeCalculationTypeOptions, template.chargeAppliesToOptions, template.chargeTimeTypeOptions, template.chargePaymetModeOptions); } public static ChargeData instance(final Long id, final String name, final BigDecimal amount, final CurrencyData currency, final EnumOptionData chargeTimeType, final EnumOptionData chargeAppliesTo, final EnumOptionData chargeCalculationType, final EnumOptionData chargePaymentMode, final boolean penalty, final boolean active) { - return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode, penalty, active, - null, null, null, null, null); + return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode, + penalty, active, null, null, null, null, null); } public static ChargeData lookup(final Long id, final String name, final boolean isPenalty) { - BigDecimal amount = null; - CurrencyData currency = null; - EnumOptionData chargeTimeType = null; - EnumOptionData chargeAppliesTo = null; - EnumOptionData chargeCalculationType = null; - EnumOptionData chargePaymentMode = null; - Boolean penalty = isPenalty; - Boolean active = false; - Collection currencyOptions = null; - List chargeCalculationTypeOptions = null; - List chargeAppliesToOptions = null; - List chargeTimeTypeOptions = null; - List chargePaymentModeOptions = null; - return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode, penalty, - active, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, chargePaymentModeOptions); + final BigDecimal amount = null; + final CurrencyData currency = null; + final EnumOptionData chargeTimeType = null; + final EnumOptionData chargeAppliesTo = null; + final EnumOptionData chargeCalculationType = null; + final EnumOptionData chargePaymentMode = null; + final Boolean penalty = isPenalty; + final Boolean active = false; + final Collection currencyOptions = null; + final List chargeCalculationTypeOptions = null; + final List chargeAppliesToOptions = null; + final List chargeTimeTypeOptions = null; + final List chargePaymentModeOptions = null; + return new ChargeData(id, name, amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, chargePaymentMode, + penalty, active, currencyOptions, chargeCalculationTypeOptions, chargeAppliesToOptions, chargeTimeTypeOptions, + chargePaymentModeOptions); } private ChargeData(final Long id, final String name, final BigDecimal amount, final CurrencyData currency, final EnumOptionData chargeTimeType, final EnumOptionData chargeAppliesTo, final EnumOptionData chargeCalculationType, - EnumOptionData chargePaymentMode, final boolean penalty, final boolean active, + final EnumOptionData chargePaymentMode, final boolean penalty, final boolean active, final Collection currencyOptions, final List chargeCalculationTypeOptions, - final List chargeAppliesToOptions, final List chargeTimeTypeOptions, List chargePaymentModeOptions) { + final List chargeAppliesToOptions, final List chargeTimeTypeOptions, + final List chargePaymentModeOptions) { this.id = id; this.name = name; this.amount = amount; @@ -101,7 +103,7 @@ public class ChargeData implements Comparable, Serializable { @Override public boolean equals(final Object obj) { - ChargeData chargeData = (ChargeData) obj; + final ChargeData chargeData = (ChargeData) obj; return this.id.equals(chargeData.id); } @@ -125,11 +127,11 @@ public class ChargeData implements Comparable, Serializable { } return LoanChargeData.newLoanChargeDetails(this.id, this.name, this.currency, this.amount, percentage, this.chargeTimeType, - this.chargeCalculationType, this.penalty,this.chargePaymentMode); + this.chargeCalculationType, this.penalty, this.chargePaymentMode); } - - public SavingsAccountChargeData toSavingsAccountChargeData(){ - + + public SavingsAccountChargeData toSavingsAccountChargeData() { + final Long savingsChargeId = null; final BigDecimal amountPaid = BigDecimal.ZERO; final BigDecimal amountWaived = BigDecimal.ZERO; @@ -139,7 +141,7 @@ public class ChargeData implements Comparable, Serializable { final BigDecimal amountPercentageAppliedTo = BigDecimal.ZERO; final Collection chargeOptions = null; final LocalDate dueAsOfDate = null; - + return SavingsAccountChargeData.instance(savingsChargeId, this.id, this.name, this.currency, this.amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, this.chargeTimeType, dueAsOfDate, this.chargeCalculationType, percentage, amountPercentageAppliedTo, chargeOptions, this.penalty); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/Charge.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/Charge.java index 4ce9e5914..0562aacb0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/Charge.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/Charge.java @@ -52,7 +52,7 @@ public class Charge extends AbstractPersistable { @Column(name = "charge_calculation_enum") private Integer chargeCalculation; - + @Column(name = "charge_payment_mode_enum") private Integer chargePaymentMode; @@ -88,8 +88,8 @@ public class Charge extends AbstractPersistable { } private Charge(final String name, final BigDecimal amount, final String currencyCode, final ChargeAppliesTo chargeAppliesTo, - final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculationType, final boolean penalty, final boolean active, - final ChargePaymentMode paymentMode) { + final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculationType, final boolean penalty, + final boolean active, final ChargePaymentMode paymentMode) { this.name = name; this.amount = amount; this.currencyCode = currencyCode; @@ -114,14 +114,14 @@ public class Charge extends AbstractPersistable { baseDataValidator.reset().parameter("chargeCalculationType").value(this.chargeCalculation) .failWithCodeNoParameterAddedToErrorCode("not.allowed.charge.calculation.type.for.savings"); } - + } else if (isLoanCharge()) { - + if (penalty && chargeTime.isTimeOfDisbursement()) { throw new ChargeDueAtDisbursementCannotBePenaltyException(name); } - + if (!isAllowedLoanChargeTime()) { baseDataValidator.reset().parameter("chargeTimeType").value(this.chargeTime) - .failWithCodeNoParameterAddedToErrorCode("not.allowed.charge.time.for.loan"); + .failWithCodeNoParameterAddedToErrorCode("not.allowed.charge.time.for.loan"); } } @@ -133,77 +133,77 @@ public class Charge extends AbstractPersistable { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } - LoanCharge rhs = (LoanCharge) obj; + final LoanCharge rhs = (LoanCharge) obj; return new EqualsBuilder().appendSuper(super.equals(obj)) // - .append(this.getId(), rhs.getId()) // + .append(getId(), rhs.getId()) // .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(3, 5) // - .append(this.getId()) // + .append(getId()) // .toHashCode(); } public String getName() { - return name; + return this.name; } public BigDecimal getAmount() { - return amount; + return this.amount; } public String getCurrencyCode() { - return currencyCode; + return this.currencyCode; } public Integer getChargeTime() { - return chargeTime; + return this.chargeTime; } public Integer getChargeCalculation() { - return chargeCalculation; + return this.chargeCalculation; } public boolean isActive() { - return active; + return this.active; } public boolean isPenalty() { - return penalty; + return this.penalty; } public boolean isDeleted() { - return deleted; + return this.deleted; } - - public boolean isLoanCharge(){ + + public boolean isLoanCharge() { return ChargeAppliesTo.fromInt(this.chargeAppliesTo).isLoanCharge(); } - - public boolean isAllowedLoanChargeTime(){ + + public boolean isAllowedLoanChargeTime() { return ChargeTimeType.fromInt(this.chargeTime).isAllowedLoanChargeTime(); } - - public boolean isSavingsCharge(){ + + public boolean isSavingsCharge() { return ChargeAppliesTo.fromInt(this.chargeAppliesTo).isSavingsCharge(); } - - public boolean isAllowedSavingsChargeTime(){ + + public boolean isAllowedSavingsChargeTime() { return ChargeTimeType.fromInt(this.chargeTime).isAllowedSavingsChargeTime(); } - public boolean isAllowedSavingsChargeCalculationType(){ + public boolean isAllowedSavingsChargeCalculationType() { return ChargeCalculationType.fromInt(this.chargeCalculation).isAllowedSavingsChargeCalculationType(); } - + public Map update(final JsonCommand command) { final Map actualChanges = new LinkedHashMap(7); final String localeAsInput = command.locale(); - + final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charges"); @@ -244,7 +244,7 @@ public class Charge extends AbstractPersistable { } else if (isLoanCharge()) { if (!isAllowedLoanChargeTime()) { baseDataValidator.reset().parameter("chargeTimeType").value(this.chargeTime) - .failWithCodeNoParameterAddedToErrorCode("not.allowed.charge.time.for.loan"); + .failWithCodeNoParameterAddedToErrorCode("not.allowed.charge.time.for.loan"); } } @@ -252,12 +252,15 @@ public class Charge extends AbstractPersistable { final String chargeAppliesToParamName = "chargeAppliesTo"; if (command.isChangeInIntegerParameterNamed(chargeAppliesToParamName, this.chargeAppliesTo)) { - /*final Integer newValue = command.integerValueOfParameterNamed(chargeAppliesToParamName); - actualChanges.put(chargeAppliesToParamName, newValue); - actualChanges.put("locale", localeAsInput); - this.chargeAppliesTo = ChargeAppliesTo.fromInt(newValue).getValue();*/ - - //AA: Do not allow to change chargeAppliesTo. + /* + * final Integer newValue = + * command.integerValueOfParameterNamed(chargeAppliesToParamName); + * actualChanges.put(chargeAppliesToParamName, newValue); + * actualChanges.put("locale", localeAsInput); this.chargeAppliesTo + * = ChargeAppliesTo.fromInt(newValue).getValue(); + */ + + // AA: Do not allow to change chargeAppliesTo. final String errorMessage = "Update of Charge applies to is not supported"; throw new ChargeParameterUpdateNotSupportedException("charge.applies.to", errorMessage); } @@ -268,7 +271,7 @@ public class Charge extends AbstractPersistable { actualChanges.put(chargeCalculationParamName, newValue); actualChanges.put("locale", localeAsInput); this.chargeCalculation = ChargeCalculationType.fromInt(newValue).getValue(); - + if (isSavingsCharge()) { if (!isAllowedSavingsChargeCalculationType()) { baseDataValidator.reset().parameter("chargeCalculationType").value(this.chargeCalculation) @@ -276,7 +279,7 @@ public class Charge extends AbstractPersistable { } } } - + final String paymentModeParamName = "chargePaymentMode"; if (command.isChangeInIntegerParameterNamed(paymentModeParamName, this.chargePaymentMode)) { final Integer newValue = command.integerValueOfParameterNamed(paymentModeParamName); @@ -285,7 +288,6 @@ public class Charge extends AbstractPersistable { this.chargePaymentMode = ChargePaymentMode.fromInt(newValue).getValue(); } - final String penaltyParamName = "penalty"; if (command.isChangeInBooleanParameterNamed(penaltyParamName, this.penalty)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(penaltyParamName); @@ -301,10 +303,10 @@ public class Charge extends AbstractPersistable { } if (this.penalty && ChargeTimeType.fromInt(this.chargeTime).isTimeOfDisbursement()) { throw new ChargeDueAtDisbursementCannotBePenaltyException( - name); } - + this.name); } + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } - + return actualChanges; } @@ -316,21 +318,20 @@ public class Charge extends AbstractPersistable { */ public void delete() { this.deleted = true; - this.name = this.getId() + "_" + this.name; + this.name = getId() + "_" + this.name; } public ChargeData toData() { - EnumOptionData chargeTimeType = ChargeEnumerations.chargeTimeType(this.chargeTime); - EnumOptionData chargeAppliesTo = ChargeEnumerations.chargeAppliesTo(this.chargeAppliesTo); - EnumOptionData chargeCalculationType = ChargeEnumerations.chargeCalculationType(this.chargeCalculation); - EnumOptionData chargePaymentmode = ChargeEnumerations.chargePaymentMode(this.chargePaymentMode); - CurrencyData currency = new CurrencyData(this.currencyCode, null, 0, 0, null, null); - return ChargeData.instance(this.getId(), this.name, this.amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, - chargePaymentmode, penalty, active); + final EnumOptionData chargeTimeType = ChargeEnumerations.chargeTimeType(this.chargeTime); + final EnumOptionData chargeAppliesTo = ChargeEnumerations.chargeAppliesTo(this.chargeAppliesTo); + final EnumOptionData chargeCalculationType = ChargeEnumerations.chargeCalculationType(this.chargeCalculation); + final EnumOptionData chargePaymentmode = ChargeEnumerations.chargePaymentMode(this.chargePaymentMode); + final CurrencyData currency = new CurrencyData(this.currencyCode, null, 0, 0, null, null); + return ChargeData.instance(getId(), this.name, this.amount, currency, chargeTimeType, chargeAppliesTo, chargeCalculationType, + chargePaymentmode, this.penalty, this.active); } - public Integer getChargePaymentMode() { return this.chargePaymentMode; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeAppliesTo.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeAppliesTo.java index 85c056c0e..73189df9a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeAppliesTo.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeAppliesTo.java @@ -8,33 +8,32 @@ package org.mifosplatform.portfolio.charge.domain; public enum ChargeAppliesTo { INVALID(0, "chargeAppliesTo.invalid"), // - LOAN(1, "chargeAppliesTo.loan"), - SAVINGS(2, "chargeAppliesTo.savings"); + LOAN(1, "chargeAppliesTo.loan"), SAVINGS(2, "chargeAppliesTo.savings"); private final Integer value; private final String code; - private ChargeAppliesTo(Integer value, String code) { + private ChargeAppliesTo(final Integer value, final String code) { this.value = value; this.code = code; } public Integer getValue() { - return value; + return this.value; } public String getCode() { - return code; + return this.code; } - public static int minValue(){ + public static int minValue() { return 1; } - - public static int maxValue(){ - return 2;//modify whenever a new value added + + public static int maxValue() { + return 2;// modify whenever a new value added } - + public static ChargeAppliesTo fromInt(final Integer chargeAppliesTo) { ChargeAppliesTo chargeAppliesToType = ChargeAppliesTo.INVALID; switch (chargeAppliesTo) { @@ -50,12 +49,12 @@ public enum ChargeAppliesTo { } return chargeAppliesToType; } - - public boolean isLoanCharge(){ + + public boolean isLoanCharge() { return this.value.equals(ChargeAppliesTo.LOAN.getValue()); } - - public boolean isSavingsCharge(){ + + public boolean isSavingsCharge() { return this.value.equals(ChargeAppliesTo.SAVINGS.getValue()); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeCalculationType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeCalculationType.java index fbd70d5bb..22a107ff9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeCalculationType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeCalculationType.java @@ -22,11 +22,11 @@ public enum ChargeCalculationType { } public Integer getValue() { - return value; + return this.value; } public String getCode() { - return code; + return this.code; } public static ChargeCalculationType fromInt(final Integer chargeCalculation) { @@ -47,16 +47,16 @@ public enum ChargeCalculationType { } return chargeCalculationType; } - - public boolean isPercentageOfAmount(){ + + public boolean isPercentageOfAmount() { return this.value.equals(ChargeCalculationType.PERCENT_OF_AMOUNT.getValue()); } - - public boolean isFlat(){ + + public boolean isFlat() { return this.value.equals(ChargeCalculationType.FLAT.getValue()); } - - public boolean isAllowedSavingsChargeCalculationType(){ - return this.isFlat(); + + public boolean isAllowedSavingsChargeCalculationType() { + return isFlat(); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargePaymentMode.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargePaymentMode.java index 1bca59ebc..e802fbeda 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargePaymentMode.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargePaymentMode.java @@ -8,17 +8,17 @@ public enum ChargePaymentMode { private final Integer value; private final String code; - private ChargePaymentMode(Integer value, String code) { + private ChargePaymentMode(final Integer value, final String code) { this.value = value; this.code = code; } public Integer getValue() { - return value; + return this.value; } public String getCode() { - return code; + return this.code; } public static ChargePaymentMode fromInt(final Integer paymentMode) { @@ -33,8 +33,8 @@ public enum ChargePaymentMode { } return chargeAppliesToType; } - - public boolean isPaymentModeAccountTransfer(){ + + public boolean isPaymentModeAccountTransfer() { return this.value.equals(ChargePaymentMode.ACCOUNT_TRANSFER.getValue()); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeTimeType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeTimeType.java index 7b157e749..e79085c51 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeTimeType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/domain/ChargeTimeType.java @@ -5,39 +5,36 @@ */ package org.mifosplatform.portfolio.charge.domain; - public enum ChargeTimeType { INVALID(0, "chargeTimeType.invalid"), // DISBURSEMENT(1, "chargeTimeType.disbursement"), // - SPECIFIED_DUE_DATE(2, "chargeTimeType.specifiedDueDate"), - MONTHLY(3, "chargeTimeType.monthly"), - YEARLY(4, "chargeTimeType.yearly"); + SPECIFIED_DUE_DATE(2, "chargeTimeType.specifiedDueDate"), MONTHLY(3, "chargeTimeType.monthly"), YEARLY(4, "chargeTimeType.yearly"); private final Integer value; private final String code; - private ChargeTimeType(Integer value, String code) { + private ChargeTimeType(final Integer value, final String code) { this.value = value; this.code = code; } public Integer getValue() { - return value; + return this.value; } public String getCode() { - return code; + return this.code; } - public static int minValue(){ + public static int minValue() { return 1; } - - public static int maxValue(){ + + public static int maxValue() { return 4; } - + public static ChargeTimeType fromInt(final Integer chargeTime) { ChargeTimeType chargeTimeType = ChargeTimeType.INVALID; switch (chargeTime) { @@ -63,24 +60,24 @@ public enum ChargeTimeType { public boolean isTimeOfDisbursement() { return ChargeTimeType.DISBURSEMENT.getValue().equals(this.value); } - + public boolean isOnSpecifiedDueDate() { return this.value.equals(ChargeTimeType.SPECIFIED_DUE_DATE.getValue()); } - - public boolean isMonthly(){ + + public boolean isMonthly() { return this.value.equals(ChargeTimeType.MONTHLY.getValue()); } - - public boolean isYearly(){ + + public boolean isYearly() { return this.value.equals(ChargeTimeType.YEARLY.getValue()); } - - public boolean isAllowedLoanChargeTime(){ - return this.isTimeOfDisbursement() || this.isOnSpecifiedDueDate(); + + public boolean isAllowedLoanChargeTime() { + return isTimeOfDisbursement() || isOnSpecifiedDueDate(); } - - public boolean isAllowedSavingsChargeTime(){ - return this.isOnSpecifiedDueDate() || this.isMonthly() || this.isYearly(); + + public boolean isAllowedSavingsChargeTime() { + return isOnSpecifiedDueDate() || isMonthly() || isYearly(); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeCannotBeAppliedToException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeCannotBeAppliedToException.java index 10439f943..354eed8b2 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeCannotBeAppliedToException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeCannotBeAppliedToException.java @@ -2,12 +2,11 @@ package org.mifosplatform.portfolio.charge.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - public class ChargeCannotBeAppliedToException extends AbstractPlatformDomainRuleException { - public ChargeCannotBeAppliedToException(String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { - + public ChargeCannotBeAppliedToException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { + super("error.msg.charge.cannot.be.applied.to" + postFix, defaultUserMessage, defaultUserMessageArgs); } - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeCannotBeDeletedException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeCannotBeDeletedException.java index 517d467cf..f4abe9fac 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeCannotBeDeletedException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeCannotBeDeletedException.java @@ -2,12 +2,12 @@ package org.mifosplatform.portfolio.charge.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - public class ChargeCannotBeDeletedException extends AbstractPlatformDomainRuleException { - public ChargeCannotBeDeletedException(String globalisationMessageCode, String defaultUserMessage, Object... defaultUserMessageArgs) { - + public ChargeCannotBeDeletedException(final String globalisationMessageCode, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { + super(globalisationMessageCode, defaultUserMessage, defaultUserMessageArgs); } - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeParameterUpdateNotSupportedException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeParameterUpdateNotSupportedException.java index b6a23b85d..46c670162 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeParameterUpdateNotSupportedException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/ChargeParameterUpdateNotSupportedException.java @@ -12,7 +12,8 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class ChargeParameterUpdateNotSupportedException extends AbstractPlatformDomainRuleException { - public ChargeParameterUpdateNotSupportedException(String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { + public ChargeParameterUpdateNotSupportedException(final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg.charge.update.of." + postFix + ".is.not.supported", defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeCannotBeAddedException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeCannotBeAddedException.java index eddfb6f04..5b5f9abf6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeCannotBeAddedException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeCannotBeAddedException.java @@ -8,12 +8,14 @@ package org.mifosplatform.portfolio.charge.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown when loan charge is not allowed to be added to the loan. + * {@link AbstractPlatformDomainRuleException} thrown when loan charge is not + * allowed to be added to the loan. */ public class LoanChargeCannotBeAddedException extends AbstractPlatformDomainRuleException { - public LoanChargeCannotBeAddedException(final String entity, final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { - super("error.msg."+entity+".cannot.be.added.as." + postFix, defaultUserMessage, defaultUserMessageArgs); + public LoanChargeCannotBeAddedException(final String entity, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { + super("error.msg." + entity + ".cannot.be.added.as." + postFix, defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeCannotBePayedException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeCannotBePayedException.java index 2f4406979..5db80c6f7 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeCannotBePayedException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeCannotBePayedException.java @@ -19,11 +19,9 @@ public class LoanChargeCannotBePayedException extends AbstractPlatformDomainRule } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { return "This loan charge has already been waived"; } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) { - return "This loan charge can be payed as the loan associated with it is currently inactive"; - }else if(name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) { - return "This loan charge can be payed as the charge payment mode is not account transfer"; - } - + return "This loan charge can be payed as the loan associated with it is currently inactive"; + } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) { return "This loan charge can be payed as the charge payment mode is not account transfer"; } + return name().toString(); } @@ -32,11 +30,9 @@ public class LoanChargeCannotBePayedException extends AbstractPlatformDomainRule return "error.msg.loan.charge.already.paid"; } else if (name().toString().equalsIgnoreCase("ALREADY_WAIVED")) { return "error.msg.loan.charge.already.waived"; - } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) { - return "error.msg.loan.charge.associated.loan.inactive"; - }else if(name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) { - return "error.msg.loan.charge.payment.mode.not.account.transfer"; - } + } else if (name().toString().equalsIgnoreCase("LOAN_INACTIVE")) { + return "error.msg.loan.charge.associated.loan.inactive"; + } else if (name().toString().equalsIgnoreCase("CHARGE_NOT_ACCOUNT_TRANSFER")) { return "error.msg.loan.charge.payment.mode.not.account.transfer"; } return name().toString(); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeWithoutMandatoryFieldException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeWithoutMandatoryFieldException.java index 91d955432..24e227b7b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeWithoutMandatoryFieldException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/LoanChargeWithoutMandatoryFieldException.java @@ -8,12 +8,14 @@ package org.mifosplatform.portfolio.charge.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown when currency mismatch occurs + * {@link AbstractPlatformDomainRuleException} thrown when currency mismatch + * occurs */ public class LoanChargeWithoutMandatoryFieldException extends AbstractPlatformDomainRuleException { - public LoanChargeWithoutMandatoryFieldException(final String entity, final String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg."+entity+"."+postFix+".cannot.be.blank", defaultUserMessage, defaultUserMessageArgs); + public LoanChargeWithoutMandatoryFieldException(final String entity, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { + super("error.msg." + entity + "." + postFix + ".cannot.be.blank", defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/SavingsAccountChargeNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/SavingsAccountChargeNotFoundException.java index b5a3ff80d..917603079 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/SavingsAccountChargeNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/SavingsAccountChargeNotFoundException.java @@ -9,8 +9,8 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * {@link AbstractPlatformDomainRuleException} thrown when savings account charge does not - * exist. + * {@link AbstractPlatformDomainRuleException} thrown when savings account + * charge does not exist. */ public class SavingsAccountChargeNotFoundException extends AbstractPlatformResourceNotFoundException { @@ -19,7 +19,7 @@ public class SavingsAccountChargeNotFoundException extends AbstractPlatformResou } public SavingsAccountChargeNotFoundException(final Long id, final Long savingsAccountId) { - super("error.msg.savings.account.charge.id.invalid.for.given.savings.account", "Savings Account charge with identifier " + id + " does not exist for Savings Account " + savingsAccountId, - id, savingsAccountId); + super("error.msg.savings.account.charge.id.invalid.for.given.savings.account", "Savings Account charge with identifier " + id + + " does not exist for Savings Account " + savingsAccountId, id, savingsAccountId); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/SavingsAccountChargeWithoutMandatoryFieldException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/SavingsAccountChargeWithoutMandatoryFieldException.java index b9b59e0cd..f75c94cac 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/SavingsAccountChargeWithoutMandatoryFieldException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/exception/SavingsAccountChargeWithoutMandatoryFieldException.java @@ -8,12 +8,14 @@ package org.mifosplatform.portfolio.charge.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown when currency mismatch occurs + * {@link AbstractPlatformDomainRuleException} thrown when currency mismatch + * occurs */ public class SavingsAccountChargeWithoutMandatoryFieldException extends AbstractPlatformDomainRuleException { - public SavingsAccountChargeWithoutMandatoryFieldException(final String entity, final String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg."+entity+"."+postFix+".cannot.be.blank", defaultUserMessage, defaultUserMessageArgs); + public SavingsAccountChargeWithoutMandatoryFieldException(final String entity, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { + super("error.msg." + entity + "." + postFix + ".cannot.be.blank", defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/serialization/ChargeDefinitionCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/serialization/ChargeDefinitionCommandFromApiJsonDeserializer.java index 2eb5fb4fb..fb2ce138b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/serialization/ChargeDefinitionCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/serialization/ChargeDefinitionCommandFromApiJsonDeserializer.java @@ -37,7 +37,7 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer { */ private final Set supportedParameters = new HashSet(Arrays.asList("name", "amount", "locale", "currencyCode", "currencyOptions", "chargeAppliesTo", "chargeTimeType", "chargeCalculationType", "chargeCalculationTypeOptions", "penalty", - "active","chargePaymentMode")); + "active", "chargePaymentMode")); private final FromJsonHelper fromApiJsonHelper; @@ -50,41 +50,44 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); - final String currencyCode = fromApiJsonHelper.extractStringNamed("currencyCode", element); + final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element); baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element.getAsJsonObject()); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element.getAsJsonObject()); baseDataValidator.reset().parameter("amount").value(amount).notNull().positiveAmount(); - final Integer chargeAppliesTo = fromApiJsonHelper.extractIntegerNamed("chargeAppliesTo", element, Locale.getDefault()); - baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull().inMinMaxRange(ChargeAppliesTo.minValue(), ChargeAppliesTo.maxValue()); + final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerNamed("chargeAppliesTo", element, Locale.getDefault()); + baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull() + .inMinMaxRange(ChargeAppliesTo.minValue(), ChargeAppliesTo.maxValue()); - final Integer chargeTimeType = fromApiJsonHelper.extractIntegerNamed("chargeTimeType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull().inMinMaxRange(ChargeTimeType.minValue(), ChargeTimeType.maxValue()); + final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed("chargeTimeType", element, Locale.getDefault()); + baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull() + .inMinMaxRange(ChargeTimeType.minValue(), ChargeTimeType.maxValue()); - final Integer chargeCalculationType = fromApiJsonHelper.extractIntegerNamed("chargeCalculationType", element, Locale.getDefault()); + final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed("chargeCalculationType", element, + Locale.getDefault()); baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType).notNull().inMinMaxRange(1, 4); - final Integer chargePaymentMode = fromApiJsonHelper.extractIntegerNamed("chargePaymentMode", element, Locale.getDefault()); + final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerNamed("chargePaymentMode", element, Locale.getDefault()); baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode).notNull().inMinMaxRange(0, 1); - if (fromApiJsonHelper.parameterExists("penalty", element)) { - final Boolean penalty = fromApiJsonHelper.extractBooleanNamed("penalty", element); + if (this.fromApiJsonHelper.parameterExists("penalty", element)) { + final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed("penalty", element); baseDataValidator.reset().parameter("penalty").value(penalty).notNull(); } - if (fromApiJsonHelper.parameterExists("active", element)) { - final Boolean active = fromApiJsonHelper.extractBooleanNamed("active", element); + if (this.fromApiJsonHelper.parameterExists("active", element)) { + final Boolean active = this.fromApiJsonHelper.extractBooleanNamed("active", element); baseDataValidator.reset().parameter("active").value(active).notNull(); } @@ -95,55 +98,57 @@ public final class ChargeDefinitionCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("charge"); - final JsonElement element = fromApiJsonHelper.parse(json); - if (fromApiJsonHelper.parameterExists("name", element)) { - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + if (this.fromApiJsonHelper.parameterExists("name", element)) { + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("currencyCode", element)) { - final String currencyCode = fromApiJsonHelper.extractStringNamed("currencyCode", element); + if (this.fromApiJsonHelper.parameterExists("currencyCode", element)) { + final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element); baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3); } - if (fromApiJsonHelper.parameterExists("amount", element)) { - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element.getAsJsonObject()); + if (this.fromApiJsonHelper.parameterExists("amount", element)) { + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element.getAsJsonObject()); baseDataValidator.reset().parameter("amount").value(amount).notNull().positiveAmount(); } - if (fromApiJsonHelper.parameterExists("chargeAppliesTo", element)) { - final Integer chargeAppliesTo = fromApiJsonHelper.extractIntegerNamed("chargeAppliesTo", element, Locale.getDefault()); - baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull().inMinMaxRange(ChargeAppliesTo.minValue(), ChargeAppliesTo.maxValue()); + if (this.fromApiJsonHelper.parameterExists("chargeAppliesTo", element)) { + final Integer chargeAppliesTo = this.fromApiJsonHelper.extractIntegerNamed("chargeAppliesTo", element, Locale.getDefault()); + baseDataValidator.reset().parameter("chargeAppliesTo").value(chargeAppliesTo).notNull() + .inMinMaxRange(ChargeAppliesTo.minValue(), ChargeAppliesTo.maxValue()); } - if (fromApiJsonHelper.parameterExists("chargeTimeType", element)) { - final Integer chargeTimeType = fromApiJsonHelper.extractIntegerNamed("chargeTimeType", element, Locale.getDefault()); - baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull().inMinMaxRange(ChargeTimeType.minValue(), ChargeTimeType.maxValue()); + if (this.fromApiJsonHelper.parameterExists("chargeTimeType", element)) { + final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed("chargeTimeType", element, Locale.getDefault()); + baseDataValidator.reset().parameter("chargeTimeType").value(chargeTimeType).notNull() + .inMinMaxRange(ChargeTimeType.minValue(), ChargeTimeType.maxValue()); } - if (fromApiJsonHelper.parameterExists("chargeCalculationType", element)) { - final Integer chargeCalculationType = fromApiJsonHelper.extractIntegerNamed("chargeCalculationType", element, + if (this.fromApiJsonHelper.parameterExists("chargeCalculationType", element)) { + final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed("chargeCalculationType", element, Locale.getDefault()); baseDataValidator.reset().parameter("chargeCalculationType").value(chargeCalculationType).notNull().inMinMaxRange(1, 4); } - - if (fromApiJsonHelper.parameterExists("chargePaymentMode", element)) { - final Integer chargePaymentMode = fromApiJsonHelper.extractIntegerNamed("chargePaymentMode", element, Locale.getDefault()); + + if (this.fromApiJsonHelper.parameterExists("chargePaymentMode", element)) { + final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerNamed("chargePaymentMode", element, Locale.getDefault()); baseDataValidator.reset().parameter("chargePaymentMode").value(chargePaymentMode).notNull().inMinMaxRange(0, 1); } - if (fromApiJsonHelper.parameterExists("penalty", element)) { - final Boolean penalty = fromApiJsonHelper.extractBooleanNamed("penalty", element); + if (this.fromApiJsonHelper.parameterExists("penalty", element)) { + final Boolean penalty = this.fromApiJsonHelper.extractBooleanNamed("penalty", element); baseDataValidator.reset().parameter("penalty").value(penalty).notNull(); } - if (fromApiJsonHelper.parameterExists("active", element)) { - final Boolean active = fromApiJsonHelper.extractBooleanNamed("active", element); + if (this.fromApiJsonHelper.parameterExists("active", element)) { + final Boolean active = this.fromApiJsonHelper.extractBooleanNamed("active", element); baseDataValidator.reset().parameter("active").value(active).notNull(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformService.java index 706fac9da..f5e445e47 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformService.java @@ -16,6 +16,6 @@ public interface ChargeDropdownReadPlatformService { List retrieveApplicableToTypes(); List retrieveCollectionTimeTypes(); - + List retrivePaymentModes(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java index c25906054..fcf2d9998 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeDropdownReadPlatformServiceImpl.java @@ -34,9 +34,11 @@ public class ChargeDropdownReadPlatformServiceImpl implements ChargeDropdownRead @Override public List retrieveApplicableToTypes() { - List chargeAppliesToTypes = new ArrayList(); - for (ChargeAppliesTo chargeAppliesTo : ChargeAppliesTo.values()) { - if(ChargeAppliesTo.INVALID.equals(chargeAppliesTo)) continue; + final List chargeAppliesToTypes = new ArrayList(); + for (final ChargeAppliesTo chargeAppliesTo : ChargeAppliesTo.values()) { + if (ChargeAppliesTo.INVALID.equals(chargeAppliesTo)) { + continue; + } chargeAppliesToTypes.add(ChargeEnumerations.chargeAppliesTo(chargeAppliesTo)); } return chargeAppliesToTypes; @@ -44,12 +46,19 @@ public class ChargeDropdownReadPlatformServiceImpl implements ChargeDropdownRead @Override public List retrieveCollectionTimeTypes() { - List chargeTimeTypes = new ArrayList(); - for (ChargeTimeType chargeTimeType : ChargeTimeType.values()) { - if (ChargeTimeType.INVALID.equals(chargeTimeType) - || ChargeTimeType.MONTHLY.equals(chargeTimeType) // To be implemented for Savings - || ChargeTimeType.YEARLY.equals(chargeTimeType)) // To be implemented for Savings + final List chargeTimeTypes = new ArrayList(); + for (final ChargeTimeType chargeTimeType : ChargeTimeType.values()) { + if (ChargeTimeType.INVALID.equals(chargeTimeType) || ChargeTimeType.MONTHLY.equals(chargeTimeType) // To + // be + // implemented + // for + // Savings + || ChargeTimeType.YEARLY.equals(chargeTimeType)) { + // implemented + // for + // Savings continue; + } chargeTimeTypes.add(ChargeEnumerations.chargeTimeType(chargeTimeType)); } return chargeTimeTypes; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeEnumerations.java index 899179497..b5da02db2 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeEnumerations.java @@ -29,12 +29,10 @@ public class ChargeEnumerations { ChargeTimeType.SPECIFIED_DUE_DATE.getCode(), "Specified due date"); break; case MONTHLY: - optionData = new EnumOptionData(ChargeTimeType.MONTHLY.getValue().longValue(), - ChargeTimeType.MONTHLY.getCode(), "Monthly"); + optionData = new EnumOptionData(ChargeTimeType.MONTHLY.getValue().longValue(), ChargeTimeType.MONTHLY.getCode(), "Monthly"); break; case YEARLY: - optionData = new EnumOptionData(ChargeTimeType.YEARLY.getValue().longValue(), - ChargeTimeType.YEARLY.getCode(), "Yearly"); + optionData = new EnumOptionData(ChargeTimeType.YEARLY.getValue().longValue(), ChargeTimeType.YEARLY.getCode(), "Yearly"); break; default: optionData = new EnumOptionData(ChargeTimeType.INVALID.getValue().longValue(), ChargeTimeType.INVALID.getCode(), "Invalid"); @@ -54,7 +52,8 @@ public class ChargeEnumerations { optionData = new EnumOptionData(ChargeAppliesTo.LOAN.getValue().longValue(), ChargeAppliesTo.LOAN.getCode(), "Loan"); break; case SAVINGS: - optionData = new EnumOptionData(ChargeAppliesTo.SAVINGS.getValue().longValue(), ChargeAppliesTo.SAVINGS.getCode(), "Savings"); + optionData = new EnumOptionData(ChargeAppliesTo.SAVINGS.getValue().longValue(), ChargeAppliesTo.SAVINGS.getCode(), + "Savings"); break; default: optionData = new EnumOptionData(ChargeAppliesTo.INVALID.getValue().longValue(), ChargeAppliesTo.INVALID.getCode(), @@ -94,12 +93,11 @@ public class ChargeEnumerations { } return optionData; } - + public static EnumOptionData chargePaymentMode(final int id) { return chargePaymentMode(ChargePaymentMode.fromInt(id)); } - public static EnumOptionData chargePaymentMode(final ChargePaymentMode type) { EnumOptionData optionData = null; switch (type) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeReadPlatformService.java index d373160a2..b071b5195 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeReadPlatformService.java @@ -22,7 +22,7 @@ public interface ChargeReadPlatformService { Collection retrieveLoanApplicablePenalties(); Collection retrieveLoanProductCharges(Long loanProductId); - + Collection retrieveSavingsAccountApplicableCharges(boolean feeChargesOnly); Collection retrieveSavingsAccountApplicablePenalties(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeReadPlatformServiceImpl.java index 5d2447cd5..424852e07 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeReadPlatformServiceImpl.java @@ -67,7 +67,7 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService final String sql = "select " + rm.chargeSchema() + " where c.id = ? and c.is_deleted=0 "; return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { chargeId }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new ChargeNotFoundException(chargeId); } } @@ -77,7 +77,7 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService this.context.authenticatedUser(); - final Collection currencyOptions = currencyReadPlatformService.retrieveAllowedCurrencies(); + final Collection currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies(); final List allowedChargeCalculationTypeOptions = this.chargeDropdownReadPlatformService.retrieveCalculationTypes(); final List allowedChargeAppliesToOptions = this.chargeDropdownReadPlatformService.retrieveApplicableToTypes(); final List allowedChargeTimeOptions = this.chargeDropdownReadPlatformService.retrieveCollectionTimeTypes(); @@ -121,7 +121,7 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService final ChargeMapper rm = new ChargeMapper(); - String sql = "select " + rm.chargeSchema() + final String sql = "select " + rm.chargeSchema() + " where c.is_deleted=0 and c.is_active=1 and c.is_penalty=1 and c.charge_applies_to_enum=? order by c.name "; return this.jdbcTemplate.query(sql, rm, new Object[] { ChargeAppliesTo.LOAN.getValue() }); } @@ -131,7 +131,7 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService public String chargeSchema() { return "c.id as id, c.name as name, c.amount as amount, c.currency_code as currencyCode, " + "c.charge_applies_to_enum as chargeAppliesTo, c.charge_time_enum as chargeTime, " - +"c.charge_payment_mode_enum as chargePaymentMode, " + + "c.charge_payment_mode_enum as chargePaymentMode, " + "c.charge_calculation_enum as chargeCalculation, c.is_penalty as penalty, c.is_active as active, oc.name as currencyName, " + "oc.decimal_places as currencyDecimalPlaces,oc.currency_multiplesof as inMultiplesOf, oc.display_symbol as currencyDisplaySymbol, " + "oc.internationalized_name_code as currencyNameCode from m_charge c " @@ -141,7 +141,7 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService public String loanProductChargeSchema() { return chargeSchema() + " join m_product_loan_charge plc on plc.charge_id = c.id"; } - + public String savingsProductChargeSchema() { return chargeSchema() + " join m_savings_product_charge spc on spc.charge_id = c.id"; } @@ -174,17 +174,16 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService final int paymentMode = rs.getInt("chargePaymentMode"); final EnumOptionData chargePaymentMode = ChargeEnumerations.chargePaymentMode(paymentMode); - final boolean penalty = rs.getBoolean("penalty"); final boolean active = rs.getBoolean("active"); - return ChargeData.instance(id, name, amount, currency, chargeTimeType, chargeAppliesToType, chargeCalculationType, chargePaymentMode, - penalty, active); + return ChargeData.instance(id, name, amount, currency, chargeTimeType, chargeAppliesToType, chargeCalculationType, + chargePaymentMode, penalty, active); } } @Override - public Collection retrieveSavingsAccountApplicableCharges(boolean feeChargesOnly) { + public Collection retrieveSavingsAccountApplicableCharges(final boolean feeChargesOnly) { this.context.authenticatedUser(); final ChargeMapper rm = new ChargeMapper(); @@ -205,20 +204,21 @@ public class ChargeReadPlatformServiceImpl implements ChargeReadPlatformService final ChargeMapper rm = new ChargeMapper(); - String sql = "select " + rm.chargeSchema() + final String sql = "select " + rm.chargeSchema() + " where c.is_deleted=0 and c.is_active=1 and c.is_penalty=1 and c.charge_applies_to_enum=? order by c.name "; return this.jdbcTemplate.query(sql, rm, new Object[] { ChargeAppliesTo.SAVINGS.getValue() }); } @Override - public Collection retrieveSavingsProductCharges(Long savingsProductId) { + public Collection retrieveSavingsProductCharges(final Long savingsProductId) { this.context.authenticatedUser(); final ChargeMapper rm = new ChargeMapper(); - final String sql = "select " + rm.savingsProductChargeSchema() + " where c.is_deleted=0 and c.is_active=1 and spc.savings_product_id=?"; + final String sql = "select " + rm.savingsProductChargeSchema() + + " where c.is_deleted=0 and c.is_active=1 and spc.savings_product_id=?"; return this.jdbcTemplate.query(sql, rm, new Object[] { savingsProductId }); } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java index c17ab5a1d..7e246e9b2 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/charge/service/ChargeWritePlatformServiceJpaRepositoryImpl.java @@ -43,6 +43,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP private final DataSource dataSource; private final ChargeRepository chargeRepository; private final LoanProductRepository loanProductRepository; + @Autowired public ChargeWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final ChargeDefinitionCommandFromApiJsonDeserializer fromApiJsonDeserializer, final ChargeRepository chargeRepository, @@ -66,9 +67,9 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP final Charge charge = Charge.fromJson(command); this.chargeRepository.save(charge); - + return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(charge.getId()).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -94,7 +95,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP } return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(chargeId).with(changes).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -109,17 +110,17 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP final Charge chargeForDelete = this.chargeRepository.findOne(chargeId); if (chargeForDelete == null || chargeForDelete.isDeleted()) { throw new ChargeNotFoundException(chargeId); } - - Collection loanProducts = this.loanProductRepository.retrieveLoanProductsByChargeId(chargeId); - Boolean isChargeExistWithLoans = isAnyLoansAssociateWithThisCharge(chargeId); - + + final Collection loanProducts = this.loanProductRepository.retrieveLoanProductsByChargeId(chargeId); + final Boolean isChargeExistWithLoans = isAnyLoansAssociateWithThisCharge(chargeId); + if (!loanProducts.isEmpty() || isChargeExistWithLoans) { throw new ChargeCannotBeDeletedException( "error.msg.charge.cannot.be.deleted.it.is.already.used.in.loan", "This charge cannot be deleted, it is already used in loan"); } - + chargeForDelete.delete(); - - chargeRepository.save(chargeForDelete); + + this.chargeRepository.save(chargeForDelete); return new CommandProcessingResultBuilder().withEntityId(chargeForDelete.getId()).build(); } @@ -130,7 +131,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP */ private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("name")) { final String name = command.stringValueOfParameterNamed("name"); throw new PlatformDataIntegrityException("error.msg.charge.duplicate.name", "Charge with name `" + name + "` already exists", @@ -141,7 +142,7 @@ public class ChargeWritePlatformServiceJpaRepositoryImpl implements ChargeWriteP throw new PlatformDataIntegrityException("error.msg.charge.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage()); } - + private boolean isAnyLoansAssociateWithThisCharge(final Long chargeId) { final String sql = "select if((exists (select 1 from m_loan_charge lc where lc.charge_id = ?)) = 1, 'true', 'false')"; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/api/ClientsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/api/ClientsApiResource.java index 56da375f4..362da5993 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/api/ClientsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/api/ClientsApiResource.java @@ -80,10 +80,10 @@ public class ClientsApiResource { @QueryParam("commandParam") final String commandParam, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly) { - context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); ClientData clientData = null; - context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); if (is(commandParam, "close")) { clientData = this.clientReadPlatformService.retrieveAllClosureReasons(ClientApiConstants.CLIENT_CLOSURE_REASON); } else if (is(commandParam, "acceptTransfer")) { @@ -92,7 +92,7 @@ public class ClientsApiResource { clientData = this.clientReadPlatformService.retrieveTemplate(officeId, staffInSelectedOfficeOnly); } - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, clientData, ClientApiConstants.CLIENT_RESPONSE_DATA_PARAMETERS); } @@ -106,14 +106,14 @@ public class ClientsApiResource { @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, @QueryParam("orderBy") final String orderBy, @QueryParam("sortOrder") final String sortOrder) { - context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); final SearchParameters searchParameters = SearchParameters.forClients(sqlSearch, officeId, externalId, displayName, firstname, lastname, hierarchy, offset, limit, orderBy, sortOrder); final Page clientData = this.clientReadPlatformService.retrieveAll(searchParameters); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, clientData, ClientApiConstants.CLIENT_RESPONSE_DATA_PARAMETERS); } @@ -124,9 +124,9 @@ public class ClientsApiResource { public String retrieveOne(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo, @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly) { - context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); ClientData clientData = this.clientReadPlatformService.retrieveOne(clientId); if (settings.isTemplate()) { @@ -239,13 +239,13 @@ public class ClientsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAssociatedAccounts(@PathParam("clientId") final Long clientId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(ClientApiConstants.CLIENT_RESOURCE_NAME); final AccountSummaryCollectionData clientAccount = this.accountDetailsReadPlatformService.retrieveClientAccountDetails(clientId); final Set CLIENT_ACCOUNTS_DATA_PARAMETERS = new HashSet(Arrays.asList("loanAccounts", "savingsAccounts")); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.clientAccountSummaryToApiJsonSerializer.serialize(settings, clientAccount, CLIENT_ACCOUNTS_DATA_PARAMETERS); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/command/ClientIdentifierCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/command/ClientIdentifierCommand.java index 28983fc0d..038249f43 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/command/ClientIdentifierCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/command/ClientIdentifierCommand.java @@ -28,21 +28,21 @@ public class ClientIdentifierCommand { } public Long getDocumentTypeId() { - return documentTypeId; + return this.documentTypeId; } public String getDocumentKey() { - return documentKey; + return this.documentKey; } public String getDescription() { - return description; + return this.description; } public void validateForCreate() { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("clientIdentifier"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("clientIdentifier"); baseDataValidator.reset().parameter("documentTypeId").value(this.documentTypeId).notNull().integerGreaterThanZero(); baseDataValidator.reset().parameter("documentKey").value(this.documentKey).notBlank(); @@ -52,9 +52,9 @@ public class ClientIdentifierCommand { } public void validateForUpdate() { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("clientIdentifier"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("clientIdentifier"); baseDataValidator.reset().parameter("documentKey").value(this.documentKey).ignoreIfNull().notBlank(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/command/ClientNoteCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/command/ClientNoteCommand.java index 391bddf70..6c73a7f82 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/command/ClientNoteCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/command/ClientNoteCommand.java @@ -24,9 +24,9 @@ public class ClientNoteCommand { } public void validate() { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("clientnote"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("clientnote"); baseDataValidator.reset().parameter("note").value(this.note).notBlank().notExceedingLengthOf(1000); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientData.java index 39295e40d..585b408cd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientData.java @@ -110,9 +110,9 @@ final public class ClientData implements Comparable { this.accountNo = accountNo; this.status = status; if (status != null) { - active = status.getId().equals(300L); + this.active = status.getId().equals(300L); } else { - active = null; + this.active = null; } this.officeId = officeId; this.officeName = officeName; @@ -182,7 +182,7 @@ final public class ClientData implements Comparable { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } - ClientData rhs = (ClientData) obj; + final ClientData rhs = (ClientData) obj; return new EqualsBuilder() // .append(this.id, rhs.id) // .append(this.displayName, rhs.displayName) // diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientDataValidator.java index 9a3ca297c..38582b7d6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientDataValidator.java @@ -349,7 +349,7 @@ public final class ClientDataValidator { } - public void validateForAssignStaff(String json) { + public void validateForAssignStaff(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } @@ -390,10 +390,11 @@ public final class ClientDataValidator { final LocalDate closureDate = this.fromApiJsonHelper.extractLocalDateNamed(ClientApiConstants.closureDateParamName, element); baseDataValidator.reset().parameter(ClientApiConstants.closureDateParamName).value(closureDate).notNull(); - + final Long closureReasonId = this.fromApiJsonHelper.extractLongNamed(ClientApiConstants.closureReasonIdParamName, element); - baseDataValidator.reset().parameter(ClientApiConstants.closureReasonIdParamName).value(closureReasonId).notNull().longGreaterThanZero(); - + baseDataValidator.reset().parameter(ClientApiConstants.closureReasonIdParamName).value(closureReasonId).notNull() + .longGreaterThanZero(); + throwExceptionIfValidationWarningsExist(dataValidationErrors); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientIdentifierData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientIdentifierData.java index 5b18717c8..aee731cb9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientIdentifierData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/data/ClientIdentifierData.java @@ -14,44 +14,34 @@ import org.mifosplatform.infrastructure.codes.data.CodeValueData; */ public class ClientIdentifierData { - private final Long id; - private final Long clientId; - private final CodeValueData documentType; - private final String documentKey; - private final String description; - @SuppressWarnings("unused") - private final Collection allowedDocumentTypes; + private final Long id; + private final Long clientId; + private final CodeValueData documentType; + private final String documentKey; + private final String description; + @SuppressWarnings("unused") + private final Collection allowedDocumentTypes; - public static ClientIdentifierData singleItem(final Long id, - final Long clientId, final CodeValueData documentType, - final String documentKey, final String description) { - return new ClientIdentifierData(id, clientId, documentType, - documentKey, description, null); - } + public static ClientIdentifierData singleItem(final Long id, final Long clientId, final CodeValueData documentType, + final String documentKey, final String description) { + return new ClientIdentifierData(id, clientId, documentType, documentKey, description, null); + } - public static ClientIdentifierData template( - final Collection codeValues) { - return new ClientIdentifierData(null, null, null, null, null, - codeValues); - } + public static ClientIdentifierData template(final Collection codeValues) { + return new ClientIdentifierData(null, null, null, null, null, codeValues); + } - public static ClientIdentifierData template( - final ClientIdentifierData data, - final Collection codeValues) { - return new ClientIdentifierData(data.id, data.clientId, - data.documentType, data.documentKey, data.description, - codeValues); - } + public static ClientIdentifierData template(final ClientIdentifierData data, final Collection codeValues) { + return new ClientIdentifierData(data.id, data.clientId, data.documentType, data.documentKey, data.description, codeValues); + } - public ClientIdentifierData(final Long id, final Long clientId, - final CodeValueData documentType, final String documentKey, - final String description, - final Collection allowedDocumentTypes) { - this.id = id; - this.clientId = clientId; - this.documentType = documentType; - this.documentKey = documentKey; - this.description = description; - this.allowedDocumentTypes = allowedDocumentTypes; - } + public ClientIdentifierData(final Long id, final Long clientId, final CodeValueData documentType, final String documentKey, + final String description, final Collection allowedDocumentTypes) { + this.id = id; + this.clientId = clientId; + this.documentType = documentType; + this.documentKey = documentKey; + this.description = description; + this.allowedDocumentTypes = allowedDocumentTypes; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/AccountNumberGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/AccountNumberGenerator.java index 60780e291..2b46bd833 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/AccountNumberGenerator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/AccountNumberGenerator.java @@ -6,7 +6,8 @@ package org.mifosplatform.portfolio.client.domain; /** - * Responsible for generating unique account number based on some rules or patterns. + * Responsible for generating unique account number based on some rules or + * patterns. * * @see ZeroPaddedAccountNumberGenerator */ diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/Client.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/Client.java index 65461f88d..f76c8f35b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/Client.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/Client.java @@ -259,7 +259,7 @@ public final class Client extends AbstractPersistable { } this.activationDate = activationLocalDate.toDate(); - this.officeJoiningDate = activationDate; + this.officeJoiningDate = this.activationDate; this.status = ClientStatus.ACTIVE.getValue(); validate(); @@ -280,8 +280,8 @@ public final class Client extends AbstractPersistable { public boolean isTransferInProgress() { return ClientStatus.fromInt(this.status).isTransferInProgress(); } - - public boolean isTransferOnHold () { + + public boolean isTransferOnHold() { return ClientStatus.fromInt(this.status).isTransferOnHold(); } @@ -363,7 +363,7 @@ public final class Client extends AbstractPersistable { final LocalDate newValue = command.localDateValueOfParameterNamed(ClientApiConstants.activationDateParamName); this.activationDate = newValue.toDate(); - this.officeJoiningDate = activationDate; + this.officeJoiningDate = this.activationDate; } validate(); @@ -529,7 +529,7 @@ public final class Client extends AbstractPersistable { return this.status; } - public void setStatus(Integer status) { + public void setStatus(final Integer status) { this.status = status; } @@ -539,8 +539,8 @@ public final class Client extends AbstractPersistable { public boolean isChildOfGroup(final Long groupId) { if (groupId != null && this.groups != null && !this.groups.isEmpty()) { - for (Group group : this.groups) { - if (group.getId().equals(groupId)) return true; + for (final Group group : this.groups) { + if (group.getId().equals(groupId)) { return true; } } } return false; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientIdentifier.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientIdentifier.java index 276e1e4bf..46a75e728 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientIdentifier.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientIdentifier.java @@ -23,89 +23,77 @@ import org.mifosplatform.useradministration.domain.AppUser; @Entity @Table(name = "m_client_identifier", uniqueConstraints = { - @UniqueConstraint(columnNames = { "document_type_id", "document_key" }, name = "unique_identifier_key"), - @UniqueConstraint(columnNames = { "client_id", "document_type_id" }, name = "unique_client_identifier") }) + @UniqueConstraint(columnNames = { "document_type_id", "document_key" }, name = "unique_identifier_key"), + @UniqueConstraint(columnNames = { "client_id", "document_type_id" }, name = "unique_client_identifier") }) public class ClientIdentifier extends AbstractAuditableCustom { - @ManyToOne - @JoinColumn(name = "client_id", nullable = false) - private Client client; + @ManyToOne + @JoinColumn(name = "client_id", nullable = false) + private Client client; - @ManyToOne - @JoinColumn(name = "document_type_id", nullable = false) - private CodeValue documentType; + @ManyToOne + @JoinColumn(name = "document_type_id", nullable = false) + private CodeValue documentType; - @Column(name = "document_key", length = 1000) - private String documentKey; + @Column(name = "document_key", length = 1000) + private String documentKey; - @Column(name = "description", length = 1000) - private String description; + @Column(name = "description", length = 1000) + private String description; - public static ClientIdentifier fromJson(final Client client, - final CodeValue documentType, final JsonCommand command) { - final String documentKey = command - .stringValueOfParameterNamed("documentKey"); - final String description = command - .stringValueOfParameterNamed("description"); - return new ClientIdentifier(client, documentType, documentKey, - description); - } + public static ClientIdentifier fromJson(final Client client, final CodeValue documentType, final JsonCommand command) { + final String documentKey = command.stringValueOfParameterNamed("documentKey"); + final String description = command.stringValueOfParameterNamed("description"); + return new ClientIdentifier(client, documentType, documentKey, description); + } - protected ClientIdentifier() { - // - } + protected ClientIdentifier() { + // + } - private ClientIdentifier(final Client client, final CodeValue documentType, - final String documentKey, final String description) { - this.client = client; - this.documentType = documentType; - this.documentKey = StringUtils.defaultIfEmpty(documentKey, null); - this.description = StringUtils.defaultIfEmpty(description, null); - } + private ClientIdentifier(final Client client, final CodeValue documentType, final String documentKey, final String description) { + this.client = client; + this.documentType = documentType; + this.documentKey = StringUtils.defaultIfEmpty(documentKey, null); + this.description = StringUtils.defaultIfEmpty(description, null); + } - public void update(final CodeValue documentType) { - this.documentType = documentType; - } + public void update(final CodeValue documentType) { + this.documentType = documentType; + } - public Map update(final JsonCommand command) { + public Map update(final JsonCommand command) { - final Map actualChanges = new LinkedHashMap( - 7); + final Map actualChanges = new LinkedHashMap(7); - final String documentTypeIdParamName = "documentTypeId"; - if (command.isChangeInLongParameterNamed(documentTypeIdParamName, - this.documentType.getId())) { - final Long newValue = command - .longValueOfParameterNamed(documentTypeIdParamName); - actualChanges.put(documentTypeIdParamName, newValue); - } + final String documentTypeIdParamName = "documentTypeId"; + if (command.isChangeInLongParameterNamed(documentTypeIdParamName, this.documentType.getId())) { + final Long newValue = command.longValueOfParameterNamed(documentTypeIdParamName); + actualChanges.put(documentTypeIdParamName, newValue); + } - final String documentKeyParamName = "documentKey"; - if (command.isChangeInStringParameterNamed(documentKeyParamName, - this.documentKey)) { - final String newValue = command - .stringValueOfParameterNamed(documentKeyParamName); - actualChanges.put(documentKeyParamName, newValue); - this.documentKey = StringUtils.defaultIfEmpty(newValue, null); - } + final String documentKeyParamName = "documentKey"; + if (command.isChangeInStringParameterNamed(documentKeyParamName, this.documentKey)) { + final String newValue = command.stringValueOfParameterNamed(documentKeyParamName); + actualChanges.put(documentKeyParamName, newValue); + this.documentKey = StringUtils.defaultIfEmpty(newValue, null); + } - final String descriptionParamName = "description"; - if (command.isChangeInStringParameterNamed(descriptionParamName, - this.description)) { - final String newValue = command - .stringValueOfParameterNamed(descriptionParamName); - actualChanges.put(descriptionParamName, newValue); - this.description = StringUtils.defaultIfEmpty(newValue, null); - } + final String descriptionParamName = "description"; + if (command.isChangeInStringParameterNamed(descriptionParamName, this.description)) { + final String newValue = command.stringValueOfParameterNamed(descriptionParamName); + actualChanges.put(descriptionParamName, newValue); + this.description = StringUtils.defaultIfEmpty(newValue, null); + } - return actualChanges; - } + return actualChanges; + } - public String documentKey() { - return this.documentKey; - } + public String documentKey() { + return this.documentKey; + } - public Long documentTypeId() { - return this.documentType.getId(); - } + public Long documentTypeId() { + return this.documentType.getId(); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientRepositoryWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientRepositoryWrapper.java index b60fca8bf..5c26af704 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientRepositoryWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientRepositoryWrapper.java @@ -30,7 +30,7 @@ public class ClientRepositoryWrapper { if (client == null) { throw new ClientNotFoundException(id); } return client; } - + public void save(final Client client) { this.repository.save(client); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientStatus.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientStatus.java index 327db48b7..405b48f7e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientStatus.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientStatus.java @@ -29,10 +29,10 @@ public enum ClientStatus { break; case 300: enumeration = ClientStatus.ACTIVE; - break; + break; case 303: enumeration = ClientStatus.TRANSFER_IN_PROGRESS; - break; + break; case 304: enumeration = ClientStatus.TRANSFER_ON_HOLD; break; @@ -57,7 +57,7 @@ public enum ClientStatus { } public String getCode() { - return code; + return this.code; } public boolean isPending() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ZeroPaddedAccountNumberGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ZeroPaddedAccountNumberGenerator.java index 6ab056e8f..9e18e0dd5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ZeroPaddedAccountNumberGenerator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ZeroPaddedAccountNumberGenerator.java @@ -15,13 +15,13 @@ public class ZeroPaddedAccountNumberGenerator implements AccountNumberGenerator private final Long id; private final int maxLength; - public ZeroPaddedAccountNumberGenerator(final Long id, int maxLength) { + public ZeroPaddedAccountNumberGenerator(final Long id, final int maxLength) { this.id = id; this.maxLength = maxLength; } @Override public String generate() { - return String.format("%0" + maxLength + "d", id); + return String.format("%0" + this.maxLength + "d", this.id); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/exception/DuplicateClientIdentifierException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/exception/DuplicateClientIdentifierException.java index c6eca6b32..970954223 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/exception/DuplicateClientIdentifierException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/exception/DuplicateClientIdentifierException.java @@ -15,7 +15,7 @@ public class DuplicateClientIdentifierException extends AbstractPlatformDomainRu private Long documentTypeId; private String identifierKey; - private String identifierType; + private final String identifierType; public DuplicateClientIdentifierException(final String identifierType) { super("error.msg.clientIdentifier.type.duplicate", "Client identifier of type " + identifierType @@ -40,14 +40,14 @@ public class DuplicateClientIdentifierException extends AbstractPlatformDomainRu } public Long getDocumentTypeId() { - return documentTypeId; + return this.documentTypeId; } public String getIdentifierKey() { - return identifierKey; + return this.identifierKey; } public String getIdentifierType() { - return identifierType; + return this.identifierType; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/exception/InvalidClientStateTransitionException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/exception/InvalidClientStateTransitionException.java index b78cabf04..f7166210b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/exception/InvalidClientStateTransitionException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/exception/InvalidClientStateTransitionException.java @@ -8,11 +8,13 @@ package org.mifosplatform.portfolio.client.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown an action to transition a loan from one state to another violates a domain rule. + * {@link AbstractPlatformDomainRuleException} thrown an action to transition a + * loan from one state to another violates a domain rule. */ public class InvalidClientStateTransitionException extends AbstractPlatformDomainRuleException { - public InvalidClientStateTransitionException(final String action, String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { + public InvalidClientStateTransitionException(final String action, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg.client." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); // TODO Auto-generated constructor stub } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/handler/AssignClientStaffCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/handler/AssignClientStaffCommandHandler.java index 5b087ec3f..646d8c018 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/handler/AssignClientStaffCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/handler/AssignClientStaffCommandHandler.java @@ -10,9 +10,9 @@ import org.springframework.transaction.annotation.Transactional; @Service public class AssignClientStaffCommandHandler implements NewCommandSourceHandler { - + private final ClientWritePlatformService clientWritePlatformService; - + @Autowired public AssignClientStaffCommandHandler(final ClientWritePlatformService clientWritePlatformService) { this.clientWritePlatformService = clientWritePlatformService; @@ -20,7 +20,7 @@ public class AssignClientStaffCommandHandler implements NewCommandSourceHandler @Transactional @Override - public CommandProcessingResult processCommand(JsonCommand command) { + public CommandProcessingResult processCommand(final JsonCommand command) { return this.clientWritePlatformService.assignClientStaff(command.entityId(), command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/serialization/ClientIdentifierCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/serialization/ClientIdentifierCommandFromApiJsonDeserializer.java index 2bfc6d928..e7626da2c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/serialization/ClientIdentifierCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/serialization/ClientIdentifierCommandFromApiJsonDeserializer.java @@ -24,8 +24,8 @@ import com.google.gson.JsonElement; import com.google.gson.reflect.TypeToken; /** - * Implementation of {@link FromApiJsonDeserializer} for {@link ClientIdentifierCommandFromApiJsonDeserializer} - * 's. + * Implementation of {@link FromApiJsonDeserializer} for + * {@link ClientIdentifierCommandFromApiJsonDeserializer} 's. */ @Component public final class ClientIdentifierCommandFromApiJsonDeserializer extends AbstractFromApiJsonDeserializer { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformService.java index 2d769e9c3..da9286677 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformService.java @@ -28,7 +28,7 @@ public interface ClientReadPlatformService { Collection retrieveClientMembersOfGroup(Long groupId); Collection retrieveActiveClientMembersOfGroup(Long groupId); - + Collection retrieveActiveClientMembersOfCenter(final Long centerId); ClientData retrieveAllClosureReasons(String clientClosureReason); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformServiceImpl.java index 15d840193..ce8e39e8f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientReadPlatformServiceImpl.java @@ -72,7 +72,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final Long defaultOfficeId = defaultToUsersOfficeIfNull(officeId); - final Collection offices = officeReadPlatformService.retrieveAllOfficesForDropdown(); + final Collection offices = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); Collection staffOptions = null; @@ -93,11 +93,11 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService @Override public Page retrieveAll(final SearchParameters searchParameters) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - StringBuilder sqlBuilder = new StringBuilder(200); + final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append(this.clientMapper.schema()); sqlBuilder.append(" where o.hierarchy like ? or transferToOffice.hierarchy like ?"); @@ -180,23 +180,23 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService @Override public ClientData retrieveOne(final Long clientId) { try { - AppUser currentUser = context.authenticatedUser(); - String hierarchy = currentUser.getOffice().getHierarchy(); - String hierarchySearchString = hierarchy + "%"; + final AppUser currentUser = this.context.authenticatedUser(); + final String hierarchy = currentUser.getOffice().getHierarchy(); + final String hierarchySearchString = hierarchy + "%"; - String sql = "select " + this.clientMapper.schema() + final String sql = "select " + this.clientMapper.schema() + " where ( o.hierarchy like ? or transferToOffice.hierarchy like ?) and c.id = ?"; - ClientData clientData = this.jdbcTemplate.queryForObject(sql, this.clientMapper, new Object[] { hierarchySearchString, + final ClientData clientData = this.jdbcTemplate.queryForObject(sql, this.clientMapper, new Object[] { hierarchySearchString, hierarchySearchString, clientId }); - String clientGroupsSql = "select " + this.clientGroupsMapper.parentGroupsSchema(); + final String clientGroupsSql = "select " + this.clientGroupsMapper.parentGroupsSchema(); - Collection parentGroups = this.jdbcTemplate.query(clientGroupsSql, this.clientGroupsMapper, + final Collection parentGroups = this.jdbcTemplate.query(clientGroupsSql, this.clientGroupsMapper, new Object[] { clientId }); return ClientData.setParentGroups(clientData, parentGroups); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new ClientNotFoundException(clientId); } } @@ -224,7 +224,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService @Override public Collection retrieveClientMembersOfGroup(final Long groupId) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; @@ -236,7 +236,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService @Override public Collection retrieveActiveClientMembersOfGroup(final Long groupId) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; @@ -308,7 +308,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService @Override public Collection retrieveActiveClientMembersOfCenter(final Long centerId) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; @@ -325,7 +325,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService private final String schema; public ClientMapper() { - StringBuilder builder = new StringBuilder(400); + final StringBuilder builder = new StringBuilder(400); builder.append("c.id as id, c.account_no as accountNo, c.external_id as externalId, c.status_enum as statusEnum, "); builder.append("c.office_id as officeId, o.name as officeName, "); @@ -398,7 +398,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService private final String schema; public ClientLookupMapper() { - StringBuilder builder = new StringBuilder(200); + final StringBuilder builder = new StringBuilder(200); builder.append("c.id as id, c.display_name as displayName, "); builder.append("c.office_id as officeId, o.name as officeName "); @@ -431,8 +431,8 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService final String sql = "select " + mapper.clientLookupByIdentifierSchema(); - return jdbcTemplate.queryForObject(sql, mapper, new Object[] { identifierTypeId, identifierKey }); - } catch (EmptyResultDataAccessException e) { + return this.jdbcTemplate.queryForObject(sql, mapper, new Object[] { identifierTypeId, identifierKey }); + } catch (final EmptyResultDataAccessException e) { return null; } } @@ -482,7 +482,7 @@ public class ClientReadPlatformServiceImpl implements ClientReadPlatformService @Override public ClientData retrieveAllClosureReasons(final String clientClosureReason) { final List closureReasons = new ArrayList( - codeValueReadPlatformService.retrieveCodeValuesByCode(clientClosureReason)); + this.codeValueReadPlatformService.retrieveCodeValuesByCode(clientClosureReason)); return ClientData.template(null, null, null, null, closureReasons); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientWritePlatformService.java index eb4f6fe74..8e58cfc46 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientWritePlatformService.java @@ -19,7 +19,7 @@ public interface ClientWritePlatformService { CommandProcessingResult deleteClient(Long clientId); CommandProcessingResult unassignClientStaff(Long clientId, JsonCommand command); - + CommandProcessingResult closeClient(final Long clientId, final JsonCommand command); CommandProcessingResult assignClientStaff(Long clientId, JsonCommand command); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java index 7da023864..1285b4e27 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/ClientWritePlatformServiceJpaRepositoryImpl.java @@ -334,11 +334,11 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP try { this.fromApiJsonDeserializer.validateClose(command); - Client client = this.clientRepository.findOneWithNotFoundDetection(clientId); + final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId); final LocalDate closureDate = command.localDateValueOfParameterNamed(ClientApiConstants.closureDateParamName); final Long closureReasonId = command.longValueOfParameterNamed(ClientApiConstants.closureReasonIdParamName); - CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( + final CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( ClientApiConstants.CLIENT_CLOSURE_REASON, closureReasonId); if (ClientStatus.fromInt(client.getStatus()).isClosed()) { @@ -355,10 +355,10 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP closureDate, client.getActivationLocalDate()); } - List clientLoans = this.loanRepository.findLoanByClientId(clientId); + final List clientLoans = this.loanRepository.findLoanByClientId(clientId); - for (Loan loan : clientLoans) { - LoanStatusMapper loanStatus = new LoanStatusMapper(loan.status().getValue()); + for (final Loan loan : clientLoans) { + final LoanStatusMapper loanStatus = new LoanStatusMapper(loan.status().getValue()); if (loanStatus.isOpen()) { final String errorMessage = "Client cannot be closed because of non-closed loans."; throw new InvalidClientStateTransitionException("close", "loan.non-closed", errorMessage); @@ -374,9 +374,9 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP throw new InvalidClientStateTransitionException("close", "loan.non-closed", errorMessage); } } - List clientSavingAccounts = this.savingsRepository.findSavingAccountByClientId(clientId); + final List clientSavingAccounts = this.savingsRepository.findSavingAccountByClientId(clientId); - for (SavingsAccount saving : clientSavingAccounts) { + for (final SavingsAccount saving : clientSavingAccounts) { if (saving.isActive()) { final String errorMessage = "Client cannot be closed because of non-closed savings account."; throw new InvalidClientStateTransitionException("close", "non-closed.savings.account", errorMessage); @@ -397,7 +397,7 @@ public class ClientWritePlatformServiceJpaRepositoryImpl implements ClientWriteP .withClientId(clientId) // .withEntityId(clientId) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/LoanStatusMapper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/LoanStatusMapper.java index 9ba704fbd..881bb4991 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/LoanStatusMapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/service/LoanStatusMapper.java @@ -9,31 +9,31 @@ public class LoanStatusMapper { private final Integer statusId; - public LoanStatusMapper(Integer statusId) { + public LoanStatusMapper(final Integer statusId) { this.statusId = statusId; } public boolean isPendingApproval() { - return Integer.valueOf(100).equals(statusId); + return Integer.valueOf(100).equals(this.statusId); } public boolean isAwaitingDisbursal() { - return Integer.valueOf(200).equals(statusId); + return Integer.valueOf(200).equals(this.statusId); } public boolean isOpen() { - return Integer.valueOf(300).equals(statusId); + return Integer.valueOf(300).equals(this.statusId); } public boolean isWithdrawnByClient() { - return Integer.valueOf(400).equals(statusId); + return Integer.valueOf(400).equals(this.statusId); } public boolean isRejected() { - return Integer.valueOf(500).equals(statusId); + return Integer.valueOf(500).equals(this.statusId); } public boolean isClosed() { - return Integer.valueOf(600).equals(statusId) || isWithdrawnByClient() || isRejected(); + return Integer.valueOf(600).equals(this.statusId) || isWithdrawnByClient() || isRejected(); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/api/CollateralApiConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/api/CollateralApiConstants.java index 1f6ce9ff0..797b5fca5 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/api/CollateralApiConstants.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/api/CollateralApiConstants.java @@ -26,7 +26,7 @@ public class CollateralApiConstants { private static final Set values = new HashSet(); static { - for (COLLATERAL_JSON_INPUT_PARAMS type : COLLATERAL_JSON_INPUT_PARAMS.values()) { + for (final COLLATERAL_JSON_INPUT_PARAMS type : COLLATERAL_JSON_INPUT_PARAMS.values()) { values.add(type.value); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/api/CollateralsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/api/CollateralsApiResource.java index 499f68212..409465ad9 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/api/CollateralsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/api/CollateralsApiResource.java @@ -75,7 +75,7 @@ public class CollateralsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String newCollateralTemplate(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); @@ -90,11 +90,11 @@ public class CollateralsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveCollateralDetails(@Context final UriInfo uriInfo, @PathParam("loanId") final Long loanId) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); - List CollateralDatas = collateralReadPlatformService.retrieveCollateralsForValidLoan(loanId); + final List CollateralDatas = this.collateralReadPlatformService.retrieveCollateralsForValidLoan(loanId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.apiJsonSerializerService.serialize(settings, CollateralDatas, RESPONSE_DATA_PARAMETERS); } @@ -105,11 +105,11 @@ public class CollateralsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveCollateralDetails(@Context final UriInfo uriInfo, @PathParam("loanId") final Long loanId, @PathParam("collateralId") final Long CollateralId) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); - CollateralData CollateralData = collateralReadPlatformService.retrieveCollateral(loanId, CollateralId); + CollateralData CollateralData = this.collateralReadPlatformService.retrieveCollateral(loanId, CollateralId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (settings.isTemplate()) { final Collection codeValues = this.codeValueReadPlatformService .retrieveCodeValuesByCode(CollateralApiConstants.COLLATERAL_CODE_NAME); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/command/CollateralCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/command/CollateralCommand.java index d459579a8..5c1f35fe4 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/command/CollateralCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/command/CollateralCommand.java @@ -42,9 +42,9 @@ public class CollateralCommand { } public void validateForCreate() { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("collateral"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("collateral"); baseDataValidator.reset().parameter(COLLATERAL_JSON_INPUT_PARAMS.COLLATERAL_TYPE_ID.getValue()).value(this.collateralTypeId) .notNull().integerGreaterThanZero(); @@ -58,9 +58,9 @@ public class CollateralCommand { } public void validateForUpdate() { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("collateral"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("collateral"); baseDataValidator.reset().parameter(COLLATERAL_JSON_INPUT_PARAMS.COLLATERAL_TYPE_ID.getValue()).value(this.collateralTypeId) .ignoreIfNull().integerGreaterThanZero(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/data/CollateralData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/data/CollateralData.java index 3e9a09965..9f2248f01 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/data/CollateralData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/data/CollateralData.java @@ -44,7 +44,7 @@ public class CollateralData { } private CollateralData(final Long id, final CodeValueData type, final BigDecimal value, final String description, - final CurrencyData currencyData, Collection allowedCollateralTypes) { + final CurrencyData currencyData, final Collection allowedCollateralTypes) { this.id = id; this.type = type; this.value = value; @@ -53,7 +53,7 @@ public class CollateralData { this.allowedCollateralTypes = allowedCollateralTypes; } - public CollateralData template(CollateralData collateralData, Collection codeValues) { + public CollateralData template(final CollateralData collateralData, final Collection codeValues) { return new CollateralData(collateralData.id, collateralData.type, collateralData.value, collateralData.description, collateralData.currency, codeValues); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/exception/CollateralNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/exception/CollateralNotFoundException.java index a0b1ded9c..c2b38703a 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/exception/CollateralNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/exception/CollateralNotFoundException.java @@ -12,7 +12,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN */ public class CollateralNotFoundException extends AbstractPlatformResourceNotFoundException { - public CollateralNotFoundException(Long loanId, Long collateralId) { + public CollateralNotFoundException(final Long loanId, final Long collateralId) { super("error.msg.loan.collateral.", "Collateral with Id " + collateralId + " does not exist for loan with Id " + loanId, loanId, collateralId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/serialization/CollateralCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/serialization/CollateralCommandFromApiJsonDeserializer.java index 5329c5f6f..85781ddc1 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/serialization/CollateralCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/serialization/CollateralCommandFromApiJsonDeserializer.java @@ -40,22 +40,24 @@ public final class CollateralCommandFromApiJsonDeserializer extends AbstractFrom } @Override - public CollateralCommand commandFromApiJson(String json) { + public CollateralCommand commandFromApiJson(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - Set supportedParameters = COLLATERAL_JSON_INPUT_PARAMS.getAllValues(); + final Set supportedParameters = COLLATERAL_JSON_INPUT_PARAMS.getAllValues(); supportedParameters.add("locale"); supportedParameters.add("dateFormat"); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); - Long collateralTypeId = fromApiJsonHelper.extractLongNamed(COLLATERAL_JSON_INPUT_PARAMS.COLLATERAL_TYPE_ID.getValue(), element); - String description = fromApiJsonHelper.extractStringNamed(COLLATERAL_JSON_INPUT_PARAMS.DESCRIPTION.getValue(), element); - BigDecimal value = fromApiJsonHelper.extractBigDecimalNamed(COLLATERAL_JSON_INPUT_PARAMS.VALUE.getValue(), element, locale); + final Long collateralTypeId = this.fromApiJsonHelper.extractLongNamed(COLLATERAL_JSON_INPUT_PARAMS.COLLATERAL_TYPE_ID.getValue(), + element); + final String description = this.fromApiJsonHelper.extractStringNamed(COLLATERAL_JSON_INPUT_PARAMS.DESCRIPTION.getValue(), element); + final BigDecimal value = this.fromApiJsonHelper.extractBigDecimalNamed(COLLATERAL_JSON_INPUT_PARAMS.VALUE.getValue(), element, + locale); return new CollateralCommand(collateralTypeId, value, description); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralAssembler.java index e325c23f1..f3e39e194 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralAssembler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralAssembler.java @@ -52,16 +52,16 @@ public class CollateralAssembler { final JsonObject collateralItemElement = array.get(i).getAsJsonObject(); - final Long id = fromApiJsonHelper.extractLongNamed("id", collateralItemElement); - final Long collateralTypeId = fromApiJsonHelper.extractLongNamed("type", collateralItemElement); + final Long id = this.fromApiJsonHelper.extractLongNamed("id", collateralItemElement); + final Long collateralTypeId = this.fromApiJsonHelper.extractLongNamed("type", collateralItemElement); final CodeValue collateralType = this.codeValueRepository.findOneWithNotFoundDetection(collateralTypeId); - final String description = fromApiJsonHelper.extractStringNamed("description", collateralItemElement); - final BigDecimal value = fromApiJsonHelper.extractBigDecimalNamed("value", collateralItemElement, locale); + final String description = this.fromApiJsonHelper.extractStringNamed("description", collateralItemElement); + final BigDecimal value = this.fromApiJsonHelper.extractBigDecimalNamed("value", collateralItemElement, locale); if (id == null) { collateralItems.add(LoanCollateral.from(collateralType, value, description)); } else { - LoanCollateral loanCollateralItem = this.loanCollateralRepository.findOne(id); + final LoanCollateral loanCollateralItem = this.loanCollateralRepository.findOne(id); if (loanCollateralItem == null) { throw new CollateralNotFoundException(id); } loanCollateralItem.assembleFrom(collateralType, value, description); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralReadPlatformServiceImpl.java index b6caef1dd..13b44bf4a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralReadPlatformServiceImpl.java @@ -43,7 +43,7 @@ public class CollateralReadPlatformServiceImpl implements CollateralReadPlatform private static final class CollateralMapper implements RowMapper { - private StringBuilder sqlBuilder = new StringBuilder( + private final StringBuilder sqlBuilder = new StringBuilder( "lc.id as id, lc.description as description, lc.value as value, cv.id as typeId, cv.code_value as typeName, oc.code as currencyCode, ") .append(" oc.name as currencyName,oc.decimal_places as currencyDecimalPlaces, oc.currency_multiplesof as inMultiplesOf, oc.display_symbol as currencyDisplaySymbol, oc.internationalized_name_code as currencyNameCode") .append(" FROM m_loan_collateral lc") // @@ -52,7 +52,7 @@ public class CollateralReadPlatformServiceImpl implements CollateralReadPlatform .append(" JOIN m_organisation_currency oc on loan.currency_code = oc.code"); public String schema() { - return sqlBuilder.toString(); + return this.sqlBuilder.toString(); } @Override @@ -92,7 +92,7 @@ public class CollateralReadPlatformServiceImpl implements CollateralReadPlatform } @Override - public CollateralData retrieveCollateral(Long loanId, Long collateralId) { + public CollateralData retrieveCollateral(final Long loanId, final Long collateralId) { try { final CollateralMapper rm = new CollateralMapper(); String sql = "select " + rm.schema(); @@ -105,8 +105,8 @@ public class CollateralReadPlatformServiceImpl implements CollateralReadPlatform } @Override - public List retrieveCollateralsForValidLoan(Long loanId) { - Loan loan = this.loanRepository.findOne(loanId); + public List retrieveCollateralsForValidLoan(final Long loanId) { + final Loan loan = this.loanRepository.findOne(loanId); if (loan == null) { throw new LoanNotFoundException(loanId); } return retrieveCollaterals(loanId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralWritePlatformServiceJpaRepositoryImpl.java index 71cdb63a3..eb54a3f0c 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collateral/service/CollateralWritePlatformServiceJpaRepositoryImpl.java @@ -103,7 +103,7 @@ public class CollateralWritePlatformServiceJpaRepositoryImpl implements Collater final CollateralCommand collateralCommand = this.collateralCommandFromApiJsonDeserializer.commandFromApiJson(command.json()); collateralCommand.validateForUpdate(); - Long collateralTypeId = collateralCommand.getCollateralTypeId(); + final Long collateralTypeId = collateralCommand.getCollateralTypeId(); try { final Loan loan = this.loanRepository.findOne(loanId); if (loan == null) { throw new LoanNotFoundException(loanId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/CollectionSheetBulkDisbursalCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/CollectionSheetBulkDisbursalCommand.java index ef47670bd..788de27b8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/CollectionSheetBulkDisbursalCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/CollectionSheetBulkDisbursalCommand.java @@ -7,7 +7,6 @@ package org.mifosplatform.portfolio.collectionsheet.command; import org.joda.time.LocalDate; - /** * Immutable command for loan bulk disburse. */ @@ -17,7 +16,8 @@ public class CollectionSheetBulkDisbursalCommand { private final LocalDate transactionDate; private final SingleDisbursalCommand[] disburseTransactions; - public CollectionSheetBulkDisbursalCommand(String note, final LocalDate transactionDate, SingleDisbursalCommand[] disburseTransactions) { + public CollectionSheetBulkDisbursalCommand(final String note, final LocalDate transactionDate, + final SingleDisbursalCommand[] disburseTransactions) { this.note = note; this.transactionDate = transactionDate; this.disburseTransactions = disburseTransactions; @@ -26,7 +26,7 @@ public class CollectionSheetBulkDisbursalCommand { public String getNote() { return this.note; } - + public SingleDisbursalCommand[] getDisburseTransactions() { return this.disburseTransactions; } @@ -34,5 +34,5 @@ public class CollectionSheetBulkDisbursalCommand { public LocalDate getTransactionDate() { return this.transactionDate; } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/CollectionSheetBulkRepaymentCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/CollectionSheetBulkRepaymentCommand.java index 747bbc766..18b5528ad 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/CollectionSheetBulkRepaymentCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/CollectionSheetBulkRepaymentCommand.java @@ -7,7 +7,6 @@ package org.mifosplatform.portfolio.collectionsheet.command; import org.joda.time.LocalDate; - /** * Immutable command for loan bulk repayment. */ @@ -17,7 +16,8 @@ public class CollectionSheetBulkRepaymentCommand { private final LocalDate transactionDate; private final SingleRepaymentCommand[] repaymentTransactions; - public CollectionSheetBulkRepaymentCommand(String note, final LocalDate transactionDate, SingleRepaymentCommand[] repaymentTransactions) { + public CollectionSheetBulkRepaymentCommand(final String note, final LocalDate transactionDate, + final SingleRepaymentCommand[] repaymentTransactions) { this.note = note; this.transactionDate = transactionDate; this.repaymentTransactions = repaymentTransactions; @@ -31,9 +31,8 @@ public class CollectionSheetBulkRepaymentCommand { return this.repaymentTransactions; } - public LocalDate getTransactionDate() { return this.transactionDate; } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/SingleDisbursalCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/SingleDisbursalCommand.java index 9a4f8a45f..dd9d14a38 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/SingleDisbursalCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/SingleDisbursalCommand.java @@ -9,7 +9,6 @@ import java.math.BigDecimal; import org.joda.time.LocalDate; - /** * Immutable command for Single loan repayment. */ @@ -18,22 +17,23 @@ public class SingleDisbursalCommand { private final Long loanId; private final BigDecimal transactionAmount; private final LocalDate transactionDate; - public SingleDisbursalCommand(Long loanId, BigDecimal transactionAmount, LocalDate transactionDate) { + + public SingleDisbursalCommand(final Long loanId, final BigDecimal transactionAmount, final LocalDate transactionDate) { this.loanId = loanId; this.transactionAmount = transactionAmount; this.transactionDate = transactionDate; } - + public Long getLoanId() { return this.loanId; } - + public BigDecimal getTransactionAmount() { return this.transactionAmount; } - + public LocalDate getTransactionDate() { return this.transactionDate; } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/SingleRepaymentCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/SingleRepaymentCommand.java index e118c203f..aa5362299 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/SingleRepaymentCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/command/SingleRepaymentCommand.java @@ -9,7 +9,6 @@ import java.math.BigDecimal; import org.joda.time.LocalDate; - /** * Immutable command for Single loan repayment. */ @@ -18,22 +17,23 @@ public class SingleRepaymentCommand { private final Long loanId; private final BigDecimal transactionAmount; private final LocalDate transactionDate; - public SingleRepaymentCommand(Long loanId, BigDecimal transactionAmount, LocalDate transactionDate) { + + public SingleRepaymentCommand(final Long loanId, final BigDecimal transactionAmount, final LocalDate transactionDate) { this.loanId = loanId; this.transactionAmount = transactionAmount; this.transactionDate = transactionDate; } - + public Long getLoanId() { return this.loanId; } - + public BigDecimal getTransactionAmount() { return this.transactionAmount; } - + public LocalDate getTransactionDate() { return this.transactionDate; } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/CollectionSheetTransactionDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/CollectionSheetTransactionDataValidator.java index f1464e75b..d9a7f0170 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/CollectionSheetTransactionDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/CollectionSheetTransactionDataValidator.java @@ -56,18 +56,18 @@ public class CollectionSheetTransactionDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, COLLECTIONSHEET_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, COLLECTIONSHEET_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(COLLECTIONSHEET_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed(transactionDateParamName, element); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(transactionDateParamName, element); baseDataValidator.reset().parameter(transactionDateParamName).value(transactionDate).notNull(); - final String note = fromApiJsonHelper.extractStringNamed(noteParamName, element); + final String note = this.fromApiJsonHelper.extractStringNamed(noteParamName, element); if (StringUtils.isNotBlank(note)) { baseDataValidator.reset().parameter(noteParamName).value(note).notExceedingLengthOf(1000); } @@ -76,9 +76,9 @@ public class CollectionSheetTransactionDataValidator { baseDataValidator.reset().parameter(calendarIdParamName).value(calendarId).notNull(); validateAttendanceDetails(element, baseDataValidator); - + validateDisbursementTransactions(element, baseDataValidator); - + validateRepaymentTransactions(element, baseDataValidator); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -147,7 +147,7 @@ public class CollectionSheetTransactionDataValidator { } } } - + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGClientData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGClientData.java index 618e96ea3..a0644e3c5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGClientData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGClientData.java @@ -10,7 +10,8 @@ import java.util.Collection; import org.mifosplatform.infrastructure.core.data.EnumOptionData; /** - * Immutable data object for clients with loans due for disbursement or collection. + * Immutable data object for clients with loans due for disbursement or + * collection. */ public class JLGClientData { @@ -20,7 +21,8 @@ public class JLGClientData { @SuppressWarnings("unused") private final EnumOptionData attendanceType; - public JLGClientData(final Long clientId, final String clientName, final Collection loans, final EnumOptionData attendanceType) { + public JLGClientData(final Long clientId, final String clientName, final Collection loans, + final EnumOptionData attendanceType) { this.clientId = clientId; this.clientName = clientName; this.loans = loans; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGCollectionSheetData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGCollectionSheetData.java index 77917ac3a..c61ffdf44 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGCollectionSheetData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGCollectionSheetData.java @@ -21,7 +21,7 @@ public class JLGCollectionSheetData { private final Collection loanProducts; private final Collection groups; @SuppressWarnings("unused") - private final List attendanceTypeOptions; + private final List attendanceTypeOptions; public JLGCollectionSheetData(final LocalDate date, final Collection loanProducts, final Collection groups, final List attendanceTypeOptions) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGCollectionSheetFlatData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGCollectionSheetFlatData.java index f87f217f6..5d82309ec 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGCollectionSheetFlatData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGCollectionSheetFlatData.java @@ -11,7 +11,8 @@ import org.mifosplatform.infrastructure.core.data.EnumOptionData; import org.mifosplatform.organisation.monetary.data.CurrencyData; /** - * Immutable data object for extracting flat data for joint liability group's collection sheet. + * Immutable data object for extracting flat data for joint liability group's + * collection sheet. */ public class JLGCollectionSheetFlatData { @@ -41,7 +42,8 @@ public class JLGCollectionSheetFlatData { final Long levelId, final String levelName, final String clientName, final Long clientId, final Long loanId, final String accountId, final Integer accountStatusId, final String productShortName, final Long productId, final CurrencyData currency, final BigDecimal disbursementAmount, final BigDecimal principalDue, - final BigDecimal principalPaid, final BigDecimal interestDue, final BigDecimal interestPaid, final BigDecimal chargesDue, final EnumOptionData attendanceType) { + final BigDecimal principalPaid, final BigDecimal interestDue, final BigDecimal interestPaid, final BigDecimal chargesDue, + final EnumOptionData attendanceType) { this.groupName = groupName; this.groupId = groupId; this.staffId = staffId; @@ -116,7 +118,7 @@ public class JLGCollectionSheetFlatData { public Long getProductId() { return this.productId; } - + public CurrencyData getCurrency() { return this.currency; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGGroupData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGGroupData.java index 4c341e9a0..d825680da 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGGroupData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/JLGGroupData.java @@ -8,7 +8,8 @@ package org.mifosplatform.portfolio.collectionsheet.data; import java.util.Collection; /** - * Immutable data object for groups with clients due for disbursement or collection. + * Immutable data object for groups with clients due for disbursement or + * collection. */ public class JLGGroupData { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/LoanDueData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/LoanDueData.java index ee76bb8a8..44d42fc53 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/LoanDueData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/data/LoanDueData.java @@ -10,7 +10,8 @@ import java.math.BigDecimal; import org.mifosplatform.organisation.monetary.data.CurrencyData; /** - * Immutable data object for representing loan with dues (example: loan is due for disbursement, repayments). + * Immutable data object for representing loan with dues (example: loan is due + * for disbursement, repayments). */ public class LoanDueData { @@ -29,9 +30,8 @@ public class LoanDueData { private BigDecimal totalDue = BigDecimal.ZERO; public LoanDueData(final Long loanId, final String accountId, final Integer accountStatusId, final String productShortName, - final Long productId, final CurrencyData currency, final BigDecimal disbursementAmount, - final BigDecimal principalDue, final BigDecimal principalPaid, final BigDecimal interestDue, final BigDecimal interestPaid, - final BigDecimal chargesDue) { + final Long productId, final CurrencyData currency, final BigDecimal disbursementAmount, final BigDecimal principalDue, + final BigDecimal principalPaid, final BigDecimal interestDue, final BigDecimal interestPaid, final BigDecimal chargesDue) { this.loanId = loanId; this.accountId = accountId; this.accountStatusId = accountStatusId; @@ -66,7 +66,7 @@ public class LoanDueData { public Long getProductId() { return this.productId; } - + public CurrencyData getCurrency() { return this.currency; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer.java index 4ce3161d2..e0844c05b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer.java @@ -28,12 +28,13 @@ import com.google.gson.JsonObject; * {@link CollectionSheetBulkDisbursalCommand}'s. */ @Component -public final class CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer extends AbstractFromApiJsonDeserializer { +public final class CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer extends + AbstractFromApiJsonDeserializer { private final FromJsonHelper fromApiJsonHelper; @Autowired - public CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer(FromJsonHelper fromApiJsonHelper) { + public CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { this.fromApiJsonHelper = fromApiJsonHelper; } @@ -45,8 +46,8 @@ public final class CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer ex final JsonObject topLevelJsonElement = element.getAsJsonObject(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); SingleDisbursalCommand[] loanDisbursementTransactions = null; @@ -57,9 +58,10 @@ public final class CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer ex loanDisbursementTransactions = new SingleDisbursalCommand[array.size()]; for (int i = 0; i < array.size(); i++) { final JsonObject loanTransactionElement = array.get(i).getAsJsonObject(); - + final Long loanId = this.fromApiJsonHelper.extractLongNamed("loanId", loanTransactionElement); - final BigDecimal disbursementAmount = this.fromApiJsonHelper.extractBigDecimalNamed("transactionAmount", loanTransactionElement, locale); + final BigDecimal disbursementAmount = this.fromApiJsonHelper.extractBigDecimalNamed("transactionAmount", + loanTransactionElement, locale); loanDisbursementTransactions[i] = new SingleDisbursalCommand(loanId, disbursementAmount, transactionDate); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer.java index 7b93f9817..31e30c447 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer.java @@ -28,12 +28,13 @@ import com.google.gson.JsonObject; * {@link CollectionSheetBulkRepaymentCommand}'s. */ @Component -public final class CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer extends AbstractFromApiJsonDeserializer { +public final class CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer extends + AbstractFromApiJsonDeserializer { private final FromJsonHelper fromApiJsonHelper; @Autowired - public CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer(FromJsonHelper fromApiJsonHelper) { + public CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer(final FromJsonHelper fromApiJsonHelper) { this.fromApiJsonHelper = fromApiJsonHelper; } @@ -43,25 +44,25 @@ public final class CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer ex final JsonElement element = this.fromApiJsonHelper.parse(json); - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); + + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); - final String note = fromApiJsonHelper.extractStringNamed("note", element); - final JsonObject topLevelJsonElement = element.getAsJsonObject(); final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); SingleRepaymentCommand[] loanRepaymentTransactions = null; if (element.isJsonObject()) { - if (topLevelJsonElement.has("bulkRepaymentTransactions") - && topLevelJsonElement.get("bulkRepaymentTransactions").isJsonArray()) { + if (topLevelJsonElement.has("bulkRepaymentTransactions") && topLevelJsonElement.get("bulkRepaymentTransactions").isJsonArray()) { final JsonArray array = topLevelJsonElement.get("bulkRepaymentTransactions").getAsJsonArray(); loanRepaymentTransactions = new SingleRepaymentCommand[array.size()]; for (int i = 0; i < array.size(); i++) { final JsonObject loanTransactionElement = array.get(i).getAsJsonObject(); - + final Long loanId = this.fromApiJsonHelper.extractLongNamed("loanId", loanTransactionElement); - final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalNamed("transactionAmount", loanTransactionElement, locale); + final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalNamed("transactionAmount", + loanTransactionElement, locale); loanRepaymentTransactions[i] = new SingleRepaymentCommand(loanId, transactionAmount, transactionDate); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetGenerateCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetGenerateCommandFromApiJsonDeserializer.java index cad90abe1..8b95bdc30 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetGenerateCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/serialization/CollectionSheetGenerateCommandFromApiJsonDeserializer.java @@ -5,6 +5,11 @@ */ package org.mifosplatform.portfolio.collectionsheet.serialization; +import static org.mifosplatform.portfolio.collectionsheet.CollectionSheetConstants.calendarIdParamName; +import static org.mifosplatform.portfolio.collectionsheet.CollectionSheetConstants.dateFormatParamName; +import static org.mifosplatform.portfolio.collectionsheet.CollectionSheetConstants.localeParamName; +import static org.mifosplatform.portfolio.collectionsheet.CollectionSheetConstants.transactionDateParamName; + import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; @@ -13,11 +18,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import static org.mifosplatform.portfolio.collectionsheet.CollectionSheetConstants.localeParamName; -import static org.mifosplatform.portfolio.collectionsheet.CollectionSheetConstants.dateFormatParamName; -import static org.mifosplatform.portfolio.collectionsheet.CollectionSheetConstants.calendarIdParamName; -import static org.mifosplatform.portfolio.collectionsheet.CollectionSheetConstants.transactionDateParamName; - import org.apache.commons.lang.StringUtils; import org.joda.time.LocalDate; import org.mifosplatform.infrastructure.core.data.ApiParameterError; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetReadPlatformService.java index 333bd336f..6f8108e59 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetReadPlatformService.java @@ -15,9 +15,9 @@ import org.mifosplatform.portfolio.collectionsheet.data.JLGCollectionSheetFlatDa public interface CollectionSheetReadPlatformService { JLGCollectionSheetData retriveCollectionSheet(LocalDate localDate, Long groupId); - + JLGCollectionSheetData generateGroupCollectionSheet(final Long groupId, final JsonQuery query); - + JLGCollectionSheetData generateCenterCollectionSheet(final Long groupId, final JsonQuery query); Collection retriveJLGCollectionSheet(String groupHierarchy, String officeHierarchy, LocalDate dueDate); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetReadPlatformServiceImpl.java index 37544a752..47414f955 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetReadPlatformServiceImpl.java @@ -88,7 +88,7 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe final CenterData center = this.centerReadPlatformService.retrieveOne(centerId); final String groupHierarchy = center.getHierarchy() + "%"; - Collection collectionSheetFlatDatas = this.retriveJLGCollectionSheet(groupHierarchy, officeHierarchy, + final Collection collectionSheetFlatDatas = retriveJLGCollectionSheet(groupHierarchy, officeHierarchy, dueDate); final JLGCollectionSheetData jlgCollectionSheetData = buildJLGCollectionSheet(dueDate, collectionSheetFlatDatas); @@ -116,7 +116,7 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe JLGCollectionSheetData jlgCollectionSheetData = null; JLGCollectionSheetFlatData prevCollectioSheetFlatData = null; JLGCollectionSheetFlatData corrCollectioSheetFlatData = null; - Set loanProducts = new HashSet(); + final Set loanProducts = new HashSet(); if (jlgCollectionSheetFlatData != null) { for (final JLGCollectionSheetFlatData collectionSheetFlatData : jlgCollectionSheetFlatData) { @@ -182,7 +182,7 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe } jlgCollectionSheetData = new JLGCollectionSheetData(dueDate, loanProducts, jlgGroupsData, - attendanceDropdownReadPlatformService.retrieveAttendanceTypeOptions()); + this.attendanceDropdownReadPlatformService.retrieveAttendanceTypeOptions()); } return jlgCollectionSheetData; @@ -315,10 +315,10 @@ public class CollectionSheetReadPlatformServiceImpl implements CollectionSheetRe final JLGCollectionSheetFaltDataMapper mapper = new JLGCollectionSheetFaltDataMapper(); - StringBuilder sql = new StringBuilder(mapper.collectionSheetSchema()); + final StringBuilder sql = new StringBuilder(mapper.collectionSheetSchema()); sql.append(" WHERE gp.id = :groupId GROUP BY gp.id ,cl.id , ln.id ORDER BY gp.id , cl.id , ln.id "); - //entityType should be center if it's within a center + // entityType should be center if it's within a center final CalendarEntityType entityType = (group.isChildGroup()) ? CalendarEntityType.CENTERS : CalendarEntityType.GROUPS; final SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("dueDate", transactionDateStr) diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetWritePlatformService.java index d3c2128fc..2c9f5ea9c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetWritePlatformService.java @@ -9,6 +9,6 @@ import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; public interface CollectionSheetWritePlatformService { - + CommandProcessingResult updateCollectionSheet(JsonCommand command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetWritePlatformServiceJpaRepositoryImpl.java index 2907520da..58c453b9a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/collectionsheet/service/CollectionSheetWritePlatformServiceJpaRepositoryImpl.java @@ -32,10 +32,11 @@ public class CollectionSheetWritePlatformServiceJpaRepositoryImpl implements Col private final MeetingWritePlatformService meetingWritePlatformService; @Autowired - public CollectionSheetWritePlatformServiceJpaRepositoryImpl(LoanWritePlatformService loanWritePlatformService, - CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer bulkRepaymentCommandFromApiJsonDeserializer, - CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer bulkDisbursalCommandFromApiJsonDeserializer, - final CollectionSheetTransactionDataValidator transactionDataValidator, final MeetingWritePlatformService meetingWritePlatformService) { + public CollectionSheetWritePlatformServiceJpaRepositoryImpl(final LoanWritePlatformService loanWritePlatformService, + final CollectionSheetBulkRepaymentCommandFromApiJsonDeserializer bulkRepaymentCommandFromApiJsonDeserializer, + final CollectionSheetBulkDisbursalCommandFromApiJsonDeserializer bulkDisbursalCommandFromApiJsonDeserializer, + final CollectionSheetTransactionDataValidator transactionDataValidator, + final MeetingWritePlatformService meetingWritePlatformService) { this.loanWritePlatformService = loanWritePlatformService; this.bulkRepaymentCommandFromApiJsonDeserializer = bulkRepaymentCommandFromApiJsonDeserializer; this.bulkDisbursalCommandFromApiJsonDeserializer = bulkDisbursalCommandFromApiJsonDeserializer; @@ -44,43 +45,44 @@ public class CollectionSheetWritePlatformServiceJpaRepositoryImpl implements Col } @Override - public CommandProcessingResult updateCollectionSheet(JsonCommand command) { - + public CommandProcessingResult updateCollectionSheet(final JsonCommand command) { + this.transactionDataValidator.validateTransaction(command); - - Map changes = new HashMap(); + + final Map changes = new HashMap(); changes.put("locale", command.locale()); changes.put("dateFormat", command.dateFormat()); - + final String noteText = command.stringValueOfParameterNamed("note"); if (StringUtils.isNotBlank(noteText)) { changes.put("note", noteText); } - + changes.putAll(updateBulkReapayments(command)); changes.putAll(updateBulkDisbursals(command)); - + this.meetingWritePlatformService.updateCollectionSheetAttendance(command); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(command.entityId()) // .withGroupId(command.entityId()) // - .with(changes) - .with(changes).build(); + .with(changes).with(changes).build(); } - private Map updateBulkReapayments(JsonCommand command) { - Map changes = new HashMap(); - final CollectionSheetBulkRepaymentCommand bulkRepaymentCommand = this.bulkRepaymentCommandFromApiJsonDeserializer.commandFromApiJson(command.json()); + private Map updateBulkReapayments(final JsonCommand command) { + final Map changes = new HashMap(); + final CollectionSheetBulkRepaymentCommand bulkRepaymentCommand = this.bulkRepaymentCommandFromApiJsonDeserializer + .commandFromApiJson(command.json()); changes.putAll(this.loanWritePlatformService.makeLoanBulkRepayment(bulkRepaymentCommand)); return changes; } - private Map updateBulkDisbursals(JsonCommand command) { - Map changes = new HashMap(); - final CollectionSheetBulkDisbursalCommand bulkDisbursalCommand = this.bulkDisbursalCommandFromApiJsonDeserializer.commandFromApiJson(command.json()); + private Map updateBulkDisbursals(final JsonCommand command) { + final Map changes = new HashMap(); + final CollectionSheetBulkDisbursalCommand bulkDisbursalCommand = this.bulkDisbursalCommandFromApiJsonDeserializer + .commandFromApiJson(command.json()); changes.putAll(this.loanWritePlatformService.bulkLoanDisbursal(command, bulkDisbursalCommand)); return changes; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/api/FundsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/api/FundsApiResource.java index 82a43ba69..504fee687 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/api/FundsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/api/FundsApiResource.java @@ -70,12 +70,12 @@ public class FundsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveFunds(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Collection funds = this.readPlatformService.retrieveAllFunds(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, funds, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, funds, this.RESPONSE_DATA_PARAMETERS); } @POST @@ -96,12 +96,12 @@ public class FundsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retreiveFund(@PathParam("fundId") final Long fundId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final FundData fund = this.readPlatformService.retrieveFund(fundId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, fund, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, fund, this.RESPONSE_DATA_PARAMETERS); } @PUT diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/data/FundData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/data/FundData.java index bb7109439..cc12e39e3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/data/FundData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/data/FundData.java @@ -13,11 +13,11 @@ import java.io.Serializable; public class FundData implements Serializable { @SuppressWarnings("unused") - private Long id; + private final Long id; @SuppressWarnings("unused") - private String name; + private final String name; @SuppressWarnings("unused") - private String externalId; + private final String externalId; public static FundData instance(final Long id, final String name, final String externalId) { return new FundData(id, name, externalId); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/domain/FundRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/domain/FundRepository.java index b4979e08d..510494d8d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/domain/FundRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/domain/FundRepository.java @@ -9,5 +9,5 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface FundRepository extends JpaRepository, JpaSpecificationExecutor { - // no added behaviour + // no added behaviour } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/serialization/FundCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/serialization/FundCommandFromApiJsonDeserializer.java index 709e2b6ab..63c72116f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/serialization/FundCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/serialization/FundCommandFromApiJsonDeserializer.java @@ -44,17 +44,17 @@ public final class FundCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("fund"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); + final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element); baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -64,19 +64,19 @@ public final class FundCommandFromApiJsonDeserializer { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("fund"); - final JsonElement element = fromApiJsonHelper.parse(json); - if (fromApiJsonHelper.parameterExists("name", element)) { - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + if (this.fromApiJsonHelper.parameterExists("name", element)) { + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("externalId", element)) { - final String externalId = fromApiJsonHelper.extractStringNamed("externalId", element); + if (this.fromApiJsonHelper.parameterExists("externalId", element)) { + final String externalId = this.fromApiJsonHelper.extractStringNamed("externalId", element); baseDataValidator.reset().parameter("externalId").value(externalId).notExceedingLengthOf(100); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundReadPlatformServiceImpl.java index f99a92fa7..52a980136 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundReadPlatformServiceImpl.java @@ -53,7 +53,7 @@ public class FundReadPlatformServiceImpl implements FundReadPlatformService { @Cacheable(value = "funds", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('fn')") public Collection retrieveAllFunds() { - context.authenticatedUser(); + this.context.authenticatedUser(); final FundMapper rm = new FundMapper(); final String sql = "select " + rm.schema() + " order by f.name"; @@ -65,7 +65,7 @@ public class FundReadPlatformServiceImpl implements FundReadPlatformService { public FundData retrieveFund(final Long fundId) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); final FundMapper rm = new FundMapper(); final String sql = "select " + rm.schema() + " where f.id = ?"; @@ -73,7 +73,7 @@ public class FundReadPlatformServiceImpl implements FundReadPlatformService { final FundData selectedFund = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { fundId }); return selectedFund; - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new FundNotFoundException(fundId); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java index 35c77f59f..532601d11 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/fund/service/FundWritePlatformServiceJpaRepositoryImpl.java @@ -47,7 +47,7 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf public CommandProcessingResult createFund(final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); @@ -56,7 +56,7 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf this.fundRepository.save(fund); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(fund.getId()).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleFundDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -68,7 +68,7 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf public CommandProcessingResult updateFund(final Long fundId, final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); @@ -81,7 +81,7 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf } return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(fund.getId()).with(changes).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleFundDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -91,9 +91,9 @@ public class FundWritePlatformServiceJpaRepositoryImpl implements FundWritePlatf * Guaranteed to throw an exception no matter what the data integrity issue * is. */ - private void handleFundDataIntegrityIssues(final JsonCommand command, DataIntegrityViolationException dve) { + private void handleFundDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("fund_externalid_org")) { final String externalId = command.stringValueOfParameterNamed("externalId"); throw new PlatformDataIntegrityException("error.msg.fund.duplicate.externalId", "A fund with external id '" + externalId diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/CentersApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/CentersApiResource.java index e10324171..ea52302cd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/CentersApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/CentersApiResource.java @@ -78,7 +78,8 @@ public class CentersApiResource { final ApiRequestParameterHelper apiRequestParameterHelper, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, final CollectionSheetReadPlatformService collectionSheetReadPlatformService, final FromJsonHelper fromJsonHelper, - final AccountDetailsReadPlatformService accountDetailsReadPlatformService, final CalendarReadPlatformService calendarReadPlatformService) { + final AccountDetailsReadPlatformService accountDetailsReadPlatformService, + final CalendarReadPlatformService calendarReadPlatformService) { this.context = context; this.centerReadPlatformService = centerReadPlatformService; this.centerApiJsonSerializer = centerApiJsonSerializer; @@ -104,9 +105,10 @@ public class CentersApiResource { if (is(commandParam, "close")) { final CenterData centerClosureTemplate = this.centerReadPlatformService.retrieveCenterWithClosureReasons(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.centerApiJsonSerializer.serialize(settings, centerClosureTemplate, GroupingTypesApiConstants.CENTER_RESPONSE_DATA_PARAMETERS); + return this.centerApiJsonSerializer.serialize(settings, centerClosureTemplate, + GroupingTypesApiConstants.CENTER_RESPONSE_DATA_PARAMETERS); } - + final CenterData template = this.centerReadPlatformService.retrieveTemplate(officeId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); @@ -128,7 +130,7 @@ public class CentersApiResource { limit, orderBy, sortOrder); final Page centers = this.centerReadPlatformService.retrieveAll(searchParameters); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, centers, GroupingTypesApiConstants.CENTER_RESPONSE_DATA_PARAMETERS); } @@ -154,17 +156,17 @@ public class CentersApiResource { if (associationParameters.contains("groupMembers")) { groups = this.centerReadPlatformService.retrieveAssociatedGroups(centerId); } - + if (associationParameters.contains("collectionMeetingCalendar")) { - collectionMeetingCalendar = this.calendarReadPlatformService.retrieveCollctionCalendarByEntity(centerId, CalendarEntityType.CENTERS.getValue()); - if(collectionMeetingCalendar != null){ + collectionMeetingCalendar = this.calendarReadPlatformService.retrieveCollctionCalendarByEntity(centerId, + CalendarEntityType.CENTERS.getValue()); + if (collectionMeetingCalendar != null) { collectionMeetingCalendar = this.calendarReadPlatformService.generateRecurringDate(collectionMeetingCalendar); } } center = CenterData.withAssociations(center, groups, collectionMeetingCalendar); } - final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.centerApiJsonSerializer.serialize(settings, center, GroupingTypesApiConstants.CENTER_RESPONSE_DATA_PARAMETERS); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupingTypesApiConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupingTypesApiConstants.java index 38eb9e9bb..ced073ce3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupingTypesApiConstants.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupingTypesApiConstants.java @@ -16,19 +16,18 @@ public class GroupingTypesApiConstants { public static final String CENTER_RESOURCE_NAME = "center"; public static final String GROUP_RESOURCE_NAME = "group"; public static final String COMMUNAL_BANK_RESOURCE_NAME = "communalbank"; - - //group roles + + // group roles public static final String GROUP_ROLE_RESOURCE_NAME = "grouprole"; public static final String GROUP_ROLE_NAME = "GROUPROLE"; - + public static final String GROUP_CLOSURE_REASON = "GroupClosureReason"; - + public static final String roleParamName = "role"; public static final String groupIdParamName = "groupId"; public static final String clientIdParamName = "clientId"; public static final String groupRolesParamName = "groupRoles"; - // general public static final String localeParamName = "locale"; public static final String dateFormatParamName = "dateFormat"; @@ -56,8 +55,8 @@ public class GroupingTypesApiConstants { public static final String staffOptionsParamName = "staffOptions"; public static final String clientOptionsParamName = "clientOptions"; public static final String collectionMeetingCalendar = "collectionMeetingCalendar"; - - //group close parameters + + // group close parameters public static final String closureDateParamName = "closureDate"; public static final String closureReasonIdParamName = "closureReasonId"; @@ -68,8 +67,9 @@ public class GroupingTypesApiConstants { public static final Set GROUP_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, dateFormatParamName, idParamName, nameParamName, externalIdParamName, centerIdParamName, officeIdParamName, staffIdParamName, activeParamName, activationDateParamName, clientMembersParamName, collectionMeetingCalendar)); - - public static final Set GROUP_ROLES_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(roleParamName, clientIdParamName)); + + public static final Set GROUP_ROLES_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(roleParamName, + clientIdParamName)); /** * These parameters will match the class level parameters of @@ -90,10 +90,10 @@ public class GroupingTypesApiConstants { public static final Set ACTIVATION_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, dateFormatParamName, activationDateParamName)); - - - public static final Set COLLECTIONSHEET_DATA_PARAMETERS = new HashSet(Arrays.asList("dueDate", "loanProducts", "groups")); - + + public static final Set COLLECTIONSHEET_DATA_PARAMETERS = new HashSet( + Arrays.asList("dueDate", "loanProducts", "groups")); + public static final Set GROUP_CLOSE_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, dateFormatParamName, closureDateParamName, closureReasonIdParamName)); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupsApiResource.java index 1bf6993b7..1faa23e43 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupsApiResource.java @@ -125,9 +125,10 @@ public class GroupsApiResource { if (is(commandParam, "close")) { final GroupGeneralData groupClosureTemplate = this.groupReadPlatformService.retrieveGroupWithClosureReasons(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.groupGeneralApiJsonSerializer.serialize(settings, groupClosureTemplate, GroupingTypesApiConstants.GROUP_RESPONSE_DATA_PARAMETERS); + return this.groupGeneralApiJsonSerializer.serialize(settings, groupClosureTemplate, + GroupingTypesApiConstants.GROUP_RESPONSE_DATA_PARAMETERS); } - + if (centerId != null) { final GroupGeneralData centerGroupTemplate = this.centerReadPlatformService.retrieveCenterGroupTemplate(centerId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupsLevelApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupsLevelApiResource.java index 6a4fc6e46..faa9999a5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupsLevelApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/api/GroupsLevelApiResource.java @@ -33,8 +33,8 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class GroupsLevelApiResource { - private static final Set GROUPLEVEL_DATA_PARAMETERS = new HashSet(Arrays.asList("levelId", "levelName", "parentLevelId", - "parentLevelName", "childLevelId", "childLevelName" , "superParent" , "recursable" , "canHaveClients")); + private static final Set GROUPLEVEL_DATA_PARAMETERS = new HashSet(Arrays.asList("levelId", "levelName", + "parentLevelId", "parentLevelName", "childLevelId", "childLevelName", "superParent", "recursable", "canHaveClients")); private final PlatformSecurityContext context; private final GroupLevelReadPlatformService groupLevelReadPlatformService; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/data/CenterData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/data/CenterData.java index b77e8ddbe..8ecd24ca4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/data/CenterData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/data/CenterData.java @@ -75,10 +75,12 @@ public class CenterData { groupMembers, officeOptions, staffOptions, groupMembersOptions, collectionMeetingCalendar, closureReasons); } - public static CenterData withAssociations(final CenterData centerData, final Collection groupMembers, final CalendarData collectionMeetingCalendar) { + public static CenterData withAssociations(final CenterData centerData, final Collection groupMembers, + final CalendarData collectionMeetingCalendar) { return new CenterData(centerData.id, centerData.name, centerData.externalId, centerData.status, centerData.activationDate, centerData.officeId, centerData.officeName, centerData.staffId, centerData.staffName, centerData.hierarchy, groupMembers, - centerData.officeOptions, centerData.staffOptions, centerData.groupMembersOptions, collectionMeetingCalendar, centerData.closureReasons); + centerData.officeOptions, centerData.staffOptions, centerData.groupMembersOptions, collectionMeetingCalendar, + centerData.closureReasons); } public static CenterData withClosureReasons(final Collection closureReasons) { @@ -100,7 +102,7 @@ public class CenterData { return new CenterData(id, name, externalId, status, activationDate, officeId, officeName, staffId, staffName, hierarchy, groupMembers, officeOptions, staffOptions, groupMembersOptions, collectionMeetingCalendar, closureReasons); } - + private CenterData(final Long id, final String name, final String externalId, final EnumOptionData status, final LocalDate activationDate, final Long officeId, final String officeName, final Long staffId, final String staffName, final String hierarchy, final Collection groupMembers, final Collection officeOptions, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/data/GroupGeneralData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/data/GroupGeneralData.java index 9de2c69ba..f5236e2ae 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/data/GroupGeneralData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/data/GroupGeneralData.java @@ -42,7 +42,7 @@ public class GroupGeneralData { private final Collection clientMembers; private final Collection groupRoles; private final Collection calendarsData; - private final CalendarData collectionMeetingCalendar; + private final CalendarData collectionMeetingCalendar; // template private final Collection centerOptions; @@ -71,7 +71,8 @@ public class GroupGeneralData { final Collection closureReasons = null; return new GroupGeneralData(null, null, null, null, null, officeId, null, centerId, centerName, staffId, staffName, null, - clientMembers, centerOptions, officeOptions, staffOptions, clientOptions, groupRoles, availableRoles, null, null, null, closureReasons); + clientMembers, centerOptions, officeOptions, staffOptions, clientOptions, groupRoles, availableRoles, null, null, null, + closureReasons); } public static GroupGeneralData withTemplate(final GroupGeneralData templatedGrouping, final GroupGeneralData grouping) { @@ -83,11 +84,13 @@ public class GroupGeneralData { } public static GroupGeneralData withAssocations(final GroupGeneralData grouping, final Collection membersOfGroup, - final Collection groupRoles, final Collection calendarsData, final CalendarData collectionMeetingCalendar) { + final Collection groupRoles, final Collection calendarsData, + final CalendarData collectionMeetingCalendar) { return new GroupGeneralData(grouping.id, grouping.name, grouping.externalId, grouping.status, grouping.activationDate, grouping.officeId, grouping.officeName, grouping.centerId, grouping.centerName, grouping.staffId, grouping.staffName, grouping.hierarchy, membersOfGroup, grouping.centerOptions, grouping.officeOptions, grouping.staffOptions, - grouping.clientOptions, groupRoles, grouping.availableRoles, grouping.selectedRole, calendarsData, collectionMeetingCalendar, grouping.closureReasons); + grouping.clientOptions, groupRoles, grouping.availableRoles, grouping.selectedRole, calendarsData, + collectionMeetingCalendar, grouping.closureReasons); } public static GroupGeneralData instance(final Long id, final String name, final String externalId, final EnumOptionData status, @@ -117,7 +120,8 @@ public class GroupGeneralData { final Collection centerOptions, final Collection officeOptions, final Collection staffOptions, final Collection clientOptions, final Collection groupRoles, final Collection availableRoles, final GroupRoleData role, - final Collection calendarsData, final CalendarData collectionMeetingCalendar, final Collection closureReasons) { + final Collection calendarsData, final CalendarData collectionMeetingCalendar, + final Collection closureReasons) { this.id = id; this.name = name; this.externalId = externalId; @@ -172,21 +176,21 @@ public class GroupGeneralData { public String getHierarchy() { return this.hierarchy; } - - public boolean isChildGroup(){ + + public boolean isChildGroup() { return this.centerId == null ? false : true; } - public Long getParentId(){ + public Long getParentId() { return this.centerId; } - - + public static GroupGeneralData updateSelectedRole(final GroupGeneralData grouping, final GroupRoleData selectedRole) { return new GroupGeneralData(grouping.id, grouping.name, grouping.externalId, grouping.status, grouping.activationDate, grouping.officeId, grouping.officeName, grouping.centerId, grouping.centerName, grouping.staffId, grouping.staffName, grouping.hierarchy, grouping.clientMembers, grouping.centerOptions, grouping.officeOptions, grouping.staffOptions, - grouping.clientOptions, grouping.groupRoles, grouping.availableRoles, selectedRole, grouping.calendarsData, grouping.collectionMeetingCalendar, grouping.closureReasons); + grouping.clientOptions, grouping.groupRoles, grouping.availableRoles, selectedRole, grouping.calendarsData, + grouping.collectionMeetingCalendar, grouping.closureReasons); } public static GroupGeneralData withClosureReasons(final Collection closureReasons) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/Group.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/Group.java index 0f0dfe515..235e94ea3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/Group.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/Group.java @@ -97,11 +97,11 @@ public final class Group extends AbstractPersistable { @ManyToMany @JoinTable(name = "m_group_client", joinColumns = @JoinColumn(name = "group_id"), inverseJoinColumns = @JoinColumn(name = "client_id")) private Set clientMembers; - + @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "closure_reason_cv_id", nullable = true) private CodeValue closureReason; - + @Column(name = "closedon_date", nullable = true) @Temporal(TemporalType.DATE) private Date closureDate; @@ -397,7 +397,7 @@ public final class Group extends AbstractPersistable { public boolean isTransferInProgress() { return GroupingTypeStatus.fromInt(this.status).isTransferInProgress(); } - + public boolean isTransferOnHold() { return GroupingTypeStatus.fromInt(this.status).isTransferOnHold(); } @@ -409,50 +409,50 @@ public final class Group extends AbstractPersistable { public boolean isChildClient(final Long clientId) { if (clientId != null && this.clientMembers != null && !this.clientMembers.isEmpty()) { for (final Client client : this.clientMembers) { - if (client.getId().equals(clientId)) { - return true; - } + if (client.getId().equals(clientId)) { return true; } } } return false; } - public boolean isChildGroup(){ + public boolean isChildGroup() { return (this.parent == null) ? false : true; } - - public boolean isClosed(){ + + public boolean isClosed() { return GroupingTypeStatus.fromInt(this.status).isClosed(); } - - public void close(final CodeValue closureReason, final LocalDate closureDate){ - - if (this.isClosed()) { - final String errorMessage = "Group with identifier " + this.getId() + " is alread closed."; - throw new InvalidGroupStateTransitionException(this.groupLevel.getLevelName(), "close", "already.closed", errorMessage, this.getId()); + + public void close(final CodeValue closureReason, final LocalDate closureDate) { + + if (isClosed()) { + final String errorMessage = "Group with identifier " + getId() + " is alread closed."; + throw new InvalidGroupStateTransitionException(this.groupLevel.getLevelName(), "close", "already.closed", errorMessage, getId()); } - - if (this.isNotPending() && this.getActivationLocalDate().isAfter(closureDate)) { - final String errorMessage = "The Group closure Date " + closureDate + " cannot be before the group Activation Date " + this.getActivationLocalDate() + "."; - throw new InvalidGroupStateTransitionException(this.groupLevel.getLevelName(), "close", "date.cannot.before.group.actvation.date", errorMessage, closureDate, this.getActivationLocalDate()); + + if (isNotPending() && getActivationLocalDate().isAfter(closureDate)) { + final String errorMessage = "The Group closure Date " + closureDate + " cannot be before the group Activation Date " + + getActivationLocalDate() + "."; + throw new InvalidGroupStateTransitionException(this.groupLevel.getLevelName(), "close", + "date.cannot.before.group.actvation.date", errorMessage, closureDate, getActivationLocalDate()); } - + this.closureReason = closureReason; this.closureDate = closureDate.toDate(); this.status = GroupingTypeStatus.CLOSED.getValue(); } - - public boolean hasActiveClients(){ - for (Client client : this.clientMembers) { - if(!client.isClosed()) return true; + + public boolean hasActiveClients() { + for (final Client client : this.clientMembers) { + if (!client.isClosed()) { return true; } } return false; } - - public boolean hasActiveGroups(){ - for(Group group : this.groupMembers){ - if(!group.isClosed()) return true; + + public boolean hasActiveGroups() { + for (final Group group : this.groupMembers) { + if (!group.isClosed()) { return true; } } return false; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupRepository.java index 4a0402fef..c56c33718 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupRepository.java @@ -11,5 +11,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface GroupRepository extends JpaRepository, JpaSpecificationExecutor { + Collection findByParentId(Long parentId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupingTypeEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupingTypeEnumerations.java index a82e3df2d..2cdca41cd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupingTypeEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupingTypeEnumerations.java @@ -34,12 +34,12 @@ public class GroupingTypeEnumerations { "Closed"); break; case TRANSFER_IN_PROGRESS: - optionData = new EnumOptionData(GroupingTypeStatus.TRANSFER_IN_PROGRESS.getValue().longValue(), GroupingTypeStatus.TRANSFER_IN_PROGRESS.getCode(), - "Transfer in progress"); + optionData = new EnumOptionData(GroupingTypeStatus.TRANSFER_IN_PROGRESS.getValue().longValue(), + GroupingTypeStatus.TRANSFER_IN_PROGRESS.getCode(), "Transfer in progress"); break; case TRANSFER_ON_HOLD: - optionData = new EnumOptionData(GroupingTypeStatus.TRANSFER_ON_HOLD.getValue().longValue(), GroupingTypeStatus.TRANSFER_ON_HOLD.getCode(), - "Transfer on hold"); + optionData = new EnumOptionData(GroupingTypeStatus.TRANSFER_ON_HOLD.getValue().longValue(), + GroupingTypeStatus.TRANSFER_ON_HOLD.getCode(), "Transfer on hold"); break; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupingTypeStatus.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupingTypeStatus.java index a52b1d1be..a47bbdcbc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupingTypeStatus.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/domain/GroupingTypeStatus.java @@ -51,7 +51,7 @@ public enum GroupingTypeStatus { } public String getCode() { - return code; + return this.code; } public boolean isPending() { @@ -67,11 +67,11 @@ public enum GroupingTypeStatus { } public boolean isTransferInProgress() { - return this.isTransferInProgress(); + return isTransferInProgress(); } public boolean isTransferOnHold() { - return this.isTransferOnHold(); + return isTransferOnHold(); } public boolean isUnderTransfer() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/ClientExistInGroupException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/ClientExistInGroupException.java index b7c47ed2f..19f3db5bc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/ClientExistInGroupException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/ClientExistInGroupException.java @@ -10,8 +10,8 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul public class ClientExistInGroupException extends AbstractPlatformDomainRuleException { public ClientExistInGroupException(final Long clientId, final Long groupId) { - super("error.msg.group.client.exist.in.group", "Client with identifier " + clientId + " is already exists in Group with identifier " + groupId, - clientId, groupId); + super("error.msg.group.client.exist.in.group", "Client with identifier " + clientId + + " is already exists in Group with identifier " + groupId, clientId, groupId); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/ClientNotInGroupException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/ClientNotInGroupException.java index c87e5eb42..884720ce6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/ClientNotInGroupException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/ClientNotInGroupException.java @@ -10,12 +10,13 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul public class ClientNotInGroupException extends AbstractPlatformDomainRuleException { public ClientNotInGroupException(final Long clientId, final Long groupId) { - this("group.client.not.in.group", "Client with identifier " + clientId + " is not in Group with identifier " + groupId, clientId, groupId); - + this("group.client.not.in.group", "Client with identifier " + clientId + " is not in Group with identifier " + groupId, clientId, + groupId); + } - - public ClientNotInGroupException(String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg." + postFix , defaultUserMessage, defaultUserMessageArgs); + + public ClientNotInGroupException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { + super("error.msg." + postFix, defaultUserMessage, defaultUserMessageArgs); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/GroupAccountExistsException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/GroupAccountExistsException.java index 3657c287d..eefd43215 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/GroupAccountExistsException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/GroupAccountExistsException.java @@ -9,7 +9,8 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul public class GroupAccountExistsException extends AbstractPlatformDomainRuleException { - public GroupAccountExistsException(final String action, String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { + public GroupAccountExistsException(final String action, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg.group." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/InvalidGroupStateTransitionException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/InvalidGroupStateTransitionException.java index f745779f3..aa31163ce 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/InvalidGroupStateTransitionException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/exception/InvalidGroupStateTransitionException.java @@ -7,7 +7,6 @@ package org.mifosplatform.portfolio.group.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - public class InvalidGroupStateTransitionException extends AbstractPlatformDomainRuleException { public InvalidGroupStateTransitionException(final String levelName, final String action, final String postFix, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/AssignGroupStaffCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/AssignGroupStaffCommandHandler.java index 1896e641b..cfe26fe23 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/AssignGroupStaffCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/AssignGroupStaffCommandHandler.java @@ -15,14 +15,14 @@ import org.springframework.transaction.annotation.Transactional; @Service public class AssignGroupStaffCommandHandler implements NewCommandSourceHandler { - + private final GroupingTypesWritePlatformService groupWritePlatformService; - + @Autowired public AssignGroupStaffCommandHandler(final GroupingTypesWritePlatformService groupWritePlatformService) { this.groupWritePlatformService = groupWritePlatformService; } - + @Transactional @Override public CommandProcessingResult processCommand(final JsonCommand command) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/CloseCenterCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/CloseCenterCommandHandler.java index 854e984cf..fd4ee3c95 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/CloseCenterCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/CloseCenterCommandHandler.java @@ -10,9 +10,9 @@ import org.springframework.transaction.annotation.Transactional; @Service public class CloseCenterCommandHandler implements NewCommandSourceHandler { - + private final GroupingTypesWritePlatformService groupingTypesWritePlatformService; - + @Autowired public CloseCenterCommandHandler(final GroupingTypesWritePlatformService groupingTypesWritePlatformService) { this.groupingTypesWritePlatformService = groupingTypesWritePlatformService; @@ -20,7 +20,7 @@ public class CloseCenterCommandHandler implements NewCommandSourceHandler { @Override @Transactional - public CommandProcessingResult processCommand(JsonCommand command) { + public CommandProcessingResult processCommand(final JsonCommand command) { return this.groupingTypesWritePlatformService.closeCenter(command.entityId(), command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/CloseGroupCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/CloseGroupCommandHandler.java index 714ce10ff..b354dad68 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/CloseGroupCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/CloseGroupCommandHandler.java @@ -10,9 +10,9 @@ import org.springframework.transaction.annotation.Transactional; @Service public class CloseGroupCommandHandler implements NewCommandSourceHandler { - + private final GroupingTypesWritePlatformService groupingTypesWritePlatformService; - + @Autowired public CloseGroupCommandHandler(final GroupingTypesWritePlatformService groupingTypesWritePlatformService) { this.groupingTypesWritePlatformService = groupingTypesWritePlatformService; @@ -20,7 +20,7 @@ public class CloseGroupCommandHandler implements NewCommandSourceHandler { @Override @Transactional - public CommandProcessingResult processCommand(JsonCommand command) { + public CommandProcessingResult processCommand(final JsonCommand command) { return this.groupingTypesWritePlatformService.closeGroup(command.entityId(), command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/UnassignRoleCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/UnassignRoleCommandHandler.java index 94662f1bd..9a3a151a6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/UnassignRoleCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/UnassignRoleCommandHandler.java @@ -10,9 +10,9 @@ import org.springframework.transaction.annotation.Transactional; @Service public class UnassignRoleCommandHandler implements NewCommandSourceHandler { - + private final GroupRolesWritePlatformService groupRolesWritePlatformService; - + @Autowired public UnassignRoleCommandHandler(final GroupRolesWritePlatformService groupRolesWritePlatformService) { this.groupRolesWritePlatformService = groupRolesWritePlatformService; @@ -20,8 +20,8 @@ public class UnassignRoleCommandHandler implements NewCommandSourceHandler { @Override @Transactional - public CommandProcessingResult processCommand(JsonCommand command) { - return this.groupRolesWritePlatformService.deleteRole(command.entityId()); + public CommandProcessingResult processCommand(final JsonCommand command) { + return this.groupRolesWritePlatformService.deleteRole(command.entityId()); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/UpdateGroupRoleCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/UpdateGroupRoleCommandHandler.java index 5671cb633..bc69e1d75 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/UpdateGroupRoleCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/handler/UpdateGroupRoleCommandHandler.java @@ -10,9 +10,9 @@ import org.springframework.transaction.annotation.Transactional; @Service public class UpdateGroupRoleCommandHandler implements NewCommandSourceHandler { - + private final GroupRolesWritePlatformService groupRolesWritePlatformService; - + @Autowired public UpdateGroupRoleCommandHandler(final GroupRolesWritePlatformService groupRolesWritePlatformService) { this.groupRolesWritePlatformService = groupRolesWritePlatformService; @@ -20,7 +20,7 @@ public class UpdateGroupRoleCommandHandler implements NewCommandSourceHandler { @Override @Transactional - public CommandProcessingResult processCommand(JsonCommand command) { + public CommandProcessingResult processCommand(final JsonCommand command) { return this.groupRolesWritePlatformService.updateRole(command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/serialization/GroupRolesDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/serialization/GroupRolesDataValidator.java index 01ca0ccf6..fdaa183a7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/serialization/GroupRolesDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/serialization/GroupRolesDataValidator.java @@ -85,5 +85,5 @@ public class GroupRolesDataValidator { throwExceptionIfValidationWarningsExist(dataValidationErrors); } - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/serialization/GroupingTypesDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/serialization/GroupingTypesDataValidator.java index 4a519758c..41ac94d6d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/serialization/GroupingTypesDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/serialization/GroupingTypesDataValidator.java @@ -60,7 +60,7 @@ public final class GroupingTypesDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(GroupingTypesApiConstants.CENTER_RESOURCE_NAME); - JsonElement element = command.parsedJson(); + final JsonElement element = command.parsedJson(); final String name = this.fromApiJsonHelper.extractStringNamed(GroupingTypesApiConstants.nameParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.nameParamName).value(name).notNull().notExceedingLengthOf(100); @@ -78,16 +78,16 @@ public final class GroupingTypesDataValidator { baseDataValidator.reset().parameter(GroupingTypesApiConstants.staffIdParamName).value(staffId).integerGreaterThanZero(); } - final Boolean active = fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); + final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); if (active != null) { if (active.booleanValue()) { - final LocalDate joinedDate = fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, - element); + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed( + GroupingTypesApiConstants.activationDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull(); } else { // TODO - KW - not using config for now - just supporting move // to pending or active out of box. - boolean isPendingApprovalEnabled = true; + final boolean isPendingApprovalEnabled = true; if (!isPendingApprovalEnabled) { baseDataValidator.reset().parameter(GroupingTypesApiConstants.activeParamName) .failWithCode(".pending.status.not.allowed"); @@ -114,7 +114,7 @@ public final class GroupingTypesDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(GroupingTypesApiConstants.GROUP_RESOURCE_NAME); - JsonElement element = command.parsedJson(); + final JsonElement element = command.parsedJson(); final String name = this.fromApiJsonHelper.extractStringNamed(GroupingTypesApiConstants.nameParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.nameParamName).value(name).notNull().notExceedingLengthOf(100); @@ -136,16 +136,16 @@ public final class GroupingTypesDataValidator { baseDataValidator.reset().parameter(GroupingTypesApiConstants.staffIdParamName).value(staffId).integerGreaterThanZero(); } - final Boolean active = fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); + final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); if (active != null) { if (active.booleanValue()) { - final LocalDate joinedDate = fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, - element); + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed( + GroupingTypesApiConstants.activationDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull(); } else { // TODO - KW - not using config for now - just supporting move // to pending or active out of box. - boolean isPendingApprovalEnabled = true; + final boolean isPendingApprovalEnabled = true; if (!isPendingApprovalEnabled) { baseDataValidator.reset().parameter(GroupingTypesApiConstants.activeParamName) .failWithCode(".pending.status.not.allowed"); @@ -171,7 +171,7 @@ public final class GroupingTypesDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(GroupingTypesApiConstants.GROUP_RESOURCE_NAME); - JsonElement element = command.parsedJson(); + final JsonElement element = command.parsedJson(); final String name = this.fromApiJsonHelper.extractStringNamed(GroupingTypesApiConstants.nameParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.nameParamName).value(name).notNull().notExceedingLengthOf(100); @@ -190,16 +190,16 @@ public final class GroupingTypesDataValidator { baseDataValidator.reset().parameter(GroupingTypesApiConstants.staffIdParamName).value(staffId).integerGreaterThanZero(); } - final Boolean active = fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); + final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); if (active != null) { if (active.booleanValue()) { - final LocalDate joinedDate = fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, - element); + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed( + GroupingTypesApiConstants.activationDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull(); } else { // TODO - KW - not using config for now - just supporting move // to pending or active out of box. - boolean isPendingApprovalEnabled = true; + final boolean isPendingApprovalEnabled = true; if (!isPendingApprovalEnabled) { baseDataValidator.reset().parameter(GroupingTypesApiConstants.activeParamName) .failWithCode(".pending.status.not.allowed"); @@ -225,7 +225,7 @@ public final class GroupingTypesDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(GroupingTypesApiConstants.CENTER_RESOURCE_NAME); - JsonElement element = command.parsedJson(); + final JsonElement element = command.parsedJson(); final String name = this.fromApiJsonHelper.extractStringNamed(GroupingTypesApiConstants.nameParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.nameParamName).value(name).notNull().notExceedingLengthOf(100); @@ -246,11 +246,11 @@ public final class GroupingTypesDataValidator { baseDataValidator.reset().parameter(GroupingTypesApiConstants.staffIdParamName).value(staffId).integerGreaterThanZero(); } - final Boolean active = fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); + final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); if (active != null) { if (active.booleanValue()) { - final LocalDate joinedDate = fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, - element); + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed( + GroupingTypesApiConstants.activationDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull(); } } @@ -271,7 +271,7 @@ public final class GroupingTypesDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(GroupingTypesApiConstants.GROUP_RESOURCE_NAME); - JsonElement element = command.parsedJson(); + final JsonElement element = command.parsedJson(); final String name = this.fromApiJsonHelper.extractStringNamed(GroupingTypesApiConstants.nameParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.nameParamName).value(name).notNull().notExceedingLengthOf(100); @@ -292,11 +292,11 @@ public final class GroupingTypesDataValidator { baseDataValidator.reset().parameter(GroupingTypesApiConstants.staffIdParamName).value(staffId).integerGreaterThanZero(); } - final Boolean active = fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); + final Boolean active = this.fromApiJsonHelper.extractBooleanNamed(GroupingTypesApiConstants.activeParamName, element); if (active != null) { if (active.booleanValue()) { - final LocalDate joinedDate = fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, - element); + final LocalDate joinedDate = this.fromApiJsonHelper.extractLocalDateNamed( + GroupingTypesApiConstants.activationDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(joinedDate).notNull(); } } @@ -310,15 +310,15 @@ public final class GroupingTypesDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, GroupingTypesApiConstants.ACTIVATION_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, GroupingTypesApiConstants.ACTIVATION_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(resourceName); final JsonElement element = command.parsedJson(); - final LocalDate activationDate = fromApiJsonHelper - .extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, element); + final LocalDate activationDate = this.fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.activationDateParamName, + element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.activationDateParamName).value(activationDate).notNull(); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -344,7 +344,7 @@ public final class GroupingTypesDataValidator { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - + public void validateForAssignStaff(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } @@ -366,8 +366,8 @@ public final class GroupingTypesDataValidator { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - - public void validateForAssociateClients(final String json){ + + public void validateForAssociateClients(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } @@ -381,13 +381,13 @@ public final class GroupingTypesDataValidator { final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("group"); - final String[] clients = fromApiJsonHelper.extractArrayNamed(GroupingTypesApiConstants.clientMembersParamName, element); + final String[] clients = this.fromApiJsonHelper.extractArrayNamed(GroupingTypesApiConstants.clientMembersParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.clientMembersParamName).value(clients).arrayNotEmpty(); - + throwExceptionIfValidationWarningsExist(dataValidationErrors); } - - public void validateForDisassociateClients(final String json){ + + public void validateForDisassociateClients(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } @@ -401,56 +401,60 @@ public final class GroupingTypesDataValidator { final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("group"); - final String[] clients = fromApiJsonHelper.extractArrayNamed(GroupingTypesApiConstants.clientMembersParamName, element); + final String[] clients = this.fromApiJsonHelper.extractArrayNamed(GroupingTypesApiConstants.clientMembersParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.clientMembersParamName).value(clients).arrayNotEmpty(); - + throwExceptionIfValidationWarningsExist(dataValidationErrors); } - + public void validateForGroupClose(final JsonCommand command) { final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, GroupingTypesApiConstants.GROUP_CLOSE_REQUEST_DATA_PARAMETERS); - + this.fromApiJsonHelper + .checkForUnsupportedParameters(typeOfMap, json, GroupingTypesApiConstants.GROUP_CLOSE_REQUEST_DATA_PARAMETERS); + final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(GroupingTypesApiConstants.GROUP_RESOURCE_NAME); - + final JsonElement element = command.parsedJson(); final LocalDate closureDate = this.fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.closureDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.closureDateParamName).value(closureDate).notNull(); - + final Long closureReasonId = this.fromApiJsonHelper.extractLongNamed(GroupingTypesApiConstants.closureReasonIdParamName, element); - baseDataValidator.reset().parameter(GroupingTypesApiConstants.closureReasonIdParamName).value(closureReasonId).notNull().longGreaterThanZero(); - + baseDataValidator.reset().parameter(GroupingTypesApiConstants.closureReasonIdParamName).value(closureReasonId).notNull() + .longGreaterThanZero(); + throwExceptionIfValidationWarningsExist(dataValidationErrors); } - + public void validateForCenterClose(final JsonCommand command) { final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, GroupingTypesApiConstants.GROUP_CLOSE_REQUEST_DATA_PARAMETERS); - + this.fromApiJsonHelper + .checkForUnsupportedParameters(typeOfMap, json, GroupingTypesApiConstants.GROUP_CLOSE_REQUEST_DATA_PARAMETERS); + final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(GroupingTypesApiConstants.CENTER_RESOURCE_NAME); - + final JsonElement element = command.parsedJson(); final LocalDate closureDate = this.fromApiJsonHelper.extractLocalDateNamed(GroupingTypesApiConstants.closureDateParamName, element); baseDataValidator.reset().parameter(GroupingTypesApiConstants.closureDateParamName).value(closureDate).notNull(); - + final Long closureReasonId = this.fromApiJsonHelper.extractLongNamed(GroupingTypesApiConstants.closureReasonIdParamName, element); - baseDataValidator.reset().parameter(GroupingTypesApiConstants.closureReasonIdParamName).value(closureReasonId).notNull().longGreaterThanZero(); - + baseDataValidator.reset().parameter(GroupingTypesApiConstants.closureReasonIdParamName).value(closureReasonId).notNull() + .longGreaterThanZero(); + throwExceptionIfValidationWarningsExist(dataValidationErrors); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/CenterReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/CenterReadPlatformService.java index 1535879b2..4fa01bd13 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/CenterReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/CenterReadPlatformService.java @@ -22,8 +22,8 @@ public interface CenterReadPlatformService { Page retrieveAll(SearchParameters searchParameters); GroupGeneralData retrieveCenterGroupTemplate(Long centerId); - + Collection retrieveAssociatedGroups(Long centerId); - + CenterData retrieveCenterWithClosureReasons(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/CenterReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/CenterReadPlatformServiceImpl.java index 327cea4fc..7175c324b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/CenterReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/CenterReadPlatformServiceImpl.java @@ -60,7 +60,7 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService // data mappers private final CenterDataMapper centerMapper = new CenterDataMapper(); private final GroupDataMapper groupDataMapper = new GroupDataMapper(); - + private final PaginationHelper paginationHelper = new PaginationHelper(); @Autowired @@ -194,11 +194,11 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService @Override public Page retrieveAll(final SearchParameters searchParameters) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - StringBuilder sqlBuilder = new StringBuilder(200); + final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); sqlBuilder.append(this.centerMapper.schema()); sqlBuilder.append(" where o.hierarchy like ?"); @@ -218,7 +218,7 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService if (searchParameters.isOffset()) { sqlBuilder.append(" offset ").append(searchParameters.getOffset()); } - } + } final String sqlCountRows = "SELECT FOUND_ROWS()"; return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlCountRows, sqlBuilder.toString(), @@ -228,14 +228,14 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService @Override public Collection retrieveAllForDropdown(final Long officeId) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - final String sql = "select " + centerMapper.schema() + final String sql = "select " + this.centerMapper.schema() + " where g.office_id = ? and g.parent_id is null and g.level_Id = ? and o.hierarchy like ? order by g.hierarchy"; - return this.jdbcTemplate.query(sql, centerMapper, new Object[] { officeId, GroupTypes.CENTER.getId(), hierarchySearchString }); + return this.jdbcTemplate.query(sql, this.centerMapper, new Object[] { officeId, GroupTypes.CENTER.getId(), hierarchySearchString }); } @Override @@ -265,14 +265,14 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService final Long defaultOfficeId = defaultToUsersOfficeIfNull(officeId); - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - final String sql = "select " + allGroupTypesDataMapper.schema() + final String sql = "select " + this.allGroupTypesDataMapper.schema() + " where g.office_id = ? and g.parent_id is null and g.level_Id = ? and o.hierarchy like ? order by g.hierarchy"; - return this.jdbcTemplate.query(sql, allGroupTypesDataMapper, new Object[] { defaultOfficeId, GroupTypes.GROUP.getId(), + return this.jdbcTemplate.query(sql, this.allGroupTypesDataMapper, new Object[] { defaultOfficeId, GroupTypes.GROUP.getId(), hierarchySearchString }); } @@ -288,14 +288,14 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService public CenterData retrieveOne(final Long centerId) { try { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - String sql = "select " + this.centerMapper.schema() + " where g.id = ? and o.hierarchy like ?"; + final String sql = "select " + this.centerMapper.schema() + " where g.id = ? and o.hierarchy like ?"; return this.jdbcTemplate.queryForObject(sql, this.centerMapper, new Object[] { centerId, hierarchySearchString }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new CenterNotFoundException(centerId); } } @@ -303,7 +303,7 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService @Override public GroupGeneralData retrieveCenterGroupTemplate(final Long centerId) { - final CenterData center = this.retrieveOne(centerId); + final CenterData center = retrieveOne(centerId); final Long centerOfficeId = center.officeId(); final OfficeData centerOffice = this.officeReadPlatformService.retrieveOffice(centerOfficeId); @@ -335,14 +335,14 @@ public class CenterReadPlatformServiceImpl implements CenterReadPlatformService @Override public Collection retrieveAssociatedGroups(final Long centerId) { - String sql = "select " + this.groupDataMapper.schema() + " where g.parent_id = ? "; + final String sql = "select " + this.groupDataMapper.schema() + " where g.parent_id = ? "; return this.jdbcTemplate.query(sql, this.groupDataMapper, new Object[] { centerId }); } - + @Override public CenterData retrieveCenterWithClosureReasons() { final List closureReasons = new ArrayList( - codeValueReadPlatformService.retrieveCodeValuesByCode(GroupingTypesApiConstants.GROUP_CLOSURE_REASON)); + this.codeValueReadPlatformService.retrieveCodeValuesByCode(GroupingTypesApiConstants.GROUP_CLOSURE_REASON)); return CenterData.withClosureReasons(closureReasons); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupLevelReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupLevelReadPlatformServiceImpl.java index 3a6f402fa..60f2a6bcf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupLevelReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupLevelReadPlatformServiceImpl.java @@ -24,9 +24,8 @@ public class GroupLevelReadPlatformServiceImpl implements GroupLevelReadPlatform private final PlatformSecurityContext context; private final JdbcTemplate jdbcTemplate; - @Autowired - public GroupLevelReadPlatformServiceImpl(final PlatformSecurityContext context , final RoutingDataSource dataSource) { + public GroupLevelReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource) { this.context = context; this.jdbcTemplate = new JdbcTemplate(dataSource); } @@ -34,13 +33,13 @@ public class GroupLevelReadPlatformServiceImpl implements GroupLevelReadPlatform @Override public Collection retrieveAllLevels() { this.context.authenticatedUser(); - + final GroupLevelDataMapper rm = new GroupLevelDataMapper(); final String sql = "select " + rm.groupLevelSchema(); return this.jdbcTemplate.query(sql, rm); - + } - + private static final class GroupLevelDataMapper implements RowMapper { public String groupLevelSchema() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupReadPlatformService.java index e35d37375..1f312acbd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupReadPlatformService.java @@ -19,6 +19,6 @@ public interface GroupReadPlatformService { GroupGeneralData retrieveOne(Long groupId); Collection retrieveGroupsForLookup(Long officeId); - + GroupGeneralData retrieveGroupWithClosureReasons(); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupReadPlatformServiceImpl.java index 6d80cb3b2..2a63a6763 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupReadPlatformServiceImpl.java @@ -210,8 +210,8 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { @Override public Collection retrieveGroupsForLookup(final Long officeId) { this.context.authenticatedUser(); - GroupLookupDataMapper rm = new GroupLookupDataMapper(); - String sql = "Select " + rm.schema() + " and g.office_id=?"; + final GroupLookupDataMapper rm = new GroupLookupDataMapper(); + final String sql = "Select " + rm.schema() + " and g.office_id=?"; return this.jdbcTemplate.query(sql, rm, new Object[] { officeId }); } @@ -232,8 +232,8 @@ public class GroupReadPlatformServiceImpl implements GroupReadPlatformService { @Override public GroupGeneralData retrieveGroupWithClosureReasons() { final List closureReasons = new ArrayList( - codeValueReadPlatformService.retrieveCodeValuesByCode(GroupingTypesApiConstants.GROUP_CLOSURE_REASON)); + this.codeValueReadPlatformService.retrieveCodeValuesByCode(GroupingTypesApiConstants.GROUP_CLOSURE_REASON)); return GroupGeneralData.withClosureReasons(closureReasons); } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupRolesWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupRolesWritePlatformService.java index b2fbfe1ee..4463960e5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupRolesWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupRolesWritePlatformService.java @@ -3,7 +3,6 @@ package org.mifosplatform.portfolio.group.service; import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; - public interface GroupRolesWritePlatformService { CommandProcessingResult createRole(JsonCommand command); @@ -11,5 +10,5 @@ public interface GroupRolesWritePlatformService { CommandProcessingResult updateRole(JsonCommand command); CommandProcessingResult deleteRole(Long ruleId); - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupRolesWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupRolesWritePlatformServiceJpaRepositoryImpl.java index 01cef1d85..691f8528d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupRolesWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupRolesWritePlatformServiceJpaRepositoryImpl.java @@ -35,7 +35,7 @@ public class GroupRolesWritePlatformServiceJpaRepositoryImpl implements GroupRol private final CodeValueRepositoryWrapper codeValueRepository; private final ClientRepositoryWrapper clientRepository; private final GroupRoleRepositoryWrapper groupRoleRepository; - + @Autowired public GroupRolesWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final GroupRepositoryWrapper groupRepository, final GroupRolesDataValidator fromApiJsonDeserializer, @@ -143,5 +143,5 @@ public class GroupRolesWritePlatformServiceJpaRepositoryImpl implements GroupRol this.groupRoleRepository.delete(groupRole); return new CommandProcessingResultBuilder().withEntityId(groupRole.getId()).build(); } - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupTypeEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupTypeEnumerations.java index 1c047ed1c..f40f86f3a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupTypeEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupTypeEnumerations.java @@ -24,7 +24,7 @@ public class GroupTypeEnumerations { optionData = new EnumOptionData(type.getId().longValue(), type.getCode(), "Group loan"); break; default: - optionData = new EnumOptionData(GroupTypes.INVALID.getId().longValue(), GroupTypes.INVALID.getCode() , "Invalid"); + optionData = new EnumOptionData(GroupTypes.INVALID.getId().longValue(), GroupTypes.INVALID.getCode(), "Invalid"); break; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupingTypesWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupingTypesWritePlatformService.java index 14505b84e..18a6f97aa 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupingTypesWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupingTypesWritePlatformService.java @@ -21,16 +21,16 @@ public interface GroupingTypesWritePlatformService { CommandProcessingResult updateGroup(Long groupId, JsonCommand command); CommandProcessingResult deleteGroup(Long groupId); - + CommandProcessingResult closeGroup(final Long groupId, final JsonCommand command); - + CommandProcessingResult closeCenter(final Long centerId, final JsonCommand command); CommandProcessingResult unassignGroupOrCenterStaff(Long groupId, JsonCommand command); - + CommandProcessingResult assignGroupOrCenterStaff(Long groupId, JsonCommand command); - + CommandProcessingResult associateClientsToGroup(Long groupId, JsonCommand command); - - CommandProcessingResult disassociateClientsFromGroup(Long groupId, JsonCommand command); + + CommandProcessingResult disassociateClientsFromGroup(Long groupId, JsonCommand command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupingTypesWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupingTypesWritePlatformServiceJpaRepositoryImpl.java index 20e290471..618935b22 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupingTypesWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/GroupingTypesWritePlatformServiceJpaRepositoryImpl.java @@ -80,10 +80,10 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group @Autowired public GroupingTypesWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, final GroupRepositoryWrapper groupRepository, final ClientRepositoryWrapper clientRepositoryWrapper, - final OfficeRepository officeRepository, final StaffRepositoryWrapper staffRepository, - final NoteRepository noteRepository, final GroupLevelRepository groupLevelRepository, - final GroupingTypesDataValidator fromApiJsonDeserializer, final LoanRepository loanRepository, - final SavingsAccountRepository savingsRepository, final CodeValueRepositoryWrapper codeValueRepository) { + final OfficeRepository officeRepository, final StaffRepositoryWrapper staffRepository, final NoteRepository noteRepository, + final GroupLevelRepository groupLevelRepository, final GroupingTypesDataValidator fromApiJsonDeserializer, + final LoanRepository loanRepository, final SavingsAccountRepository savingsRepository, + final CodeValueRepositoryWrapper codeValueRepository) { this.context = context; this.groupRepository = groupRepository; this.clientRepositoryWrapper = clientRepositoryWrapper; @@ -114,12 +114,12 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group final Office groupOffice = this.officeRepository.findOne(officeId); if (groupOffice == null) { throw new OfficeNotFoundException(officeId); } - + final LocalDate activationDate = command.localDateValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName); final GroupLevel groupLevel = this.groupLevelRepository.findOne(groupingType.getId()); - + validateOfficeOpeningDateisAfterGroupOrCenterOpeningDate(groupOffice, groupLevel, activationDate); - + Staff staff = null; final Long staffId = command.longValueOfParameterNamed(GroupingTypesApiConstants.staffIdParamName); if (staffId != null) { @@ -189,7 +189,7 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group final Locale locale = command.extractLocale(); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final LocalDate activationDate = command.localDateValueOfParameterNamed("activationDate"); - + validateOfficeOpeningDateisAfterGroupOrCenterOpeningDate(group.getOffice(), group.getGroupLevel(), activationDate); group.activate(fmt, activationDate); @@ -235,11 +235,11 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group final String groupHierarchy = groupOffice.getHierarchy(); this.context.validateAccessRights(groupHierarchy); - + final LocalDate activationDate = command.localDateValueOfParameterNamed(GroupingTypesApiConstants.activationDateParamName); validateOfficeOpeningDateisAfterGroupOrCenterOpeningDate(groupOffice, groupForUpdate.getGroupLevel(), activationDate); - + final Map actualChanges = groupForUpdate.update(command); if (actualChanges.containsKey(GroupingTypesApiConstants.staffIdParamName)) { @@ -360,7 +360,7 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group .build(); } - + @Override public CommandProcessingResult assignGroupOrCenterStaff(final Long grouptId, final JsonCommand command) { @@ -388,7 +388,7 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group .with(actualChanges) // .build(); } - + @Transactional @Override public CommandProcessingResult deleteGroup(final Long groupId) { @@ -410,43 +410,45 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group } @Override - public CommandProcessingResult closeGroup(Long groupId, JsonCommand command) { + public CommandProcessingResult closeGroup(final Long groupId, final JsonCommand command) { this.fromApiJsonDeserializer.validateForGroupClose(command); final Group group = this.groupRepository.findOneWithNotFoundDetection(groupId); final LocalDate closureDate = command.localDateValueOfParameterNamed(GroupingTypesApiConstants.closureDateParamName); final Long closureReasonId = command.longValueOfParameterNamed(GroupingTypesApiConstants.closureReasonIdParamName); - CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( + final CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( GroupingTypesApiConstants.GROUP_CLOSURE_REASON, closureReasonId); - - if(group.hasActiveClients()){ - final String errorMessage = group.getGroupLevel().getLevelName() + " cannot be closed because of active clients associated with it."; + + if (group.hasActiveClients()) { + final String errorMessage = group.getGroupLevel().getLevelName() + + " cannot be closed because of active clients associated with it."; throw new InvalidGroupStateTransitionException(group.getGroupLevel().getLevelName(), "close", "active.clients.exist", errorMessage); } - + validateLoansAndSavingsForGroupOrCenterClose(group, closureDate); - + group.close(closureReason, closureDate); this.groupRepository.saveAndFlush(group); return new CommandProcessingResultBuilder() // - .withGroupId(groupId) // - .withEntityId(groupId) // - .build(); + .withGroupId(groupId) // + .withEntityId(groupId) // + .build(); } - + private void validateLoansAndSavingsForGroupOrCenterClose(final Group groupOrCenter, final LocalDate closureDate) { - Collection groupLoans = this.loanRepository.findByGroupId(groupOrCenter.getId()); - for (Loan loan : groupLoans) { - LoanStatusMapper loanStatus = new LoanStatusMapper(loan.status().getValue()); + final Collection groupLoans = this.loanRepository.findByGroupId(groupOrCenter.getId()); + for (final Loan loan : groupLoans) { + final LoanStatusMapper loanStatus = new LoanStatusMapper(loan.status().getValue()); if (loanStatus.isOpen()) { final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + " cannot be closed because of non-closed loans."; throw new InvalidGroupStateTransitionException(groupOrCenter.getGroupLevel().getLevelName(), "close", "loan.not.closed", errorMessage); } else if (loanStatus.isClosed() && loan.getClosedOnDate().after(closureDate.toDate())) { - final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + "closureDate cannot be before the loan closedOnDate."; + final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + + "closureDate cannot be before the loan closedOnDate."; throw new InvalidGroupStateTransitionException(groupOrCenter.getGroupLevel().getLevelName(), "close", "date.cannot.before.loan.closed.date", errorMessage, closureDate, loan.getClosedOnDate()); } else if (loanStatus.isPendingApproval()) { @@ -460,15 +462,17 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group } } - List groupSavingAccounts = this.savingsRepository.findByGroupId(groupOrCenter.getId()); + final List groupSavingAccounts = this.savingsRepository.findByGroupId(groupOrCenter.getId()); - for (SavingsAccount saving : groupSavingAccounts) { + for (final SavingsAccount saving : groupSavingAccounts) { if (saving.isActive() || saving.isSubmittedAndPendingApproval() || saving.isApproved()) { - final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + " cannot be closed with active savings accounts associated."; - throw new InvalidGroupStateTransitionException(groupOrCenter.getGroupLevel().getLevelName(), "close", "savings.account.not.closed", - errorMessage); + final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + + " cannot be closed with active savings accounts associated."; + throw new InvalidGroupStateTransitionException(groupOrCenter.getGroupLevel().getLevelName(), "close", + "savings.account.not.closed", errorMessage); } else if (saving.isClosed() && saving.getClosedOnDate().isAfter(closureDate)) { - final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + " closureDate cannot be before the loan closedOnDate."; + final String errorMessage = groupOrCenter.getGroupLevel().getLevelName() + + " closureDate cannot be before the loan closedOnDate."; throw new InvalidGroupStateTransitionException(groupOrCenter.getGroupLevel().getLevelName(), "close", "date.cannot.before.loan.closed.date", errorMessage, closureDate, saving.getClosedOnDate()); } @@ -476,30 +480,31 @@ public class GroupingTypesWritePlatformServiceJpaRepositoryImpl implements Group } @Override - public CommandProcessingResult closeCenter(Long centerId, JsonCommand command) { + public CommandProcessingResult closeCenter(final Long centerId, final JsonCommand command) { this.fromApiJsonDeserializer.validateForCenterClose(command); final Group center = this.groupRepository.findOneWithNotFoundDetection(centerId); final LocalDate closureDate = command.localDateValueOfParameterNamed(GroupingTypesApiConstants.closureDateParamName); final Long closureReasonId = command.longValueOfParameterNamed(GroupingTypesApiConstants.closureReasonIdParamName); - CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( + final CodeValue closureReason = this.codeValueRepository.findOneByCodeNameAndIdWithNotFoundDetection( GroupingTypesApiConstants.GROUP_CLOSURE_REASON, closureReasonId); - - if(center.hasActiveGroups()){ - final String errorMessage = center.getGroupLevel().getLevelName() + " cannot be closed because of active groups associated with it."; + + if (center.hasActiveGroups()) { + final String errorMessage = center.getGroupLevel().getLevelName() + + " cannot be closed because of active groups associated with it."; throw new InvalidGroupStateTransitionException(center.getGroupLevel().getLevelName(), "close", "active.groups.exist", errorMessage); } validateLoansAndSavingsForGroupOrCenterClose(center, closureDate); - + center.close(closureReason, closureDate); this.groupRepository.saveAndFlush(center); return new CommandProcessingResultBuilder() // - .withEntityId(centerId) // - .build(); + .withEntityId(centerId) // + .build(); } private Set assembleSetOfClients(final Long groupOfficeId, final JsonCommand command) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/SearchParameters.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/SearchParameters.java index 0c023c74b..11e4bde88 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/SearchParameters.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/group/service/SearchParameters.java @@ -30,7 +30,7 @@ public final class SearchParameters { final String displayName, final String firstname, final String lastname, final String hierarchy, final Integer offset, final Integer limit, final String orderBy, final String sortOrder) { - Integer maxLimitAllowed = getCheckedLimit(limit); + final Integer maxLimitAllowed = getCheckedLimit(limit); return new SearchParameters(sqlSearch, officeId, externalId, displayName, hierarchy, firstname, lastname, offset, maxLimitAllowed, orderBy, sortOrder); @@ -39,7 +39,7 @@ public final class SearchParameters { public static SearchParameters forGroups(final String sqlSearch, final Long officeId, final String externalId, final String name, final String hierarchy, final Integer offset, final Integer limit, final String orderBy, final String sortOrder) { - Integer maxLimitAllowed = getCheckedLimit(limit); + final Integer maxLimitAllowed = getCheckedLimit(limit); return new SearchParameters(sqlSearch, officeId, externalId, name, hierarchy, null, null, offset, maxLimitAllowed, orderBy, sortOrder); @@ -48,7 +48,7 @@ public final class SearchParameters { public static SearchParameters forLoans(final String sqlSearch, final String externalId, final Integer offset, final Integer limit, final String orderBy, final String sortOrder) { - Integer maxLimitAllowed = getCheckedLimit(limit); + final Integer maxLimitAllowed = getCheckedLimit(limit); return new SearchParameters(sqlSearch, null, externalId, null, null, null, null, offset, maxLimitAllowed, orderBy, sortOrder); } @@ -56,15 +56,14 @@ public final class SearchParameters { public static SearchParameters forJournalEntries(final Long officeId, final Integer offset, final Integer limit, final String orderBy, final String sortOrder) { - Integer maxLimitAllowed = getCheckedLimit(limit); + final Integer maxLimitAllowed = getCheckedLimit(limit); return new SearchParameters(null, officeId, null, null, null, null, null, offset, maxLimitAllowed, orderBy, sortOrder); } - public static SearchParameters forPagination(final Integer offset, final Integer limit, final String orderBy, - final String sortOrder) { + public static SearchParameters forPagination(final Integer offset, final Integer limit, final String orderBy, final String sortOrder) { - Integer maxLimitAllowed = getCheckedLimit(limit); + final Integer maxLimitAllowed = getCheckedLimit(limit); return new SearchParameters(null, null, null, null, null, null, null, offset, maxLimitAllowed, orderBy, sortOrder); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/BulkLoansApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/BulkLoansApiResource.java index 3350bf505..2a022d392 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/BulkLoansApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/BulkLoansApiResource.java @@ -80,7 +80,7 @@ public class BulkLoansApiResource { public String loanReassignmentTemplate(@QueryParam("officeId") final Long officeId, @QueryParam("fromLoanOfficerId") final Long loanOfficerId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Collection offices = this.officeReadPlatformService.retrieveAllOfficesForDropdown(); @@ -98,8 +98,8 @@ public class BulkLoansApiResource { final BulkTransferLoanOfficerData loanReassignmentData = BulkTransferLoanOfficerData.templateForBulk(officeId, loanOfficerId, new LocalDate(), offices, loanOfficers, staffAccountSummaryCollectionData); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, loanReassignmentData, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, loanReassignmentData, this.RESPONSE_DATA_PARAMETERS); } @POST diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoanChargesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoanChargesApiResource.java index 4bbcb281a..ec18e5165 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoanChargesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoanChargesApiResource.java @@ -82,12 +82,12 @@ public class LoanChargesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllLoanCharges(@PathParam("loanId") final Long loanId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Collection loanCharges = this.loanChargeReadPlatformService.retrieveLoanCharges(loanId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, loanCharges, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, loanCharges, this.RESPONSE_DATA_PARAMETERS); } @GET @@ -96,14 +96,14 @@ public class LoanChargesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveTemplate(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final boolean feeChargesOnly = false; final Collection chargeOptions = this.chargeReadPlatformService.retrieveLoanApplicableCharges(feeChargesOnly); final LoanChargeData loanChargeTemplate = LoanChargeData.template(chargeOptions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, loanChargeTemplate, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, loanChargeTemplate, this.RESPONSE_DATA_PARAMETERS); } @GET @@ -113,12 +113,12 @@ public class LoanChargesApiResource { public String retrieveLoanCharge(@PathParam("loanId") final Long loanId, @PathParam("chargeId") final Long loanChargeId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final LoanChargeData loanCharge = this.loanChargeReadPlatformService.retrieveLoanChargeDetails(loanChargeId, loanId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, loanCharge, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, loanCharge, this.RESPONSE_DATA_PARAMETERS); } @POST diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoanTransactionsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoanTransactionsApiResource.java index 5a487002d..23fa5d035 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoanTransactionsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoanTransactionsApiResource.java @@ -45,7 +45,8 @@ import org.springframework.stereotype.Component; @Scope("singleton") public class LoanTransactionsApiResource { - private final Set RESPONSE_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "type", "date", "currency", "amount", "externalId")); + private final Set RESPONSE_DATA_PARAMETERS = new HashSet(Arrays.asList("id", "type", "date", "currency", "amount", + "externalId")); private final String resourceNameForPermissions = "LOAN"; @@ -81,7 +82,7 @@ public class LoanTransactionsApiResource { public String retrieveTransactionTemplate(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); LoanTransactionData transactionData = null; if (is(commandParam, "repayment")) { @@ -100,8 +101,8 @@ public class LoanTransactionsApiResource { throw new UnrecognizedQueryParamException("command", commandParam); } - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, transactionData, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, transactionData, this.RESPONSE_DATA_PARAMETERS); } @GET @@ -111,17 +112,17 @@ public class LoanTransactionsApiResource { public String retrieveTransaction(@PathParam("loanId") final Long loanId, @PathParam("transactionId") final Long transactionId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); LoanTransactionData transactionData = this.loanReadPlatformService.retrieveLoanTransaction(loanId, transactionId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (settings.isTemplate()) { - final Collection paymentTypeOptions = codeValueReadPlatformService + final Collection paymentTypeOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(PaymentDetailConstants.paymentTypeCodeName); transactionData = LoanTransactionData.templateOnTop(transactionData, paymentTypeOptions); } - return this.toApiJsonSerializer.serialize(settings, transactionData, RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, transactionData, this.RESPONSE_DATA_PARAMETERS); } @POST @@ -130,7 +131,7 @@ public class LoanTransactionsApiResource { public String executeLoanTransaction(@PathParam("loanId") final Long loanId, @QueryParam("command") final String commandParam, final String apiRequestBodyAsJson) { - CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); + final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); CommandProcessingResult result = null; if (is(commandParam, "repayment")) { @@ -162,7 +163,7 @@ public class LoanTransactionsApiResource { public String adjustLoanTransaction(@PathParam("loanId") final Long loanId, @PathParam("transactionId") final Long transactionId, final String apiRequestBodyAsJson) { - CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); + final CommandWrapperBuilder builder = new CommandWrapperBuilder().withJson(apiRequestBodyAsJson); final CommandWrapper commandRequest = builder.adjustTransaction(loanId, transactionId).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoansApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoansApiResource.java index d9d099a6a..a23bdff51 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoansApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/api/LoansApiResource.java @@ -103,7 +103,7 @@ public class LoansApiResource { "interestCalculationPeriodTypeOptions", "repaymentFrequencyTypeOptions", "termFrequencyTypeOptions", "interestRateFrequencyTypeOptions", "fundOptions", "repaymentStrategyOptions", "chargeOptions", "loanOfficerOptions", "loanPurposeOptions", "loanCollateralOptions", "chargeTemplate", "calendarOptions", "syncDisbursementWithMeeting", - "loanCounter", "loanProductCounter", "notes","accountLinkingOptions","linkedAccount")); + "loanCounter", "loanProductCounter", "notes", "accountLinkingOptions", "linkedAccount")); private final String resourceNameForPermissions = "LOAN"; @@ -177,7 +177,7 @@ public class LoansApiResource { @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); // template final Collection productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup(); @@ -203,7 +203,7 @@ public class LoansApiResource { // for JLG loan both client and group details are required if (templateType.equals("individual") || templateType.equals("jlg")) { - LoanAccountData loanAccountClientDetails = this.loanReadPlatformService.retrieveClientDetailsTemplate(clientId); + final LoanAccountData loanAccountClientDetails = this.loanReadPlatformService.retrieveClientDetailsTemplate(clientId); officeId = loanAccountClientDetails.officeId(); @@ -238,15 +238,15 @@ public class LoansApiResource { } allowedLoanOfficers = this.loanReadPlatformService.retrieveAllowedLoanOfficers(officeId, staffInSelectedOfficeOnly); - + Collection accountLinkingOptions = null; - if(clientId != null){ - CurrencyData currencyData = newLoanAccount.currency(); + if (clientId != null) { + final CurrencyData currencyData = newLoanAccount.currency(); String currencyCode = null; if (currencyData != null) { currencyCode = currencyData.code(); } - long[] accountStatus = { SavingsAccountStatusType.ACTIVE.getValue() }; + final long[] accountStatus = { SavingsAccountStatusType.ACTIVE.getValue() }; accountLinkingOptions = this.portfolioAccountReadPlatformService.retrieveAllForLookup( PortfolioAccountType.SAVINGS.getValue(), clientId, currencyCode, accountStatus); @@ -254,10 +254,11 @@ public class LoansApiResource { // add product options, allowed loan officers and calendar options // (calendar options will be null in individual loan) - newLoanAccount = LoanAccountData.associationsAndTemplate(newLoanAccount, productOptions, allowedLoanOfficers, calendarOptions,accountLinkingOptions); + newLoanAccount = LoanAccountData.associationsAndTemplate(newLoanAccount, productOptions, allowedLoanOfficers, calendarOptions, + accountLinkingOptions); } - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, newLoanAccount, LOAN_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, newLoanAccount, this.LOAN_DATA_PARAMETERS); } @GET @@ -268,7 +269,7 @@ public class LoansApiResource { @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final LoanAccountData loanBasicDetails = this.loanReadPlatformService.retrieveOne(loanId); @@ -341,7 +342,7 @@ public class LoansApiResource { notes = null; } } - + if (associationParameters.contains("linkedAccount")) { mandatoryResponseParameters.add("linkedAccount"); linkedAccount = this.accountAssociationsReadPlatformService.retriveLoanAssociation(loanId); @@ -364,19 +365,17 @@ public class LoansApiResource { Collection loanCollateralOptions = null; Collection calendarOptions = null; Collection accountLinkingOptions = null; - - final boolean template = ApiParameterHelper.template(uriInfo.getQueryParameters()); if (template) { productOptions = this.loanProductReadPlatformService.retrieveAllLoanProductsForLookup(); - loanTermFrequencyTypeOptions = dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions(); - repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions(); - interestRateFrequencyTypeOptions = dropdownReadPlatformService.retrieveInterestRateFrequencyTypeOptions(); + loanTermFrequencyTypeOptions = this.dropdownReadPlatformService.retrieveLoanTermFrequencyTypeOptions(); + repaymentFrequencyTypeOptions = this.dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions(); + interestRateFrequencyTypeOptions = this.dropdownReadPlatformService.retrieveInterestRateFrequencyTypeOptions(); - amortizationTypeOptions = dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); - interestTypeOptions = dropdownReadPlatformService.retrieveLoanInterestTypeOptions(); - interestCalculationPeriodTypeOptions = dropdownReadPlatformService.retrieveLoanInterestRateCalculatedInPeriodOptions(); + amortizationTypeOptions = this.dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); + interestTypeOptions = this.dropdownReadPlatformService.retrieveLoanInterestTypeOptions(); + interestCalculationPeriodTypeOptions = this.dropdownReadPlatformService.retrieveLoanInterestRateCalculatedInPeriodOptions(); fundOptions = this.fundReadPlatformService.retrieveAllFunds(); repaymentStrategyOptions = this.dropdownReadPlatformService.retreiveTransactionProcessingStrategies(); @@ -389,14 +388,14 @@ public class LoansApiResource { loanPurposeOptions = this.codeValueReadPlatformService.retrieveCodeValuesByCode("LoanPurpose"); loanCollateralOptions = this.codeValueReadPlatformService.retrieveCodeValuesByCode("LoanCollateral"); - CurrencyData currencyData = loanBasicDetails.currency(); + final CurrencyData currencyData = loanBasicDetails.currency(); String currencyCode = null; if (currencyData != null) { currencyCode = currencyData.code(); } - long[] accountStatus = { SavingsAccountStatusType.ACTIVE.getValue() }; - accountLinkingOptions = this.portfolioAccountReadPlatformService.retrieveAllForLookup( - PortfolioAccountType.SAVINGS.getValue(), loanBasicDetails.clientId(), currencyCode, accountStatus); + final long[] accountStatus = { SavingsAccountStatusType.ACTIVE.getValue() }; + accountLinkingOptions = this.portfolioAccountReadPlatformService.retrieveAllForLookup(PortfolioAccountType.SAVINGS.getValue(), + loanBasicDetails.clientId(), currencyCode, accountStatus); if (!associationParameters.contains("linkedAccount")) { mandatoryResponseParameters.add("linkedAccount"); @@ -414,9 +413,9 @@ public class LoansApiResource { interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, allowedLoanOfficers, loanPurposeOptions, loanCollateralOptions, calendarOptions, notes, accountLinkingOptions, linkedAccount); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters(), + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters(), mandatoryResponseParameters); - return this.toApiJsonSerializer.serialize(settings, loanAccount, LOAN_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, loanAccount, this.LOAN_DATA_PARAMETERS); } @GET @@ -427,14 +426,14 @@ public class LoansApiResource { @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, @QueryParam("orderBy") final String orderBy, @QueryParam("sortOrder") final String sortOrder) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final SearchParameters searchParameters = SearchParameters.forLoans(sqlSearch, externalId, offset, limit, orderBy, sortOrder); final Page loanBasicDetails = this.loanReadPlatformService.retrieveAll(searchParameters); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, loanBasicDetails, LOAN_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, loanBasicDetails, this.LOAN_DATA_PARAMETERS); } @POST @@ -450,7 +449,7 @@ public class LoansApiResource { final LoanScheduleModel loanSchedule = this.calculationPlatformService.calculateLoanSchedule(query); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.loanScheduleToApiJsonSerializer.serialize(settings, loanSchedule.toData(), new HashSet()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/command/LoanUpdateCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/command/LoanUpdateCommand.java index 48a1862db..265b13766 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/command/LoanUpdateCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/command/LoanUpdateCommand.java @@ -26,9 +26,9 @@ public class LoanUpdateCommand { public void validate() { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.transaction"); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.transaction"); baseDataValidator.reset().parameter("unassignedDate").value(this.unassignedDate).notNull(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/command/UndoStateTransitionCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/command/UndoStateTransitionCommand.java index d70a9700f..a930432ed 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/command/UndoStateTransitionCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/command/UndoStateTransitionCommand.java @@ -23,6 +23,6 @@ public class UndoStateTransitionCommand { } public String getNote() { - return note; + return this.note; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/DisbursementData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/DisbursementData.java index c2754a7c5..74593e6e8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/DisbursementData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/DisbursementData.java @@ -27,8 +27,8 @@ public class DisbursementData { public LocalDate disbursementDate() { LocalDate disbursementDate = this.expectedDisbursementDate; - if (actualDisbursementDate != null) { - disbursementDate = actualDisbursementDate; + if (this.actualDisbursementDate != null) { + disbursementDate = this.actualDisbursementDate; } return disbursementDate; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanAccountData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanAccountData.java index b900b006d..493fe6dcb 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanAccountData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanAccountData.java @@ -38,8 +38,8 @@ import org.springframework.util.CollectionUtils; * Immutable data object representing loan account data. */ @SuppressWarnings("unused") - public class LoanAccountData { + // basic loan details // identity @@ -105,7 +105,7 @@ public class LoanAccountData { private final Collection collateral; private final Collection guarantors; private final CalendarData meeting; - private Collection notes; + private final Collection notes; // template private final Collection productOptions; @@ -126,12 +126,12 @@ public class LoanAccountData { @Transient private final BigDecimal feeChargesAtDisbursementCharged; private final BigDecimal totalOverpaid; - - //loanCycle + + // loanCycle private final Integer loanCounter; private final Integer loanProductCounter; - - //linkable account details + + // linkable account details private final PortfolioAccountData linkedAccount; private final Collection accountLinkingOptions; @@ -213,14 +213,15 @@ public class LoanAccountData { return new LoanAccountData(id, accountNo, status, externalId, clientId, clientName, clientOfficeId, group, loanType, loanProductId, loanProductName, loanProductDescription, fundId, fundName, loanPurposeId, loanPurposeName, loanOfficerId, loanOfficerName, currencyData, principal, totalOverpaid, inArrearsTolerance, termFrequency, termPeriodFrequencyType, numberOfRepayments, - repaymentEvery, repaymentFrequencyType, transactionProcessingStrategyId, transactionProcessingStrategyName , amortizationType, interestRatePerPeriod, - interestRateFrequencyType, annualInterestRate, interestType, interestCalculationPeriodType, expectedFirstRepaymentOnDate, - graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, timeline, summary, - feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, - productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, transactionProcessingStrategyOptions, - interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, - fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, - syncDisbursementWithMeeting, loancounter, loanProductCounter, notes,accountLinkingOptions, linkedAccount); + repaymentEvery, repaymentFrequencyType, transactionProcessingStrategyId, transactionProcessingStrategyName, + amortizationType, interestRatePerPeriod, interestRateFrequencyType, annualInterestRate, interestType, + interestCalculationPeriodType, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, graceOnInterestPayment, + graceOnInterestCharged, interestChargedFromDate, timeline, summary, feeChargesDueAtDisbursementCharged, repaymentSchedule, + transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, + repaymentFrequencyTypeOptions, transactionProcessingStrategyOptions, interestRateFrequencyTypeOptions, + amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, + chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, + syncDisbursementWithMeeting, loancounter, loanProductCounter, notes, accountLinkingOptions, linkedAccount); } /** @@ -302,14 +303,15 @@ public class LoanAccountData { return new LoanAccountData(id, accountNo, status, externalId, clientId, clientName, clientOfficeId, group, loanType, loanProductId, loanProductName, loanProductDescription, fundId, fundName, loanPurposeId, loanPurposeName, loanOfficerId, loanOfficerName, currencyData, principal, totalOverpaid, inArrearsTolerance, termFrequency, termPeriodFrequencyType, numberOfRepayments, - repaymentEvery, repaymentFrequencyType, transactionProcessingStrategyId, transactionProcessingStrategyName ,amortizationType, interestRatePerPeriod, - interestRateFrequencyType, annualInterestRate, interestType, interestCalculationPeriodType, expectedFirstRepaymentOnDate, - graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, timeline, summary, - feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, - productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentStrategyOptions, - interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, - fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, - syncDisbursementWithMeeting, loancounter, loanProductCounter, notes,accountLinkingOptions, linkedAccount); + repaymentEvery, repaymentFrequencyType, transactionProcessingStrategyId, transactionProcessingStrategyName, + amortizationType, interestRatePerPeriod, interestRateFrequencyType, annualInterestRate, interestType, + interestCalculationPeriodType, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, graceOnInterestPayment, + graceOnInterestCharged, interestChargedFromDate, timeline, summary, feeChargesDueAtDisbursementCharged, repaymentSchedule, + transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, + repaymentFrequencyTypeOptions, repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, + interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, + loanPurposeOptions, loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, + notes, accountLinkingOptions, linkedAccount); } public static LoanAccountData populateClientDefaults(final LoanAccountData acc, final LoanAccountData clientAcc) { @@ -318,16 +320,17 @@ public class LoanAccountData { clientAcc.clientOfficeId, acc.group, acc.loanType, acc.loanProductId, acc.loanProductName, acc.loanProductDescription, acc.fundId, acc.fundName, acc.loanPurposeId, acc.loanPurposeName, acc.loanOfficerId, acc.loanOfficerName, acc.currency, acc.principal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, - acc.numberOfRepayments, acc.repaymentEvery, acc.repaymentFrequencyType, acc.transactionProcessingStrategyId, - acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, - acc.interestType, acc.interestCalculationPeriodType, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, - acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, clientAcc.timeline, acc.summary, - acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, - acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, - acc.transactionProcessingStrategyOptions, acc.interestRateFrequencyTypeOptions, acc.amortizationTypeOptions, - acc.interestTypeOptions, acc.interestCalculationPeriodTypeOptions, acc.fundOptions, acc.chargeOptions, null, - acc.loanOfficerOptions, acc.loanPurposeOptions, acc.loanCollateralOptions, acc.calendarOptions, acc.syncDisbursementWithMeeting, - acc.loanCounter, acc.loanProductCounter, acc.notes,acc.accountLinkingOptions, acc.linkedAccount); + acc.numberOfRepayments, acc.repaymentEvery, acc.repaymentFrequencyType, acc.transactionProcessingStrategyId, + acc.transactionProcessingStrategyName, acc.amortizationType, acc.interestRatePerPeriod, acc.interestRateFrequencyType, + acc.annualInterestRate, acc.interestType, acc.interestCalculationPeriodType, acc.expectedFirstRepaymentOnDate, + acc.graceOnPrincipalPayment, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, + clientAcc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, + acc.collateral, acc.guarantors, acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, + acc.repaymentFrequencyTypeOptions, acc.transactionProcessingStrategyOptions, acc.interestRateFrequencyTypeOptions, + acc.amortizationTypeOptions, acc.interestTypeOptions, acc.interestCalculationPeriodTypeOptions, acc.fundOptions, + acc.chargeOptions, null, acc.loanOfficerOptions, acc.loanPurposeOptions, acc.loanCollateralOptions, acc.calendarOptions, + acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, acc.notes, acc.accountLinkingOptions, + acc.linkedAccount); } /** @@ -406,18 +409,19 @@ public class LoanAccountData { final Integer loanProductCounter = null; final Collection accountLinkingOptions = null; final PortfolioAccountData linkedAccount = null; - + return new LoanAccountData(id, accountNo, status, externalId, clientId, clientName, clientOfficeId, group, loanType, loanProductId, loanProductName, loanProductDescription, fundId, fundName, loanPurposeId, loanPurposeName, loanOfficerId, loanOfficerName, currencyData, principal, totalOverpaid, inArrearsTolerance, termFrequency, termPeriodFrequencyType, numberOfRepayments, - repaymentEvery, repaymentFrequencyType, transactionProcessingStrategyId, transactionProcessingStrategyName , amortizationType, interestRatePerPeriod, - interestRateFrequencyType, annualInterestRate, interestType, interestCalculationPeriodType, expectedFirstRepaymentOnDate, - graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, timeline, summary, - feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, - productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentStrategyOptions, - interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, - fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, - syncDisbursementWithMeeting, loancounter, loanProductCounter, notes,accountLinkingOptions, linkedAccount); + repaymentEvery, repaymentFrequencyType, transactionProcessingStrategyId, transactionProcessingStrategyName, + amortizationType, interestRatePerPeriod, interestRateFrequencyType, annualInterestRate, interestType, + interestCalculationPeriodType, expectedFirstRepaymentOnDate, graceOnPrincipalPayment, graceOnInterestPayment, + graceOnInterestCharged, interestChargedFromDate, timeline, summary, feeChargesDueAtDisbursementCharged, repaymentSchedule, + transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, + repaymentFrequencyTypeOptions, repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, + interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, + loanPurposeOptions, loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, + notes, accountLinkingOptions, linkedAccount); } public static LoanAccountData populateGroupDefaults(final LoanAccountData acc, final LoanAccountData groupAcc) { @@ -426,18 +430,19 @@ public class LoanAccountData { groupAcc.group, acc.loanType, acc.loanProductId, acc.loanProductName, acc.loanProductDescription, acc.fundId, acc.fundName, acc.loanPurposeId, acc.loanPurposeName, acc.loanOfficerId, acc.loanOfficerName, acc.currency, acc.principal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, - acc.repaymentEvery, acc.repaymentFrequencyType, acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName , acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, + acc.repaymentEvery, acc.repaymentFrequencyType, acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, + acc.amortizationType, acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.interestCalculationPeriodType, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, groupAcc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, acc.meeting, acc.productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, acc.transactionProcessingStrategyOptions, acc.interestRateFrequencyTypeOptions, acc.amortizationTypeOptions, acc.interestTypeOptions, acc.interestCalculationPeriodTypeOptions, acc.fundOptions, acc.chargeOptions, null, - acc.loanOfficerOptions, acc.loanPurposeOptions, acc.loanCollateralOptions, acc.calendarOptions, - acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, acc.notes,acc.accountLinkingOptions, acc.linkedAccount); + acc.loanOfficerOptions, acc.loanPurposeOptions, acc.loanCollateralOptions, acc.calendarOptions, + acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, acc.notes, acc.accountLinkingOptions, + acc.linkedAccount); } - + public static LoanAccountData loanProductWithTemplateDefaults(final LoanProductData product, final Collection termFrequencyTypeOptions, final Collection repaymentFrequencyTypeOptions, final Collection repaymentStrategyOptions, @@ -499,10 +504,10 @@ public class LoanAccountData { final EnumOptionData termPeriodFrequencyType = product.getRepaymentFrequencyType(); final Collection charges = new ArrayList(); - for (ChargeData charge : product.charges()) { + for (final ChargeData charge : product.charges()) { charges.add(charge.toLoanChargeData()); } - + final Integer loancounter = null; final Integer loanProductCounter = null; final PortfolioAccountData linkedAccount = null; @@ -512,16 +517,16 @@ public class LoanAccountData { product.getId(), product.getName(), product.getDescription(), product.getFundId(), product.getFundName(), loanPurposeId, loanPurposeName, loanOfficerId, loanOfficerName, product.getCurrency(), product.getPrincipal(), totalOverpaid, product.getInArrearsTolerance(), termFrequency, termPeriodFrequencyType, product.getNumberOfRepayments(), - product.getRepaymentEvery(), product.getRepaymentFrequencyType(), product.getTransactionProcessingStrategyId(), transactionProcessingStrategyName , - product.getAmortizationType(), product.getInterestRatePerPeriod(), product.getInterestRateFrequencyType(), - product.getAnnualInterestRate(), product.getInterestType(), product.getInterestCalculationPeriodType(), - expectedFirstRepaymentOnDate, product.getGraceOnPrincipalPayment(), product.getGraceOnInterestPayment(), - product.getGraceOnInterestCharged(), interestChargedFromDate, timeline, summary, feeChargesDueAtDisbursementCharged, - repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, - repaymentFrequencyTypeOptions, repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, - interestTypeOptions, interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, - loanPurposeOptions, loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, notes, - accountLinkingOptions, linkedAccount); + product.getRepaymentEvery(), product.getRepaymentFrequencyType(), product.getTransactionProcessingStrategyId(), + transactionProcessingStrategyName, product.getAmortizationType(), product.getInterestRatePerPeriod(), + product.getInterestRateFrequencyType(), product.getAnnualInterestRate(), product.getInterestType(), + product.getInterestCalculationPeriodType(), expectedFirstRepaymentOnDate, product.getGraceOnPrincipalPayment(), + product.getGraceOnInterestPayment(), product.getGraceOnInterestCharged(), interestChargedFromDate, timeline, summary, + feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, + productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentStrategyOptions, + interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, + fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, + syncDisbursementWithMeeting, loancounter, loanProductCounter, notes, accountLinkingOptions, linkedAccount); } public static LoanAccountData populateLoanProductDefaults(final LoanAccountData acc, final LoanProductData product) { @@ -552,7 +557,7 @@ public class LoanAccountData { final EnumOptionData termPeriodFrequencyType = product.getRepaymentFrequencyType(); final Collection charges = new ArrayList(); - for (ChargeData charge : product.charges()) { + for (final ChargeData charge : product.charges()) { charges.add(charge.toLoanChargeData()); } @@ -561,15 +566,17 @@ public class LoanAccountData { product.getFundName(), acc.loanPurposeId, acc.loanPurposeName, acc.loanOfficerId, acc.loanOfficerName, product.getCurrency(), product.getPrincipal(), acc.totalOverpaid, product.getInArrearsTolerance(), termFrequency, termPeriodFrequencyType, product.getNumberOfRepayments(), product.getRepaymentEvery(), product.getRepaymentFrequencyType(), - product.getTransactionProcessingStrategyId(), product.getTransactionProcessingStrategyName(), product.getAmortizationType(), product.getInterestRatePerPeriod(), - product.getInterestRateFrequencyType(), product.getAnnualInterestRate(), product.getInterestType(), - product.getInterestCalculationPeriodType(), acc.expectedFirstRepaymentOnDate, product.getGraceOnPrincipalPayment(), - product.getGraceOnInterestPayment(), product.getGraceOnInterestCharged(), acc.interestChargedFromDate, acc.timeline, - acc.summary, acc.feeChargesAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, - calendarData, productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentStrategyOptions, + product.getTransactionProcessingStrategyId(), product.getTransactionProcessingStrategyName(), + product.getAmortizationType(), product.getInterestRatePerPeriod(), product.getInterestRateFrequencyType(), + product.getAnnualInterestRate(), product.getInterestType(), product.getInterestCalculationPeriodType(), + acc.expectedFirstRepaymentOnDate, product.getGraceOnPrincipalPayment(), product.getGraceOnInterestPayment(), + product.getGraceOnInterestCharged(), acc.interestChargedFromDate, acc.timeline, acc.summary, + acc.feeChargesAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, + productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, - fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, - acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, notes,acc.accountLinkingOptions, acc.linkedAccount); + fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, + acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, notes, acc.accountLinkingOptions, + acc.linkedAccount); } /* @@ -583,13 +590,13 @@ public class LoanAccountData { final String loanOfficerName, final CurrencyData currencyData, final BigDecimal principal, final BigDecimal totalOverpaid, final BigDecimal inArrearsTolerance, final Integer termFrequency, final EnumOptionData termPeriodFrequencyType, final Integer numberOfRepayments, final Integer repaymentEvery, final EnumOptionData repaymentFrequencyType, - final Long transactionStrategyId, final String transactionStrategyName , final EnumOptionData amortizationType, final BigDecimal interestRatePerPeriod, - final EnumOptionData interestRateFrequencyType, final BigDecimal annualInterestRate, final EnumOptionData interestType, - final EnumOptionData interestCalculationPeriodType, final LocalDate expectedFirstRepaymentOnDate, - final Integer graceOnPrincipalPayment, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, - final LocalDate interestChargedFromDate, final LoanApplicationTimelineData timeline, final LoanSummaryData loanSummary, - final BigDecimal feeChargesDueAtDisbursementCharged, final Boolean syncDisbursementWithMeeting, - final Integer loancounter, final Integer loanProductCounter) { + final Long transactionStrategyId, final String transactionStrategyName, final EnumOptionData amortizationType, + final BigDecimal interestRatePerPeriod, final EnumOptionData interestRateFrequencyType, final BigDecimal annualInterestRate, + final EnumOptionData interestType, final EnumOptionData interestCalculationPeriodType, + final LocalDate expectedFirstRepaymentOnDate, final Integer graceOnPrincipalPayment, final Integer graceOnInterestPayment, + final Integer graceOnInterestCharged, final LocalDate interestChargedFromDate, final LoanApplicationTimelineData timeline, + final LoanSummaryData loanSummary, final BigDecimal feeChargesDueAtDisbursementCharged, + final Boolean syncDisbursementWithMeeting, final Integer loancounter, final Integer loanProductCounter) { final LoanScheduleData repaymentSchedule = null; final Collection transactions = null; @@ -619,14 +626,15 @@ public class LoanAccountData { return new LoanAccountData(id, accountNo, status, externalId, clientId, clientName, clientOfficeId, group, loanType, loanProductId, loanProductName, loanProductDescription, fundId, fundName, loanPurposeId, loanPurposeName, loanOfficerId, loanOfficerName, currencyData, principal, totalOverpaid, inArrearsTolerance, termFrequency, termPeriodFrequencyType, numberOfRepayments, - repaymentEvery, repaymentFrequencyType, transactionStrategyId, transactionStrategyName , amortizationType, interestRatePerPeriod, - interestRateFrequencyType, annualInterestRate, interestType, interestCalculationPeriodType, expectedFirstRepaymentOnDate, - graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, timeline, loanSummary, - feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, - productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, repaymentStrategyOptions, - interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, - fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, - syncDisbursementWithMeeting, loancounter, loanProductCounter, notes,accountLinkingOptions, linkedAccount); + repaymentEvery, repaymentFrequencyType, transactionStrategyId, transactionStrategyName, amortizationType, + interestRatePerPeriod, interestRateFrequencyType, annualInterestRate, interestType, interestCalculationPeriodType, + expectedFirstRepaymentOnDate, graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, + interestChargedFromDate, timeline, loanSummary, feeChargesDueAtDisbursementCharged, repaymentSchedule, transactions, + charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, + repaymentStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, + interestCalculationPeriodTypeOptions, fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, + loanCollateralOptions, calendarOptions, syncDisbursementWithMeeting, loancounter, loanProductCounter, notes, + accountLinkingOptions, linkedAccount); } /* @@ -643,30 +651,33 @@ public class LoanAccountData { final Collection interestTypeOptions, final Collection interestCalculationPeriodTypeOptions, final Collection fundOptions, final Collection chargeOptions, final ChargeData chargeTemplate, final Collection loanOfficerOptions, final Collection loanPurposeOptions, - final Collection loanCollateralOptions, final Collection calendarOptions, final Collection notes, - final Collection accountLinkingOptions, PortfolioAccountData linkedAccount) { + final Collection loanCollateralOptions, final Collection calendarOptions, + final Collection notes, final Collection accountLinkingOptions, + final PortfolioAccountData linkedAccount) { return new LoanAccountData(acc.id, acc.accountNo, acc.status, acc.externalId, acc.clientId, acc.clientName, acc.clientOfficeId, acc.group, acc.loanType, acc.loanProductId, acc.loanProductName, acc.loanProductDescription, acc.fundId, acc.fundName, acc.loanPurposeId, acc.loanPurposeName, acc.loanOfficerId, acc.loanOfficerName, acc.currency, acc.principal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, - acc.repaymentEvery, acc.repaymentFrequencyType, acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, + acc.repaymentEvery, acc.repaymentFrequencyType, acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, + acc.amortizationType, acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.interestCalculationPeriodType, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, acc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, repaymentSchedule, transactions, charges, collateral, guarantors, calendarData, productOptions, termFrequencyTypeOptions, repaymentFrequencyTypeOptions, transactionProcessingStrategyOptions, interestRateFrequencyTypeOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, - fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, - acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, notes,accountLinkingOptions, linkedAccount); + fundOptions, chargeOptions, chargeTemplate, loanOfficerOptions, loanPurposeOptions, loanCollateralOptions, calendarOptions, + acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, notes, accountLinkingOptions, linkedAccount); } public static LoanAccountData associationsAndTemplate(final LoanAccountData acc, final Collection productOptions, - final Collection allowedLoanOfficers, final Collection calendarOptions,final Collection accountLinkingOptions) { + final Collection allowedLoanOfficers, final Collection calendarOptions, + final Collection accountLinkingOptions) { return associationsAndTemplate(acc, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, acc.meeting, productOptions, acc.termFrequencyTypeOptions, acc.repaymentFrequencyTypeOptions, acc.transactionProcessingStrategyOptions, acc.interestRateFrequencyTypeOptions, acc.amortizationTypeOptions, acc.interestTypeOptions, acc.interestCalculationPeriodTypeOptions, acc.fundOptions, acc.chargeOptions, null, - allowedLoanOfficers, acc.loanPurposeOptions, acc.loanCollateralOptions, calendarOptions, acc.notes, accountLinkingOptions, acc.linkedAccount); + allowedLoanOfficers, acc.loanPurposeOptions, acc.loanCollateralOptions, calendarOptions, acc.notes, accountLinkingOptions, + acc.linkedAccount); } public static LoanAccountData associateGroup(final LoanAccountData acc, final GroupGeneralData group) { @@ -674,9 +685,8 @@ public class LoanAccountData { group, acc.loanType, acc.loanProductId, acc.loanProductName, acc.loanProductDescription, acc.fundId, acc.fundName, acc.loanPurposeId, acc.loanPurposeName, acc.loanOfficerId, acc.loanOfficerName, acc.currency, acc.principal, acc.totalOverpaid, acc.inArrearsTolerance, acc.termFrequency, acc.termPeriodFrequencyType, acc.numberOfRepayments, - acc.repaymentEvery, acc.repaymentFrequencyType, acc.transactionProcessingStrategyId, - acc.transactionProcessingStrategyName, acc.amortizationType, - acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, + acc.repaymentEvery, acc.repaymentFrequencyType, acc.transactionProcessingStrategyId, acc.transactionProcessingStrategyName, + acc.amortizationType, acc.interestRatePerPeriod, acc.interestRateFrequencyType, acc.annualInterestRate, acc.interestType, acc.interestCalculationPeriodType, acc.expectedFirstRepaymentOnDate, acc.graceOnPrincipalPayment, acc.graceOnInterestPayment, acc.graceOnInterestCharged, acc.interestChargedFromDate, acc.timeline, acc.summary, acc.feeChargesAtDisbursementCharged, acc.repaymentSchedule, acc.transactions, acc.charges, acc.collateral, acc.guarantors, @@ -684,7 +694,8 @@ public class LoanAccountData { acc.transactionProcessingStrategyOptions, acc.interestRateFrequencyTypeOptions, acc.amortizationTypeOptions, acc.interestTypeOptions, acc.interestCalculationPeriodTypeOptions, acc.fundOptions, acc.chargeOptions, null, acc.loanOfficerOptions, acc.loanPurposeOptions, acc.loanCollateralOptions, acc.calendarOptions, - acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, acc.notes,acc.accountLinkingOptions, acc.linkedAccount); + acc.syncDisbursementWithMeeting, acc.loanCounter, acc.loanProductCounter, acc.notes, acc.accountLinkingOptions, + acc.linkedAccount); } private LoanAccountData( @@ -715,14 +726,12 @@ public class LoanAccountData { final Integer numberOfRepayments, final Integer repaymentEvery, final EnumOptionData repaymentFrequencyType, // - final Long transactionProcessingStrategyId, - final String transactionProcessingStrategyName, - final EnumOptionData amortizationType, final BigDecimal interestRatePerPeriod, - final EnumOptionData interestRateFrequencyType, final BigDecimal annualInterestRate, final EnumOptionData interestType, - final EnumOptionData interestCalculationPeriodType, final LocalDate expectedFirstRepaymentOnDate, - final Integer graceOnPrincipalPayment, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, - final LocalDate interestChargedFromDate, final LoanApplicationTimelineData timeline, final LoanSummaryData summary, - final BigDecimal feeChargesDueAtDisbursementCharged, final LoanScheduleData repaymentSchedule, + final Long transactionProcessingStrategyId, final String transactionProcessingStrategyName, + final EnumOptionData amortizationType, final BigDecimal interestRatePerPeriod, final EnumOptionData interestRateFrequencyType, + final BigDecimal annualInterestRate, final EnumOptionData interestType, final EnumOptionData interestCalculationPeriodType, + final LocalDate expectedFirstRepaymentOnDate, final Integer graceOnPrincipalPayment, final Integer graceOnInterestPayment, + final Integer graceOnInterestCharged, final LocalDate interestChargedFromDate, final LoanApplicationTimelineData timeline, + final LoanSummaryData summary, final BigDecimal feeChargesDueAtDisbursementCharged, final LoanScheduleData repaymentSchedule, final Collection transactions, final Collection charges, final Collection collateral, final Collection guarantors, final CalendarData meeting, final Collection productOptions, final Collection termFrequencyTypeOptions, @@ -733,8 +742,9 @@ public class LoanAccountData { final Collection fundOptions, final Collection chargeOptions, final ChargeData chargeTemplate, final Collection loanOfficerOptions, final Collection loanPurposeOptions, final Collection loanCollateralOptions, final Collection calendarOptions, - final Boolean syncDisbursementWithMeeting, final Integer loanCounter, final Integer loanProductCounter, final Collection notes, - final Collection accountLinkingOptions, PortfolioAccountData linkedAccount) { + final Boolean syncDisbursementWithMeeting, final Integer loanCounter, final Integer loanProductCounter, + final Collection notes, final Collection accountLinkingOptions, + final PortfolioAccountData linkedAccount) { this.id = id; this.accountNo = accountNo; this.status = status; @@ -841,10 +851,10 @@ public class LoanAccountData { } else { this.calendarOptions = calendarOptions; } - + this.loanCounter = loanCounter; this.loanProductCounter = loanProductCounter; - + this.linkedAccount = linkedAccount; this.accountLinkingOptions = accountLinkingOptions; } @@ -871,19 +881,18 @@ public class LoanAccountData { } public Long groupOfficeId() { - return group == null ? null : group.officeId(); + return this.group == null ? null : this.group.officeId(); } public Long groupId() { - return group == null ? null : group.getId(); + return this.group == null ? null : this.group.getId(); } - public CurrencyData currency() { return this.currency; } - - public Long clientId(){ + + public Long clientId() { return this.clientId; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanChargeData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanChargeData.java index 5d8f88576..6c5ae04dc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanChargeData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanChargeData.java @@ -156,7 +156,7 @@ public class LoanChargeData { this.loanId = loanId; } - public LoanChargeData(final Long id,final LocalDate dueAsOfDate,final BigDecimal amountOutstanding,final Long loanId) { + public LoanChargeData(final Long id, final LocalDate dueAsOfDate, final BigDecimal amountOutstanding, final Long loanId) { this.id = id; this.chargeId = null; this.name = null; @@ -183,7 +183,7 @@ public class LoanChargeData { public boolean isChargePayable() { boolean isAccountTransfer = false; - if(this.chargePaymentMode!=null){ + if (this.chargePaymentMode != null) { isAccountTransfer = ChargePaymentMode.fromInt(this.chargePaymentMode.getId().intValue()).isPaymentModeAccountTransfer(); } return isAccountTransfer && !this.paid && !this.waived; @@ -201,7 +201,6 @@ public class LoanChargeData { return this.loanId; } - public BigDecimal getAmountOutstanding() { return this.amountOutstanding; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanConvenienceData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanConvenienceData.java index 7cfb57a65..58b6903ef 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanConvenienceData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanConvenienceData.java @@ -7,53 +7,51 @@ package org.mifosplatform.portfolio.loanaccount.data; public class LoanConvenienceData { - private final int maxSubmittedOnOffsetFromToday; - private final int maxApprovedOnOffsetFromToday; - private final int maxDisbursedOnOffsetFromToday; - private final int expectedLoanTermInDays; - private final int actualLoanTermInDays; - private final int expectedLoanTermInMonths; - private final int actualLoanTermInMonths; + private final int maxSubmittedOnOffsetFromToday; + private final int maxApprovedOnOffsetFromToday; + private final int maxDisbursedOnOffsetFromToday; + private final int expectedLoanTermInDays; + private final int actualLoanTermInDays; + private final int expectedLoanTermInMonths; + private final int actualLoanTermInMonths; - public LoanConvenienceData(int maxSubmittedOnOffsetFromToday, - int maxApprovedOnOffsetFromToday, - int maxDisbursedOnOffsetFromToday, int expectedLoanTermInDays, - int actualLoanTermInDays, int expectedLoanTermInMonths, - int actualLoanTermInMonths) { - this.maxSubmittedOnOffsetFromToday = maxSubmittedOnOffsetFromToday; - this.maxApprovedOnOffsetFromToday = maxApprovedOnOffsetFromToday; - this.maxDisbursedOnOffsetFromToday = maxDisbursedOnOffsetFromToday; - this.expectedLoanTermInDays = expectedLoanTermInDays; - this.actualLoanTermInDays = actualLoanTermInDays; - this.expectedLoanTermInMonths = expectedLoanTermInMonths; - this.actualLoanTermInMonths = actualLoanTermInMonths; - } + public LoanConvenienceData(final int maxSubmittedOnOffsetFromToday, final int maxApprovedOnOffsetFromToday, + final int maxDisbursedOnOffsetFromToday, final int expectedLoanTermInDays, final int actualLoanTermInDays, + final int expectedLoanTermInMonths, final int actualLoanTermInMonths) { + this.maxSubmittedOnOffsetFromToday = maxSubmittedOnOffsetFromToday; + this.maxApprovedOnOffsetFromToday = maxApprovedOnOffsetFromToday; + this.maxDisbursedOnOffsetFromToday = maxDisbursedOnOffsetFromToday; + this.expectedLoanTermInDays = expectedLoanTermInDays; + this.actualLoanTermInDays = actualLoanTermInDays; + this.expectedLoanTermInMonths = expectedLoanTermInMonths; + this.actualLoanTermInMonths = actualLoanTermInMonths; + } - public int getMaxSubmittedOnOffsetFromToday() { - return maxSubmittedOnOffsetFromToday; - } + public int getMaxSubmittedOnOffsetFromToday() { + return this.maxSubmittedOnOffsetFromToday; + } - public int getMaxApprovedOnOffsetFromToday() { - return maxApprovedOnOffsetFromToday; - } + public int getMaxApprovedOnOffsetFromToday() { + return this.maxApprovedOnOffsetFromToday; + } - public int getMaxDisbursedOnOffsetFromToday() { - return maxDisbursedOnOffsetFromToday; - } + public int getMaxDisbursedOnOffsetFromToday() { + return this.maxDisbursedOnOffsetFromToday; + } - public int getExpectedLoanTermInDays() { - return expectedLoanTermInDays; - } + public int getExpectedLoanTermInDays() { + return this.expectedLoanTermInDays; + } - public int getActualLoanTermInDays() { - return actualLoanTermInDays; - } + public int getActualLoanTermInDays() { + return this.actualLoanTermInDays; + } - public int getExpectedLoanTermInMonths() { - return expectedLoanTermInMonths; - } + public int getExpectedLoanTermInMonths() { + return this.expectedLoanTermInMonths; + } - public int getActualLoanTermInMonths() { - return actualLoanTermInMonths; - } + public int getActualLoanTermInMonths() { + return this.actualLoanTermInMonths; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanTransactionData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanTransactionData.java index 8837c9eab..db19d8b74 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanTransactionData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanTransactionData.java @@ -41,20 +41,21 @@ public class LoanTransactionData { // templates final Collection paymentTypeOptions; - public static LoanTransactionData templateOnTop(LoanTransactionData loanTransactionData, Collection paymentTypeOptions) { + public static LoanTransactionData templateOnTop(final LoanTransactionData loanTransactionData, + final Collection paymentTypeOptions) { return new LoanTransactionData(loanTransactionData.id, loanTransactionData.officeId, loanTransactionData.officeName, loanTransactionData.type, loanTransactionData.paymentDetailData, loanTransactionData.currency, loanTransactionData.date, loanTransactionData.amount, loanTransactionData.principalPortion, loanTransactionData.interestPortion, loanTransactionData.feeChargesPortion, loanTransactionData.penaltyChargesPortion, paymentTypeOptions, - loanTransactionData.externalId,loanTransactionData.transfer); + loanTransactionData.externalId, loanTransactionData.transfer); } public LoanTransactionData(final Long id, final Long officeId, final String officeName, final LoanTransactionEnumData transactionType, final PaymentDetailData paymentDetailData, final CurrencyData currency, final LocalDate date, final BigDecimal amount, final BigDecimal principalPortion, final BigDecimal interestPortion, final BigDecimal feeChargesPortion, - final BigDecimal penaltyChargesPortion, final String externalId, AccountTransferData transfer) { + final BigDecimal penaltyChargesPortion, final String externalId, final AccountTransferData transfer) { this(id, officeId, officeName, transactionType, paymentDetailData, currency, date, amount, principalPortion, interestPortion, - feeChargesPortion, penaltyChargesPortion, null, externalId,transfer); + feeChargesPortion, penaltyChargesPortion, null, externalId, transfer); } public LoanTransactionData(final Long id, final Long officeId, final String officeName, final LoanTransactionEnumData transactionType, @@ -84,6 +85,6 @@ public class LoanTransactionData { } public boolean isNotDisbursement() { - return Integer.valueOf(1).equals(type.id()); + return Integer.valueOf(1).equals(this.type.id()); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanTransactionEnumData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanTransactionEnumData.java index 404c2ecb8..42f7cb31c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanTransactionEnumData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/LoanTransactionEnumData.java @@ -121,12 +121,10 @@ public class LoanTransactionEnumData { return this.rejectTransfer; } - public boolean isChargePayment() { return this.chargePayment; } - public boolean isRefund() { return this.refund; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/RepaymentScheduleRelatedLoanData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/RepaymentScheduleRelatedLoanData.java index 97191f664..e1df92867 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/RepaymentScheduleRelatedLoanData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/data/RepaymentScheduleRelatedLoanData.java @@ -35,8 +35,8 @@ public class RepaymentScheduleRelatedLoanData { public LocalDate disbursementDate() { LocalDate disbursementDate = this.expectedDisbursementDate; - if (actualDisbursementDate != null) { - disbursementDate = actualDisbursementDate; + if (this.actualDisbursementDate != null) { + disbursementDate = this.actualDisbursementDate; } return disbursementDate; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/ChangedTransactionDetail.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/ChangedTransactionDetail.java index 1d2da0be7..2cc96cba1 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/ChangedTransactionDetail.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/ChangedTransactionDetail.java @@ -16,9 +16,9 @@ import java.util.List; */ public class ChangedTransactionDetail { - private List newTransactions = new ArrayList(); + private final List newTransactions = new ArrayList(); - private List reversedTransactions = new ArrayList(); + private final List reversedTransactions = new ArrayList(); public List getNewTransactions() { return this.newTransactions; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/DefaultLoanLifecycleStateMachine.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/DefaultLoanLifecycleStateMachine.java index 52d096ab4..c2a5868ff 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/DefaultLoanLifecycleStateMachine.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/DefaultLoanLifecycleStateMachine.java @@ -11,82 +11,82 @@ public class DefaultLoanLifecycleStateMachine implements LoanLifecycleStateMachi private final List allowedLoanStatuses; - public DefaultLoanLifecycleStateMachine(List allowedLoanStatuses) { + public DefaultLoanLifecycleStateMachine(final List allowedLoanStatuses) { this.allowedLoanStatuses = allowedLoanStatuses; } @Override - public LoanStatus transition(LoanEvent loanEvent, LoanStatus from) { + public LoanStatus transition(final LoanEvent loanEvent, final LoanStatus from) { LoanStatus newState = from; switch (loanEvent) { case LOAN_CREATED: if (from == null) { - newState = stateOf(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL, allowedLoanStatuses); + newState = stateOf(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL, this.allowedLoanStatuses); } break; case LOAN_REJECTED: if (from.hasStateOf(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL)) { - newState = stateOf(LoanStatus.REJECTED, allowedLoanStatuses); + newState = stateOf(LoanStatus.REJECTED, this.allowedLoanStatuses); } break; case LOAN_APPROVED: if (from.hasStateOf(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL)) { - newState = stateOf(LoanStatus.APPROVED, allowedLoanStatuses); + newState = stateOf(LoanStatus.APPROVED, this.allowedLoanStatuses); } break; case LOAN_WITHDRAWN: - if (this.anyOfAllowedWhenComingFrom(from, LoanStatus.SUBMITTED_AND_PENDING_APPROVAL)) { - newState = stateOf(LoanStatus.WITHDRAWN_BY_CLIENT, allowedLoanStatuses); + if (anyOfAllowedWhenComingFrom(from, LoanStatus.SUBMITTED_AND_PENDING_APPROVAL)) { + newState = stateOf(LoanStatus.WITHDRAWN_BY_CLIENT, this.allowedLoanStatuses); } break; case LOAN_DISBURSED: if (from.hasStateOf(LoanStatus.APPROVED)) { - newState = stateOf(LoanStatus.ACTIVE, allowedLoanStatuses); + newState = stateOf(LoanStatus.ACTIVE, this.allowedLoanStatuses); } break; case LOAN_APPROVAL_UNDO: if (from.hasStateOf(LoanStatus.APPROVED)) { - newState = stateOf(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL, allowedLoanStatuses); + newState = stateOf(LoanStatus.SUBMITTED_AND_PENDING_APPROVAL, this.allowedLoanStatuses); } break; case LOAN_DISBURSAL_UNDO: - if (this.anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE)) { - newState = stateOf(LoanStatus.APPROVED, allowedLoanStatuses); + if (anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE)) { + newState = stateOf(LoanStatus.APPROVED, this.allowedLoanStatuses); } break; case LOAN_CHARGE_PAYMENT: case LOAN_REPAYMENT_OR_WAIVER: - if (this.anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE, LoanStatus.CLOSED_OBLIGATIONS_MET, LoanStatus.OVERPAID)) { - newState = stateOf(LoanStatus.ACTIVE, allowedLoanStatuses); + if (anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE, LoanStatus.CLOSED_OBLIGATIONS_MET, LoanStatus.OVERPAID)) { + newState = stateOf(LoanStatus.ACTIVE, this.allowedLoanStatuses); } else { newState = from; } break; case REPAID_IN_FULL: - if (this.anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE, LoanStatus.OVERPAID)) { - newState = stateOf(LoanStatus.CLOSED_OBLIGATIONS_MET, allowedLoanStatuses); + if (anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE, LoanStatus.OVERPAID)) { + newState = stateOf(LoanStatus.CLOSED_OBLIGATIONS_MET, this.allowedLoanStatuses); } break; case WRITE_OFF_OUTSTANDING: - if (this.anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE)) { - newState = stateOf(LoanStatus.CLOSED_WRITTEN_OFF, allowedLoanStatuses); + if (anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE)) { + newState = stateOf(LoanStatus.CLOSED_WRITTEN_OFF, this.allowedLoanStatuses); } break; case LOAN_RESCHEDULE: - if (this.anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE)) { - newState = stateOf(LoanStatus.CLOSED_RESCHEDULE_OUTSTANDING_AMOUNT, allowedLoanStatuses); + if (anyOfAllowedWhenComingFrom(from, LoanStatus.ACTIVE)) { + newState = stateOf(LoanStatus.CLOSED_RESCHEDULE_OUTSTANDING_AMOUNT, this.allowedLoanStatuses); } break; case INTERST_REBATE_OWED: - if (this.anyOfAllowedWhenComingFrom(from, LoanStatus.CLOSED_OBLIGATIONS_MET)) { - newState = stateOf(LoanStatus.CLOSED_OBLIGATIONS_MET, allowedLoanStatuses); + if (anyOfAllowedWhenComingFrom(from, LoanStatus.CLOSED_OBLIGATIONS_MET)) { + newState = stateOf(LoanStatus.CLOSED_OBLIGATIONS_MET, this.allowedLoanStatuses); } break; case LOAN_OVERPAYMENT: - if (this.anyOfAllowedWhenComingFrom(from, LoanStatus.CLOSED_OBLIGATIONS_MET, LoanStatus.ACTIVE)) { - newState = stateOf(LoanStatus.OVERPAID, allowedLoanStatuses); + if (anyOfAllowedWhenComingFrom(from, LoanStatus.CLOSED_OBLIGATIONS_MET, LoanStatus.ACTIVE)) { + newState = stateOf(LoanStatus.OVERPAID, this.allowedLoanStatuses); } break; } @@ -94,9 +94,9 @@ public class DefaultLoanLifecycleStateMachine implements LoanLifecycleStateMachi return newState; } - private LoanStatus stateOf(LoanStatus state, List allowedLoanStatuses) { + private LoanStatus stateOf(final LoanStatus state, final List allowedLoanStatuses) { LoanStatus match = null; - for (LoanStatus loanStatus : allowedLoanStatuses) { + for (final LoanStatus loanStatus : allowedLoanStatuses) { if (loanStatus.hasStateOf(state)) { match = loanStatus; break; @@ -108,7 +108,7 @@ public class DefaultLoanLifecycleStateMachine implements LoanLifecycleStateMachi private boolean anyOfAllowedWhenComingFrom(final LoanStatus state, final LoanStatus... allowedStates) { boolean allowed = false; - for (LoanStatus allowedState : allowedStates) { + for (final LoanStatus allowedState : allowedStates) { if (state.hasStateOf(allowedState)) { allowed = true; break; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/Loan.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/Loan.java index 4ccd0aedc..fd788bc21 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/Loan.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/Loan.java @@ -495,7 +495,7 @@ public class Loan extends AbstractPersistable { } } - final LoanTransaction applyLoanChargeTransaction = LoanTransaction.applyLoanCharge(this, this.getOffice(), chargeAmount, + final LoanTransaction applyLoanChargeTransaction = LoanTransaction.applyLoanCharge(this, getOffice(), chargeAmount, transactionDate, feeCharges, penaltyCharges); this.loanTransactions.add(applyLoanChargeTransaction); return applyLoanChargeTransaction; @@ -504,7 +504,7 @@ public class Loan extends AbstractPersistable { private void handleChargePaidTransaction(final LoanCharge charge, final LoanTransaction chargesPayment, final LoanLifecycleStateMachine loanLifecycleStateMachine) { chargesPayment.updateLoan(this); - LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(chargesPayment, charge, chargesPayment.getAmount(getCurrency()) + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(chargesPayment, charge, chargesPayment.getAmount(getCurrency()) .getAmount()); chargesPayment.getLoanChargesPaid().add(loanChargePaidBy); this.loanTransactions.add(chargesPayment); @@ -514,16 +514,16 @@ public class Loan extends AbstractPersistable { final LoanRepaymentScheduleTransactionProcessor loanRepaymentScheduleTransactionProcessor = this.transactionProcessorFactory .determineProcessor(this.transactionProcessingStrategy); - List chargePaymentInstallments = new ArrayList(); + final List chargePaymentInstallments = new ArrayList(); LocalDate startDate = getDisbursementDate(); - for (LoanRepaymentScheduleInstallment installment : this.repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : this.repaymentScheduleInstallments) { if (charge.isDueForCollectionFromAndUpToAndIncluding(startDate, installment.getDueDate())) { chargePaymentInstallments.add(installment); break; } startDate = installment.getDueDate(); } - Set loanCharges = new HashSet(1); + final Set loanCharges = new HashSet(1); loanCharges.add(charge); loanRepaymentScheduleTransactionProcessor.handleTransaction(chargesPayment, getCurrency(), chargePaymentInstallments, loanCharges); updateLoanSummaryDerivedFields(); @@ -683,7 +683,7 @@ public class Loan extends AbstractPersistable { existingTransactionIds.addAll(findExistingTransactionIds()); existingReversedTransactionIds.addAll(findExistingReversedTransactionIds()); - final LoanTransaction waiveLoanChargeTransaction = LoanTransaction.waiveLoanCharge(this, this.getOffice(), amountWaived, + final LoanTransaction waiveLoanChargeTransaction = LoanTransaction.waiveLoanCharge(this, getOffice(), amountWaived, transactionDate, feeChargesWaived, penaltyChargesWaived); this.loanTransactions.add(waiveLoanChargeTransaction); @@ -1390,7 +1390,7 @@ public class Loan extends AbstractPersistable { } final Money interestApplied = Money.of(getCurrency(), this.summary.getTotalInterestCharged()); - final LoanTransaction interestAppliedTransaction = LoanTransaction.applyInterest(this.getOffice(), this, interestApplied, + final LoanTransaction interestAppliedTransaction = LoanTransaction.applyInterest(getOffice(), this, interestApplied, actualDisbursementDate); this.loanTransactions.add(interestAppliedTransaction); } @@ -1434,7 +1434,7 @@ public class Loan extends AbstractPersistable { private LoanTransaction handleDisbursementTransaction(final PaymentDetail paymentDetail, final LocalDate disbursedOn, final String txnExternalId) { // track disbursement transaction - final LoanTransaction disbursementTransaction = LoanTransaction.disbursement(this.getOffice(), + final LoanTransaction disbursementTransaction = LoanTransaction.disbursement(getOffice(), this.loanRepaymentScheduleDetail.getPrincipal(), paymentDetail, disbursedOn, txnExternalId); disbursementTransaction.updateLoan(this); this.loanTransactions.add(disbursementTransaction); @@ -1447,33 +1447,33 @@ public class Loan extends AbstractPersistable { * for repayments at disbursements too? ***/ final Money totalFeeChargesDueAtDisbursement = this.summary.getTotalFeeChargesDueAtDisbursement(loanCurrency()); - /** - * all Charges repaid at disbursal is marked as repaid and - * "APPLY Charge" transactions are created for all other fees ( - * which are created during disbursal but not repaid) - **/ - Money disbursentMoney = Money.zero(getCurrency()); - final LoanTransaction chargesPayment = LoanTransaction.repaymentAtDisbursement(this.getOffice(), - disbursentMoney, null, disbursedOn, txnExternalId); - for (final LoanCharge charge : setOfLoanCharges()) { - if (charge.isDueAtDisbursement()) { - if (totalFeeChargesDueAtDisbursement.isGreaterThanZero() && !charge.getChargePaymentMode().isPaymentModeAccountTransfer()) { - charge.markAsFullyPaid(); - // Add "Loan Charge Paid By" details to this transaction - final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(chargesPayment, charge, charge.amount()); - chargesPayment.getLoanChargesPaid().add(loanChargePaidBy); - disbursentMoney = disbursentMoney.plus(charge.amount()); - } - } else { - handleChargeAppliedTransaction(charge, disbursedOn); + /** + * all Charges repaid at disbursal is marked as repaid and + * "APPLY Charge" transactions are created for all other fees ( which + * are created during disbursal but not repaid) + **/ + Money disbursentMoney = Money.zero(getCurrency()); + final LoanTransaction chargesPayment = LoanTransaction.repaymentAtDisbursement(getOffice(), disbursentMoney, null, disbursedOn, + txnExternalId); + for (final LoanCharge charge : setOfLoanCharges()) { + if (charge.isDueAtDisbursement()) { + if (totalFeeChargesDueAtDisbursement.isGreaterThanZero() && !charge.getChargePaymentMode().isPaymentModeAccountTransfer()) { + charge.markAsFullyPaid(); + // Add "Loan Charge Paid By" details to this transaction + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(chargesPayment, charge, charge.amount()); + chargesPayment.getLoanChargesPaid().add(loanChargePaidBy); + disbursentMoney = disbursentMoney.plus(charge.amount()); } + } else { + handleChargeAppliedTransaction(charge, disbursedOn); } - if(disbursentMoney.isGreaterThanZero()){ - final Money zero = Money.zero(getCurrency()); - chargesPayment.updateComponentsAndTotal(zero, zero, disbursentMoney, zero); - chargesPayment.updateLoan(this); - this.loanTransactions.add(chargesPayment); - } + } + if (disbursentMoney.isGreaterThanZero()) { + final Money zero = Money.zero(getCurrency()); + chargesPayment.updateComponentsAndTotal(zero, zero, disbursentMoney, zero); + chargesPayment.updateLoan(this); + this.loanTransactions.add(chargesPayment); + } if (getApprovedOnDate() != null && disbursedOn.isBefore(getApprovedOnDate())) { final String errorMessage = "The date on which a loan is disbursed cannot be before its approval date: " @@ -1495,7 +1495,7 @@ public class Loan extends AbstractPersistable { public LoanTransaction handlePayDisbursementTransaction(final Long chargeId, final LoanTransaction chargesPayment) { LoanCharge charge = null; - for (LoanCharge loanCharge : this.charges) { + for (final LoanCharge loanCharge : this.charges) { if (chargeId.equals(loanCharge.getId())) { charge = loanCharge; } @@ -1517,7 +1517,7 @@ public class Loan extends AbstractPersistable { final LoanStatus currentStatus = LoanStatus.fromInt(this.loanStatus); final LoanStatus statusEnum = this.loanLifecycleStateMachine.transition(LoanEvent.LOAN_DISBURSAL_UNDO, currentStatus); - validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent.LOAN_DISBURSAL_UNDO, this.getDisbursementDate()); + validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent.LOAN_DISBURSAL_UNDO, getDisbursementDate()); if (!statusEnum.hasStateOf(currentStatus)) { this.loanStatus = statusEnum.getValue(); actualChanges.put("status", LoanEnumerations.status(this.loanStatus)); @@ -1599,7 +1599,7 @@ public class Loan extends AbstractPersistable { public void makeChargePayment(final Long chargeId, final LoanLifecycleStateMachine loanLifecycleStateMachine, final List existingTransactionIds, final List existingReversedTransactionIds, final boolean allowTransactionsOnHoliday, final List holidays, final WorkingDays workingDays, - final boolean allowTransactionsOnNonWorkingDay, LoanTransaction paymentTransaction) { + final boolean allowTransactionsOnNonWorkingDay, final LoanTransaction paymentTransaction) { validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent.LOAN_CHARGE_PAYMENT, paymentTransaction.getTransactionDate()); validateRepaymentDateIsOnHoliday(paymentTransaction.getTransactionDate(), allowTransactionsOnHoliday, holidays); @@ -1613,7 +1613,7 @@ public class Loan extends AbstractPersistable { existingTransactionIds.addAll(findExistingTransactionIds()); existingReversedTransactionIds.addAll(findExistingReversedTransactionIds()); LoanCharge charge = null; - for (LoanCharge loanCharge : this.charges) { + for (final LoanCharge loanCharge : this.charges) { if (chargeId.equals(loanCharge.getId())) { charge = loanCharge; } @@ -1635,9 +1635,9 @@ public class Loan extends AbstractPersistable { if (status().isOverpaid()) { if (this.totalOverpaid.compareTo(loanTransaction.getAmount(getCurrency()).getAmount()) == -1) { final String errorMessage = "The refund amount must be less than or equal to overpaid amount "; - throw new InvalidLoanStateTransitionException("transaction", "is.exceeding.overpaid.amount", errorMessage, totalOverpaid, - loanTransaction.getAmount(getCurrency()).getAmount()); - } else if (!isAfterLatRepayment(loanTransaction, loanTransactions)) { + throw new InvalidLoanStateTransitionException("transaction", "is.exceeding.overpaid.amount", errorMessage, + this.totalOverpaid, loanTransaction.getAmount(getCurrency()).getAmount()); + } else if (!isAfterLatRepayment(loanTransaction, this.loanTransactions)) { final String errorMessage = "Transfer funds is allowed only after last repayment date"; throw new InvalidLoanStateTransitionException("transaction", "is.not.after.repayment.date", errorMessage); } @@ -1748,7 +1748,7 @@ public class Loan extends AbstractPersistable { private void handleLoanRepaymentInFull(final LocalDate transactionDate, final LoanLifecycleStateMachine loanLifecycleStateMachine) { boolean isAllChargesPaid = true; - for (LoanCharge loanCharge : this.charges) { + for (final LoanCharge loanCharge : this.charges) { if (!(loanCharge.isPaid() || loanCharge.isWaived())) { isAllChargesPaid = false; break; @@ -1889,7 +1889,7 @@ public class Loan extends AbstractPersistable { } } - return LoanTransaction.waiver(this.getOffice(), this, possibleInterestToWaive, transactionDate); + return LoanTransaction.waiver(getOffice(), this, possibleInterestToWaive, transactionDate); } public ChangedTransactionDetail adjustExistingTransaction(final LoanTransaction newTransactionDetail, @@ -1968,7 +1968,7 @@ public class Loan extends AbstractPersistable { cumulativeTotalWaivedOnInstallments = cumulativeTotalWaivedOnInstallments.plus(scheduledRepayment.getInterestWaived(currency)); } - for (LoanTransaction loanTransaction : this.loanTransactions) { + for (final LoanTransaction loanTransaction : this.loanTransactions) { if (loanTransaction.isRefund() && !loanTransaction.isReversed()) { totalPaidInRepayments = totalPaidInRepayments.minus(loanTransaction.getAmount(currency)); } @@ -2021,7 +2021,7 @@ public class Loan extends AbstractPersistable { throw new InvalidLoanStateTransitionException("writeoff", "cannot.be.a.future.date", errorMessage, writtenOffOnLocalDate); } - loanTransaction = LoanTransaction.writeoff(this, this.getOffice(), writtenOffOnLocalDate, txnExternalId); + loanTransaction = LoanTransaction.writeoff(this, getOffice(), writtenOffOnLocalDate, txnExternalId); final boolean isLastTransaction = isChronologicallyLatestTransaction(loanTransaction, this.loanTransactions); if (!isLastTransaction) { final String errorMessage = "The date of the writeoff transaction must occur on or before previous transactions."; @@ -2079,7 +2079,7 @@ public class Loan extends AbstractPersistable { } this.closedOnDate = closureDate.toDate(); - loanTransaction = LoanTransaction.writeoff(this, this.getOffice(), closureDate, txnExternalId); + loanTransaction = LoanTransaction.writeoff(this, getOffice(), closureDate, txnExternalId); final boolean isLastTransaction = isChronologicallyLatestTransaction(loanTransaction, this.loanTransactions); if (!isLastTransaction) { final String errorMessage = "The closing date of the loan must be on or after latest transaction date."; @@ -2575,7 +2575,7 @@ public class Loan extends AbstractPersistable { public void updateLoanRepaymentScheduleDates(final LocalDate meetingStartDate, final String recuringRule, final boolean isHolidayEnabled, final List holidays, final WorkingDays workingDays) { // first repayment's from date is same as disbursement date. - LocalDate tmpFromDate = this.getDisbursementDate(); + LocalDate tmpFromDate = getDisbursementDate(); final PeriodFrequencyType repaymentPeriodFrequencyType = this.loanRepaymentScheduleDetail.getRepaymentPeriodFrequencyType(); final Integer loanRepaymentInterval = this.loanRepaymentScheduleDetail.getRepayEvery(); final String frequency = CalendarUtils.getMeetingFrequencyFromPeriodFrequencyType(repaymentPeriodFrequencyType); @@ -2706,7 +2706,7 @@ public class Loan extends AbstractPersistable { return this.group; } - public void updateGroup(Group newGroup) { + public void updateGroup(final Group newGroup) { this.group = newGroup; } @@ -2746,7 +2746,7 @@ public class Loan extends AbstractPersistable { return this.loanTransactions; } - public void setLoanStatus(Integer loanStatus) { + public void setLoanStatus(final Integer loanStatus) { this.loanStatus = loanStatus; } @@ -2758,9 +2758,9 @@ public class Loan extends AbstractPersistable { } - private void validateActivityNotBeforeClientOrGroupTransferDate(LoanEvent event, LocalDate activityDate) { + private void validateActivityNotBeforeClientOrGroupTransferDate(final LoanEvent event, final LocalDate activityDate) { if (this.client != null && this.client.getOfficeJoiningLocalDate() != null) { - LocalDate clientOfficeJoiningDate = client.getOfficeJoiningLocalDate(); + final LocalDate clientOfficeJoiningDate = this.client.getOfficeJoiningLocalDate(); if (activityDate.isBefore(clientOfficeJoiningDate)) { String errorMessage = null; String action = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanAccountDomainService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanAccountDomainService.java index 81346f8d0..8d6d6a742 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanAccountDomainService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanAccountDomainService.java @@ -15,10 +15,10 @@ public interface LoanAccountDomainService { LoanTransaction makeRepayment(Loan loan, CommandProcessingResultBuilder builderResult, LocalDate transactionDate, BigDecimal transactionAmount, PaymentDetail paymentDetail, String noteText, String txnExternalId); - + LoanTransaction makeRefund(Long accountId, CommandProcessingResultBuilder builderResult, LocalDate transactionDate, BigDecimal transactionAmount, PaymentDetail paymentDetail, String noteText, String txnExternalId); - + void reverseTransfer(LoanTransaction loanTransaction); LoanTransaction makeChargePayment(Loan loan, Long chargeId, LocalDate transactionDate, BigDecimal transactionAmount, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanAccountDomainServiceJpa.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanAccountDomainServiceJpa.java index 85e4b6a1d..32d88f2b7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanAccountDomainServiceJpa.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanAccountDomainServiceJpa.java @@ -148,8 +148,8 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { final List existingReversedTransactionIds = new ArrayList(); final Money paymentAmout = Money.of(loan.getCurrency(), transactionAmount); - LoanTransactionType loanTransactionType = LoanTransactionType.fromInt(transactionType); - + final LoanTransactionType loanTransactionType = LoanTransactionType.fromInt(transactionType); + final LoanTransaction newPaymentTransaction = LoanTransaction.loanPayment(null, loan.getOffice(), paymentAmout, paymentDetail, transactionDate, txnExternalId, loanTransactionType); final boolean allowTransactionsOnHoliday = this.configurationDomainService.allowTransactionsOnHolidayEnabled(); @@ -157,11 +157,11 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { .findByOfficeIdAndGreaterThanDate(loan.getOfficeId(), transactionDate.toDate()); final WorkingDays workingDays = this.workingDaysRepository.findOne(); final boolean allowTransactionsOnNonWorkingDay = this.configurationDomainService.allowTransactionsOnNonWorkingDayEnabled(); - if(loanTransactionType.isRepaymentAtDisbursement()){ + if (loanTransactionType.isRepaymentAtDisbursement()) { loan.handlePayDisbursementTransaction(chargeId, newPaymentTransaction); - }else{ - loan.makeChargePayment(chargeId, defaultLoanLifecycleStateMachine(), existingTransactionIds, existingReversedTransactionIds, - allowTransactionsOnHoliday, holidays, workingDays, allowTransactionsOnNonWorkingDay, newPaymentTransaction); + } else { + loan.makeChargePayment(chargeId, defaultLoanLifecycleStateMachine(), existingTransactionIds, existingReversedTransactionIds, + allowTransactionsOnHoliday, holidays, workingDays, allowTransactionsOnNonWorkingDay, newPaymentTransaction); } this.loanTransactionRepository.save(newPaymentTransaction); this.loanRepository.saveAndFlush(loan); @@ -203,8 +203,9 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { } @Override - public LoanTransaction makeRefund(Long accountId, CommandProcessingResultBuilder builderResult, LocalDate transactionDate, - BigDecimal transactionAmount, PaymentDetail paymentDetail, String noteText, String txnExternalId) { + public LoanTransaction makeRefund(final Long accountId, final CommandProcessingResultBuilder builderResult, + final LocalDate transactionDate, final BigDecimal transactionAmount, final PaymentDetail paymentDetail, final String noteText, + final String txnExternalId) { final Loan loan = this.loanAccountAssembler.assembleFrom(accountId); checkClientOrGroupActive(loan); @@ -242,7 +243,7 @@ public class LoanAccountDomainServiceJpa implements LoanAccountDomainService { } @Override - public void reverseTransfer(LoanTransaction loanTransaction) { + public void reverseTransfer(final LoanTransaction loanTransaction) { loanTransaction.reverse(); this.loanTransactionRepository.save(loanTransaction); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanCharge.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanCharge.java index d147f8abb..9319ac09e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanCharge.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanCharge.java @@ -55,7 +55,7 @@ public class LoanCharge extends AbstractPersistable { @Column(name = "charge_calculation_enum") private Integer chargeCalculation; - + @Column(name = "charge_payment_mode_enum") private Integer chargePaymentMode; @@ -94,18 +94,20 @@ public class LoanCharge extends AbstractPersistable { final BigDecimal amount = command.bigDecimalValueOfParameterNamed("amount"); final LocalDate dueDate = command.localDateValueOfParameterNamed("dueDate"); - ChargeTimeType chargeTime = null; - ChargeCalculationType chargeCalculation = null; - ChargePaymentMode chargePaymentMode = null; + final ChargeTimeType chargeTime = null; + final ChargeCalculationType chargeCalculation = null; + final ChargePaymentMode chargePaymentMode = null; - return new LoanCharge(loan, chargeDefinition, loan.getPrincpal().getAmount(), amount, chargeTime, chargeCalculation, dueDate, chargePaymentMode); + return new LoanCharge(loan, chargeDefinition, loan.getPrincpal().getAmount(), amount, chargeTime, chargeCalculation, dueDate, + chargePaymentMode); } /* * loanPrincipal is required for charges that are percentage based */ public static LoanCharge createNewWithoutLoan(final Charge chargeDefinition, final BigDecimal loanPrincipal, final BigDecimal amount, - final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculation, final LocalDate dueDate, ChargePaymentMode chargePaymentMode) { + final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculation, final LocalDate dueDate, + final ChargePaymentMode chargePaymentMode) { return new LoanCharge(null, chargeDefinition, loanPrincipal, amount, chargeTime, chargeCalculation, dueDate, chargePaymentMode); } @@ -114,7 +116,8 @@ public class LoanCharge extends AbstractPersistable { } public LoanCharge(final Loan loan, final Charge chargeDefinition, final BigDecimal loanPrincipal, final BigDecimal amount, - final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculation, final LocalDate dueDate, ChargePaymentMode chargePaymentMode) { + final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculation, final LocalDate dueDate, + final ChargePaymentMode chargePaymentMode) { this.loan = loan; this.charge = chargeDefinition; this.penaltyCharge = chargeDefinition.isPenalty(); @@ -146,9 +149,9 @@ public class LoanCharge extends AbstractPersistable { if (amount != null) { chargeAmount = amount; } - + this.chargePaymentMode = chargeDefinition.getChargePaymentMode(); - if(chargePaymentMode != null){ + if (chargePaymentMode != null) { this.chargePaymentMode = chargePaymentMode.getValue(); } @@ -344,8 +347,7 @@ public class LoanCharge extends AbstractPersistable { } public LoanChargeCommand toCommand() { - return new LoanChargeCommand(this.getId(), this.charge.getId(), this.amount, this.chargeTime, this.chargeCalculation, - getDueLocalDate()); + return new LoanChargeCommand(getId(), this.charge.getId(), this.amount, this.chargeTime, this.chargeCalculation, getDueLocalDate()); } public LocalDate getDueLocalDate() { @@ -388,7 +390,7 @@ public class LoanCharge extends AbstractPersistable { if (isGreaterThanZero(value)) { final MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); - BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc); + final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc); percentageOf = value.multiply(multiplicand, mc); } @@ -398,8 +400,8 @@ public class LoanCharge extends AbstractPersistable { public BigDecimal amount() { return this.amount; } - - public BigDecimal amountOutstanding(){ + + public BigDecimal amountOutstanding() { return this.amountOutstanding; } @@ -471,7 +473,7 @@ public class LoanCharge extends AbstractPersistable { public Money updatePaidAmountBy(final Money incrementBy) { Money amountPaidToDate = Money.of(incrementBy.getCurrency(), this.amountPaid); - Money amountOutstanding = Money.of(incrementBy.getCurrency(), this.amountOutstanding); + final Money amountOutstanding = Money.of(incrementBy.getCurrency(), this.amountOutstanding); Money amountPaidOnThisCharge = Money.zero(incrementBy.getCurrency()); if (incrementBy.isGreaterThanOrEqualTo(amountOutstanding)) { @@ -484,7 +486,7 @@ public class LoanCharge extends AbstractPersistable { amountPaidToDate = amountPaidToDate.plus(incrementBy); this.amountPaid = amountPaidToDate.getAmount(); - Money amountExpected = Money.of(incrementBy.getCurrency(), this.amount); + final Money amountExpected = Money.of(incrementBy.getCurrency(), this.amount); this.amountOutstanding = amountExpected.minus(amountPaidToDate).getAmount(); } @@ -510,25 +512,24 @@ public class LoanCharge extends AbstractPersistable { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } - LoanCharge rhs = (LoanCharge) obj; + final LoanCharge rhs = (LoanCharge) obj; return new EqualsBuilder().appendSuper(super.equals(obj)) // - .append(this.getId(), rhs.getId()) // + .append(getId(), rhs.getId()) // .append(this.charge.getId(), rhs.charge.getId()) // .append(this.amount, rhs.amount) // - .append(this.getDueLocalDate(), rhs.getDueLocalDate()) // + .append(getDueLocalDate(), rhs.getDueLocalDate()) // .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(3, 5) // - .append(this.getId()) // + .append(getId()) // .append(this.charge.getId()) // - .append(this.amount).append(this.getDueLocalDate()) // + .append(this.amount).append(getDueLocalDate()) // .toHashCode(); } - public ChargePaymentMode getChargePaymentMode() { return ChargePaymentMode.fromInt(this.chargePaymentMode); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanChargePaidBy.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanChargePaidBy.java index 5da1ae192..1124225c4 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanChargePaidBy.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanChargePaidBy.java @@ -29,7 +29,7 @@ public class LoanChargePaidBy extends AbstractPersistable { } - public LoanChargePaidBy(LoanTransaction loanTransaction, LoanCharge loanCharge, BigDecimal amount) { + public LoanChargePaidBy(final LoanTransaction loanTransaction, final LoanCharge loanCharge, final BigDecimal amount) { this.loanTransaction = loanTransaction; this.loanCharge = loanCharge; this.amount = amount; @@ -39,7 +39,7 @@ public class LoanChargePaidBy extends AbstractPersistable { return this.loanTransaction; } - public void setLoanTransaction(LoanTransaction loanTransaction) { + public void setLoanTransaction(final LoanTransaction loanTransaction) { this.loanTransaction = loanTransaction; } @@ -47,7 +47,7 @@ public class LoanChargePaidBy extends AbstractPersistable { return this.loanCharge; } - public void setLoanCharge(LoanCharge loanCharge) { + public void setLoanCharge(final LoanCharge loanCharge) { this.loanCharge = loanCharge; } @@ -55,7 +55,7 @@ public class LoanChargePaidBy extends AbstractPersistable { return this.amount; } - public void setAmount(BigDecimal amount) { + public void setAmount(final BigDecimal amount) { this.amount = amount; } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanEvent.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanEvent.java index 7f06285e3..cb3eda664 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanEvent.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanEvent.java @@ -10,18 +10,17 @@ package org.mifosplatform.portfolio.loanaccount.domain; */ public enum LoanEvent { - LOAN_CREATED, // - LOAN_REJECTED, // - LOAN_WITHDRAWN, // - LOAN_APPROVED, // - LOAN_APPROVAL_UNDO, // - LOAN_DISBURSED, // - LOAN_DISBURSAL_UNDO, // - LOAN_REPAYMENT_OR_WAIVER, // - REPAID_IN_FULL, // - WRITE_OFF_OUTSTANDING, // - LOAN_RESCHEDULE, // - INTERST_REBATE_OWED, // - LOAN_OVERPAYMENT, - LOAN_CHARGE_PAYMENT; + LOAN_CREATED, // + LOAN_REJECTED, // + LOAN_WITHDRAWN, // + LOAN_APPROVED, // + LOAN_APPROVAL_UNDO, // + LOAN_DISBURSED, // + LOAN_DISBURSAL_UNDO, // + LOAN_REPAYMENT_OR_WAIVER, // + REPAID_IN_FULL, // + WRITE_OFF_OUTSTANDING, // + LOAN_RESCHEDULE, // + INTERST_REBATE_OWED, // + LOAN_OVERPAYMENT, LOAN_CHARGE_PAYMENT; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanOfficerAssignmentHistory.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanOfficerAssignmentHistory.java index bcad5845d..bc428c409 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanOfficerAssignmentHistory.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanOfficerAssignmentHistory.java @@ -85,19 +85,20 @@ public class LoanOfficerAssignmentHistory extends AbstractAuditableCustom repaymentPeriods, final Set loanCharges) { LocalDate startDate = disbursementDate; - for (LoanRepaymentScheduleInstallment period : repaymentPeriods) { + for (final LoanRepaymentScheduleInstallment period : repaymentPeriods) { final Money feeChargesDueForRepaymentPeriod = cumulativeFeeChargesDueWithin(startDate, period.getDueDate(), loanCharges, currency); @@ -51,7 +51,7 @@ public class LoanRepaymentScheduleProcessingWrapper { Money cumulative = Money.zero(monetaryCurrency); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(periodStart, periodEnd) && loanCharge.isFeeCharge()) { cumulative = cumulative.plus(loanCharge.amount()); } @@ -65,7 +65,7 @@ public class LoanRepaymentScheduleProcessingWrapper { Money cumulative = Money.zero(currency); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(periodStart, periodEnd) && loanCharge.isFeeCharge()) { cumulative = cumulative.plus(loanCharge.getAmountWaived(currency)); } @@ -79,7 +79,7 @@ public class LoanRepaymentScheduleProcessingWrapper { Money cumulative = Money.zero(currency); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(periodStart, periodEnd) && loanCharge.isFeeCharge()) { cumulative = cumulative.plus(loanCharge.getAmountWrittenOff(currency)); } @@ -93,7 +93,7 @@ public class LoanRepaymentScheduleProcessingWrapper { Money cumulative = Money.zero(currency); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(periodStart, periodEnd) && loanCharge.isPenaltyCharge()) { cumulative = cumulative.plus(loanCharge.amount()); } @@ -107,7 +107,7 @@ public class LoanRepaymentScheduleProcessingWrapper { Money cumulative = Money.zero(currency); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(periodStart, periodEnd) && loanCharge.isPenaltyCharge()) { cumulative = cumulative.plus(loanCharge.getAmountWaived(currency)); } @@ -121,7 +121,7 @@ public class LoanRepaymentScheduleProcessingWrapper { Money cumulative = Money.zero(currency); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(periodStart, periodEnd) && loanCharge.isPenaltyCharge()) { cumulative = cumulative.plus(loanCharge.getAmountWrittenOff(currency)); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanRepository.java index 66fc8c2a6..2a4bbb727 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanRepository.java @@ -91,7 +91,7 @@ public interface LoanRepository extends JpaRepository, JpaSpecificat @Query("from Loan loan where loan.client.id = :clientId and loan.group.id = :groupId") List findByClientIdAndGroupId(@Param("clientId") Long clientId, @Param("groupId") Long groupId); - + @Query("from Loan loan where loan.client.id = :clientId") List findLoanByClientId(@Param("clientId") Long clientId); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanStatus.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanStatus.java index 74c852e91..8906bf8b7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanStatus.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanStatus.java @@ -81,7 +81,7 @@ public enum LoanStatus { } public String getCode() { - return code; + return this.code; } public boolean isSubmittedAndPendingApproval() { @@ -121,7 +121,7 @@ public enum LoanStatus { } public boolean isActiveOrAwaitingApprovalOrDisbursal() { - return this.isApproved() || this.isSubmittedAndPendingApproval() || this.isActive(); + return isApproved() || isSubmittedAndPendingApproval() || isActive(); } public boolean isTransferInProgress() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanSummary.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanSummary.java index 72812237c..8fe9f03dd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanSummary.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanSummary.java @@ -137,32 +137,26 @@ public final class LoanSummary { return this.totalInterestCharged; } - public BigDecimal getTotalPrincipalOutstanding() { return this.totalPrincipalOutstanding; } - public BigDecimal getTotalInterestOutstanding() { return this.totalInterestOutstanding; } - public BigDecimal getTotalFeeChargesOutstanding() { return this.totalFeeChargesOutstanding; } - public BigDecimal getTotalPenaltyChargesOutstanding() { return this.totalPenaltyChargesOutstanding; } - - + public BigDecimal getTotalOutstanding() { return this.totalOutstanding; } - /** * All fields but totalFeeChargesDueAtDisbursement should be * reset. diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanSummaryWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanSummaryWrapper.java index 07ca49181..30f3ae19c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanSummaryWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanSummaryWrapper.java @@ -22,7 +22,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalPrincipalRepaid(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getPrincipalCompleted(currency)); } return total; @@ -31,7 +31,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalPrincipalWrittenOff(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getPrincipalWrittenOff(currency)); } return total; @@ -40,7 +40,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalPrincipalOverdueOn(final List repaymentScheduleInstallments, final MonetaryCurrency currency, final LocalDate overdueAsOf) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { if (installment.isOverdueOn(overdueAsOf)) { total = total.plus(installment.getPrincipalOutstanding(currency)); } @@ -51,7 +51,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalInterestCharged(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getInterestCharged(currency)); } return total; @@ -60,7 +60,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalInterestRepaid(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getInterestPaid(currency)); } return total; @@ -69,7 +69,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalInterestWaived(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getInterestWaived(currency)); } return total; @@ -78,7 +78,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalInterestWrittenOff(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getInterestWrittenOff(currency)); } return total; @@ -87,7 +87,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalInterestOverdueOn(final List repaymentScheduleInstallments, final MonetaryCurrency currency, final LocalDate overdueAsOf) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { if (installment.isOverdueOn(overdueAsOf)) { total = total.plus(installment.getInterestOutstanding(currency)); } @@ -98,7 +98,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalFeeChargesCharged(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getFeeChargesCharged(currency)); } return total; @@ -107,7 +107,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalFeeChargesRepaid(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getFeeChargesPaid(currency)); } return total; @@ -116,7 +116,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalFeeChargesWaived(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getFeeChargesWaived(currency)); } return total; @@ -125,7 +125,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalFeeChargesWrittenOff(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getFeeChargesWrittenOff(currency)); } return total; @@ -134,7 +134,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalFeeChargesOverdueOn(final List repaymentScheduleInstallments, final MonetaryCurrency currency, final LocalDate overdueAsOf) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { if (installment.isOverdueOn(overdueAsOf)) { total = total.plus(installment.getFeeChargesOutstanding(currency)); } @@ -145,7 +145,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalPenaltyChargesCharged(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getPenaltyChargesCharged(currency)); } return total; @@ -154,7 +154,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalPenaltyChargesRepaid(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getPenaltyChargesPaid(currency)); } return total; @@ -163,7 +163,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalPenaltyChargesWaived(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getPenaltyChargesWaived(currency)); } return total; @@ -172,7 +172,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalPenaltyChargesWrittenOff(final List repaymentScheduleInstallments, final MonetaryCurrency currency) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { total = total.plus(installment.getPenaltyChargesWrittenOff(currency)); } return total; @@ -181,7 +181,7 @@ public final class LoanSummaryWrapper { public Money calculateTotalPenaltyChargesOverdueOn(final List repaymentScheduleInstallments, final MonetaryCurrency currency, final LocalDate overdueAsOf) { Money total = Money.zero(currency); - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { if (installment.isOverdueOn(overdueAsOf)) { total = total.plus(installment.getPenaltyChargesOutstanding(currency)); } @@ -206,7 +206,7 @@ public final class LoanSummaryWrapper { LocalDate overdueSince = null; final Money totalOverdue = calculateTotalOverdueOn(repaymentScheduleInstallments, currency, from); if (totalOverdue.isGreaterThanZero()) { - for (LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { + for (final LoanRepaymentScheduleInstallment installment : repaymentScheduleInstallments) { if (installment.isOverdueOn(from)) { if (overdueSince == null || overdueSince.isAfter(installment.getDueDate())) { overdueSince = installment.getDueDate(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransaction.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransaction.java index 61109ad42..212c5de8c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransaction.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransaction.java @@ -108,11 +108,10 @@ public final class LoanTransaction extends AbstractPersistable { final LocalDate paymentDate, final String externalId) { return new LoanTransaction(null, office, LoanTransactionType.REPAYMENT, paymentDetail, amount.getAmount(), paymentDate, externalId); } - - public static LoanTransaction loanPayment(final Loan loan ,final Office office, final Money amount, final PaymentDetail paymentDetail, - final LocalDate paymentDate, final String externalId,final LoanTransactionType transactionType){ - return new LoanTransaction(loan, office, transactionType, paymentDetail, amount.getAmount(), paymentDate, - externalId); + + public static LoanTransaction loanPayment(final Loan loan, final Office office, final Money amount, final PaymentDetail paymentDetail, + final LocalDate paymentDate, final String externalId, final LoanTransactionType transactionType) { + return new LoanTransaction(loan, office, transactionType, paymentDetail, amount.getAmount(), paymentDate, externalId); } public static LoanTransaction repaymentAtDisbursement(final Office office, final Money amount, final PaymentDetail paymentDetail, @@ -156,7 +155,7 @@ public final class LoanTransaction extends AbstractPersistable { return new LoanTransaction(null, office, LoanTransactionType.REFUND, paymentDetail, amount.getAmount(), paymentDate, externalId); } - public static LoanTransaction copyTransactionProperties(LoanTransaction loanTransaction) { + public static LoanTransaction copyTransactionProperties(final LoanTransaction loanTransaction) { return new LoanTransaction(loanTransaction.loan, loanTransaction.office, loanTransaction.typeOf, loanTransaction.dateOf, loanTransaction.amount, loanTransaction.principalPortion, loanTransaction.interestPortion, loanTransaction.feeChargesPortion, loanTransaction.penaltyChargesPortion, loanTransaction.reversed, @@ -165,14 +164,14 @@ public final class LoanTransaction extends AbstractPersistable { public static LoanTransaction applyLoanCharge(final Loan loan, final Office office, final Money amount, final LocalDate applyDate, final Money feeCharges, final Money penaltyCharges) { - LoanTransaction applyCharge = new LoanTransaction(loan, office, LoanTransactionType.APPLY_CHARGES, amount.getAmount(), applyDate, - null); + final LoanTransaction applyCharge = new LoanTransaction(loan, office, LoanTransactionType.APPLY_CHARGES, amount.getAmount(), + applyDate, null); applyCharge.updateChargesComponents(feeCharges, penaltyCharges); return applyCharge; } - public static boolean transactionAmountsMatch(MonetaryCurrency currency, LoanTransaction loanTransaction, - LoanTransaction newLoanTransaction) { + public static boolean transactionAmountsMatch(final MonetaryCurrency currency, final LoanTransaction loanTransaction, + final LoanTransaction newLoanTransaction) { if (loanTransaction.getAmount(currency).isEqualTo(newLoanTransaction.getAmount(currency)) && (loanTransaction.getPrincipalPortion(currency).isEqualTo(newLoanTransaction.getPrincipalPortion(currency))) && (loanTransaction.getInterestPortion(currency).isEqualTo(newLoanTransaction.getInterestPortion(currency))) @@ -181,9 +180,9 @@ public final class LoanTransaction extends AbstractPersistable { return false; } - private LoanTransaction(Loan loan, Office office, Integer typeOf, Date dateOf, BigDecimal amount, BigDecimal principalPortion, - BigDecimal interestPortion, BigDecimal feeChargesPortion, BigDecimal penaltyChargesPortion, boolean reversed, - PaymentDetail paymentDetail) { + private LoanTransaction(final Loan loan, final Office office, final Integer typeOf, final Date dateOf, final BigDecimal amount, + final BigDecimal principalPortion, final BigDecimal interestPortion, final BigDecimal feeChargesPortion, + final BigDecimal penaltyChargesPortion, final boolean reversed, final PaymentDetail paymentDetail) { super(); this.loan = loan; this.typeOf = typeOf; @@ -200,7 +199,8 @@ public final class LoanTransaction extends AbstractPersistable { public static LoanTransaction waiveLoanCharge(final Loan loan, final Office office, final Money waived, final LocalDate waiveDate, final Money feeChargesWaived, final Money penaltyChargesWaived) { - LoanTransaction waiver = new LoanTransaction(loan, office, LoanTransactionType.WAIVE_CHARGES, waived.getAmount(), waiveDate, null); + final LoanTransaction waiver = new LoanTransaction(loan, office, LoanTransactionType.WAIVE_CHARGES, waived.getAmount(), waiveDate, + null); waiver.updateChargesComponents(feeChargesWaived, penaltyChargesWaived); return waiver; @@ -303,7 +303,7 @@ public final class LoanTransaction extends AbstractPersistable { } public Date getDateOf() { - return dateOf; + return this.dateOf; } public LoanTransactionType getTypeOf() { @@ -361,15 +361,15 @@ public final class LoanTransaction extends AbstractPersistable { public boolean isNotWaiver() { return !isInterestWaiver() && !isChargesWaiver(); } - - public boolean isChargePayment(){ + + public boolean isChargePayment() { return getTypeOf().isChargePayment() && isNotReversed(); } - - public boolean isPenaltyPayment(){ + + public boolean isPenaltyPayment() { boolean isPenalty = false; - if(isChargePayment()){ - for(LoanChargePaidBy chargePaidBy:this.loanChargesPaid){ + if (isChargePayment()) { + for (final LoanChargePaidBy chargePaidBy : this.loanChargesPaid) { isPenalty = chargePaidBy.getLoanCharge().isPenaltyCharge(); break; } @@ -382,7 +382,7 @@ public final class LoanTransaction extends AbstractPersistable { } public boolean isIdentifiedBy(final Long identifier) { - return this.getId().equals(identifier); + return getId().equals(identifier); } public boolean isBelongingToLoanOf(final Loan check) { @@ -417,13 +417,13 @@ public final class LoanTransaction extends AbstractPersistable { return result; } - public LoanTransactionData toData(final CurrencyData currencyData,final AccountTransferData transfer) { + public LoanTransactionData toData(final CurrencyData currencyData, final AccountTransferData transfer) { final LoanTransactionEnumData transactionType = LoanEnumerations.transactionType(this.typeOf); PaymentDetailData paymentDetailData = null; if (this.paymentDetail != null) { - paymentDetailData = paymentDetail.toData(); + paymentDetailData = this.paymentDetail.toData(); } - return new LoanTransactionData(this.getId(), this.office.getId(), this.office.getName(), transactionType, paymentDetailData, + return new LoanTransactionData(getId(), this.office.getId(), this.office.getName(), transactionType, paymentDetailData, currencyData, getTransactionDate(), this.amount, this.principalPortion, this.interestPortion, this.feeChargesPortion, this.penaltyChargesPortion, this.externalId, transfer); } @@ -433,11 +433,11 @@ public final class LoanTransaction extends AbstractPersistable { final LoanTransactionEnumData transactionType = LoanEnumerations.transactionType(this.typeOf); - thisTransactionData.put("id", this.getId()); + thisTransactionData.put("id", getId()); thisTransactionData.put("officeId", this.office.getId()); thisTransactionData.put("type", transactionType); - thisTransactionData.put("reversed", Boolean.valueOf(this.isReversed())); - thisTransactionData.put("date", this.getTransactionDate()); + thisTransactionData.put("reversed", Boolean.valueOf(isReversed())); + thisTransactionData.put("date", getTransactionDate()); thisTransactionData.put("currency", currencyData); thisTransactionData.put("amount", this.amount); thisTransactionData.put("principalPortion", this.principalPortion); @@ -451,7 +451,7 @@ public final class LoanTransaction extends AbstractPersistable { if (!this.loanChargesPaid.isEmpty()) { final List> loanChargesPaidData = new ArrayList>(); - for (LoanChargePaidBy chargePaidBy : this.loanChargesPaid) { + for (final LoanChargePaidBy chargePaidBy : this.loanChargesPaid) { final Map loanChargePaidData = new LinkedHashMap(); loanChargePaidData.put("chargeId", chargePaidBy.getLoanCharge().getCharge().getId()); loanChargePaidData.put("isPenalty", chargePaidBy.getLoanCharge().getCharge().isPenalty()); @@ -474,12 +474,12 @@ public final class LoanTransaction extends AbstractPersistable { return this.loanChargesPaid; } - public void setLoanChargesPaid(Set loanChargesPaid) { + public void setLoanChargesPaid(final Set loanChargesPaid) { this.loanChargesPaid = loanChargesPaid; } public String getExternalId() { - return externalId; + return this.externalId; } public boolean isRefund() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionProcessingStrategyRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionProcessingStrategyRepository.java index ee51f616c..4d859af2e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionProcessingStrategyRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionProcessingStrategyRepository.java @@ -10,6 +10,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface LoanTransactionProcessingStrategyRepository extends JpaRepository, - JpaSpecificationExecutor { - // no added behaviour + JpaSpecificationExecutor { + // no added behaviour } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionRepository.java index 8220ac67b..8a8b8d415 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionRepository.java @@ -8,7 +8,6 @@ package org.mifosplatform.portfolio.loanaccount.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface LoanTransactionRepository extends JpaRepository, - JpaSpecificationExecutor { - // no added behaviour +public interface LoanTransactionRepository extends JpaRepository, JpaSpecificationExecutor { + // no added behaviour } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionType.java index 9ef8421d3..f85a56e9c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/LoanTransactionType.java @@ -33,9 +33,8 @@ public enum LoanTransactionType { APPROVE_TRANSFER(13, "loanTransactionType.approveTransfer"), // WITHDRAW_TRANSFER(14, "loanTransactionType.withdrawTransfer"), // REJECT_TRANSFER(15, "loanTransactionType.rejectTransfer"), - - REFUND(16,"loanTransactionType.refund"), - CHARGE_PAYMENT(17,"loanTransactionType.chargePayment"); + + REFUND(16, "loanTransactionType.refund"), CHARGE_PAYMENT(17, "loanTransactionType.chargePayment"); private final Integer value; private final String code; @@ -50,7 +49,7 @@ public enum LoanTransactionType { } public String getCode() { - return code; + return this.code; } public static LoanTransactionType fromInt(final Integer transactionType) { @@ -109,7 +108,7 @@ public enum LoanTransactionType { break; case 17: loanTransactionType = LoanTransactionType.CHARGE_PAYMENT; - break; + break; default: loanTransactionType = LoanTransactionType.INVALID; break; @@ -148,8 +147,8 @@ public enum LoanTransactionType { public boolean isWriteOff() { return this.value.equals(LoanTransactionType.WRITEOFF.getValue()); } - - public boolean isChargePayment(){ + + public boolean isChargePayment() { return this.value.equals(LoanTransactionType.CHARGE_PAYMENT.getValue()); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/TransactionProccessingResult.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/TransactionProccessingResult.java index 03c3ed6bd..02d017c9e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/TransactionProccessingResult.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/TransactionProccessingResult.java @@ -9,19 +9,19 @@ import org.mifosplatform.organisation.monetary.domain.Money; public class TransactionProccessingResult { - private final Money overPaymentAmount; - private final boolean overPayment; + private final Money overPaymentAmount; + private final boolean overPayment; - public TransactionProccessingResult(final Money overPaymentAmount, final boolean overPayment) { - this.overPaymentAmount = overPaymentAmount; - this.overPayment = overPayment; - } + public TransactionProccessingResult(final Money overPaymentAmount, final boolean overPayment) { + this.overPaymentAmount = overPaymentAmount; + this.overPayment = overPayment; + } - public Money getOverPaymentAmount() { - return overPaymentAmount; - } + public Money getOverPaymentAmount() { + return this.overPaymentAmount; + } - public boolean isOverPayment() { - return overPayment; - } + public boolean isOverPayment() { + return this.overPayment; + } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/AbstractLoanRepaymentScheduleTransactionProcessor.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/AbstractLoanRepaymentScheduleTransactionProcessor.java index add759921..404e3d290 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/AbstractLoanRepaymentScheduleTransactionProcessor.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/AbstractLoanRepaymentScheduleTransactionProcessor.java @@ -47,37 +47,37 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen final List installments, final Set charges) { if (charges != null) { - for (LoanCharge loanCharge : charges) { + for (final LoanCharge loanCharge : charges) { if (!loanCharge.isDueAtDisbursement()) { loanCharge.resetPaidAmount(currency); } } } - for (LoanRepaymentScheduleInstallment currentInstallment : installments) { + for (final LoanRepaymentScheduleInstallment currentInstallment : installments) { currentInstallment.resetDerivedComponents(); currentInstallment.updateDerivedFields(currency, disbursementDate); } // re-process loan charges over repayment periods (picking up on waived // loan charges) - LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper(); + final LoanRepaymentScheduleProcessingWrapper wrapper = new LoanRepaymentScheduleProcessingWrapper(); wrapper.reprocess(currency, disbursementDate, installments, charges); - ChangedTransactionDetail changedTransactionDetail = new ChangedTransactionDetail(); - List transactionstoBeProcessed = new ArrayList(); - for (LoanTransaction loanTransaction : transactionsPostDisbursement) { - if (loanTransaction.isChargePayment()){ - Set chargePaidBies =loanTransaction.getLoanChargesPaid(); - Set transferCharges = new HashSet(); - for(LoanChargePaidBy chargePaidBy: chargePaidBies){ + final ChangedTransactionDetail changedTransactionDetail = new ChangedTransactionDetail(); + final List transactionstoBeProcessed = new ArrayList(); + for (final LoanTransaction loanTransaction : transactionsPostDisbursement) { + if (loanTransaction.isChargePayment()) { + final Set chargePaidBies = loanTransaction.getLoanChargesPaid(); + final Set transferCharges = new HashSet(); + for (final LoanChargePaidBy chargePaidBy : chargePaidBies) { transferCharges.add(chargePaidBy.getLoanCharge()); } - List chargePaymentInstallments = new ArrayList(); + final List chargePaymentInstallments = new ArrayList(); LocalDate startDate = disbursementDate; - for(LoanRepaymentScheduleInstallment installment:installments){ - for(LoanCharge loanCharge :transferCharges){ - if(loanCharge.isDueForCollectionFromAndUpToAndIncluding(startDate, installment.getDueDate())){ + for (final LoanRepaymentScheduleInstallment installment : installments) { + for (final LoanCharge loanCharge : transferCharges) { + if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(startDate, installment.getDueDate())) { chargePaymentInstallments.add(installment); break; } @@ -86,12 +86,12 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen } loanTransaction.resetDerivedComponents(); handleTransaction(loanTransaction, currency, chargePaymentInstallments, transferCharges); - }else{ + } else { transactionstoBeProcessed.add(loanTransaction); } } - - for (LoanTransaction loanTransaction : transactionstoBeProcessed) { + + for (final LoanTransaction loanTransaction : transactionstoBeProcessed) { if (loanTransaction.isRepayment() || loanTransaction.isInterestWaiver()) { // pass through for new transactions @@ -104,7 +104,7 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen * breakup (principal, interest, fees, penalties) has * changed.
**/ - LoanTransaction newLoanTransaction = LoanTransaction.copyTransactionProperties(loanTransaction); + final LoanTransaction newLoanTransaction = LoanTransaction.copyTransactionProperties(loanTransaction); // Reset derived component of new loan transaction and // re-process transaction @@ -146,7 +146,7 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen final LocalDate transactionDate = loanTransaction.getTransactionDate(); Money transactionAmountUnprocessed = loanTransaction.getAmount(currency); - for (LoanRepaymentScheduleInstallment currentInstallment : installments) { + for (final LoanRepaymentScheduleInstallment currentInstallment : installments) { if (currentInstallment.isNotFullyPaidOff()) { @@ -170,16 +170,16 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen installmentIndex++; } - Set loanFees = extractFeeCharges(charges); - Set loanPenalties = extractPenaltyCharges(charges); + final Set loanFees = extractFeeCharges(charges); + final Set loanPenalties = extractPenaltyCharges(charges); if (loanTransaction.isNotWaiver()) { - Money feeCharges = loanTransaction.getFeeChargesPortion(currency); + final Money feeCharges = loanTransaction.getFeeChargesPortion(currency); if (feeCharges.isGreaterThanZero()) { updateFeeChargesPaidAmountBy(loanTransaction, feeCharges, loanFees); } - Money penaltyCharges = loanTransaction.getPenaltyChargesPortion(currency); + final Money penaltyCharges = loanTransaction.getPenaltyChargesPortion(currency); if (penaltyCharges.isGreaterThanZero()) { updatePenaltyChargesPaidAmountBy(loanTransaction, penaltyCharges, loanPenalties); } @@ -190,9 +190,9 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen } } - private Set extractFeeCharges(Set loanCharges) { + private Set extractFeeCharges(final Set loanCharges) { final Set feeCharges = new HashSet(); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isFeeCharge()) { feeCharges.add(loanCharge); } @@ -200,9 +200,9 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen return feeCharges; } - private Set extractPenaltyCharges(Set loanCharges) { + private Set extractPenaltyCharges(final Set loanCharges) { final Set penaltyCharges = new HashSet(); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isPenaltyCharge()) { penaltyCharges.add(loanCharge); } @@ -213,14 +213,14 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen private void updateFeeChargesPaidAmountBy(final LoanTransaction loanTransaction, final Money feeCharges, final Set charges) { Money amountRemaining = feeCharges; - for (LoanCharge loanCharge : charges) { + for (final LoanCharge loanCharge : charges) { if (!loanCharge.isDueAtDisbursement()) { if (loanCharge.isFeeCharge() && loanCharge.isNotFullyPaid() && amountRemaining.isGreaterThanZero()) { final LoanCharge unpaidCharge = findEarliestUnpaidChargeFromUnOrderedSet(charges); - Money amountPaidTowardsCharge = unpaidCharge.updatePaidAmountBy(amountRemaining); + final Money amountPaidTowardsCharge = unpaidCharge.updatePaidAmountBy(amountRemaining); if (!amountPaidTowardsCharge.isZero()) { - if(!loanTransaction.isChargePayment()){ - LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(loanTransaction, loanCharge, + if (!loanTransaction.isChargePayment()) { + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(loanTransaction, loanCharge, amountPaidTowardsCharge.getAmount()); loanTransaction.getLoanChargesPaid().add(loanChargePaidBy); } @@ -235,15 +235,15 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen final Set charges) { Money amountRemaining = feeCharges; - for (LoanCharge loanCharge : charges) { + for (final LoanCharge loanCharge : charges) { if (!loanCharge.isDueAtDisbursement()) { if (loanCharge.isPenaltyCharge() && loanCharge.isNotFullyPaid() && amountRemaining.isGreaterThanZero()) { final LoanCharge unpaidCharge = findEarliestUnpaidChargeFromUnOrderedSet(charges); - Money amountPaidTowardsCharge = unpaidCharge.updatePaidAmountBy(amountRemaining); + final Money amountPaidTowardsCharge = unpaidCharge.updatePaidAmountBy(amountRemaining); if (!amountPaidTowardsCharge.isZero()) { - if(!loanTransaction.isChargePayment()){ - LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(loanTransaction, loanCharge, + if (!loanTransaction.isChargePayment()) { + final LoanChargePaidBy loanChargePaidBy = new LoanChargePaidBy(loanTransaction, loanCharge, amountPaidTowardsCharge.getAmount()); loanTransaction.getLoanChargesPaid().add(loanChargePaidBy); } @@ -257,7 +257,7 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen private LoanCharge findEarliestUnpaidChargeFromUnOrderedSet(final Set charges) { LoanCharge earliestUnpaidCharge = null; - for (LoanCharge loanCharge : charges) { + for (final LoanCharge loanCharge : charges) { if (loanCharge.isNotFullyPaid() && !loanCharge.isDueAtDisbursement()) { if (earliestUnpaidCharge == null || loanCharge.getDueLocalDate().isBefore(earliestUnpaidCharge.getDueLocalDate())) { earliestUnpaidCharge = loanCharge; @@ -272,7 +272,7 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen public void handleWriteOff(final LoanTransaction loanTransaction, final MonetaryCurrency currency, final List installments) { - LocalDate transactionDate = loanTransaction.getTransactionDate(); + final LocalDate transactionDate = loanTransaction.getTransactionDate(); Money principalPortion = Money.zero(currency); Money interestPortion = Money.zero(currency); Money feeChargesPortion = Money.zero(currency); @@ -280,7 +280,7 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen // determine how much is written off in total and breakdown for // principal, interest and charges - for (LoanRepaymentScheduleInstallment currentInstallment : installments) { + for (final LoanRepaymentScheduleInstallment currentInstallment : installments) { if (currentInstallment.isNotFullyPaidOff()) { principalPortion = principalPortion.plus(currentInstallment.writeOffOutstandingPrincipal(transactionDate, currency)); @@ -305,7 +305,7 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen protected boolean isTransactionALateRepaymentOnInstallment(final int installmentIndex, final List installments, final LocalDate transactionDate) { - LoanRepaymentScheduleInstallment currentInstallment = installments.get(installmentIndex); + final LoanRepaymentScheduleInstallment currentInstallment = installments.get(installmentIndex); return transactionDate.isAfter(currentInstallment.getDueDate()); } @@ -328,7 +328,7 @@ public abstract class AbstractLoanRepaymentScheduleTransactionProcessor implemen final List installments, final LocalDate transactionDate, @SuppressWarnings("unused") final Money transactionAmount) { - LoanRepaymentScheduleInstallment currentInstallment = installments.get(currentInstallmentIndex); + final LoanRepaymentScheduleInstallment currentInstallment = installments.get(currentInstallmentIndex); return transactionDate.isBefore(currentInstallment.getDueDate()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/LoanRepaymentScheduleTransactionProcessor.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/LoanRepaymentScheduleTransactionProcessor.java index b8f6a12ac..5b85ef517 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/LoanRepaymentScheduleTransactionProcessor.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/LoanRepaymentScheduleTransactionProcessor.java @@ -20,8 +20,8 @@ public interface LoanRepaymentScheduleTransactionProcessor { void handleTransaction(LoanTransaction loanTransaction, MonetaryCurrency currency, List installments, Set charges); - ChangedTransactionDetail handleTransaction(LocalDate disbursementDate, List repaymentsOrWaivers, MonetaryCurrency currency, - List repaymentScheduleInstallments, Set charges); + ChangedTransactionDetail handleTransaction(LocalDate disbursementDate, List repaymentsOrWaivers, + MonetaryCurrency currency, List repaymentScheduleInstallments, Set charges); void handleWriteOff(LoanTransaction loanTransaction, MonetaryCurrency loanCurrency, List repaymentScheduleInstallments); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/CreocoreLoanRepaymentScheduleTransactionProcessor.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/CreocoreLoanRepaymentScheduleTransactionProcessor.java index d94d91f29..d087de705 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/CreocoreLoanRepaymentScheduleTransactionProcessor.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/CreocoreLoanRepaymentScheduleTransactionProcessor.java @@ -39,7 +39,7 @@ public class CreocoreLoanRepaymentScheduleTransactionProcessor extends AbstractL protected boolean isTransactionInAdvanceOfInstallment(final int currentInstallmentIndex, final List installments, final LocalDate transactionDate, final Money transactionAmount) { - LoanRepaymentScheduleInstallment currentInstallment = installments.get(currentInstallmentIndex); + final LoanRepaymentScheduleInstallment currentInstallment = installments.get(currentInstallmentIndex); return transactionDate.isBefore(currentInstallment.getDueDate()); } @@ -97,15 +97,15 @@ public class CreocoreLoanRepaymentScheduleTransactionProcessor extends AbstractL } else if (loanTransaction.isInterestWaiver()) { interestPortion = currentInstallment.waiveInterestComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(interestPortion); - } else if(loanTransaction.isChargePayment()){ - if(loanTransaction.isPenaltyPayment()){ + } else if (loanTransaction.isChargePayment()) { + if (loanTransaction.isPenaltyPayment()) { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - }else{ + } else { feeChargesPortion = currentInstallment.payFeeChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } - }else { + } else { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/HeavensFamilyLoanRepaymentScheduleTransactionProcessor.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/HeavensFamilyLoanRepaymentScheduleTransactionProcessor.java index b4fec4ea7..dc27b9c15 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/HeavensFamilyLoanRepaymentScheduleTransactionProcessor.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/HeavensFamilyLoanRepaymentScheduleTransactionProcessor.java @@ -55,7 +55,7 @@ public class HeavensFamilyLoanRepaymentScheduleTransactionProcessor extends Abst previousInstallmentIndex = currentInstallmentIndex - 1; } - LoanRepaymentScheduleInstallment previousInstallment = installments.get(previousInstallmentIndex); + final LoanRepaymentScheduleInstallment previousInstallment = installments.get(previousInstallmentIndex); lastInstallmentDueDate = previousInstallment.getDueDate(); isInAdvance = !(transactionDate.isAfter(lastInstallmentDueDate) || (transactionDate.isEqual(lastInstallmentDueDate))); @@ -81,15 +81,15 @@ public class HeavensFamilyLoanRepaymentScheduleTransactionProcessor extends Abst if (loanTransaction.isInterestWaiver()) { interestPortion = currentInstallment.waiveInterestComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(interestPortion); - } else if(loanTransaction.isChargePayment()){ - if(loanTransaction.isPenaltyPayment()){ + } else if (loanTransaction.isChargePayment()) { + if (loanTransaction.isPenaltyPayment()) { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - }else{ + } else { feeChargesPortion = currentInstallment.payFeeChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } - }else { + } else { if (currentInstallment.isPrincipalNotCompleted(currency)) { principalPortion = currentInstallment.payPrincipalComponent(transactionDate, transactionAmountRemaining); @@ -149,15 +149,15 @@ public class HeavensFamilyLoanRepaymentScheduleTransactionProcessor extends Abst } else if (loanTransaction.isInterestWaiver()) { interestPortion = currentInstallment.waiveInterestComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(interestPortion); - } else if(loanTransaction.isChargePayment()){ - if(loanTransaction.isPenaltyPayment()){ + } else if (loanTransaction.isChargePayment()) { + if (loanTransaction.isPenaltyPayment()) { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - }else{ + } else { feeChargesPortion = currentInstallment.payFeeChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } - }else { + } else { // 1. pay of principal before interest. principalPortion = currentInstallment.payPrincipalComponent(transactionDate, transactionAmountRemaining); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java index e64f7cbcf..47a8992bc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java @@ -71,16 +71,16 @@ public class InterestPrincipalPenaltyFeesOrderLoanRepaymentScheduleTransactionPr transactionAmountRemaining = transactionAmountRemaining.minus(interestPortion); loanTransaction.updateComponents(principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion); - } else if(loanTransaction.isChargePayment()){ - if(loanTransaction.isPenaltyPayment()){ + } else if (loanTransaction.isChargePayment()) { + if (loanTransaction.isPenaltyPayment()) { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - }else{ + } else { feeChargesPortion = currentInstallment.payFeeChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } loanTransaction.updateComponents(principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion); - }else { + } else { interestPortion = currentInstallment.payInterestComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(interestPortion); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/MifosStyleLoanRepaymentScheduleTransactionProcessor.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/MifosStyleLoanRepaymentScheduleTransactionProcessor.java index 81eb39446..9838c223a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/MifosStyleLoanRepaymentScheduleTransactionProcessor.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/MifosStyleLoanRepaymentScheduleTransactionProcessor.java @@ -33,7 +33,7 @@ public class MifosStyleLoanRepaymentScheduleTransactionProcessor extends Abstrac protected boolean isTransactionInAdvanceOfInstallment(final int currentInstallmentIndex, final List installments, final LocalDate transactionDate, final Money transactionAmount) { - LoanRepaymentScheduleInstallment currentInstallment = installments.get(currentInstallmentIndex); + final LoanRepaymentScheduleInstallment currentInstallment = installments.get(currentInstallmentIndex); return transactionDate.isBefore(currentInstallment.getDueDate()); } @@ -85,11 +85,11 @@ public class MifosStyleLoanRepaymentScheduleTransactionProcessor extends Abstrac transactionAmountRemaining = transactionAmountRemaining.minus(interestPortion); loanTransaction.updateComponents(principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion); - } else if(loanTransaction.isChargePayment()){ - if(loanTransaction.isPenaltyPayment()){ + } else if (loanTransaction.isChargePayment()) { + if (loanTransaction.isPenaltyPayment()) { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - }else{ + } else { feeChargesPortion = currentInstallment.payFeeChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java index ce492facf..89fc19aa3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionProcessor.java @@ -71,16 +71,16 @@ public class PrincipalInterestPenaltyFeesOrderLoanRepaymentScheduleTransactionPr transactionAmountRemaining = transactionAmountRemaining.minus(interestPortion); loanTransaction.updateComponents(principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion); - } else if(loanTransaction.isChargePayment()){ - if(loanTransaction.isPenaltyPayment()){ + } else if (loanTransaction.isChargePayment()) { + if (loanTransaction.isPenaltyPayment()) { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - }else{ + } else { feeChargesPortion = currentInstallment.payFeeChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } loanTransaction.updateComponents(principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion); - }else { + } else { principalPortion = currentInstallment.payPrincipalComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(principalPortion); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/RBILoanRepaymentScheduleTransactionProcessor.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/RBILoanRepaymentScheduleTransactionProcessor.java index e670743aa..f8b3a37a8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/RBILoanRepaymentScheduleTransactionProcessor.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/domain/transactionprocessor/impl/RBILoanRepaymentScheduleTransactionProcessor.java @@ -40,7 +40,7 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe protected boolean isTransactionInAdvanceOfInstallment(final int currentInstallmentIndex, final List installments, final LocalDate transactionDate, final Money transactionAmount) { - LoanRepaymentScheduleInstallment currentInstallment = installments.get(currentInstallmentIndex); + final LoanRepaymentScheduleInstallment currentInstallment = installments.get(currentInstallmentIndex); return transactionDate.isBefore(currentInstallment.getDueDate()); } @@ -80,23 +80,23 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe final Money principalPortion = Money.zero(transactionAmountRemaining.getCurrency()); loanTransaction.updateComponents(principalPortion, interestWaivedPortion, feeChargesPortion, penaltyChargesPortion); - } else if(loanTransaction.isChargePayment()){ - Money principalPortion = Money.zero(currency); - Money interestPortion = Money.zero(currency); - if(loanTransaction.isPenaltyPayment()){ + } else if (loanTransaction.isChargePayment()) { + final Money principalPortion = Money.zero(currency); + final Money interestPortion = Money.zero(currency); + if (loanTransaction.isPenaltyPayment()) { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - }else{ + } else { feeChargesPortion = currentInstallment.payFeeChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } loanTransaction.updateComponents(principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion); - }else { + } else { - LoanRepaymentScheduleInstallment currentInstallmentBasedOnTransactionDate = nearestInstallment( + final LoanRepaymentScheduleInstallment currentInstallmentBasedOnTransactionDate = nearestInstallment( loanTransaction.getTransactionDate(), installments); - for (LoanRepaymentScheduleInstallment installment : installments) { + for (final LoanRepaymentScheduleInstallment installment : installments) { if (installment.isInterestDue(currency) && (installment.isOverdueOn(loanTransaction.getTransactionDate()) || installment.getInstallmentNumber().equals( currentInstallmentBasedOnTransactionDate.getInstallmentNumber()))) { @@ -106,22 +106,22 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe feeChargesPortion = currentInstallment.payFeeChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); - Money interestPortion = installment.payInterestComponent(transactionDate, transactionAmountRemaining); + final Money interestPortion = installment.payInterestComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(interestPortion); - Money principalPortion = Money.zero(currency); + final Money principalPortion = Money.zero(currency); loanTransaction.updateComponents(principalPortion, interestPortion, Money.zero(currency), Money.zero(currency)); } } // With whatever is remaining, pay off principal components of // installments - for (LoanRepaymentScheduleInstallment installment : installments) { + for (final LoanRepaymentScheduleInstallment installment : installments) { if (installment.isPrincipalNotCompleted(currency) && transactionAmountRemaining.isGreaterThanZero()) { - Money principalPortion = installment.payPrincipalComponent(transactionDate, transactionAmountRemaining); + final Money principalPortion = installment.payPrincipalComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(principalPortion); - Money interestPortion = Money.zero(currency); + final Money interestPortion = Money.zero(currency); loanTransaction.updateComponents(principalPortion, interestPortion, Money.zero(currency), Money.zero(currency)); } } @@ -135,7 +135,7 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe LoanRepaymentScheduleInstallment nearest = installments.get(0); - for (LoanRepaymentScheduleInstallment installment : installments) { + for (final LoanRepaymentScheduleInstallment installment : installments) { if (installment.getDueDate().isAfter(transactionDate) || installment.getDueDate().isEqual(transactionDate)) { nearest = installment; break; @@ -172,15 +172,15 @@ public class RBILoanRepaymentScheduleTransactionProcessor extends AbstractLoanRe } else if (loanTransaction.isInterestWaiver()) { interestPortion = currentInstallment.waiveInterestComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(interestPortion); - } else if(loanTransaction.isChargePayment()){ - if(loanTransaction.isPenaltyPayment()){ + } else if (loanTransaction.isChargePayment()) { + if (loanTransaction.isPenaltyPayment()) { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); - }else{ + } else { feeChargesPortion = currentInstallment.payFeeChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(feeChargesPortion); } - }else { + } else { penaltyChargesPortion = currentInstallment.payPenaltyChargesComponent(transactionDate, transactionAmountRemaining); transactionAmountRemaining = transactionAmountRemaining.minus(penaltyChargesPortion); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/InvalidLoanStateTransitionException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/InvalidLoanStateTransitionException.java index 4d786ba1e..286475a53 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/InvalidLoanStateTransitionException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/InvalidLoanStateTransitionException.java @@ -8,11 +8,13 @@ package org.mifosplatform.portfolio.loanaccount.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown an action to transition a loan from one state to another violates a domain rule. + * {@link AbstractPlatformDomainRuleException} thrown an action to transition a + * loan from one state to another violates a domain rule. */ public class InvalidLoanStateTransitionException extends AbstractPlatformDomainRuleException { - public InvalidLoanStateTransitionException(final String action, String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg.loan." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); - } + public InvalidLoanStateTransitionException(final String action, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { + super("error.msg.loan." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/InvalidLoanTransactionTypeException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/InvalidLoanTransactionTypeException.java index 606ff98cc..50a351fcd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/InvalidLoanTransactionTypeException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/InvalidLoanTransactionTypeException.java @@ -8,11 +8,13 @@ package org.mifosplatform.portfolio.loanaccount.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown an action to transition a loan from one state to another violates a domain rule. + * {@link AbstractPlatformDomainRuleException} thrown an action to transition a + * loan from one state to another violates a domain rule. */ public class InvalidLoanTransactionTypeException extends AbstractPlatformDomainRuleException { - public InvalidLoanTransactionTypeException(final String action, String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg.loan." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); - } + public InvalidLoanTransactionTypeException(final String action, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { + super("error.msg.loan." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanApplicationDateException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanApplicationDateException.java index 944e32c9b..41b473b19 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanApplicationDateException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanApplicationDateException.java @@ -9,8 +9,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul public class LoanApplicationDateException extends AbstractPlatformDomainRuleException { - public LoanApplicationDateException(String postFix, String defaultUserMessage, - Object... defaultUserMessageArgs) { + public LoanApplicationDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.loan.application." + postFix, defaultUserMessage, defaultUserMessageArgs); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerAssignmentDateException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerAssignmentDateException.java index 4424cb412..abdb2ddfd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerAssignmentDateException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerAssignmentDateException.java @@ -9,8 +9,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul public class LoanOfficerAssignmentDateException extends AbstractPlatformDomainRuleException { - public LoanOfficerAssignmentDateException(String postFix, String defaultUserMessage, - Object... defaultUserMessageArgs) { + public LoanOfficerAssignmentDateException(final String postFix, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg.loan.assignment.date." + postFix, defaultUserMessage, defaultUserMessageArgs); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerUnassignmentDateException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerUnassignmentDateException.java index fe7bc1cc2..23ba880e0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerUnassignmentDateException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerUnassignmentDateException.java @@ -9,8 +9,8 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul public class LoanOfficerUnassignmentDateException extends AbstractPlatformDomainRuleException { - public LoanOfficerUnassignmentDateException(String postFix, String defaultUserMessage, - Object... defaultUserMessageArgs) { + public LoanOfficerUnassignmentDateException(final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg.loan.loanofficer.unassign.date." + postFix, defaultUserMessage, defaultUserMessageArgs); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerUnassignmentException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerUnassignmentException.java index 3030ffad0..607049715 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerUnassignmentException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanOfficerUnassignmentException.java @@ -10,7 +10,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul public class LoanOfficerUnassignmentException extends AbstractPlatformDomainRuleException { public LoanOfficerUnassignmentException(final Long loanId) { - super("error.msg.loan.not.assigned.to.loan.officer", "Loan with identifier " + loanId - + " is not assigned to any loan officer.", loanId); + super("error.msg.loan.not.assigned.to.loan.officer", "Loan with identifier " + loanId + " is not assigned to any loan officer.", + loanId); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTemplateTypeRequiredException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTemplateTypeRequiredException.java index 2456018fa..74d45b88d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTemplateTypeRequiredException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTemplateTypeRequiredException.java @@ -8,11 +8,12 @@ package org.mifosplatform.portfolio.loanaccount.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown when not supported loan template type is sent. + * {@link AbstractPlatformDomainRuleException} thrown when not supported loan + * template type is sent. */ public class LoanTemplateTypeRequiredException extends AbstractPlatformDomainRuleException { - public LoanTemplateTypeRequiredException(String defaultUserMessage) { - super("error.msg.loan.template.type.required", defaultUserMessage); - } + public LoanTemplateTypeRequiredException(final String defaultUserMessage) { + super("error.msg.loan.template.type.required", defaultUserMessage); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTransactionNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTransactionNotFoundException.java index 917597f34..d0fe5758b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTransactionNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTransactionNotFoundException.java @@ -12,11 +12,12 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN */ public class LoanTransactionNotFoundException extends AbstractPlatformResourceNotFoundException { - public LoanTransactionNotFoundException(Long id) { - super("error.msg.loan.id.invalid", "Transaction with identifier " + id + " does not exist", id); - } + public LoanTransactionNotFoundException(final Long id) { + super("error.msg.loan.id.invalid", "Transaction with identifier " + id + " does not exist", id); + } - public LoanTransactionNotFoundException(Long id, Long loanId) { - super("error.msg.loan.id.invalid", "Transaction with identifier " + id + " does not exist for loan with identifier " + loanId + "." , id, loanId); - } + public LoanTransactionNotFoundException(final Long id, final Long loanId) { + super("error.msg.loan.id.invalid", + "Transaction with identifier " + id + " does not exist for loan with identifier " + loanId + ".", id, loanId); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTransactionProcessingStrategyNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTransactionProcessingStrategyNotFoundException.java index d34f69096..8e526be09 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTransactionProcessingStrategyNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/LoanTransactionProcessingStrategyNotFoundException.java @@ -8,11 +8,13 @@ package org.mifosplatform.portfolio.loanaccount.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when loan transactions processing strategy resources are not found. + * A {@link RuntimeException} thrown when loan transactions processing strategy + * resources are not found. */ public class LoanTransactionProcessingStrategyNotFoundException extends AbstractPlatformResourceNotFoundException { - public LoanTransactionProcessingStrategyNotFoundException(final Long id) { - super("error.msg.transactions.processing.strategy.id.invalid", "Loan transaction processing strategy with identifier " + id + " does not exist", id); - } + public LoanTransactionProcessingStrategyNotFoundException(final Long id) { + super("error.msg.transactions.processing.strategy.id.invalid", "Loan transaction processing strategy with identifier " + id + + " does not exist", id); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/NotSupportedLoanTemplateTypeException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/NotSupportedLoanTemplateTypeException.java index 70ebd3966..aca4ec121 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/NotSupportedLoanTemplateTypeException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/exception/NotSupportedLoanTemplateTypeException.java @@ -8,11 +8,12 @@ package org.mifosplatform.portfolio.loanaccount.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown when not supported loan template type is sent. + * {@link AbstractPlatformDomainRuleException} thrown when not supported loan + * template type is sent. */ public class NotSupportedLoanTemplateTypeException extends AbstractPlatformDomainRuleException { - public NotSupportedLoanTemplateTypeException(String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg.loan.template.type.not.supported", defaultUserMessage, defaultUserMessageArgs); - } + public NotSupportedLoanTemplateTypeException(final String defaultUserMessage, final Object... defaultUserMessageArgs) { + super("error.msg.loan.template.type.not.supported", defaultUserMessage, defaultUserMessageArgs); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/GuarantorConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/GuarantorConstants.java index 993768a41..93588397d 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/GuarantorConstants.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/GuarantorConstants.java @@ -29,7 +29,7 @@ public class GuarantorConstants { private static final Set values = new HashSet(); static { - for (GUARANTOR_JSON_INPUT_PARAMS type : GUARANTOR_JSON_INPUT_PARAMS.values()) { + for (final GUARANTOR_JSON_INPUT_PARAMS type : GUARANTOR_JSON_INPUT_PARAMS.values()) { values.add(type.value); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/api/GuarantorsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/api/GuarantorsApiResource.java index b54f217e9..b99cc90dd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/api/GuarantorsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/api/GuarantorsApiResource.java @@ -80,14 +80,14 @@ public class GuarantorsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String newGuarantorTemplate(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); final List guarantorTypeOptions = GuarantorEnumerations.guarantorType(GuarantorType.values()); final Collection allowedClientRelationshipTypes = this.codeValueReadPlatformService .retrieveCodeValuesByCode(GuarantorConstants.GUARANTOR_RELATIONSHIP_CODE_NAME); - GuarantorData guarantorData = GuarantorData.template(guarantorTypeOptions, allowedClientRelationshipTypes); + final GuarantorData guarantorData = GuarantorData.template(guarantorTypeOptions, allowedClientRelationshipTypes); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.apiJsonSerializerService.serialize(settings, guarantorData, RESPONSE_DATA_PARAMETERS); } @@ -95,11 +95,11 @@ public class GuarantorsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String retrieveGuarantorDetails(@Context final UriInfo uriInfo, @PathParam("loanId") final Long loanId) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); - List guarantorDatas = guarantorReadPlatformService.retrieveGuarantorsForValidLoan(loanId); + final List guarantorDatas = this.guarantorReadPlatformService.retrieveGuarantorsForValidLoan(loanId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.apiJsonSerializerService.serialize(settings, guarantorDatas, RESPONSE_DATA_PARAMETERS); } @@ -110,11 +110,11 @@ public class GuarantorsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveGuarantorDetails(@Context final UriInfo uriInfo, @PathParam("loanId") final Long loanId, @PathParam("guarantorId") final Long guarantorId) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermission); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermission); - GuarantorData guarantorData = guarantorReadPlatformService.retrieveGuarantor(loanId, guarantorId); + GuarantorData guarantorData = this.guarantorReadPlatformService.retrieveGuarantor(loanId, guarantorId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (settings.isTemplate()) { final Collection allowedClientRelationshipTypes = this.codeValueReadPlatformService .retrieveCodeValuesByCode(GuarantorConstants.GUARANTOR_RELATIONSHIP_CODE_NAME); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/command/GuarantorCommand.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/command/GuarantorCommand.java index 12b4b108e..1a5f86f89 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/command/GuarantorCommand.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/command/GuarantorCommand.java @@ -69,7 +69,7 @@ public class GuarantorCommand { } public boolean isExternalGuarantor() { - return GuarantorType.EXTERNAL.getValue().equals(guarantorTypeId); + return GuarantorType.EXTERNAL.getValue().equals(this.guarantorTypeId); } public Date getDobAsDate() { @@ -78,9 +78,9 @@ public class GuarantorCommand { public void validateForCreate() { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = getDataValidator(dataValidationErrors); + final DataValidatorBuilder baseDataValidator = getDataValidator(dataValidationErrors); baseDataValidator.reset().parameter(GUARANTOR_JSON_INPUT_PARAMS.CLIENT_RELATIONSHIP_TYPE_ID.getValue()) .value(this.clientRelationshipTypeId).ignoreIfNull().integerGreaterThanZero(); @@ -89,7 +89,7 @@ public class GuarantorCommand { .inMinMaxRange(GuarantorType.getMinValue(), GuarantorType.getMaxValue()); // validate for existing Client or Staff serving as gurantor - if (!this.isExternalGuarantor()) { + if (!isExternalGuarantor()) { baseDataValidator.reset().parameter(GUARANTOR_JSON_INPUT_PARAMS.ENTITY_ID.getValue()).value(this.entityId).notNull() .integerGreaterThanZero(); } else { @@ -106,9 +106,9 @@ public class GuarantorCommand { } public void validateForUpdate() { - List dataValidationErrors = new ArrayList(); + final List dataValidationErrors = new ArrayList(); - DataValidatorBuilder baseDataValidator = getDataValidator(dataValidationErrors); + final DataValidatorBuilder baseDataValidator = getDataValidator(dataValidationErrors); baseDataValidator.reset().parameter(GUARANTOR_JSON_INPUT_PARAMS.CLIENT_RELATIONSHIP_TYPE_ID.getValue()) .value(this.clientRelationshipTypeId).ignoreIfNull().integerGreaterThanZero(); @@ -117,7 +117,7 @@ public class GuarantorCommand { .ignoreIfNull().inMinMaxRange(GuarantorType.getMinValue(), GuarantorType.getMaxValue()); // validate for existing Client or Staff serving as gurantor - if (!this.isExternalGuarantor()) { + if (!isExternalGuarantor()) { baseDataValidator.reset().parameter(GUARANTOR_JSON_INPUT_PARAMS.ENTITY_ID.getValue()).value(this.entityId).ignoreIfNull() .integerGreaterThanZero(); } else { @@ -143,7 +143,7 @@ public class GuarantorCommand { /** * @param baseDataValidator */ - private void validateNonMandatoryFieldsForMaxLength(DataValidatorBuilder baseDataValidator) { + private void validateNonMandatoryFieldsForMaxLength(final DataValidatorBuilder baseDataValidator) { // validate non mandatory fields for length baseDataValidator.reset().parameter(GUARANTOR_JSON_INPUT_PARAMS.ADDRESS_LINE_1.getValue()).value(this.addressLine1).ignoreIfNull() .notExceedingLengthOf(500); @@ -169,15 +169,15 @@ public class GuarantorCommand { * @param dataValidationErrors * @return */ - private DataValidatorBuilder getDataValidator(List dataValidationErrors) { - DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("Guarantor"); + private DataValidatorBuilder getDataValidator(final List dataValidationErrors) { + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("Guarantor"); return baseDataValidator; } public Long getClientRelationshipTypeId() { return this.clientRelationshipTypeId; } - + public Long getEntityId() { return this.entityId; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/data/GuarantorData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/data/GuarantorData.java index 823c3a46c..432b7cf0f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/data/GuarantorData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/data/GuarantorData.java @@ -80,9 +80,10 @@ public class GuarantorData { null, null, null, staffData.getOfficeName(), null, null, null, guarantorData.allowedClientRelationshipTypes); } - public GuarantorData(final Long id, final Long loanId, final CodeValueData clientRelationshipType, final Long entityId, final EnumOptionData guarantorType, - final String firstname, final String lastname, final LocalDate dob, final String addressLine1, final String addressLine2, final String city, final String state, - final String zip, final String country, final String mobileNumber, final String housePhoneNumber, final String comment, final String officeName, + public GuarantorData(final Long id, final Long loanId, final CodeValueData clientRelationshipType, final Long entityId, + final EnumOptionData guarantorType, final String firstname, final String lastname, final LocalDate dob, + final String addressLine1, final String addressLine2, final String city, final String state, final String zip, + final String country, final String mobileNumber, final String housePhoneNumber, final String comment, final String officeName, final LocalDate joinedDate, final String externalId, final List guarantorTypeOptions, final Collection allowedClientRelationshipTypes) { this.id = id; @@ -110,15 +111,15 @@ public class GuarantorData { } public boolean isExternalGuarantor() { - return GuarantorType.EXTERNAL.getValue().equals(guarantorType.getId().intValue()); + return GuarantorType.EXTERNAL.getValue().equals(this.guarantorType.getId().intValue()); } public boolean isExistingClient() { - return GuarantorType.CUSTOMER.getValue().equals(guarantorType.getId().intValue()); + return GuarantorType.CUSTOMER.getValue().equals(this.guarantorType.getId().intValue()); } public boolean isStaffMember() { - return GuarantorType.STAFF.getValue().equals(guarantorType.getId().intValue()); + return GuarantorType.STAFF.getValue().equals(this.guarantorType.getId().intValue()); } public Long getEntityId() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/Guarantor.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/Guarantor.java index 04c680560..925bfa482 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/Guarantor.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/Guarantor.java @@ -83,16 +83,18 @@ public class Guarantor extends AbstractPersistable { } - public static Guarantor createNew(Loan loan, CodeValue clientRelationshipType, Integer gurantorType, Long entityId, String firstname, - String lastname, Date dateOfBirth, String addressLine1, String addressLine2, String city, String state, String country, - String zip, String housePhoneNumber, String mobilePhoneNumber, String comment) { + public static Guarantor createNew(final Loan loan, final CodeValue clientRelationshipType, final Integer gurantorType, + final Long entityId, final String firstname, final String lastname, final Date dateOfBirth, final String addressLine1, + final String addressLine2, final String city, final String state, final String country, final String zip, + final String housePhoneNumber, final String mobilePhoneNumber, final String comment) { return new Guarantor(loan, clientRelationshipType, gurantorType, entityId, firstname, lastname, dateOfBirth, addressLine1, addressLine2, city, state, country, zip, housePhoneNumber, mobilePhoneNumber, comment); } - public Guarantor(Loan loan, CodeValue clientRelationshipType, Integer gurantorType, Long entityId, String firstname, String lastname, - Date dateOfBirth, String addressLine1, String addressLine2, String city, String state, String country, String zip, - String housePhoneNumber, String mobilePhoneNumber, String comment) { + public Guarantor(final Loan loan, final CodeValue clientRelationshipType, final Integer gurantorType, final Long entityId, + final String firstname, final String lastname, final Date dateOfBirth, final String addressLine1, final String addressLine2, + final String city, final String state, final String country, final String zip, final String housePhoneNumber, + final String mobilePhoneNumber, final String comment) { this.loan = loan; this.clientRelationshipType = clientRelationshipType; this.gurantorType = gurantorType; @@ -112,22 +114,23 @@ public class Guarantor extends AbstractPersistable { } public static Guarantor fromJson(final Loan loan, final CodeValue clientRelationshipType, final JsonCommand command) { - Integer gurantorType = command.integerValueSansLocaleOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.GUARANTOR_TYPE_ID.getValue()); - Long entityId = command.longValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.ENTITY_ID.getValue()); + final Integer gurantorType = command.integerValueSansLocaleOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.GUARANTOR_TYPE_ID + .getValue()); + final Long entityId = command.longValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.ENTITY_ID.getValue()); if (GuarantorType.EXTERNAL.getValue().equals(gurantorType)) { - String firstname = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.FIRSTNAME.getValue()); - String lastname = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.LASTNAME.getValue()); - Date dateOfBirth = command.DateValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.DATE_OF_BIRTH.getValue()); - String addressLine1 = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.ADDRESS_LINE_1.getValue()); - String addressLine2 = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.ADDRESS_LINE_2.getValue()); - String city = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.CITY.getValue()); - String state = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.STATE.getValue()); - String country = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.COUNTRY.getValue()); - String zip = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.ZIP.getValue()); - String housePhoneNumber = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.PHONE_NUMBER.getValue()); - String mobilePhoneNumber = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.MOBILE_NUMBER.getValue()); - String comment = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.COMMENT.getValue()); + final String firstname = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.FIRSTNAME.getValue()); + final String lastname = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.LASTNAME.getValue()); + final Date dateOfBirth = command.DateValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.DATE_OF_BIRTH.getValue()); + final String addressLine1 = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.ADDRESS_LINE_1.getValue()); + final String addressLine2 = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.ADDRESS_LINE_2.getValue()); + final String city = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.CITY.getValue()); + final String state = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.STATE.getValue()); + final String country = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.COUNTRY.getValue()); + final String zip = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.ZIP.getValue()); + final String housePhoneNumber = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.PHONE_NUMBER.getValue()); + final String mobilePhoneNumber = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.MOBILE_NUMBER.getValue()); + final String comment = command.stringValueOfParameterNamed(GUARANTOR_JSON_INPUT_PARAMS.COMMENT.getValue()); return new Guarantor(loan, clientRelationshipType, gurantorType, entityId, firstname, lastname, dateOfBirth, addressLine1, addressLine2, city, state, country, zip, housePhoneNumber, mobilePhoneNumber, comment); @@ -145,7 +148,7 @@ public class Guarantor extends AbstractPersistable { handlePropertyUpdate(command, actualChanges, GUARANTOR_JSON_INPUT_PARAMS.GUARANTOR_TYPE_ID.getValue(), this.gurantorType, true); handlePropertyUpdate(command, actualChanges, GUARANTOR_JSON_INPUT_PARAMS.CLIENT_RELATIONSHIP_TYPE_ID.getValue(), 0, true); - if (this.isExternalGuarantor()) { + if (isExternalGuarantor()) { handlePropertyUpdate(command, actualChanges, GUARANTOR_JSON_INPUT_PARAMS.FIRSTNAME.getValue(), this.firstname); handlePropertyUpdate(command, actualChanges, GUARANTOR_JSON_INPUT_PARAMS.LASTNAME.getValue(), this.lastname); handlePropertyUpdate(command, actualChanges, GUARANTOR_JSON_INPUT_PARAMS.DATE_OF_BIRTH.getValue(), this.dateOfBirth); @@ -180,7 +183,7 @@ public class Guarantor extends AbstractPersistable { } private void handlePropertyUpdate(final JsonCommand command, final Map actualChanges, final String paramName, - Integer propertyToBeUpdated, boolean sansLocale) { + Integer propertyToBeUpdated, final boolean sansLocale) { if (command.isChangeInIntegerParameterNamed(paramName, propertyToBeUpdated)) { Integer newValue = null; if (sansLocale) { @@ -280,7 +283,7 @@ public class Guarantor extends AbstractPersistable { return this.clientRelationshipType; } - public void updateClientRelationshipType(CodeValue clientRelationshipType) { + public void updateClientRelationshipType(final CodeValue clientRelationshipType) { this.clientRelationshipType = clientRelationshipType; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/GuarantorRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/GuarantorRepository.java index 296bd4f5d..32bdd2cad 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/GuarantorRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/GuarantorRepository.java @@ -14,5 +14,6 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface GuarantorRepository extends JpaRepository, JpaSpecificationExecutor { Guarantor findByLoanAndId(Loan loan, Long id); + List findByLoan(Loan loan); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/GuarantorType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/GuarantorType.java index 8eb65782e..cd1c214c0 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/GuarantorType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/domain/GuarantorType.java @@ -24,7 +24,7 @@ public enum GuarantorType { } public String getCode() { - return code; + return this.code; } private static final Map intToEnumMap = new HashMap(); @@ -32,7 +32,7 @@ public enum GuarantorType { private static int maxValue; static { int i = 0; - for (GuarantorType type : GuarantorType.values()) { + for (final GuarantorType type : GuarantorType.values()) { if (i == 0) { minValue = type.value; } @@ -47,8 +47,8 @@ public enum GuarantorType { } } - public static GuarantorType fromInt(int i) { - GuarantorType type = intToEnumMap.get(Integer.valueOf(i)); + public static GuarantorType fromInt(final int i) { + final GuarantorType type = intToEnumMap.get(Integer.valueOf(i)); return type; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/DuplicateGuarantorException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/DuplicateGuarantorException.java index 87ca9125e..925069910 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/DuplicateGuarantorException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/DuplicateGuarantorException.java @@ -2,10 +2,10 @@ package org.mifosplatform.portfolio.loanaccount.guarantor.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - public class DuplicateGuarantorException extends AbstractPlatformDomainRuleException { - public DuplicateGuarantorException(final String action, String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { + public DuplicateGuarantorException(final String action, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg." + action + "." + postFix, defaultUserMessage, defaultUserMessageArgs); // TODO Auto-generated constructor stub } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/GuarantorNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/GuarantorNotFoundException.java index 0ba23a30f..e1052dfbd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/GuarantorNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/GuarantorNotFoundException.java @@ -12,11 +12,11 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN */ public class GuarantorNotFoundException extends AbstractPlatformResourceNotFoundException { - public GuarantorNotFoundException(Long id) { + public GuarantorNotFoundException(final Long id) { super("error.msg.loan.guarantor.", "Guarantor with identifier " + id + " does not exist", id); } - public GuarantorNotFoundException(Long loanId, Long guarantorId) { + public GuarantorNotFoundException(final Long loanId, final Long guarantorId) { super("error.msg.loan.guarantor.", "Guarantor with identifier " + guarantorId + " does not exist for loan with Identifier " + loanId, loanId, guarantorId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/InvalidGuarantorException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/InvalidGuarantorException.java index aedd5d2b6..2bb47ab2b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/InvalidGuarantorException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/exception/InvalidGuarantorException.java @@ -13,7 +13,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class InvalidGuarantorException extends AbstractPlatformDomainRuleException { - public InvalidGuarantorException(Long clientId, Long loanId) { + public InvalidGuarantorException(final Long clientId, final Long loanId) { super("error.msg.invalid.guarantor", "Tried to set Client with id " + clientId + " as a guarantor to his/her own loan with loan identifier =" + loanId, clientId, loanId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/serialization/GuarantorCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/serialization/GuarantorCommandFromApiJsonDeserializer.java index 66b4cf11a..f377ca777 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/serialization/GuarantorCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/serialization/GuarantorCommandFromApiJsonDeserializer.java @@ -38,34 +38,38 @@ public final class GuarantorCommandFromApiJsonDeserializer extends AbstractFromA } @Override - public GuarantorCommand commandFromApiJson(String json) { + public GuarantorCommand commandFromApiJson(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - Set supportedParameters = GUARANTOR_JSON_INPUT_PARAMS.getAllValues(); + final Set supportedParameters = GUARANTOR_JSON_INPUT_PARAMS.getAllValues(); supportedParameters.add("locale"); supportedParameters.add("dateFormat"); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - Long clientRelationshipTypeId = fromApiJsonHelper.extractLongNamed( + final Long clientRelationshipTypeId = this.fromApiJsonHelper.extractLongNamed( GUARANTOR_JSON_INPUT_PARAMS.CLIENT_RELATIONSHIP_TYPE_ID.getValue(), element); - Integer guarantorTypeId = fromApiJsonHelper.extractIntegerSansLocaleNamed(GUARANTOR_JSON_INPUT_PARAMS.GUARANTOR_TYPE_ID.getValue(), + final Integer guarantorTypeId = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( + GUARANTOR_JSON_INPUT_PARAMS.GUARANTOR_TYPE_ID.getValue(), element); + final Long entityId = this.fromApiJsonHelper.extractLongNamed(GUARANTOR_JSON_INPUT_PARAMS.ENTITY_ID.getValue(), element); + final String firstname = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.FIRSTNAME.getValue(), element); + final String lastname = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.LASTNAME.getValue(), element); + final String addressLine1 = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.ADDRESS_LINE_1.getValue(), element); - Long entityId = fromApiJsonHelper.extractLongNamed(GUARANTOR_JSON_INPUT_PARAMS.ENTITY_ID.getValue(), element); - String firstname = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.FIRSTNAME.getValue(), element); - String lastname = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.LASTNAME.getValue(), element); - String addressLine1 = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.ADDRESS_LINE_1.getValue(), element); - String addressLine2 = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.ADDRESS_LINE_2.getValue(), element); - String city = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.CITY.getValue(), element); - String state = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.STATE.getValue(), element); - String zip = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.ZIP.getValue(), element); - String country = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.COUNTRY.getValue(), element); - String mobileNumber = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.MOBILE_NUMBER.getValue(), element); - String housePhoneNumber = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.PHONE_NUMBER.getValue(), element); - String comment = fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.COMMENT.getValue(), element); - LocalDate dob = fromApiJsonHelper.extractLocalDateNamed(GUARANTOR_JSON_INPUT_PARAMS.DATE_OF_BIRTH.getValue(), element); + final String addressLine2 = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.ADDRESS_LINE_2.getValue(), + element); + final String city = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.CITY.getValue(), element); + final String state = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.STATE.getValue(), element); + final String zip = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.ZIP.getValue(), element); + final String country = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.COUNTRY.getValue(), element); + final String mobileNumber = this.fromApiJsonHelper + .extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.MOBILE_NUMBER.getValue(), element); + final String housePhoneNumber = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.PHONE_NUMBER.getValue(), + element); + final String comment = this.fromApiJsonHelper.extractStringNamed(GUARANTOR_JSON_INPUT_PARAMS.COMMENT.getValue(), element); + final LocalDate dob = this.fromApiJsonHelper.extractLocalDateNamed(GUARANTOR_JSON_INPUT_PARAMS.DATE_OF_BIRTH.getValue(), element); return new GuarantorCommand(clientRelationshipTypeId, guarantorTypeId, entityId, firstname, lastname, addressLine1, addressLine2, city, state, zip, country, mobileNumber, housePhoneNumber, comment, dob); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorEnumerations.java index 3c3310789..5867ac79a 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorEnumerations.java @@ -18,14 +18,14 @@ public class GuarantorEnumerations { } public static EnumOptionData guarantorType(final GuarantorType guarantorType) { - EnumOptionData optionData = new EnumOptionData(guarantorType.getValue().longValue(), guarantorType.getCode(), + final EnumOptionData optionData = new EnumOptionData(guarantorType.getValue().longValue(), guarantorType.getCode(), guarantorType.toString()); return optionData; } - public static List guarantorType(GuarantorType[] guarantorTypes) { - List optionDatas = new ArrayList(); - for (GuarantorType guarantorType : guarantorTypes) { + public static List guarantorType(final GuarantorType[] guarantorTypes) { + final List optionDatas = new ArrayList(); + for (final GuarantorType guarantorType : guarantorTypes) { optionDatas.add(guarantorType(guarantorType)); } return optionDatas; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformServiceImpl.java index 318e1916b..6e859100d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorReadPlatformServiceImpl.java @@ -37,9 +37,8 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe private final LoanRepository loanRepository; @Autowired - public GuarantorReadPlatformServiceImpl(final RoutingDataSource dataSource, - final ClientReadPlatformService clientReadPlatformService, final StaffReadPlatformService staffReadPlatformService, - final LoanRepository loanRepository) { + public GuarantorReadPlatformServiceImpl(final RoutingDataSource dataSource, final ClientReadPlatformService clientReadPlatformService, + final StaffReadPlatformService staffReadPlatformService, final LoanRepository loanRepository) { this.jdbcTemplate = new JdbcTemplate(dataSource); this.clientReadPlatformService = clientReadPlatformService; this.staffReadPlatformService = staffReadPlatformService; @@ -48,21 +47,21 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe private static final class GuarantorMapper implements RowMapper { - private StringBuilder sqlBuilder = new StringBuilder( + private final StringBuilder sqlBuilder = new StringBuilder( " g.id as id, g.loan_id as loanId, g.client_reln_cv_id clientRelationshipTypeId, g.entity_id as entityId, g.type_enum guarantorType ,g.firstname as firstname, g.lastname as lastname, g.dob as dateOfBirth, g.address_line_1 as addressLine1, g.address_line_2 as addressLine2, g.city as city, g.state as state, g.country as country, g.zip as zip, g.house_phone_number as housePhoneNumber, g.mobile_number as mobilePhoneNumber, g.comment as comment, ") .append(" cv.code_value as typeName")// .append(" FROM m_guarantor g") // .append(" left JOIN m_code_value cv on g.client_reln_cv_id = cv.id"); public String schema() { - return sqlBuilder.toString(); + return this.sqlBuilder.toString(); } @Override public GuarantorData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException { - Long id = rs.getLong("id"); - Long loanId = rs.getLong("loanId"); - Long clientRelationshipTypeId = JdbcSupport.getLong(rs, "clientRelationshipTypeId"); + final Long id = rs.getLong("id"); + final Long loanId = rs.getLong("loanId"); + final Long clientRelationshipTypeId = JdbcSupport.getLong(rs, "clientRelationshipTypeId"); CodeValueData clientRelationshipType = null; if (clientRelationshipTypeId != null) { @@ -70,54 +69,54 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe clientRelationshipType = CodeValueData.instance(clientRelationshipTypeId, typeName); } - Integer guarantorTypeId = rs.getInt("guarantorType"); + final Integer guarantorTypeId = rs.getInt("guarantorType"); final EnumOptionData guarantorType = GuarantorEnumerations.guarantorType(guarantorTypeId); - Long entityId = rs.getLong("entityId"); - String firstname = rs.getString("firstname"); - String lastname = rs.getString("lastname"); - LocalDate dob = JdbcSupport.getLocalDate(rs, "dateOfBirth"); - String addressLine1 = rs.getString("addressLine1"); - String addressLine2 = rs.getString("addressLine2"); - String city = rs.getString("city"); - String state = rs.getString("state"); - String zip = rs.getString("zip"); - String country = rs.getString("country"); - String mobileNumber = rs.getString("mobilePhoneNumber"); - String housePhoneNumber = rs.getString("housePhoneNumber"); - String comment = rs.getString("comment"); + final Long entityId = rs.getLong("entityId"); + final String firstname = rs.getString("firstname"); + final String lastname = rs.getString("lastname"); + final LocalDate dob = JdbcSupport.getLocalDate(rs, "dateOfBirth"); + final String addressLine1 = rs.getString("addressLine1"); + final String addressLine2 = rs.getString("addressLine2"); + final String city = rs.getString("city"); + final String state = rs.getString("state"); + final String zip = rs.getString("zip"); + final String country = rs.getString("country"); + final String mobileNumber = rs.getString("mobilePhoneNumber"); + final String housePhoneNumber = rs.getString("housePhoneNumber"); + final String comment = rs.getString("comment"); return new GuarantorData(id, loanId, clientRelationshipType, entityId, guarantorType, firstname, lastname, dob, addressLine1, addressLine2, city, state, zip, country, mobileNumber, housePhoneNumber, comment, null, null, null, null, null); } } @Override - public List retrieveGuarantorsForValidLoan(Long loanId) { - Loan loan = this.loanRepository.findOne(loanId); + public List retrieveGuarantorsForValidLoan(final Long loanId) { + final Loan loan = this.loanRepository.findOne(loanId); if (loan == null) { throw new LoanNotFoundException(loanId); } return retrieveGuarantorsForLoan(loanId); } @Override - public List retrieveGuarantorsForLoan(Long loanId) { + public List retrieveGuarantorsForLoan(final Long loanId) { final GuarantorMapper rm = new GuarantorMapper(); String sql = "select " + rm.schema(); sql += " where loan_id = ?"; - List guarantorDatas = this.jdbcTemplate.query(sql, rm, new Object[] { loanId }); + final List guarantorDatas = this.jdbcTemplate.query(sql, rm, new Object[] { loanId }); - List mergedGuarantorDatas = new ArrayList(); + final List mergedGuarantorDatas = new ArrayList(); - for (GuarantorData guarantorData : guarantorDatas) { + for (final GuarantorData guarantorData : guarantorDatas) { mergedGuarantorDatas.add(mergeDetailsForClientOrStaffGuarantor(guarantorData)); } return mergedGuarantorDatas; } @Override - public GuarantorData retrieveGuarantor(Long loanId, Long guarantorId) { + public GuarantorData retrieveGuarantor(final Long loanId, final Long guarantorId) { final GuarantorMapper rm = new GuarantorMapper(); String sql = "select " + rm.schema(); sql += " where g.loan_id = ? and g.id = ?"; - GuarantorData guarantorData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { loanId, guarantorId }); + final GuarantorData guarantorData = this.jdbcTemplate.queryForObject(sql, rm, new Object[] { loanId, guarantorId }); return mergeDetailsForClientOrStaffGuarantor(guarantorData); } @@ -125,12 +124,12 @@ public class GuarantorReadPlatformServiceImpl implements GuarantorReadPlatformSe /** * @param guarantorData */ - private GuarantorData mergeDetailsForClientOrStaffGuarantor(GuarantorData guarantorData) { + private GuarantorData mergeDetailsForClientOrStaffGuarantor(final GuarantorData guarantorData) { if (guarantorData.isExistingClient()) { - ClientData clientData = clientReadPlatformService.retrieveOne(guarantorData.getEntityId()); + final ClientData clientData = this.clientReadPlatformService.retrieveOne(guarantorData.getEntityId()); return GuarantorData.mergeClientData(clientData, guarantorData); } else if (guarantorData.isStaffMember()) { - StaffData staffData = staffReadPlatformService.retrieveStaff(guarantorData.getEntityId()); + final StaffData staffData = this.staffReadPlatformService.retrieveStaff(guarantorData.getEntityId()); return GuarantorData.mergeStaffData(staffData, guarantorData); } return guarantorData; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformServiceJpaRepositoryIImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformServiceJpaRepositoryIImpl.java index fa16c6f38..a48e695ec 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformServiceJpaRepositoryIImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/guarantor/service/GuarantorWritePlatformServiceJpaRepositoryIImpl.java @@ -67,28 +67,28 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto final GuarantorCommand guarantorCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json()); guarantorCommand.validateForCreate(); - Loan loan = this.loanRepositoryWrapper.findOneWithNotFoundDetection(loanId); + final Loan loan = this.loanRepositoryWrapper.findOneWithNotFoundDetection(loanId); - Long clientRelationshipId = guarantorCommand.getClientRelationshipTypeId(); + final Long clientRelationshipId = guarantorCommand.getClientRelationshipTypeId(); CodeValue clientRelationshipType = null; if (clientRelationshipId != null) { clientRelationshipType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( GuarantorConstants.GUARANTOR_RELATIONSHIP_CODE_NAME, clientRelationshipId); } - - List existGuarantorList = this.guarantorRepository.findByLoan(loan); - Long entityId = guarantorCommand.getEntityId(); - for (Guarantor guarantor : existGuarantorList) { + final List existGuarantorList = this.guarantorRepository.findByLoan(loan); + final Long entityId = guarantorCommand.getEntityId(); + + for (final Guarantor guarantor : existGuarantorList) { if (guarantor.getLoanId() == loanId && guarantor.getEntityId() == entityId) { String defaultUserMessage = this.clientRepositoryWrapper.findOneWithNotFoundDetection(entityId).getDisplayName(); defaultUserMessage = defaultUserMessage + " is already exist as a guarantor for this loan"; - String action = loan.client() != null ? "client.guarantor" : "group.guarantor"; + final String action = loan.client() != null ? "client.guarantor" : "group.guarantor"; throw new DuplicateGuarantorException(action, "is.already.exist.same.loan", defaultUserMessage, entityId, loanId); } } - + Guarantor guarantor = null; guarantor = Guarantor.fromJson(loan, clientRelationshipType, command); @@ -98,7 +98,7 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(guarantor.getOfficeId()) .withEntityId(guarantor.getId()).withLoanId(loanId).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleGuarantorDataIntegrityIssues(dve); return CommandProcessingResult.empty(); } @@ -118,7 +118,7 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto final Map changesOnly = guarantorForUpdate.update(command); if (changesOnly.containsKey(GUARANTOR_JSON_INPUT_PARAMS.CLIENT_RELATIONSHIP_TYPE_ID.getValue())) { - Long clientRelationshipId = guarantorCommand.getClientRelationshipTypeId(); + final Long clientRelationshipId = guarantorCommand.getClientRelationshipTypeId(); CodeValue clientRelationshipType = null; if (clientRelationshipId != null) { clientRelationshipType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( @@ -126,7 +126,7 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto } guarantorForUpdate.updateClientRelationshipType(clientRelationshipType); } - + final List existGuarantorList = this.guarantorRepository.findByLoan(loan); final Integer guarantorTypeId = guarantorCommand.getGuarantorTypeId(); final GuarantorType guarantorType = GuarantorType.fromInt(guarantorTypeId); @@ -147,14 +147,14 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto || changesOnly.containsKey(GUARANTOR_JSON_INPUT_PARAMS.GUARANTOR_TYPE_ID)) { validateGuarantorBusinessRules(guarantorForUpdate); } - + if (!changesOnly.isEmpty()) { this.guarantorRepository.saveAndFlush(guarantorForUpdate); } return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withOfficeId(guarantorForUpdate.getOfficeId()) .withEntityId(guarantorForUpdate.getId()).withOfficeId(guarantorForUpdate.getLoanId()).with(changesOnly).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleGuarantorDataIntegrityIssues(dve); return CommandProcessingResult.empty(); } @@ -177,7 +177,7 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto // validate guarantor conditions if (guarantor.isExistingCustomer()) { // check client exists - clientRepositoryWrapper.findOneWithNotFoundDetection(guarantor.getEntityId()); + this.clientRepositoryWrapper.findOneWithNotFoundDetection(guarantor.getEntityId()); // validate that the client is not set as a self guarantor if (guarantor.getClientId() != null) { if (guarantor.getClientId().equals(guarantor.getEntityId())) { @@ -186,12 +186,12 @@ public class GuarantorWritePlatformServiceJpaRepositoryIImpl implements Guaranto } } } else if (guarantor.isExistingEmployee()) { - staffRepositoryWrapper.findOneWithNotFoundDetection(guarantor.getEntityId()); + this.staffRepositoryWrapper.findOneWithNotFoundDetection(guarantor.getEntityId()); } } private void handleGuarantorDataIntegrityIssues(final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); logger.error(dve.getMessage(), dve); throw new PlatformDataIntegrityException("error.msg.guarantor.unknown.data.integrity.issue", "Unknown data integrity issue with resource Guarantor: " + realCause.getMessage()); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/data/LoanScheduleData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/data/LoanScheduleData.java index baa33502e..d019a371e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/data/LoanScheduleData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/data/LoanScheduleData.java @@ -74,6 +74,6 @@ public class LoanScheduleData { } public Collection getPeriods() { - return periods; + return this.periods; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/data/LoanSchedulePeriodData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/data/LoanSchedulePeriodData.java index 0c7ba56cf..27ee6fb82 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/data/LoanSchedulePeriodData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/data/LoanSchedulePeriodData.java @@ -72,8 +72,8 @@ public class LoanSchedulePeriodData { public static LoanSchedulePeriodData disbursementOnlyPeriod(final LocalDate disbursementDate, final BigDecimal principalDisbursed, final BigDecimal feeChargesDueAtTimeOfDisbursement, final boolean isDisbursed) { - Integer periodNumber = Integer.valueOf(0); - LocalDate from = null; + final Integer periodNumber = Integer.valueOf(0); + final LocalDate from = null; return new LoanSchedulePeriodData(periodNumber, from, disbursementDate, principalDisbursed, feeChargesDueAtTimeOfDisbursement, isDisbursed); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/AbstractLoanScheduleGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/AbstractLoanScheduleGenerator.java index b2327b98a..f00a9d94a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/AbstractLoanScheduleGenerator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/AbstractLoanScheduleGenerator.java @@ -35,7 +35,8 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener final List holidays, final WorkingDays workingDays) { // 1. generate list of proposed schedule due dates - final List scheduledDates = this.scheduledDateGenerator.generate(loanApplicationTerms, isHolidayEnabled, holidays, workingDays); + final List scheduledDates = this.scheduledDateGenerator.generate(loanApplicationTerms, isHolidayEnabled, holidays, + workingDays); // 2. determine the total charges due at time of disbursement final BigDecimal chargesDueAtTimeOfDisbursement = deriveTotalChargesDueAtTimeOfDisbursement(loanCharges); @@ -49,12 +50,12 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener // variables for cumulative totals int loanTermInDays = Integer.valueOf(0); BigDecimal totalPrincipalExpected = BigDecimal.ZERO; - BigDecimal totalPrincipalPaid = BigDecimal.ZERO; + final BigDecimal totalPrincipalPaid = BigDecimal.ZERO; BigDecimal totalInterestCharged = BigDecimal.ZERO; BigDecimal totalFeeChargesCharged = chargesDueAtTimeOfDisbursement; BigDecimal totalPenaltyChargesCharged = BigDecimal.ZERO; BigDecimal totalRepaymentExpected = chargesDueAtTimeOfDisbursement; - BigDecimal totalOutstanding = BigDecimal.ZERO; + final BigDecimal totalOutstanding = BigDecimal.ZERO; final Collection periods = createNewLoanScheduleListWithDisbursementDetails(numberOfRepayments, loanApplicationTerms, chargesDueAtTimeOfDisbursement); @@ -73,17 +74,17 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener Money totalCumulativeInterest = principalDisbursed.zero(); Money totalOutstandingInterestPaymentDueToGrace = principalDisbursed.zero(); Money outstandingBalance = principalDisbursed; - for (LocalDate scheduledDueDate : scheduledDates) { + for (final LocalDate scheduledDueDate : scheduledDates) { final int daysInPeriod = Days.daysBetween(startDate, scheduledDueDate).getDays(); - double interestCalculationGraceOnRepaymentPeriodFraction = this.paymentPeriodsInOneYearCalculator + final double interestCalculationGraceOnRepaymentPeriodFraction = this.paymentPeriodsInOneYearCalculator .calculatePortionOfRepaymentPeriodInterestChargingGrace(repaymentPeriodStartDate, scheduledDueDate, loanApplicationTerms.getInterestChargedFromLocalDate(), loanApplicationTerms.getLoanTermPeriodFrequencyType(), loanApplicationTerms.getRepaymentEvery()); // 5 determine principal,interest of repayment period - PrincipalInterest principalInterestForThisPeriod = calculatePrincipalInterestComponentsForPeriod( + final PrincipalInterest principalInterestForThisPeriod = calculatePrincipalInterestComponentsForPeriod( this.paymentPeriodsInOneYearCalculator, interestCalculationGraceOnRepaymentPeriodFraction, totalCumulativePrincipal, totalCumulativeInterest, totalInterestChargedForFullLoanTerm, totalOutstandingInterestPaymentDueToGrace, daysInPeriod, outstandingBalance, loanApplicationTerms, periodNumber, mc); @@ -141,7 +142,7 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener private BigDecimal deriveTotalChargesDueAtTimeOfDisbursement(final Set loanCharges) { BigDecimal chargesDueAtTimeOfDisbursement = BigDecimal.ZERO; - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueAtDisbursement()) { chargesDueAtTimeOfDisbursement = chargesDueAtTimeOfDisbursement.add(loanCharge.amount()); } @@ -166,7 +167,7 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener Money cumulative = Money.zero(monetaryCurrency); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(periodStart, periodEnd) && loanCharge.isFeeCharge()) { cumulative = cumulative.plus(loanCharge.amount()); } @@ -180,7 +181,7 @@ public abstract class AbstractLoanScheduleGenerator implements LoanScheduleGener Money cumulative = Money.zero(monetaryCurrency); - for (LoanCharge loanCharge : loanCharges) { + for (final LoanCharge loanCharge : loanCharges) { if (loanCharge.isDueForCollectionFromAndUpToAndIncluding(periodStart, periodEnd) && loanCharge.isPenaltyCharge()) { cumulative = cumulative.plus(loanCharge.amount()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DecliningBalanceInterestLoanScheduleGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DecliningBalanceInterestLoanScheduleGenerator.java index a6b9e95ac..09437f6e4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DecliningBalanceInterestLoanScheduleGenerator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DecliningBalanceInterestLoanScheduleGenerator.java @@ -42,21 +42,21 @@ public class DecliningBalanceInterestLoanScheduleGenerator extends AbstractLoanS final double interestCalculationGraceOnRepaymentPeriodFraction, final Money totalCumulativePrincipal, @SuppressWarnings("unused") final Money totalCumulativeInterest, @SuppressWarnings("unused") final Money totalInterestDueForLoan, final Money cumulatingInterestPaymentDueToGrace, - final int daysInPeriod, final Money outstandingBalance, - final LoanApplicationTerms loanApplicationTerms, final int periodNumber, final MathContext mc) { + final int daysInPeriod, final Money outstandingBalance, final LoanApplicationTerms loanApplicationTerms, + final int periodNumber, final MathContext mc) { - PrincipalInterest result = loanApplicationTerms.calculateTotalInterestForPeriod(calculator, + final PrincipalInterest result = loanApplicationTerms.calculateTotalInterestForPeriod(calculator, interestCalculationGraceOnRepaymentPeriodFraction, periodNumber, mc, cumulatingInterestPaymentDueToGrace, daysInPeriod, outstandingBalance); - Money interestForThisInstallment = result.interest(); + final Money interestForThisInstallment = result.interest(); Money principalForThisInstallment = loanApplicationTerms.calculateTotalPrincipalForPeriod(calculator, daysInPeriod, outstandingBalance, periodNumber, mc); // update cumulative fields for principal & interest - Money interestBroughtFowardDueToGrace = result.interestPaymentDueToGrace(); - Money totalCumulativePrincipalToDate = totalCumulativePrincipal.plus(principalForThisInstallment); + final Money interestBroughtFowardDueToGrace = result.interestPaymentDueToGrace(); + final Money totalCumulativePrincipalToDate = totalCumulativePrincipal.plus(principalForThisInstallment); // adjust if needed principalForThisInstallment = loanApplicationTerms.adjustPrincipalIfLastRepaymentPeriod(principalForThisInstallment, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DefaultPaymentPeriodsInOneYearCalculator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DefaultPaymentPeriodsInOneYearCalculator.java index 914697e9f..83e715c1a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DefaultPaymentPeriodsInOneYearCalculator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DefaultPaymentPeriodsInOneYearCalculator.java @@ -43,14 +43,14 @@ public class DefaultPaymentPeriodsInOneYearCalculator implements PaymentPeriodsI Double periodFraction = Double.valueOf("0.0"); - LocalDateInterval repaymentPeriod = new LocalDateInterval(repaymentPeriodStartDate, scheduledDueDate); + final LocalDateInterval repaymentPeriod = new LocalDateInterval(repaymentPeriodStartDate, scheduledDueDate); if (interestChargedFromLocalDate != null && repaymentPeriod.fallsBefore(interestChargedFromLocalDate.plusDays(1))) { periodFraction = Double.valueOf("1.0"); } else if (interestChargedFromLocalDate != null && repaymentPeriod.contains(interestChargedFromLocalDate)) { - int numberOfDaysInterestCalculationGraceInPeriod = Days.daysBetween(repaymentPeriodStartDate, interestChargedFromLocalDate) - .getDays(); + final int numberOfDaysInterestCalculationGraceInPeriod = Days.daysBetween(repaymentPeriodStartDate, + interestChargedFromLocalDate).getDays(); periodFraction = calculateRepaymentPeriodFraction(repaymentPeriodFrequencyType, repaidEvery, numberOfDaysInterestCalculationGraceInPeriod); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DefaultScheduledDateGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DefaultScheduledDateGenerator.java index 3af0e561d..80e183142 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DefaultScheduledDateGenerator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/DefaultScheduledDateGenerator.java @@ -36,23 +36,24 @@ public class DefaultScheduledDateGenerator implements ScheduledDateGenerator { } else { dueRepaymentPeriodDate = getRepaymentPeriodDate(loanApplicationTerms, startDate); } - + startDate = dueRepaymentPeriodDate; - LocalDate nextDueRepaymentPeriodDate = getRepaymentPeriodDate(loanApplicationTerms, dueRepaymentPeriodDate); - - dueRepaymentPeriodDate = WorkingDaysUtil.getOffSetDateIfNonWorkingDay(dueRepaymentPeriodDate, nextDueRepaymentPeriodDate, workingDays); - - if(isHolidayEnabled){ + final LocalDate nextDueRepaymentPeriodDate = getRepaymentPeriodDate(loanApplicationTerms, dueRepaymentPeriodDate); + + dueRepaymentPeriodDate = WorkingDaysUtil.getOffSetDateIfNonWorkingDay(dueRepaymentPeriodDate, nextDueRepaymentPeriodDate, + workingDays); + + if (isHolidayEnabled) { dueRepaymentPeriodDate = HolidayUtil.getRepaymentRescheduleDateToIfHoliday(dueRepaymentPeriodDate, holidays); } dueRepaymentPeriodDates.add(dueRepaymentPeriodDate); } - + return dueRepaymentPeriodDates; } - private LocalDate getRepaymentPeriodDate(final LoanApplicationTerms loanApplicationTerms, LocalDate startDate) { + private LocalDate getRepaymentPeriodDate(final LoanApplicationTerms loanApplicationTerms, final LocalDate startDate) { final int repaidEvery = loanApplicationTerms.getRepaymentEvery(); LocalDate dueRepaymentPeriodDate = startDate; switch (loanApplicationTerms.getRepaymentPeriodFrequencyType()) { @@ -78,7 +79,7 @@ public class DefaultScheduledDateGenerator implements ScheduledDateGenerator { public LocalDate idealDisbursementDateBasedOnFirstRepaymentDate(final PeriodFrequencyType repaymentPeriodFrequencyType, final int repaidEvery, final List scheduledDates) { - LocalDate firstRepaymentDate = scheduledDates.get(0); + final LocalDate firstRepaymentDate = scheduledDates.get(0); LocalDate idealDisbursementDate = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/FinanicalFunctions.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/FinanicalFunctions.java index f24bbbab2..454d54129 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/FinanicalFunctions.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/FinanicalFunctions.java @@ -32,7 +32,7 @@ public class FinanicalFunctions { if (interestRateFraction == 0) { payment = -1 * (futureValue + principal) / numberOfPayments; } else { - double r1 = interestRateFraction + 1; + final double r1 = interestRateFraction + 1; payment = (futureValue + principal * Math.pow(r1, numberOfPayments)) * interestRateFraction / ((type ? r1 : 1) * (1 - Math.pow(r1, numberOfPayments))); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/FlatInterestLoanScheduleGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/FlatInterestLoanScheduleGenerator.java index 50ed49518..ee3eb4dbc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/FlatInterestLoanScheduleGenerator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/FlatInterestLoanScheduleGenerator.java @@ -15,21 +15,21 @@ public class FlatInterestLoanScheduleGenerator extends AbstractLoanScheduleGener public PrincipalInterest calculatePrincipalInterestComponentsForPeriod(final PaymentPeriodsInOneYearCalculator calculator, final double interestCalculationGraceOnRepaymentPeriodFraction, final Money totalCumulativePrincipal, final Money totalCumulativeInterest, final Money totalInterestDueForLoan, final Money cumulatingInterestPaymentDueToGrace, - final int daysInPeriod, final Money outstandingBalance, - final LoanApplicationTerms loanApplicationTerms, final int periodNumber, final MathContext mc) { + final int daysInPeriod, final Money outstandingBalance, final LoanApplicationTerms loanApplicationTerms, + final int periodNumber, final MathContext mc) { Money principalForThisInstallment = loanApplicationTerms.calculateTotalPrincipalForPeriod(calculator, daysInPeriod, outstandingBalance, periodNumber, mc); - PrincipalInterest result = loanApplicationTerms.calculateTotalInterestForPeriod(calculator, + final PrincipalInterest result = loanApplicationTerms.calculateTotalInterestForPeriod(calculator, interestCalculationGraceOnRepaymentPeriodFraction, periodNumber, mc, cumulatingInterestPaymentDueToGrace, daysInPeriod, outstandingBalance); Money interestForThisInstallment = result.interest(); // update cumulative fields for principal & interest - Money interestBroughtForwardDueToGrace = result.interestPaymentDueToGrace(); - Money totalCumulativePrincipalToDate = totalCumulativePrincipal.plus(principalForThisInstallment); - Money totalCumulativeInterestToDate = totalCumulativeInterest.plus(interestForThisInstallment); + final Money interestBroughtForwardDueToGrace = result.interestPaymentDueToGrace(); + final Money totalCumulativePrincipalToDate = totalCumulativePrincipal.plus(principalForThisInstallment); + final Money totalCumulativeInterestToDate = totalCumulativeInterest.plus(interestForThisInstallment); // adjust if needed principalForThisInstallment = loanApplicationTerms.adjustPrincipalIfLastRepaymentPeriod(principalForThisInstallment, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanApplicationTerms.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanApplicationTerms.java index f32d691f2..008e70ddc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanApplicationTerms.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanApplicationTerms.java @@ -50,7 +50,7 @@ public final class LoanApplicationTerms { * Integer representing the number of 'repayment frequencies' or * installments where 'grace' should apply to the payment of interest in a * loans repayment period (installment). - * + * * Note: Interest is still calculated taking into account the full * loan term, the interest is simply offset to a later period. */ @@ -60,7 +60,7 @@ public final class LoanApplicationTerms { * Integer representing the number of 'repayment frequencies' or * installments where 'grace' should apply to the charging of interest in a * loans repayment period (installment). - * + * * Note: The loan is interest-free for the period of time * indicated. */ @@ -68,7 +68,7 @@ public final class LoanApplicationTerms { /** * Legacy method of support 'grace' on the charging of interest on a loan. - * + * *

* For the typical structured loan, its reasonable to use an integer to * indicate the number of 'repayment frequency' periods the 'grace' should @@ -173,7 +173,8 @@ public final class LoanApplicationTerms { final Money totalPrincipalRemaining = this.principal.minus(totalCumulativePrincipalToDate); if (totalPrincipalRemaining.isLessThanZero()) { - // paid too much principal, subtract amount that overpays from principal paid for period. + // paid too much principal, subtract amount that overpays from + // principal paid for period. adjusted = principalForPeriod.minus(totalPrincipalRemaining.abs()); } else if (isLastRepaymentPeriod(this.numberOfRepayments, periodNumber)) { @@ -195,7 +196,8 @@ public final class LoanApplicationTerms { final Money totalInterestRemaining = totalInterestDueForLoan.minus(totalCumulativeInterestToDate); if (totalInterestRemaining.isLessThanZero()) { - // paid too much interest, subtract amount that overpays from interest paid for period. + // paid too much interest, subtract amount that overpays from + // interest paid for period. adjusted = interestForThisPeriod.minus(totalInterestRemaining.abs()); } else if (isLastRepaymentPeriod(this.numberOfRepayments, periodNumber)) { final Money interestDifference = totalCumulativeInterestToDate.minus(totalInterestDueForLoan); @@ -214,7 +216,7 @@ public final class LoanApplicationTerms { /** * Calculates the total interest to be charged on loan taking into account * grace settings. - * + * */ public Money calculateTotalInterestCharged(final PaymentPeriodsInOneYearCalculator calculator, final MathContext mc) { @@ -315,11 +317,11 @@ public final class LoanApplicationTerms { break; case DECLINING_BALANCE: - final Money interestForThisInstallmentBeforeGrace = calculateDecliningInterestDueForInstallmentBeforeApplyingGrace(calculator, - mc, daysInPeriod, outstandingBalance); + final Money interestForThisInstallmentBeforeGrace = calculateDecliningInterestDueForInstallmentBeforeApplyingGrace( + calculator, mc, daysInPeriod, outstandingBalance); - final Money interestForThisInstallmentAfterGrace = calculateDecliningInterestDueForInstallmentAfterApplyingGrace(calculator, - interestCalculationGraceOnRepaymentPeriodFraction, mc, daysInPeriod, outstandingBalance, periodNumber); + final Money interestForThisInstallmentAfterGrace = calculateDecliningInterestDueForInstallmentAfterApplyingGrace( + calculator, interestCalculationGraceOnRepaymentPeriodFraction, mc, daysInPeriod, outstandingBalance, periodNumber); interestForInstallment = interestForThisInstallmentAfterGrace; if (interestForThisInstallmentAfterGrace.isGreaterThanZero()) { @@ -542,7 +544,8 @@ public final class LoanApplicationTerms { final BigDecimal dailyInterestRate = this.annualNominalInterestRate.divide(BigDecimal.valueOf(Long.valueOf(365)), mc) .divide(BigDecimal.valueOf(Double.valueOf("100.0")), mc).multiply(BigDecimal.valueOf(this.repaymentEvery)); - final BigDecimal equivalentInterestRateForPeriod = dailyInterestRate.multiply(BigDecimal.valueOf(Long.valueOf(daysInPeriod))); + final BigDecimal equivalentInterestRateForPeriod = dailyInterestRate + .multiply(BigDecimal.valueOf(Long.valueOf(daysInPeriod))); interestDue = outstandingBalance.multiplyRetainScale(equivalentInterestRateForPeriod, mc.getRoundingMode()); break; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanScheduleModel.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanScheduleModel.java index c337a0f50..98b796534 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanScheduleModel.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanScheduleModel.java @@ -63,18 +63,18 @@ public final class LoanScheduleModel { final int decimalPlaces = this.totalPrincipalDisbursed.getCurrencyDigitsAfterDecimal(); final Integer inMultiplesOf = this.totalPrincipalDisbursed.getCurrencyInMultiplesOf(); - final CurrencyData currency = applicationCurrency.toData(decimalPlaces,inMultiplesOf); + final CurrencyData currency = this.applicationCurrency.toData(decimalPlaces, inMultiplesOf); final Collection periodsData = new ArrayList(); - for (LoanScheduleModelPeriod modelPeriod : this.periods) { + for (final LoanScheduleModelPeriod modelPeriod : this.periods) { periodsData.add(modelPeriod.toData()); } - BigDecimal totalWaived = null; - BigDecimal totalWrittenOff = null; - BigDecimal totalRepayment = null; - BigDecimal totalPaidInAdvance = null; - BigDecimal totalPaidLate = null; + final BigDecimal totalWaived = null; + final BigDecimal totalWrittenOff = null; + final BigDecimal totalRepayment = null; + final BigDecimal totalPaidInAdvance = null; + final BigDecimal totalPaidLate = null; return new LoanScheduleData(currency, periodsData, this.loanTermInDays, this.totalPrincipalDisbursed.getAmount(), this.totalPrincipalExpected, this.totalPrincipalPaid, this.totalInterestCharged, this.totalFeeChargesCharged, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelRepaymentPeriod.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelRepaymentPeriod.java index 87727cb51..b649da90f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelRepaymentPeriod.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/LoanScheduleModelRepaymentPeriod.java @@ -51,7 +51,7 @@ public final class LoanScheduleModelRepaymentPeriod implements LoanScheduleModel @Override public LoanSchedulePeriodData toData() { - return LoanSchedulePeriodData.repaymentOnlyPeriod(periodNumber, this.fromDate, this.dueDate, this.principalDue.getAmount(), + return LoanSchedulePeriodData.repaymentOnlyPeriod(this.periodNumber, this.fromDate, this.dueDate, this.principalDue.getAmount(), this.outstandingLoanBalance.getAmount(), this.interestDue.getAmount(), this.feeChargesDue.getAmount(), this.penaltyChargesDue.getAmount(), this.totalDue.getAmount()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/ScheduledDateGenerator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/ScheduledDateGenerator.java index 4c54c29c7..4c6e4a76c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/ScheduledDateGenerator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/domain/ScheduledDateGenerator.java @@ -14,7 +14,8 @@ import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType; public interface ScheduledDateGenerator { - List generate(LoanApplicationTerms loanApplicationTerms, boolean isHolidayEnabled, List holidays, final WorkingDays workingDays); + List generate(LoanApplicationTerms loanApplicationTerms, boolean isHolidayEnabled, List holidays, + final WorkingDays workingDays); LocalDate idealDisbursementDateBasedOnFirstRepaymentDate(PeriodFrequencyType repaymentPeriodFrequencyType, int repaidEvery, List scheduledDates); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/service/LoanScheduleAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/service/LoanScheduleAssembler.java index 9634c8be5..344ae5dc6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/service/LoanScheduleAssembler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/service/LoanScheduleAssembler.java @@ -21,8 +21,8 @@ import org.mifosplatform.organisation.monetary.domain.ApplicationCurrency; import org.mifosplatform.organisation.monetary.domain.ApplicationCurrencyRepositoryWrapper; import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; import org.mifosplatform.organisation.monetary.domain.Money; -import org.mifosplatform.organisation.workingdays.domain.WorkingDaysRepositoryWrapper; import org.mifosplatform.organisation.workingdays.domain.WorkingDays; +import org.mifosplatform.organisation.workingdays.domain.WorkingDaysRepositoryWrapper; import org.mifosplatform.organisation.workingdays.service.WorkingDaysUtil; import org.mifosplatform.portfolio.calendar.domain.Calendar; import org.mifosplatform.portfolio.calendar.domain.CalendarRepository; @@ -66,7 +66,7 @@ public class LoanScheduleAssembler { private final CalendarRepository calendarRepository; private final HolidayRepository holidayRepository; private final ConfigurationDomainService configurationDomainService; - private final ClientRepositoryWrapper clientRepository; + private final ClientRepositoryWrapper clientRepository; private final GroupRepositoryWrapper groupRepository; private final WorkingDaysRepositoryWrapper workingDaysRepository; @@ -93,7 +93,7 @@ public class LoanScheduleAssembler { } public LoanApplicationTerms assembleLoanTerms(final JsonElement element) { - final Long loanProductId = fromApiJsonHelper.extractLongNamed("productId", element); + final Long loanProductId = this.fromApiJsonHelper.extractLongNamed("productId", element); final LoanProduct loanProduct = this.loanProductRepository.findOne(loanProductId); if (loanProduct == null) { throw new LoanProductNotFoundException(loanProductId); } @@ -107,28 +107,28 @@ public class LoanScheduleAssembler { final ApplicationCurrency applicationCurrency = this.applicationCurrencyRepository.findOneWithNotFoundDetection(currency); // loan terms - final Integer loanTermFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed("loanTermFrequency", element); - final Integer loanTermFrequencyType = fromApiJsonHelper.extractIntegerWithLocaleNamed("loanTermFrequencyType", element); + final Integer loanTermFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("loanTermFrequency", element); + final Integer loanTermFrequencyType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("loanTermFrequencyType", element); final PeriodFrequencyType loanTermPeriodFrequencyType = PeriodFrequencyType.fromInt(loanTermFrequencyType); - final Integer numberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed("numberOfRepayments", element); - final Integer repaymentEvery = fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element); - final Integer repaymentFrequencyType = fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentFrequencyType", element); + final Integer numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("numberOfRepayments", element); + final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element); + final Integer repaymentFrequencyType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentFrequencyType", element); final PeriodFrequencyType repaymentPeriodFrequencyType = PeriodFrequencyType.fromInt(repaymentFrequencyType); - final Integer amortizationType = fromApiJsonHelper.extractIntegerWithLocaleNamed("amortizationType", element); + final Integer amortizationType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("amortizationType", element); final AmortizationMethod amortizationMethod = AmortizationMethod.fromInt(amortizationType); // interest terms - final Integer interestType = fromApiJsonHelper.extractIntegerWithLocaleNamed("interestType", element); + final Integer interestType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("interestType", element); final InterestMethod interestMethod = InterestMethod.fromInt(interestType); - final Integer interestCalculationPeriodType = fromApiJsonHelper.extractIntegerWithLocaleNamed("interestCalculationPeriodType", + final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("interestCalculationPeriodType", element); final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod .fromInt(interestCalculationPeriodType); - final BigDecimal interestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element); + final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element); final PeriodFrequencyType interestRatePeriodFrequencyType = loanProduct.getInterestPeriodFrequencyType(); final BigDecimal annualNominalInterestRate = this.aprCalculator.calculateFrom(interestRatePeriodFrequencyType, @@ -137,35 +137,40 @@ public class LoanScheduleAssembler { // disbursement details final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); final Money principalMoney = Money.of(currency, principal); - + final LocalDate expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed("expectedDisbursementDate", element); final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper.extractLocalDateNamed("repaymentsStartingFromDate", element); LocalDate calculatedRepaymentsStartingFromDate = repaymentsStartingFromDate; - final Boolean synchDisbursement = fromApiJsonHelper.extractBooleanNamed("syncDisbursementWithMeeting", element); + final Boolean synchDisbursement = this.fromApiJsonHelper.extractBooleanNamed("syncDisbursementWithMeeting", element); final Long calendarId = this.fromApiJsonHelper.extractLongNamed("calendarId", element); Calendar calendar = null; if ((synchDisbursement != null && synchDisbursement.booleanValue()) || (calendarId != null && calendarId != 0)) { calendar = this.calendarRepository.findOne(calendarId); if (calendar == null) { throw new CalendarNotFoundException(calendarId); } - // validate repayment frequency and interval with meeting frequency and interval - PeriodFrequencyType meetingPeriodFrequency = CalendarUtils.getMeetingPeriodFrequencyType(calendar.getRecurrence()); + // validate repayment frequency and interval with meeting frequency + // and interval + final PeriodFrequencyType meetingPeriodFrequency = CalendarUtils.getMeetingPeriodFrequencyType(calendar.getRecurrence()); validateRepaymentFrequencyIsSameAsMeetingFrequency(meetingPeriodFrequency.getValue(), repaymentFrequencyType, CalendarUtils.getInterval(calendar.getRecurrence()), repaymentEvery); } - + if (synchDisbursement != null && synchDisbursement.booleanValue()) { validateDisbursementDateWithMeetingDates(expectedDisbursementDate, calendar); } - - // if calendar is attached (not null) then reschedule repayment dates according to meeting + + // if calendar is attached (not null) then reschedule repayment dates + // according to meeting if (null != calendar) { // TODO : AA - Is it require to reset repaymentsStartingFromDate or // set only if it is not provided (or null) - // Currently provided repaymentsStartingFromDate takes precedence over system generated next meeting date + // Currently provided repaymentsStartingFromDate takes precedence + // over system generated next meeting date if (calculatedRepaymentsStartingFromDate == null) { - // FIXME: AA - Possibility of having next meeting date immediately after disbursement date, - // need to have minimum number of days gap between disbursement and first repayment date. + // FIXME: AA - Possibility of having next meeting date + // immediately after disbursement date, + // need to have minimum number of days gap between disbursement + // and first repayment date. final String frequency = CalendarUtils.getMeetingFrequencyFromPeriodFrequencyType(repaymentPeriodFrequencyType); calculatedRepaymentsStartingFromDate = CalendarUtils.getFirstRepaymentMeetingDate(calendar, expectedDisbursementDate, repaymentEvery, frequency); @@ -177,7 +182,7 @@ public class LoanScheduleAssembler { final Integer graceOnPrincipalPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); final Integer graceOnInterestPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); - final LocalDate interestChargedFromDate = fromApiJsonHelper.extractLocalDateNamed("interestChargedFromDate", element); + final LocalDate interestChargedFromDate = this.fromApiJsonHelper.extractLocalDateNamed("interestChargedFromDate", element); // other final BigDecimal inArrearsTolerance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element); @@ -186,10 +191,10 @@ public class LoanScheduleAssembler { return LoanApplicationTerms.assembleFrom(applicationCurrency, loanTermFrequency, loanTermPeriodFrequencyType, numberOfRepayments, repaymentEvery, repaymentPeriodFrequencyType, amortizationMethod, interestMethod, interestRatePerPeriod, interestRatePeriodFrequencyType, annualNominalInterestRate, interestCalculationPeriodMethod, principalMoney, - expectedDisbursementDate, repaymentsStartingFromDate, calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, graceOnInterestPayment, - graceOnInterestCharged, interestChargedFromDate, inArrearsToleranceMoney); + expectedDisbursementDate, repaymentsStartingFromDate, calculatedRepaymentsStartingFromDate, graceOnPrincipalPayment, + graceOnInterestPayment, graceOnInterestCharged, interestChargedFromDate, inArrearsToleranceMoney); } - + private void validateRepaymentsStartDateWithMeetingDates(final LocalDate repaymentsStartingFromDate, final Calendar calendar) { if (repaymentsStartingFromDate != null && !CalendarUtils.isValidRedurringDate(calendar.getRecurrence(), calendar.getStartDateLocalDate(), @@ -219,7 +224,8 @@ public class LoanScheduleAssembler { throw new MeetingFrequencyMismatchException("loanapplication.repayment.frequency", "Loan repayment frequency period must match that of meeting frequency period", repaymentFrequency); } else if (meetingFrequency.equals(repaymentFrequency)) { - // repayment frequency is same as meeting frequency repayment interval should be same or multiple of meeting interval + // repayment frequency is same as meeting frequency repayment + // interval should be same or multiple of meeting interval if (repaymentInterval % meetingInterval != 0) { // throw exception: Loan product frequency/interval throw new MeetingFrequencyMismatchException("loanapplication.repayment.interval", @@ -228,39 +234,39 @@ public class LoanScheduleAssembler { } } } - + public LoanProductRelatedDetail assembleLoanProductRelatedDetail(final JsonElement element) { - LoanApplicationTerms loanApplicationTerms = assembleLoanTerms(element); + final LoanApplicationTerms loanApplicationTerms = assembleLoanTerms(element); return loanApplicationTerms.toLoanProductRelatedDetail(); } public LoanScheduleModel assembleLoanScheduleFrom(final JsonElement element) { - //This method is getting called from calculate loan schedule. + // This method is getting called from calculate loan schedule. final LoanApplicationTerms loanApplicationTerms = assembleLoanTerms(element); - //Get holiday details + // Get holiday details final boolean isHolidayEnabled = this.configurationDomainService.isRescheduleRepaymentsOnHolidaysEnabled(); - - final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element); - final Long groupId = fromApiJsonHelper.extractLongNamed("groupId", element); - + + final Long clientId = this.fromApiJsonHelper.extractLongNamed("clientId", element); + final Long groupId = this.fromApiJsonHelper.extractLongNamed("groupId", element); + Client client = null; Group group = null; Long officeId = null; - if(clientId != null){ + if (clientId != null) { client = this.clientRepository.findOneWithNotFoundDetection(clientId); officeId = client.getOffice().getId(); - }else if (groupId != null){ + } else if (groupId != null) { group = this.groupRepository.findOneWithNotFoundDetection(groupId); officeId = group.getOffice().getId(); } - + final LocalDate expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed("expectedDisbursementDate", element); final List holidays = this.holidayRepository.findByOfficeIdAndGreaterThanDate(officeId, expectedDisbursementDate.toDate()); final WorkingDays workingDays = this.workingDaysRepository.findOne(); - + validateDisbursementDateIsOnNonWorkingDay(loanApplicationTerms.getExpectedDisbursementDate(), workingDays); validateDisbursementDateIsOnHoliday(loanApplicationTerms.getExpectedDisbursementDate(), isHolidayEnabled, holidays); - + return assembleLoanScheduleFrom(loanApplicationTerms, isHolidayEnabled, holidays, workingDays, element); } @@ -276,17 +282,19 @@ public class LoanScheduleAssembler { final MonetaryCurrency currency = loanApplicationTerms.getCurrency(); final ApplicationCurrency applicationCurrency = this.applicationCurrencyRepository.findOneWithNotFoundDetection(currency); - return loanScheduleGenerator.generate(mc, applicationCurrency, loanApplicationTerms, loanCharges, isHolidayEnabled, holidays, workingDays); + return loanScheduleGenerator.generate(mc, applicationCurrency, loanApplicationTerms, loanCharges, isHolidayEnabled, holidays, + workingDays); } - + private void validateDisbursementDateIsOnNonWorkingDay(final LocalDate disbursementDate, final WorkingDays workingDays) { - if(!WorkingDaysUtil.isWorkingDay(workingDays, disbursementDate)){ + if (!WorkingDaysUtil.isWorkingDay(workingDays, disbursementDate)) { final String errorMessage = "The expected disbursement date cannot be on a non working day"; throw new LoanApplicationDateException("disbursement.date.on.non.working.day", errorMessage, disbursementDate); } } - private void validateDisbursementDateIsOnHoliday(final LocalDate disbursementDate, final boolean isHolidayEnabled, final List holidays) { + private void validateDisbursementDateIsOnHoliday(final LocalDate disbursementDate, final boolean isHolidayEnabled, + final List holidays) { if (isHolidayEnabled) { if (HolidayUtil.isHoliday(disbursementDate, holidays)) { final String errorMessage = "The expected disbursement date cannot be on a holiday"; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/service/LoanScheduleCalculationPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/service/LoanScheduleCalculationPlatformServiceImpl.java index 2cfd8b267..11619237b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/service/LoanScheduleCalculationPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/loanschedule/service/LoanScheduleCalculationPlatformServiceImpl.java @@ -28,7 +28,7 @@ public class LoanScheduleCalculationPlatformServiceImpl implements LoanScheduleC public LoanScheduleModel calculateLoanSchedule(final JsonQuery query) { this.fromApiJsonDeserializer.validate(query.json()); - + return this.loanScheduleAssembler.assembleLoanScheduleFrom(query.parsedJson()); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/CalculateLoanScheduleQueryFromApiJsonHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/CalculateLoanScheduleQueryFromApiJsonHelper.java index 6f528cca9..1880ab1e3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/CalculateLoanScheduleQueryFromApiJsonHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/CalculateLoanScheduleQueryFromApiJsonHelper.java @@ -42,7 +42,7 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { "loanTermFrequencyType", "repaymentFrequencyType", "interestRateFrequencyType", "amortizationType", "interestType", "interestCalculationPeriodType", "expectedDisbursementDate", "repaymentsStartingFromDate", "graceOnPrincipalPayment", "graceOnInterestPayment", "graceOnInterestCharged", "interestChargedFromDate", "submittedOnDate", "submittedOnNote", "locale", - "dateFormat", "charges", "collateral", "syncDisbursementWithMeeting","linkAccountId")); + "dateFormat", "charges", "collateral", "syncDisbursementWithMeeting", "linkAccountId")); private final FromJsonHelper fromApiJsonHelper; @@ -55,37 +55,38 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); + final Long productId = this.fromApiJsonHelper.extractLongNamed("productId", element); baseDataValidator.reset().parameter("productId").value(productId).notNull().integerGreaterThanZero(); - final BigDecimal principal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); + final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); baseDataValidator.reset().parameter("principal").value(principal).notNull().positiveAmount(); final String loanTermFrequencyParameterName = "loanTermFrequency"; - final Integer loanTermFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyParameterName, element); + final Integer loanTermFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyParameterName, element); baseDataValidator.reset().parameter(loanTermFrequencyParameterName).value(loanTermFrequency).notNull().integerGreaterThanZero(); final String loanTermFrequencyTypeParameterName = "loanTermFrequencyType"; - final Integer loanTermFrequencyType = fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyTypeParameterName, element); + final Integer loanTermFrequencyType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyTypeParameterName, + element); baseDataValidator.reset().parameter(loanTermFrequencyTypeParameterName).value(loanTermFrequencyType).notNull().inMinMaxRange(0, 3); final String numberOfRepaymentsParameterName = "numberOfRepayments"; - final Integer numberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element); + final Integer numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element); baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments).notNull().integerGreaterThanZero(); final String repaymentEveryParameterName = "repaymentEvery"; - final Integer repaymentEvery = fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryParameterName, element); + final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryParameterName, element); baseDataValidator.reset().parameter(repaymentEveryParameterName).value(repaymentEvery).notNull().integerGreaterThanZero(); final String repaymentEveryFrequencyTypeParameterName = "repaymentFrequencyType"; - final Integer repaymentEveryType = fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryFrequencyTypeParameterName, + final Integer repaymentEveryType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryFrequencyTypeParameterName, element); baseDataValidator.reset().parameter(repaymentEveryFrequencyTypeParameterName).value(repaymentEveryType).notNull() .inMinMaxRange(0, 3); @@ -97,41 +98,42 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { repaymentEvery, repaymentEveryType); final String interestRatePerPeriodParameterName = "interestRatePerPeriod"; - final BigDecimal interestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, - element); + final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + interestRatePerPeriodParameterName, element); baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod).notNull() .zeroOrPositiveAmount(); final String interestTypeParameterName = "interestType"; - final Integer interestType = fromApiJsonHelper.extractIntegerWithLocaleNamed(interestTypeParameterName, element); + final Integer interestType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(interestTypeParameterName, element); baseDataValidator.reset().parameter(interestTypeParameterName).value(interestType).notNull().inMinMaxRange(0, 1); final String interestCalculationPeriodTypeParameterName = "interestCalculationPeriodType"; - final Integer interestCalculationPeriodType = fromApiJsonHelper.extractIntegerWithLocaleNamed( + final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( interestCalculationPeriodTypeParameterName, element); baseDataValidator.reset().parameter(interestCalculationPeriodTypeParameterName).value(interestCalculationPeriodType).notNull() .inMinMaxRange(0, 1); final String amortizationTypeParameterName = "amortizationType"; - final Integer amortizationType = fromApiJsonHelper.extractIntegerWithLocaleNamed(amortizationTypeParameterName, element); + final Integer amortizationType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(amortizationTypeParameterName, element); baseDataValidator.reset().parameter(amortizationTypeParameterName).value(amortizationType).notNull().inMinMaxRange(0, 1); final String expectedDisbursementDateParameterName = "expectedDisbursementDate"; - final LocalDate expectedDisbursementDate = fromApiJsonHelper.extractLocalDateNamed(expectedDisbursementDateParameterName, element); + final LocalDate expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed(expectedDisbursementDateParameterName, + element); baseDataValidator.reset().parameter(expectedDisbursementDateParameterName).value(expectedDisbursementDate).notNull(); LocalDate repaymentsStartingFromDate = null; final String repaymentsStartingFromDateParameterName = "repaymentsStartingFromDate"; - if (fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) { - repaymentsStartingFromDate = fromApiJsonHelper.extractLocalDateNamed(repaymentsStartingFromDateParameterName, element); + if (this.fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) { + repaymentsStartingFromDate = this.fromApiJsonHelper.extractLocalDateNamed(repaymentsStartingFromDateParameterName, element); baseDataValidator.reset().parameter(repaymentsStartingFromDateParameterName).value(repaymentsStartingFromDate).ignoreIfNull() .notNull(); } LocalDate interestChargedFromDate = null; final String interestChargedFromDateParameterName = "interestChargedFromDate"; - if (fromApiJsonHelper.parameterExists(interestChargedFromDateParameterName, element)) { - interestChargedFromDate = fromApiJsonHelper.extractLocalDateNamed(interestChargedFromDateParameterName, element); + if (this.fromApiJsonHelper.parameterExists(interestChargedFromDateParameterName, element)) { + interestChargedFromDate = this.fromApiJsonHelper.extractLocalDateNamed(interestChargedFromDateParameterName, element); baseDataValidator.reset().parameter(interestChargedFromDateParameterName).value(interestChargedFromDate).ignoreIfNull() .notNull(); } @@ -143,17 +145,17 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { repaymentsStartingFromDate, interestChargedFromDate); final String transactionProcessingStrategyIdParameterName = "transactionProcessingStrategyId"; - final Long transactionProcessingStrategyId = fromApiJsonHelper.extractLongNamed(transactionProcessingStrategyIdParameterName, + final Long transactionProcessingStrategyId = this.fromApiJsonHelper.extractLongNamed(transactionProcessingStrategyIdParameterName, element); baseDataValidator.reset().parameter(transactionProcessingStrategyIdParameterName).value(transactionProcessingStrategyId).notNull() .integerGreaterThanZero(); // charges final String chargesParameterName = "charges"; - if (element.isJsonObject() && fromApiJsonHelper.parameterExists(chargesParameterName, element)) { + if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(chargesParameterName, element)) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final String dateFormat = fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); - final Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.get(chargesParameterName).isJsonArray()) { final Type arrayObjectParameterTypeOfMap = new TypeToken>() {}.getType(); @@ -165,40 +167,41 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { final JsonObject loanChargeElement = array.get(i - 1).getAsJsonObject(); final String arrayObjectJson = this.fromApiJsonHelper.toJson(loanChargeElement); - fromApiJsonHelper.checkForUnsupportedParameters(arrayObjectParameterTypeOfMap, arrayObjectJson, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(arrayObjectParameterTypeOfMap, arrayObjectJson, + supportedParameters); - final Long chargeId = fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement); + final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement); baseDataValidator.reset().parameter("charges").parameterAtIndexArray("chargeId", i).value(chargeId).notNull() .integerGreaterThanZero(); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalNamed("amount", loanChargeElement, locale); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount", loanChargeElement, locale); baseDataValidator.reset().parameter("charges").parameterAtIndexArray("amount", i).value(amount).notNull() .positiveAmount(); - fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale); + this.fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale); } } } - + boolean meetingIdRequired = false; - //validate syncDisbursement + // validate syncDisbursement final String syncDisbursementParameterName = "syncDisbursementWithMeeting"; - if (fromApiJsonHelper.parameterExists(syncDisbursementParameterName, element)) { - final Boolean syncDisbursement = fromApiJsonHelper.extractBooleanNamed(syncDisbursementParameterName, element); - if(syncDisbursement == null){ - baseDataValidator.reset().parameter(syncDisbursementParameterName).value(syncDisbursement).trueOrFalseRequired(false); - }else if(syncDisbursement.booleanValue()) { - meetingIdRequired = true; - } + if (this.fromApiJsonHelper.parameterExists(syncDisbursementParameterName, element)) { + final Boolean syncDisbursement = this.fromApiJsonHelper.extractBooleanNamed(syncDisbursementParameterName, element); + if (syncDisbursement == null) { + baseDataValidator.reset().parameter(syncDisbursementParameterName).value(syncDisbursement).trueOrFalseRequired(false); + } else if (syncDisbursement.booleanValue()) { + meetingIdRequired = true; + } } - + final String calendarIdParameterName = "calendarId"; - //if disbursement is synced then must have a meeting (calendar) - if (meetingIdRequired || fromApiJsonHelper.parameterExists(calendarIdParameterName, element)) { - final Long calendarId = fromApiJsonHelper.extractLongNamed(calendarIdParameterName, element); - baseDataValidator.reset().parameter(calendarIdParameterName).value(calendarId).notNull().integerGreaterThanZero(); + // if disbursement is synced then must have a meeting (calendar) + if (meetingIdRequired || this.fromApiJsonHelper.parameterExists(calendarIdParameterName, element)) { + final Long calendarId = this.fromApiJsonHelper.extractLongNamed(calendarIdParameterName, element); + baseDataValidator.reset().parameter(calendarIdParameterName).value(calendarId).notNull().integerGreaterThanZero(); } - + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } } @@ -207,16 +210,16 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { final Integer loanTermFrequency, final Integer loanTermFrequencyType, final Integer numberOfRepayments, final Integer repaymentEvery, final Integer repaymentEveryType) { if (loanTermFrequencyType != null && !loanTermFrequencyType.equals(repaymentEveryType)) { - ApiParameterError error = ApiParameterError.parameterError( + final ApiParameterError error = ApiParameterError.parameterError( "validation.msg.loan.loanTermFrequencyType.not.the.same.as.repaymentFrequencyType", "The parameters loanTermFrequencyType and repaymentFrequencyType must be the same.", "loanTermFrequencyType", loanTermFrequencyType, repaymentEveryType); dataValidationErrors.add(error); } else { if (loanTermFrequency != null && repaymentEvery != null && numberOfRepayments != null) { - int suggestsedLoanTerm = repaymentEvery * numberOfRepayments; + final int suggestsedLoanTerm = repaymentEvery * numberOfRepayments; if (loanTermFrequency.intValue() < suggestsedLoanTerm) { - ApiParameterError error = ApiParameterError + final ApiParameterError error = ApiParameterError .parameterError( "validation.msg.loan.loanTermFrequency.less.than.repayment.structure.suggests", "The parameter loanTermFrequency is less than the suggest loan term as indicated by numberOfRepayments and repaymentEvery.", @@ -231,7 +234,7 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { final LocalDate expectedDisbursementDate, final LocalDate repaymentsStartingFromDate, final LocalDate interestChargedFromDate) { if (repaymentsStartingFromDate != null && interestChargedFromDate == null) { - ApiParameterError error = ApiParameterError.parameterError( + final ApiParameterError error = ApiParameterError.parameterError( "validation.msg.loan.interestChargedFromDate.must.be.entered.when.using.repayments.startfrom.field", "The parameter interestChargedFromDate cannot be empty when repaymentsStartingFromDate is provided.", "interestChargedFromDate", repaymentsStartingFromDate); @@ -239,7 +242,7 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { } else if (repaymentsStartingFromDate == null && interestChargedFromDate != null) { if (expectedDisbursementDate != null && expectedDisbursementDate.isAfter(interestChargedFromDate)) { - ApiParameterError error = ApiParameterError.parameterError( + final ApiParameterError error = ApiParameterError.parameterError( "validation.msg.loan.interestChargedFromDate.cannot.be.before.disbursement.date", "The parameter interestChargedFromDate cannot be before the date given for expectedDisbursementDate.", "interestChargedFromDate", interestChargedFromDate, expectedDisbursementDate); @@ -252,7 +255,7 @@ public final class CalculateLoanScheduleQueryFromApiJsonHelper { final LocalDate expectedDisbursementDate, final LocalDate repaymentsStartingFromDate) { if (expectedDisbursementDate != null) { if (repaymentsStartingFromDate != null && expectedDisbursementDate.isAfter(repaymentsStartingFromDate)) { - ApiParameterError error = ApiParameterError.parameterError( + final ApiParameterError error = ApiParameterError.parameterError( "validation.msg.loan.expectedDisbursementDate.cannot.be.after.first.repayment.date", "The parameter expectedDisbursementDate has a date which falls after the date for repaymentsStartingFromDate.", "expectedDisbursementDate", expectedDisbursementDate, repaymentsStartingFromDate); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanApplicationCommandFromApiJsonHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanApplicationCommandFromApiJsonHelper.java index a0a28bb3a..3fc5de7ae 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanApplicationCommandFromApiJsonHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanApplicationCommandFromApiJsonHelper.java @@ -50,9 +50,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { "loanPurposeId", "inArrearsTolerance", "charges", "collateral", // optional "transactionProcessingStrategyId", // settings "calendarId", // optional - "syncDisbursementWithMeeting",//optional - "linkAccountId" - )); + "syncDisbursementWithMeeting",// optional + "linkAccountId")); private final FromJsonHelper fromApiJsonHelper; private final CalculateLoanScheduleQueryFromApiJsonHelper apiJsonHelper; @@ -68,23 +67,23 @@ public final class LoanApplicationCommandFromApiJsonHelper { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); final String loanTypeParameterName = "loanType"; - final String loanTypeStr = fromApiJsonHelper.extractStringNamed(loanTypeParameterName, element); + final String loanTypeStr = this.fromApiJsonHelper.extractStringNamed(loanTypeParameterName, element); baseDataValidator.reset().parameter(loanTypeParameterName).value(loanTypeStr).notNull(); if (!StringUtils.isBlank(loanTypeStr)) { final AccountType loanType = AccountType.fromName(loanTypeStr); baseDataValidator.reset().parameter(loanTypeParameterName).value(loanType.getValue()).inMinMaxRange(1, 3); - final Long clientId = fromApiJsonHelper.extractLongNamed("clientId", element); - final Long groupId = fromApiJsonHelper.extractLongNamed("groupId", element); + final Long clientId = this.fromApiJsonHelper.extractLongNamed("clientId", element); + final Long groupId = this.fromApiJsonHelper.extractLongNamed("groupId", element); if (loanType.isIndividualAccount()) { baseDataValidator.reset().parameter("clientId").value(clientId).notNull().longGreaterThanZero(); baseDataValidator.reset().parameter("groupId").value(groupId).mustBeBlankWhenParameterProvided("clientId", clientId); @@ -102,155 +101,155 @@ public final class LoanApplicationCommandFromApiJsonHelper { } - final Long productId = fromApiJsonHelper.extractLongNamed("productId", element); + final Long productId = this.fromApiJsonHelper.extractLongNamed("productId", element); baseDataValidator.reset().parameter("productId").value(productId).notNull().integerGreaterThanZero(); final String accountNoParameterName = "accountNo"; - if (fromApiJsonHelper.parameterExists(accountNoParameterName, element)) { - final String accountNo = fromApiJsonHelper.extractStringNamed(accountNoParameterName, element); + if (this.fromApiJsonHelper.parameterExists(accountNoParameterName, element)) { + final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParameterName, element); baseDataValidator.reset().parameter(accountNoParameterName).value(accountNo).ignoreIfNull().notExceedingLengthOf(20); } final String externalIdParameterName = "externalId"; - if (fromApiJsonHelper.parameterExists(externalIdParameterName, element)) { - final String externalId = fromApiJsonHelper.extractStringNamed(externalIdParameterName, element); + if (this.fromApiJsonHelper.parameterExists(externalIdParameterName, element)) { + final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParameterName, element); baseDataValidator.reset().parameter(externalIdParameterName).value(externalId).ignoreIfNull().notExceedingLengthOf(100); } final String fundIdParameterName = "fundId"; - if (fromApiJsonHelper.parameterExists(fundIdParameterName, element)) { - final Long fundId = fromApiJsonHelper.extractLongNamed(fundIdParameterName, element); + if (this.fromApiJsonHelper.parameterExists(fundIdParameterName, element)) { + final Long fundId = this.fromApiJsonHelper.extractLongNamed(fundIdParameterName, element); baseDataValidator.reset().parameter(fundIdParameterName).value(fundId).ignoreIfNull().integerGreaterThanZero(); } final String loanOfficerIdParameterName = "loanOfficerId"; - if (fromApiJsonHelper.parameterExists(loanOfficerIdParameterName, element)) { - final Long loanOfficerId = fromApiJsonHelper.extractLongNamed(loanOfficerIdParameterName, element); + if (this.fromApiJsonHelper.parameterExists(loanOfficerIdParameterName, element)) { + final Long loanOfficerId = this.fromApiJsonHelper.extractLongNamed(loanOfficerIdParameterName, element); baseDataValidator.reset().parameter(loanOfficerIdParameterName).value(loanOfficerId).ignoreIfNull().integerGreaterThanZero(); } final String loanPurposeIdParameterName = "loanPurposeId"; - if (fromApiJsonHelper.parameterExists(loanPurposeIdParameterName, element)) { - final Long loanPurposeId = fromApiJsonHelper.extractLongNamed(loanPurposeIdParameterName, element); + if (this.fromApiJsonHelper.parameterExists(loanPurposeIdParameterName, element)) { + final Long loanPurposeId = this.fromApiJsonHelper.extractLongNamed(loanPurposeIdParameterName, element); baseDataValidator.reset().parameter(loanPurposeIdParameterName).value(loanPurposeId).ignoreIfNull().integerGreaterThanZero(); } - final BigDecimal principal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); + final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); baseDataValidator.reset().parameter("principal").value(principal).notNull().positiveAmount(); final String loanTermFrequencyParameterName = "loanTermFrequency"; - final Integer loanTermFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyParameterName, element); + final Integer loanTermFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyParameterName, element); baseDataValidator.reset().parameter(loanTermFrequencyParameterName).value(loanTermFrequency).notNull().integerGreaterThanZero(); final String loanTermFrequencyTypeParameterName = "loanTermFrequencyType"; - final Integer loanTermFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(loanTermFrequencyTypeParameterName, element); + final Integer loanTermFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(loanTermFrequencyTypeParameterName, + element); baseDataValidator.reset().parameter(loanTermFrequencyTypeParameterName).value(loanTermFrequencyType).notNull().inMinMaxRange(0, 3); final String numberOfRepaymentsParameterName = "numberOfRepayments"; - final Integer numberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element); + final Integer numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element); baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments).notNull().integerGreaterThanZero(); final String repaymentEveryParameterName = "repaymentEvery"; - final Integer repaymentEvery = fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryParameterName, element); + final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryParameterName, element); baseDataValidator.reset().parameter(repaymentEveryParameterName).value(repaymentEvery).notNull().integerGreaterThanZero(); final String repaymentEveryFrequencyTypeParameterName = "repaymentFrequencyType"; - final Integer repaymentEveryType = fromApiJsonHelper.extractIntegerSansLocaleNamed(repaymentEveryFrequencyTypeParameterName, + final Integer repaymentEveryType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(repaymentEveryFrequencyTypeParameterName, element); baseDataValidator.reset().parameter(repaymentEveryFrequencyTypeParameterName).value(repaymentEveryType).notNull() .inMinMaxRange(0, 3); final String interestRatePerPeriodParameterName = "interestRatePerPeriod"; - final BigDecimal interestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, - element); + final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + interestRatePerPeriodParameterName, element); baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod).notNull() .zeroOrPositiveAmount(); final String interestTypeParameterName = "interestType"; - final Integer interestType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestTypeParameterName, element); + final Integer interestType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(interestTypeParameterName, element); baseDataValidator.reset().parameter(interestTypeParameterName).value(interestType).notNull().inMinMaxRange(0, 1); final String interestCalculationPeriodTypeParameterName = "interestCalculationPeriodType"; - final Integer interestCalculationPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationPeriodTypeParameterName, element); baseDataValidator.reset().parameter(interestCalculationPeriodTypeParameterName).value(interestCalculationPeriodType).notNull() .inMinMaxRange(0, 1); final String amortizationTypeParameterName = "amortizationType"; - final Integer amortizationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(amortizationTypeParameterName, element); + final Integer amortizationType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(amortizationTypeParameterName, element); baseDataValidator.reset().parameter(amortizationTypeParameterName).value(amortizationType).notNull().inMinMaxRange(0, 1); final String expectedDisbursementDateParameterName = "expectedDisbursementDate"; - final LocalDate expectedDisbursementDate = fromApiJsonHelper.extractLocalDateNamed(expectedDisbursementDateParameterName, element); + final LocalDate expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed(expectedDisbursementDateParameterName, + element); baseDataValidator.reset().parameter(expectedDisbursementDateParameterName).value(expectedDisbursementDate).notNull(); // grace validation - final Integer graceOnPrincipalPayment = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); + final Integer graceOnPrincipalPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment).zeroOrPositiveAmount(); - final Integer graceOnInterestPayment = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); + final Integer graceOnInterestPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment).zeroOrPositiveAmount(); - final Integer graceOnInterestCharged = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); + final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged).zeroOrPositiveAmount(); final String interestChargedFromDateParameterName = "interestChargedFromDate"; - if (fromApiJsonHelper.parameterExists(interestChargedFromDateParameterName, element)) { - final LocalDate interestChargedFromDate = fromApiJsonHelper - .extractLocalDateNamed(interestChargedFromDateParameterName, element); + if (this.fromApiJsonHelper.parameterExists(interestChargedFromDateParameterName, element)) { + final LocalDate interestChargedFromDate = this.fromApiJsonHelper.extractLocalDateNamed(interestChargedFromDateParameterName, + element); baseDataValidator.reset().parameter(interestChargedFromDateParameterName).value(interestChargedFromDate).ignoreIfNull() .notNull(); } final String repaymentsStartingFromDateParameterName = "repaymentsStartingFromDate"; - if (fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) { - final LocalDate repaymentsStartingFromDate = fromApiJsonHelper.extractLocalDateNamed(repaymentsStartingFromDateParameterName, - element); + if (this.fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) { + final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper.extractLocalDateNamed( + repaymentsStartingFromDateParameterName, element); baseDataValidator.reset().parameter(repaymentsStartingFromDateParameterName).value(repaymentsStartingFromDate).ignoreIfNull() .notNull(); } final String inArrearsToleranceParameterName = "inArrearsTolerance"; - if (fromApiJsonHelper.parameterExists(inArrearsToleranceParameterName, element)) { - final BigDecimal inArrearsTolerance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(inArrearsToleranceParameterName, + if (this.fromApiJsonHelper.parameterExists(inArrearsToleranceParameterName, element)) { + final BigDecimal inArrearsTolerance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(inArrearsToleranceParameterName, element); baseDataValidator.reset().parameter(inArrearsToleranceParameterName).value(inArrearsTolerance).ignoreIfNull() .zeroOrPositiveAmount(); } final String submittedOnDateParameterName = "submittedOnDate"; - final LocalDate submittedOnDate = fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParameterName, element); + final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParameterName, element); if (submittedOnDate == null) { baseDataValidator.reset().parameter(submittedOnDateParameterName).value(submittedOnDate).notNull(); } final String submittedOnNoteParameterName = "submittedOnNote"; - if (fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) { - final String submittedOnNote = fromApiJsonHelper.extractStringNamed(submittedOnNoteParameterName, element); + if (this.fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) { + final String submittedOnNote = this.fromApiJsonHelper.extractStringNamed(submittedOnNoteParameterName, element); baseDataValidator.reset().parameter(submittedOnNoteParameterName).value(submittedOnNote).ignoreIfNull() .notExceedingLengthOf(500); } final String transactionProcessingStrategyIdParameterName = "transactionProcessingStrategyId"; - final Long transactionProcessingStrategyId = fromApiJsonHelper.extractLongNamed(transactionProcessingStrategyIdParameterName, + final Long transactionProcessingStrategyId = this.fromApiJsonHelper.extractLongNamed(transactionProcessingStrategyIdParameterName, element); baseDataValidator.reset().parameter(transactionProcessingStrategyIdParameterName).value(transactionProcessingStrategyId).notNull() .integerGreaterThanZero(); - + final String linkAccountIdParameterName = "linkAccountId"; - if (fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) { - final Long linkAccountId = fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element); - baseDataValidator.reset().parameter(linkAccountIdParameterName).value(linkAccountId).ignoreIfNull() - .longGreaterThanZero(); + if (this.fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) { + final Long linkAccountId = this.fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element); + baseDataValidator.reset().parameter(linkAccountIdParameterName).value(linkAccountId).ignoreIfNull().longGreaterThanZero(); } - // charges final String chargesParameterName = "charges"; - if (element.isJsonObject() && fromApiJsonHelper.parameterExists(chargesParameterName, element)) { + if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(chargesParameterName, element)) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final String dateFormat = fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); - final Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.get(chargesParameterName).isJsonArray()) { final Type arrayObjectParameterTypeOfMap = new TypeToken>() {}.getType(); @@ -262,26 +261,27 @@ public final class LoanApplicationCommandFromApiJsonHelper { final JsonObject loanChargeElement = array.get(i - 1).getAsJsonObject(); final String arrayObjectJson = this.fromApiJsonHelper.toJson(loanChargeElement); - fromApiJsonHelper.checkForUnsupportedParameters(arrayObjectParameterTypeOfMap, arrayObjectJson, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(arrayObjectParameterTypeOfMap, arrayObjectJson, + supportedParameters); - final Long chargeId = fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement); + final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement); baseDataValidator.reset().parameter("charges").parameterAtIndexArray("chargeId", i).value(chargeId).notNull() .integerGreaterThanZero(); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalNamed("amount", loanChargeElement, locale); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount", loanChargeElement, locale); baseDataValidator.reset().parameter("charges").parameterAtIndexArray("amount", i).value(amount).notNull() .positiveAmount(); - fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale); + this.fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale); } } } // collateral final String collateralParameterName = "collateral"; - if (element.isJsonObject() && fromApiJsonHelper.parameterExists(collateralParameterName, element)) { + if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(collateralParameterName, element)) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.get("collateral").isJsonArray()) { final Type collateralParameterTypeOfMap = new TypeToken>() {}.getType(); @@ -291,17 +291,18 @@ public final class LoanApplicationCommandFromApiJsonHelper { final JsonObject collateralItemElement = array.get(i - 1).getAsJsonObject(); final String collateralJson = this.fromApiJsonHelper.toJson(collateralItemElement); - fromApiJsonHelper.checkForUnsupportedParameters(collateralParameterTypeOfMap, collateralJson, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(collateralParameterTypeOfMap, collateralJson, supportedParameters); - final Long collateralTypeId = fromApiJsonHelper.extractLongNamed("type", collateralItemElement); + final Long collateralTypeId = this.fromApiJsonHelper.extractLongNamed("type", collateralItemElement); baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("type", i).value(collateralTypeId).notNull() .integerGreaterThanZero(); - final BigDecimal collateralValue = fromApiJsonHelper.extractBigDecimalNamed("value", collateralItemElement, locale); + final BigDecimal collateralValue = this.fromApiJsonHelper + .extractBigDecimalNamed("value", collateralItemElement, locale); baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("value", i).value(collateralValue) .ignoreIfNull().positiveAmount(); - final String description = fromApiJsonHelper.extractStringNamed("description", collateralItemElement); + final String description = this.fromApiJsonHelper.extractStringNamed("description", collateralItemElement); baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("description", i).value(description).notBlank() .notExceedingLengthOf(500); @@ -312,22 +313,22 @@ public final class LoanApplicationCommandFromApiJsonHelper { } boolean meetingIdRequired = false; - //validate syncDisbursement + // validate syncDisbursement final String syncDisbursementParameterName = "syncDisbursementWithMeeting"; - if (fromApiJsonHelper.parameterExists(syncDisbursementParameterName, element)) { - final Boolean syncDisbursement = fromApiJsonHelper.extractBooleanNamed(syncDisbursementParameterName, element); - if(syncDisbursement == null){ - baseDataValidator.reset().parameter(syncDisbursementParameterName).value(syncDisbursement).trueOrFalseRequired(false); - }else if(syncDisbursement.booleanValue()) { - meetingIdRequired = true; - } + if (this.fromApiJsonHelper.parameterExists(syncDisbursementParameterName, element)) { + final Boolean syncDisbursement = this.fromApiJsonHelper.extractBooleanNamed(syncDisbursementParameterName, element); + if (syncDisbursement == null) { + baseDataValidator.reset().parameter(syncDisbursementParameterName).value(syncDisbursement).trueOrFalseRequired(false); + } else if (syncDisbursement.booleanValue()) { + meetingIdRequired = true; + } } - + final String calendarIdParameterName = "calendarId"; - //if disbursement is synced then must have a meeting (calendar) - if (meetingIdRequired || fromApiJsonHelper.parameterExists(calendarIdParameterName, element)) { - final Long calendarId = fromApiJsonHelper.extractLongNamed(calendarIdParameterName, element); - baseDataValidator.reset().parameter(calendarIdParameterName).value(calendarId).notNull().integerGreaterThanZero(); + // if disbursement is synced then must have a meeting (calendar) + if (meetingIdRequired || this.fromApiJsonHelper.parameterExists(calendarIdParameterName, element)) { + final Long calendarId = this.fromApiJsonHelper.extractLongNamed(calendarIdParameterName, element); + baseDataValidator.reset().parameter(calendarIdParameterName).value(calendarId).notNull().integerGreaterThanZero(); } if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } @@ -337,230 +338,233 @@ public final class LoanApplicationCommandFromApiJsonHelper { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); boolean atLeastOneParameterPassedForUpdate = false; final String clientIdParameterName = "clientId"; - if (fromApiJsonHelper.parameterExists(clientIdParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(clientIdParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Long clientId = fromApiJsonHelper.extractLongNamed(clientIdParameterName, element); + final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParameterName, element); baseDataValidator.reset().parameter(clientIdParameterName).value(clientId).notNull().integerGreaterThanZero(); } final String groupIdParameterName = "groupId"; - if (fromApiJsonHelper.parameterExists(groupIdParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(groupIdParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Long groupId = fromApiJsonHelper.extractLongNamed(groupIdParameterName, element); + final Long groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParameterName, element); baseDataValidator.reset().parameter(groupIdParameterName).value(groupId).notNull().integerGreaterThanZero(); } final String productIdParameterName = "productId"; - if (fromApiJsonHelper.parameterExists(productIdParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(productIdParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Long productId = fromApiJsonHelper.extractLongNamed(productIdParameterName, element); + final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParameterName, element); baseDataValidator.reset().parameter(productIdParameterName).value(productId).notNull().integerGreaterThanZero(); } final String accountNoParameterName = "accountNo"; - if (fromApiJsonHelper.parameterExists(accountNoParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(accountNoParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final String accountNo = fromApiJsonHelper.extractStringNamed(accountNoParameterName, element); + final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParameterName, element); baseDataValidator.reset().parameter(accountNoParameterName).value(accountNo).notBlank().notExceedingLengthOf(20); } final String externalIdParameterName = "externalId"; - if (fromApiJsonHelper.parameterExists(externalIdParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(externalIdParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final String externalId = fromApiJsonHelper.extractStringNamed(externalIdParameterName, element); + final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParameterName, element); baseDataValidator.reset().parameter(externalIdParameterName).value(externalId).ignoreIfNull().notExceedingLengthOf(100); } final String fundIdParameterName = "fundId"; - if (fromApiJsonHelper.parameterExists(fundIdParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(fundIdParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Long fundId = fromApiJsonHelper.extractLongNamed(fundIdParameterName, element); + final Long fundId = this.fromApiJsonHelper.extractLongNamed(fundIdParameterName, element); baseDataValidator.reset().parameter(fundIdParameterName).value(fundId).ignoreIfNull().integerGreaterThanZero(); } final String loanOfficerIdParameterName = "loanOfficerId"; - if (fromApiJsonHelper.parameterExists(loanOfficerIdParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(loanOfficerIdParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Long loanOfficerId = fromApiJsonHelper.extractLongNamed(loanOfficerIdParameterName, element); + final Long loanOfficerId = this.fromApiJsonHelper.extractLongNamed(loanOfficerIdParameterName, element); baseDataValidator.reset().parameter(loanOfficerIdParameterName).value(loanOfficerId).ignoreIfNull().integerGreaterThanZero(); } final String transactionProcessingStrategyIdParameterName = "transactionProcessingStrategyId"; - if (fromApiJsonHelper.parameterExists(transactionProcessingStrategyIdParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(transactionProcessingStrategyIdParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Long transactionProcessingStrategyId = fromApiJsonHelper.extractLongNamed(transactionProcessingStrategyIdParameterName, - element); + final Long transactionProcessingStrategyId = this.fromApiJsonHelper.extractLongNamed( + transactionProcessingStrategyIdParameterName, element); baseDataValidator.reset().parameter(transactionProcessingStrategyIdParameterName).value(transactionProcessingStrategyId) .notNull().integerGreaterThanZero(); } final String principalParameterName = "principal"; - if (fromApiJsonHelper.parameterExists(principalParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(principalParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final BigDecimal principal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName, element); + final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName, element); baseDataValidator.reset().parameter(principalParameterName).value(principal).notNull().positiveAmount(); } final String inArrearsToleranceParameterName = "inArrearsTolerance"; - if (fromApiJsonHelper.parameterExists(inArrearsToleranceParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(inArrearsToleranceParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final BigDecimal principal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(inArrearsToleranceParameterName, element); + final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(inArrearsToleranceParameterName, element); baseDataValidator.reset().parameter(inArrearsToleranceParameterName).value(principal).ignoreIfNull().positiveAmount(); } final String loanTermFrequencyParameterName = "loanTermFrequency"; - if (fromApiJsonHelper.parameterExists(loanTermFrequencyParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(loanTermFrequencyParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer loanTermFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyParameterName, element); + final Integer loanTermFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyParameterName, element); baseDataValidator.reset().parameter(loanTermFrequencyParameterName).value(loanTermFrequency).notNull().integerGreaterThanZero(); } final String loanTermFrequencyTypeParameterName = "loanTermFrequencyType"; - if (fromApiJsonHelper.parameterExists(loanTermFrequencyTypeParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(loanTermFrequencyTypeParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer loanTermFrequencyType = fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyTypeParameterName, + final Integer loanTermFrequencyType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(loanTermFrequencyTypeParameterName, element); baseDataValidator.reset().parameter(loanTermFrequencyTypeParameterName).value(loanTermFrequencyType).notNull() .inMinMaxRange(0, 3); } final String numberOfRepaymentsParameterName = "numberOfRepayments"; - if (fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer numberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element); + final Integer numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, + element); baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments).notNull() .integerGreaterThanZero(); } final String repaymentEveryParameterName = "repaymentEvery"; - if (fromApiJsonHelper.parameterExists(repaymentEveryParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(repaymentEveryParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer repaymentEvery = fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryParameterName, element); + final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryParameterName, element); baseDataValidator.reset().parameter(repaymentEveryParameterName).value(repaymentEvery).notNull().integerGreaterThanZero(); } final String repaymentEveryTypeParameterName = "repaymentFrequencyType"; - if (fromApiJsonHelper.parameterExists(repaymentEveryTypeParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(repaymentEveryTypeParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer repaymentEveryType = fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryTypeParameterName, element); + final Integer repaymentEveryType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(repaymentEveryTypeParameterName, + element); baseDataValidator.reset().parameter(repaymentEveryTypeParameterName).value(repaymentEveryType).notNull().inMinMaxRange(0, 3); } final String interestRatePerPeriodParameterName = "interestRatePerPeriod"; - if (fromApiJsonHelper.parameterExists(interestRatePerPeriodParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(interestRatePerPeriodParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final BigDecimal interestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, - element); + final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + interestRatePerPeriodParameterName, element); baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod).notNull() .zeroOrPositiveAmount(); } final String interestTypeParameterName = "interestType"; - if (fromApiJsonHelper.parameterExists(interestTypeParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(interestTypeParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer interestType = fromApiJsonHelper.extractIntegerWithLocaleNamed(interestTypeParameterName, element); + final Integer interestType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(interestTypeParameterName, element); baseDataValidator.reset().parameter(interestTypeParameterName).value(interestType).notNull().inMinMaxRange(0, 1); } final String interestCalculationPeriodTypeParameterName = "interestCalculationPeriodType"; - if (fromApiJsonHelper.parameterExists(interestCalculationPeriodTypeParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(interestCalculationPeriodTypeParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer interestCalculationPeriodType = fromApiJsonHelper.extractIntegerWithLocaleNamed( + final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed( interestCalculationPeriodTypeParameterName, element); baseDataValidator.reset().parameter(interestCalculationPeriodTypeParameterName).value(interestCalculationPeriodType).notNull() .inMinMaxRange(0, 1); } final String amortizationTypeParameterName = "amortizationType"; - if (fromApiJsonHelper.parameterExists(amortizationTypeParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(amortizationTypeParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Integer amortizationType = fromApiJsonHelper.extractIntegerWithLocaleNamed(amortizationTypeParameterName, element); + final Integer amortizationType = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(amortizationTypeParameterName, element); baseDataValidator.reset().parameter(amortizationTypeParameterName).value(amortizationType).notNull().inMinMaxRange(0, 1); } final String expectedDisbursementDateParameterName = "expectedDisbursementDate"; - if (fromApiJsonHelper.parameterExists(expectedDisbursementDateParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(expectedDisbursementDateParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final String expectedDisbursementDateStr = fromApiJsonHelper.extractStringNamed(expectedDisbursementDateParameterName, element); + final String expectedDisbursementDateStr = this.fromApiJsonHelper.extractStringNamed(expectedDisbursementDateParameterName, + element); baseDataValidator.reset().parameter(expectedDisbursementDateParameterName).value(expectedDisbursementDateStr).notBlank(); - final LocalDate expectedDisbursementDate = fromApiJsonHelper.extractLocalDateNamed(expectedDisbursementDateParameterName, + final LocalDate expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed(expectedDisbursementDateParameterName, element); baseDataValidator.reset().parameter(expectedDisbursementDateParameterName).value(expectedDisbursementDate).notNull(); } // grace validation - if (fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) { - final Integer graceOnPrincipalPayment = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); + if (this.fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) { + final Integer graceOnPrincipalPayment = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment).zeroOrPositiveAmount(); } - if (fromApiJsonHelper.parameterExists("graceOnInterestPayment", element)) { - final Integer graceOnInterestPayment = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); + if (this.fromApiJsonHelper.parameterExists("graceOnInterestPayment", element)) { + final Integer graceOnInterestPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment).zeroOrPositiveAmount(); } - if (fromApiJsonHelper.parameterExists("graceOnInterestCharged", element)) { - final Integer graceOnInterestCharged = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); + if (this.fromApiJsonHelper.parameterExists("graceOnInterestCharged", element)) { + final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged).zeroOrPositiveAmount(); } final String interestChargedFromDateParameterName = "interestChargedFromDate"; - if (fromApiJsonHelper.parameterExists(interestChargedFromDateParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(interestChargedFromDateParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final LocalDate interestChargedFromDate = fromApiJsonHelper - .extractLocalDateNamed(interestChargedFromDateParameterName, element); + final LocalDate interestChargedFromDate = this.fromApiJsonHelper.extractLocalDateNamed(interestChargedFromDateParameterName, + element); baseDataValidator.reset().parameter(interestChargedFromDateParameterName).value(interestChargedFromDate).ignoreIfNull(); } final String repaymentsStartingFromDateParameterName = "repaymentsStartingFromDate"; - if (fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final LocalDate repaymentsStartingFromDate = fromApiJsonHelper.extractLocalDateNamed(repaymentsStartingFromDateParameterName, - element); + final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper.extractLocalDateNamed( + repaymentsStartingFromDateParameterName, element); baseDataValidator.reset().parameter(repaymentsStartingFromDateParameterName).value(repaymentsStartingFromDate).ignoreIfNull(); } final String submittedOnDateParameterName = "submittedOnDate"; - if (fromApiJsonHelper.parameterExists(submittedOnDateParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(submittedOnDateParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final LocalDate submittedOnDate = fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParameterName, element); + final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParameterName, element); baseDataValidator.reset().parameter(submittedOnDateParameterName).value(submittedOnDate).notNull(); } final String submittedOnNoteParameterName = "submittedOnNote"; - if (fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final String submittedOnNote = fromApiJsonHelper.extractStringNamed(submittedOnNoteParameterName, element); + final String submittedOnNote = this.fromApiJsonHelper.extractStringNamed(submittedOnNoteParameterName, element); baseDataValidator.reset().parameter(submittedOnNoteParameterName).value(submittedOnNote).ignoreIfNull() .notExceedingLengthOf(500); } - + final String linkAccountIdParameterName = "linkAccountId"; - if (fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) { + if (this.fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) { atLeastOneParameterPassedForUpdate = true; - final Long linkAccountId = fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element); - baseDataValidator.reset().parameter(linkAccountIdParameterName).value(linkAccountId).ignoreIfNull() - .longGreaterThanZero(); + final Long linkAccountId = this.fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element); + baseDataValidator.reset().parameter(linkAccountIdParameterName).value(linkAccountId).ignoreIfNull().longGreaterThanZero(); } // charges final String chargesParameterName = "charges"; - if (element.isJsonObject() && fromApiJsonHelper.parameterExists(chargesParameterName, element)) { + if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(chargesParameterName, element)) { atLeastOneParameterPassedForUpdate = true; final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final String dateFormat = fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); - final Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.get(chargesParameterName).isJsonArray()) { final Type arrayObjectParameterTypeOfMap = new TypeToken>() {}.getType(); @@ -572,26 +576,27 @@ public final class LoanApplicationCommandFromApiJsonHelper { final JsonObject loanChargeElement = array.get(i - 1).getAsJsonObject(); final String arrayObjectJson = this.fromApiJsonHelper.toJson(loanChargeElement); - fromApiJsonHelper.checkForUnsupportedParameters(arrayObjectParameterTypeOfMap, arrayObjectJson, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(arrayObjectParameterTypeOfMap, arrayObjectJson, + supportedParameters); - final Long chargeId = fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement); + final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement); baseDataValidator.reset().parameter("charges").parameterAtIndexArray("chargeId", i).value(chargeId).notNull() .integerGreaterThanZero(); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalNamed("amount", loanChargeElement, locale); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount", loanChargeElement, locale); baseDataValidator.reset().parameter("charges").parameterAtIndexArray("amount", i).value(amount).notNull() .positiveAmount(); - fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale); + this.fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale); } } } // collateral final String collateralParameterName = "collateral"; - if (element.isJsonObject() && fromApiJsonHelper.parameterExists(collateralParameterName, element)) { + if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(collateralParameterName, element)) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.get("collateral").isJsonArray()) { final Type collateralParameterTypeOfMap = new TypeToken>() {}.getType(); @@ -601,17 +606,18 @@ public final class LoanApplicationCommandFromApiJsonHelper { final JsonObject collateralItemElement = array.get(i - 1).getAsJsonObject(); final String collateralJson = this.fromApiJsonHelper.toJson(collateralItemElement); - fromApiJsonHelper.checkForUnsupportedParameters(collateralParameterTypeOfMap, collateralJson, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(collateralParameterTypeOfMap, collateralJson, supportedParameters); - final Long collateralTypeId = fromApiJsonHelper.extractLongNamed("type", collateralItemElement); + final Long collateralTypeId = this.fromApiJsonHelper.extractLongNamed("type", collateralItemElement); baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("type", i).value(collateralTypeId).notNull() .integerGreaterThanZero(); - final BigDecimal collateralValue = fromApiJsonHelper.extractBigDecimalNamed("value", collateralItemElement, locale); + final BigDecimal collateralValue = this.fromApiJsonHelper + .extractBigDecimalNamed("value", collateralItemElement, locale); baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("value", i).value(collateralValue) .ignoreIfNull().positiveAmount(); - final String description = fromApiJsonHelper.extractStringNamed("description", collateralItemElement); + final String description = this.fromApiJsonHelper.extractStringNamed("description", collateralItemElement); baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("description", i).value(description).notBlank() .notExceedingLengthOf(500); @@ -622,24 +628,24 @@ public final class LoanApplicationCommandFromApiJsonHelper { } boolean meetingIdRequired = false; - //validate syncDisbursement + // validate syncDisbursement final String syncDisbursementParameterName = "syncDisbursementWithMeeting"; - if (fromApiJsonHelper.parameterExists(syncDisbursementParameterName, element)) { - final Boolean syncDisbursement = fromApiJsonHelper.extractBooleanNamed(syncDisbursementParameterName, element); - if(syncDisbursement == null){ - baseDataValidator.reset().parameter(syncDisbursementParameterName).value(syncDisbursement).trueOrFalseRequired(false); - }else if(syncDisbursement.booleanValue()) { - meetingIdRequired = true; - } + if (this.fromApiJsonHelper.parameterExists(syncDisbursementParameterName, element)) { + final Boolean syncDisbursement = this.fromApiJsonHelper.extractBooleanNamed(syncDisbursementParameterName, element); + if (syncDisbursement == null) { + baseDataValidator.reset().parameter(syncDisbursementParameterName).value(syncDisbursement).trueOrFalseRequired(false); + } else if (syncDisbursement.booleanValue()) { + meetingIdRequired = true; + } } - + final String calendarIdParameterName = "calendarId"; - //if disbursement is synced then must have a meeting (calendar) - if (meetingIdRequired || fromApiJsonHelper.parameterExists(calendarIdParameterName, element)) { - final Long calendarId = fromApiJsonHelper.extractLongNamed(calendarIdParameterName, element); - baseDataValidator.reset().parameter(calendarIdParameterName).value(calendarId).notNull().integerGreaterThanZero(); + // if disbursement is synced then must have a meeting (calendar) + if (meetingIdRequired || this.fromApiJsonHelper.parameterExists(calendarIdParameterName, element)) { + final Long calendarId = this.fromApiJsonHelper.extractLongNamed(calendarIdParameterName, element); + baseDataValidator.reset().parameter(calendarIdParameterName).value(calendarId).notNull().integerGreaterThanZero(); } - + if (!atLeastOneParameterPassedForUpdate) { final Object forceError = null; baseDataValidator.reset().anyOfNotNull(forceError); @@ -654,15 +660,15 @@ public final class LoanApplicationCommandFromApiJsonHelper { final Set undoSupportedParameters = new HashSet(Arrays.asList("note")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, undoSupportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, undoSupportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanapplication.undo"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); final String note = "note"; - if (fromApiJsonHelper.parameterExists(note, element)) { - final String noteText = fromApiJsonHelper.extractStringNamed(note, element); + if (this.fromApiJsonHelper.parameterExists(note, element)) { + final String noteText = this.fromApiJsonHelper.extractStringNamed(note, element); baseDataValidator.reset().parameter(note).value(noteText).notExceedingLengthOf(1000); } @@ -678,8 +684,8 @@ public final class LoanApplicationCommandFromApiJsonHelper { final BigDecimal maxPrincipal = loanProduct.getMaxPrincipalAmount().getAmount(); final String principalParameterName = "principal"; - if (fromApiJsonHelper.parameterExists(principalParameterName, element)) { - final BigDecimal principal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName, element); + if (this.fromApiJsonHelper.parameterExists(principalParameterName, element)) { + final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName, element); baseDataValidator.reset().parameter(principalParameterName).value(principal).notNull().positiveAmount() .inMinAndMaxAmountRange(minPrincipal, maxPrincipal); } @@ -687,7 +693,7 @@ public final class LoanApplicationCommandFromApiJsonHelper { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } } - + public void validateLoanTermAndRepaidEveryValues(final Integer loanTermFrequency, final Integer loanTermFrequencyType, final Integer numberOfRepayments, final Integer repaymentEvery, final Integer repaymentEveryType) { final List dataValidationErrors = new ArrayList(); @@ -696,25 +702,22 @@ public final class LoanApplicationCommandFromApiJsonHelper { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } } - - public void validatelinkedSavingsAccount(final SavingsAccount savingsAccount,final Loan loanApplication) { + + public void validatelinkedSavingsAccount(final SavingsAccount savingsAccount, final Loan loanApplication) { final List dataValidationErrors = new ArrayList(); - if(savingsAccount.isNotActive()){ - ApiParameterError error = ApiParameterError.parameterError( - "validation.msg.loan.linked.savings.account.is.not.active", - "Linked Savings account with id:"+savingsAccount.getId()+ " is not in active state", "linkAccountId", + if (savingsAccount.isNotActive()) { + final ApiParameterError error = ApiParameterError.parameterError("validation.msg.loan.linked.savings.account.is.not.active", + "Linked Savings account with id:" + savingsAccount.getId() + " is not in active state", "linkAccountId", savingsAccount.getId()); dataValidationErrors.add(error); - }else if(loanApplication.getClientId() != savingsAccount.clientId()){ - ApiParameterError error = ApiParameterError.parameterError( - "validation.msg.loan.linked.savings.account.not.belongs.to.same.client", - "Linked Savings account with id:"+savingsAccount.getId()+ " is not belongs to the same client", "linkAccountId", - savingsAccount.getId()); + } else if (loanApplication.getClientId() != savingsAccount.clientId()) { + final ApiParameterError error = ApiParameterError.parameterError( + "validation.msg.loan.linked.savings.account.not.belongs.to.same.client", "Linked Savings account with id:" + + savingsAccount.getId() + " is not belongs to the same client", "linkAccountId", savingsAccount.getId()); dataValidationErrors.add(error); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", + if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", dataValidationErrors); } } - } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanApplicationTransitionApiJsonValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanApplicationTransitionApiJsonValidator.java index 9526f6246..6d3053b25 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanApplicationTransitionApiJsonValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanApplicationTransitionApiJsonValidator.java @@ -45,20 +45,19 @@ public final class LoanApplicationTransitionApiJsonValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } - final Set disbursementParameters = new HashSet(Arrays.asList("approvedOnDate", "note", "locale", - "dateFormat")); + final Set disbursementParameters = new HashSet(Arrays.asList("approvedOnDate", "note", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanapplication"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate approvedOnDate = fromApiJsonHelper.extractLocalDateNamed("approvedOnDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate approvedOnDate = this.fromApiJsonHelper.extractLocalDateNamed("approvedOnDate", element); baseDataValidator.reset().parameter("approvedOnDate").value(approvedOnDate).notNull(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -71,16 +70,16 @@ public final class LoanApplicationTransitionApiJsonValidator { final Set disbursementParameters = new HashSet(Arrays.asList("rejectedOnDate", "note", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanapplication"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate rejectedOnDate = fromApiJsonHelper.extractLocalDateNamed("rejectedOnDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate rejectedOnDate = this.fromApiJsonHelper.extractLocalDateNamed("rejectedOnDate", element); baseDataValidator.reset().parameter("rejectedOnDate").value(rejectedOnDate).notNull(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -93,16 +92,16 @@ public final class LoanApplicationTransitionApiJsonValidator { final Set disbursementParameters = new HashSet(Arrays.asList("withdrawnOnDate", "note", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanapplication"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate withdrawnOnDate = fromApiJsonHelper.extractLocalDateNamed("withdrawnOnDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate withdrawnOnDate = this.fromApiJsonHelper.extractLocalDateNamed("withdrawnOnDate", element); baseDataValidator.reset().parameter("withdrawnOnDate").value(withdrawnOnDate).notNull(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); throwExceptionIfValidationWarningsExist(dataValidationErrors); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanEventApiJsonValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanEventApiJsonValidator.java index 3b48a5046..e8c7d8ced 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanEventApiJsonValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/serialization/LoanEventApiJsonValidator.java @@ -54,16 +54,16 @@ public final class LoanEventApiJsonValidator { "locale", "dateFormat", "paymentTypeId", "accountNumber", "checkNumber", "routingCode", "receiptNumber", "bankNumber")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.disbursement"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate actualDisbursementDate = fromApiJsonHelper.extractLocalDateNamed("actualDisbursementDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate actualDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed("actualDisbursementDate", element); baseDataValidator.reset().parameter("actualDisbursementDate").value(actualDisbursementDate).notNull(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); validatePaymentDetails(baseDataValidator, element); @@ -73,7 +73,7 @@ public final class LoanEventApiJsonValidator { public void validateDisbursementDateWithMeetingDate(final LocalDate actualDisbursementDate, final CalendarInstance calendarInstance) { if (null != calendarInstance) { - Calendar calendar = calendarInstance.getCalendar(); + final Calendar calendar = calendarInstance.getCalendar(); if (calendar != null && actualDisbursementDate != null) { // Disbursement date should fall on a meeting date if (!CalendarUtils.isValidRedurringDate(calendar.getRecurrence(), calendar.getStartDateLocalDate(), actualDisbursementDate)) { @@ -96,19 +96,19 @@ public final class LoanEventApiJsonValidator { "bankNumber")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, transactionParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, transactionParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.transaction"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); baseDataValidator.reset().parameter("transactionDate").value(transactionDate).notNull(); - final BigDecimal transactionAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("transactionAmount", element); + final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("transactionAmount", element); baseDataValidator.reset().parameter("transactionAmount").value(transactionAmount).notNull().zeroOrPositiveAmount(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); validatePaymentDetails(baseDataValidator, element); @@ -124,28 +124,28 @@ public final class LoanEventApiJsonValidator { "bankNumber")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, transactionParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, transactionParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.transaction"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); baseDataValidator.reset().parameter("transactionDate").value(transactionDate).notNull(); - final BigDecimal transactionAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("transactionAmount", element); + final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("transactionAmount", element); baseDataValidator.reset().parameter("transactionAmount").value(transactionAmount).notNull().positiveAmount(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); validatePaymentDetails(baseDataValidator, element); throwExceptionIfValidationWarningsExist(dataValidationErrors); } - public void validateRepaymentDateWithMeetingDate(LocalDate repaymentDate, final CalendarInstance calendarInstance) { + public void validateRepaymentDateWithMeetingDate(final LocalDate repaymentDate, final CalendarInstance calendarInstance) { if (null != calendarInstance) { - Calendar calendar = calendarInstance.getCalendar(); + final Calendar calendar = calendarInstance.getCalendar(); if (calendar != null && repaymentDate != null) { // Disbursement date should fall on a meeting date if (!CalendarUtils.isValidRedurringDate(calendar.getRecurrence(), calendar.getStartDateLocalDate(), repaymentDate)) { @@ -160,12 +160,12 @@ public final class LoanEventApiJsonValidator { private void validatePaymentDetails(final DataValidatorBuilder baseDataValidator, final JsonElement element) { // Validate all string payment detail fields for max length - final Integer paymentTypeId = fromApiJsonHelper.extractIntegerWithLocaleNamed("paymentTypeId", element); + final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("paymentTypeId", element); baseDataValidator.reset().parameter("paymentTypeId").value(paymentTypeId).ignoreIfNull().integerGreaterThanZero(); final Set paymentDetailParameters = new HashSet(Arrays.asList("accountNumber", "checkNumber", "routingCode", "receiptNumber", "bankNumber")); - for (String paymentDetailParameterName : paymentDetailParameters) { - final String paymentDetailParameterValue = fromApiJsonHelper.extractStringNamed(paymentDetailParameterName, element); + for (final String paymentDetailParameterName : paymentDetailParameters) { + final String paymentDetailParameterValue = this.fromApiJsonHelper.extractStringNamed(paymentDetailParameterName, element); baseDataValidator.reset().parameter(paymentDetailParameterName).value(paymentDetailParameterValue).ignoreIfNull() .notExceedingLengthOf(50); } @@ -177,16 +177,16 @@ public final class LoanEventApiJsonValidator { final Set disbursementParameters = new HashSet(Arrays.asList("transactionDate", "note", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loan.transaction"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); baseDataValidator.reset().parameter("transactionDate").value(transactionDate).notNull(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -199,20 +199,20 @@ public final class LoanEventApiJsonValidator { "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanCharge"); - final JsonElement element = fromApiJsonHelper.parse(json); - final Long chargeId = fromApiJsonHelper.extractLongNamed("chargeId", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", element); baseDataValidator.reset().parameter("chargeId").value(chargeId).notNull().integerGreaterThanZero(); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element); baseDataValidator.reset().parameter("amount").value(amount).notNull().positiveAmount(); - if (fromApiJsonHelper.parameterExists("dueDate", element)) { - fromApiJsonHelper.extractLocalDateNamed("dueDate", element); + if (this.fromApiJsonHelper.parameterExists("dueDate", element)) { + this.fromApiJsonHelper.extractLocalDateNamed("dueDate", element); } throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -224,18 +224,18 @@ public final class LoanEventApiJsonValidator { final Set disbursementParameters = new HashSet(Arrays.asList("amount", "dueDate", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanCharge"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("amount", element); baseDataValidator.reset().parameter("amount").value(amount).notNull().positiveAmount(); - if (fromApiJsonHelper.parameterExists("dueDate", element)) { - fromApiJsonHelper.extractLocalDateNamed("dueDate", element); + if (this.fromApiJsonHelper.parameterExists("dueDate", element)) { + this.fromApiJsonHelper.extractLocalDateNamed("dueDate", element); } throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -248,14 +248,14 @@ public final class LoanEventApiJsonValidator { "toLoanOfficerId", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanOfficer"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final Long toLoanOfficerId = fromApiJsonHelper.extractLongNamed("toLoanOfficerId", element); + final Long toLoanOfficerId = this.fromApiJsonHelper.extractLongNamed("toLoanOfficerId", element); baseDataValidator.reset().parameter("toLoanOfficerId").value(toLoanOfficerId).notNull().integerGreaterThanZero(); final String assignmentDateStr = this.fromApiJsonHelper.extractStringNamed("assignmentDate", element); @@ -295,27 +295,27 @@ public final class LoanEventApiJsonValidator { throwExceptionIfValidationWarningsExist(dataValidationErrors); } - public void validateChargePaymentTransaction(final String json,boolean isChargeIdIncluded) { + public void validateChargePaymentTransaction(final String json, final boolean isChargeIdIncluded) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } Set transactionParameters = null; - if(isChargeIdIncluded){ - transactionParameters = new HashSet(Arrays.asList("transactionDate", "locale", "dateFormat","chargeId")); - }else{ + if (isChargeIdIncluded) { + transactionParameters = new HashSet(Arrays.asList("transactionDate", "locale", "dateFormat", "chargeId")); + } else { transactionParameters = new HashSet(Arrays.asList("transactionDate", "locale", "dateFormat")); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, transactionParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, transactionParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("loan.charge.payment.transaction"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); - if(isChargeIdIncluded){ - final Long chargeId = fromApiJsonHelper.extractLongNamed("chargeId", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed("transactionDate", element); + if (isChargeIdIncluded) { + final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", element); baseDataValidator.reset().parameter("chargeId").value(chargeId).notNull().integerGreaterThanZero(); } baseDataValidator.reset().parameter("transactionDate").value(transactionDate).notNull(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/BulkLoansReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/BulkLoansReadPlatformService.java index f9db07eed..aa38eedf1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/BulkLoansReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/BulkLoansReadPlatformService.java @@ -7,7 +7,6 @@ package org.mifosplatform.portfolio.loanaccount.service; import org.mifosplatform.organisation.staff.data.StaffAccountSummaryCollectionData; - public interface BulkLoansReadPlatformService { StaffAccountSummaryCollectionData retrieveLoanOfficerAccountSummary(final Long loanOfficerId); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/BulkLoansReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/BulkLoansReadPlatformServiceImpl.java index 6e5d1c4de..22d4ebe7f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/BulkLoansReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/BulkLoansReadPlatformServiceImpl.java @@ -41,18 +41,18 @@ public class BulkLoansReadPlatformServiceImpl implements BulkLoansReadPlatformSe @Override public StaffAccountSummaryCollectionData retrieveLoanOfficerAccountSummary(final Long loanOfficerId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final StaffClientMapper staffClientMapper = new StaffClientMapper(); - final String clientSql = "select distinct " + staffClientMapper.schema() +" and c.status_enum=?"; + final String clientSql = "select distinct " + staffClientMapper.schema() + " and c.status_enum=?"; final StaffGroupMapper staffGroupMapper = new StaffGroupMapper(); - final String groupSql = "select distinct " + staffGroupMapper.schema() +" and g.status_enum=?"; + final String groupSql = "select distinct " + staffGroupMapper.schema() + " and g.status_enum=?"; final List clientSummaryList = this.jdbcTemplate.query(clientSql, - staffClientMapper, new Object[] { loanOfficerId, ClientStatus.ACTIVE.getValue()}); + staffClientMapper, new Object[] { loanOfficerId, ClientStatus.ACTIVE.getValue() }); - for (StaffAccountSummaryCollectionData.LoanAccountSummary clientSummary : clientSummaryList) { + for (final StaffAccountSummaryCollectionData.LoanAccountSummary clientSummary : clientSummaryList) { final Collection clientLoanAccounts = this.accountDetailsReadPlatformService .retrieveClientLoanAccountsByLoanOfficerId(clientSummary.getId(), loanOfficerId); @@ -60,10 +60,10 @@ public class BulkLoansReadPlatformServiceImpl implements BulkLoansReadPlatformSe clientSummary.setLoans(clientLoanAccounts); } - final List groupSummaryList = this.jdbcTemplate.query(groupSql, staffGroupMapper, - new Object[] { loanOfficerId, GroupingTypeStatus.ACTIVE.getValue()}); + final List groupSummaryList = this.jdbcTemplate.query(groupSql, + staffGroupMapper, new Object[] { loanOfficerId, GroupingTypeStatus.ACTIVE.getValue() }); - for (StaffAccountSummaryCollectionData.LoanAccountSummary groupSummary : groupSummaryList) { + for (final StaffAccountSummaryCollectionData.LoanAccountSummary groupSummary : groupSummaryList) { final Collection groupLoanAccounts = this.accountDetailsReadPlatformService .retrieveGroupLoanAccountsByLoanOfficerId(groupSummary.getId(), loanOfficerId); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java index 343bdd345..572277ce7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanApplicationWritePlatformServiceJpaRepositoryImpl.java @@ -214,7 +214,8 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa if (savingsAccountId != null) { final SavingsAccount savingsAccount = this.savingsAccountAssembler.assembleFrom(savingsAccountId); this.fromApiJsonDeserializer.validatelinkedSavingsAccount(savingsAccount, newLoanApplication); - final AccountAssociations accountAssociations = AccountAssociations.associateSavingsAccount(newLoanApplication, savingsAccount); + final AccountAssociations accountAssociations = AccountAssociations.associateSavingsAccount(newLoanApplication, + savingsAccount); this.accountAssociationsRepository.save(accountAssociations); } @@ -361,8 +362,8 @@ public class LoanApplicationWritePlatformServiceJpaRepositoryImpl implements Loa if (calendar == null) { throw new CalendarNotFoundException(calendarId); } } - final List ciList = (List) this.calendarInstanceRepository.findByEntityIdAndEntityTypeId(loanId, - CalendarEntityType.LOANS.getValue()); + final List ciList = (List) this.calendarInstanceRepository.findByEntityIdAndEntityTypeId( + loanId, CalendarEntityType.LOANS.getValue()); if (calendar != null) { // For loans, allow to attach only one calendar instance per diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanChargeAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanChargeAssembler.java index 72b52dd56..97d68767f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanChargeAssembler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanChargeAssembler.java @@ -46,27 +46,28 @@ public class LoanChargeAssembler { final Set loanCharges = new HashSet(); - final BigDecimal principal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); + final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); if (element.isJsonObject()) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final String dateFormat = fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); - final Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.has("charges") && topLevelJsonElement.get("charges").isJsonArray()) { final JsonArray array = topLevelJsonElement.get("charges").getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject loanChargeElement = array.get(i).getAsJsonObject(); - final Long id = fromApiJsonHelper.extractLongNamed("id", loanChargeElement); - final Long chargeId = fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalNamed("amount", loanChargeElement, locale); - final Integer chargeTimeType = fromApiJsonHelper.extractIntegerNamed("chargeTimeType", loanChargeElement, locale); - final Integer chargeCalculationType = fromApiJsonHelper.extractIntegerNamed("chargeCalculationType", loanChargeElement, + final Long id = this.fromApiJsonHelper.extractLongNamed("id", loanChargeElement); + final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount", loanChargeElement, locale); + final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed("chargeTimeType", loanChargeElement, locale); + final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed("chargeCalculationType", + loanChargeElement, locale); + final LocalDate dueDate = this.fromApiJsonHelper + .extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale); + final Integer chargePaymentMode = this.fromApiJsonHelper.extractIntegerNamed("chargePaymentMode", loanChargeElement, locale); - final LocalDate dueDate = fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, - dateFormat, locale); - final Integer chargePaymentMode = fromApiJsonHelper.extractIntegerNamed("chargePaymentMode", loanChargeElement, locale); if (id == null) { final Charge chargeDefinition = this.chargeRepository.findOneWithNotFoundDetection(chargeId); ChargeTimeType chargeTime = null; @@ -78,7 +79,7 @@ public class LoanChargeAssembler { chargeCalculation = ChargeCalculationType.fromInt(chargeCalculationType); } ChargePaymentMode chargePaymentModeEnum = null; - if(chargePaymentMode != null){ + if (chargePaymentMode != null) { chargePaymentModeEnum = ChargePaymentMode.fromInt(chargePaymentMode); } final LoanCharge loanCharge = LoanCharge.createNewWithoutLoan(chargeDefinition, principal, amount, chargeTime, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanChargeReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanChargeReadPlatformServiceImpl.java index 465396218..939b1b787 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanChargeReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanChargeReadPlatformServiceImpl.java @@ -154,8 +154,7 @@ public class LoanChargeReadPlatformServiceImpl implements LoanChargeReadPlatform public String schema() { return "lc.id as id, lc.due_for_collection_as_of_date as dueAsOfDate, " - + "lc.amount_outstanding_derived as amountOutstanding, " - + "loan.id as loanId " + "from m_loan_charge lc " + + "lc.amount_outstanding_derived as amountOutstanding, " + "loan.id as loanId " + "from m_loan_charge lc " + "join m_loan loan on loan.id = lc.loan_id "; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanReadPlatformService.java index 4354bd0ee..4c50e001d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanReadPlatformService.java @@ -35,22 +35,22 @@ public interface LoanReadPlatformService { LoanTransactionData retrieveLoanTransaction(Long loanId, Long transactionId); LoanTransactionData retrieveNewClosureDetails(); - + LoanTransactionData retrieveDisbursalTemplate(Long loanId); LoanAccountData retrieveTemplateWithCompleteGroupAndProductDetails(Long groupId, Long productId); - + LoanAccountData retrieveLoanProductDetailsTemplate(Long productId); - + LoanAccountData retrieveClientDetailsTemplate(Long clientId); - + LoanAccountData retrieveGroupDetailsTemplate(Long groupId); - + LoanAccountData retrieveGroupAndMembersDetailsTemplate(Long groupId); Collection retrieveCalendars(Long groupId); Page retrieveAll(SearchParameters searchParameters); - + Collection retrieveAllowedLoanOfficers(Long selectedOfficeId, boolean staffInSelectedOfficeOnly); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java index 2a93650f2..4fadd17b0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanReadPlatformServiceImpl.java @@ -130,13 +130,13 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { public LoanAccountData retrieveOne(final Long loanId) { try { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - LoanMapper rm = new LoanMapper(); + final LoanMapper rm = new LoanMapper(); - StringBuilder sqlBuilder = new StringBuilder(); + final StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.append("select "); sqlBuilder.append(rm.loanSchema()); sqlBuilder.append(" join m_office o on (o.id = c.office_id or o.id = g.office_id) "); @@ -145,7 +145,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { return this.jdbcTemplate.queryForObject(sqlBuilder.toString(), rm, new Object[] { loanId, hierarchySearchString, hierarchySearchString }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new LoanNotFoundException(loanId); } } @@ -155,14 +155,14 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final RepaymentScheduleRelatedLoanData repaymentScheduleRelatedLoanData) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); final LoanScheduleResultSetExtractor fullResultsetExtractor = new LoanScheduleResultSetExtractor( repaymentScheduleRelatedLoanData); final String sql = "select " + fullResultsetExtractor.schema() + " where ls.loan_id = ? order by ls.loan_id, ls.installment"; return this.jdbcTemplate.query(sql, fullResultsetExtractor, new Object[] { loanId }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new LoanNotFoundException(loanId); } } @@ -170,20 +170,20 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public Collection retrieveLoanTransactions(final Long loanId) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); - LoanTransactionsMapper rm = new LoanTransactionsMapper(); + final LoanTransactionsMapper rm = new LoanTransactionsMapper(); // retrieve all loan transactions that are not invalid and have not // been 'contra'ed by another transaction // repayments at time of disbursement (e.g. charges) /*** TODO Vishwas: Remove references to "Contra" from the codebase ***/ - String sql = "select " + final String sql = "select " + rm.LoanPaymentsSchema() + " where tr.loan_id = ? and tr.transaction_type_enum not in (0, 3) and tr.is_reversed=0 order by tr.transaction_date ASC,id "; return this.jdbcTemplate.query(sql, rm, new Object[] { loanId }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { return null; } } @@ -191,13 +191,13 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public Page retrieveAll(final SearchParameters searchParameters) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - StringBuilder sqlBuilder = new StringBuilder(200); + final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); - sqlBuilder.append(loaanLoanMapper.loanSchema()); + sqlBuilder.append(this.loaanLoanMapper.loanSchema()); // TODO - for time being this will data scope list of loans returned to // only loans that have a client associated. @@ -249,7 +249,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public LoanAccountData retrieveTemplateWithClientAndProductDetails(final Long clientId, final Long productId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final ClientData clientAccount = this.clientReadPlatformService.retrieveOne(clientId); final LocalDate expectedDisbursementDate = DateUtils.getLocalDateOfTenant(); @@ -267,14 +267,14 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public LoanAccountData retrieveTemplateWithGroupAndProductDetails(final Long groupId, final Long productId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final GroupGeneralData groupAccount = this.groupReadPlatformService.retrieveOne(groupId); final LocalDate expectedDisbursementDate = DateUtils.getLocalDateOfTenant(); LoanAccountData loanDetails = LoanAccountData.groupDefaults(groupAccount, expectedDisbursementDate); if (productId != null) { - LoanProductData selectedProduct = this.loanProductReadPlatformService.retrieveLoanProduct(productId); + final LoanProductData selectedProduct = this.loanProductReadPlatformService.retrieveLoanProduct(productId); loanDetails = LoanAccountData.populateLoanProductDefaults(loanDetails, selectedProduct); } @@ -284,11 +284,11 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public LoanAccountData retrieveTemplateWithCompleteGroupAndProductDetails(final Long groupId, final Long productId) { - context.authenticatedUser(); + this.context.authenticatedUser(); GroupGeneralData groupAccount = this.groupReadPlatformService.retrieveOne(groupId); // get group associations - Collection membersOfGroup = this.clientReadPlatformService.retrieveClientMembersOfGroup(groupId); + final Collection membersOfGroup = this.clientReadPlatformService.retrieveClientMembersOfGroup(groupId); if (!CollectionUtils.isEmpty(membersOfGroup)) { final Collection calendarsData = null; final CalendarData collectionMeetingCalendar = null; @@ -301,7 +301,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { LoanAccountData loanDetails = LoanAccountData.groupDefaults(groupAccount, expectedDisbursementDate); if (productId != null) { - LoanProductData selectedProduct = this.loanProductReadPlatformService.retrieveLoanProduct(productId); + final LoanProductData selectedProduct = this.loanProductReadPlatformService.retrieveLoanProduct(productId); loanDetails = LoanAccountData.populateLoanProductDefaults(loanDetails, selectedProduct); } @@ -311,11 +311,11 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public LoanTransactionData retrieveLoanTransactionTemplate(final Long loanId) { - context.authenticatedUser(); + this.context.authenticatedUser(); // TODO - KW - OPTIMIZE - write simple sql query to fetch back date of // possible next transaction date. - Loan loan = this.loanRepository.findOne(loanId); + final Loan loan = this.loanRepository.findOne(loanId); if (loan == null) { throw new LoanNotFoundException(loanId); } final MonetaryCurrency currency = loan.getCurrency(); @@ -327,16 +327,16 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final Money possibleNextRepaymentAmount = loan.possibleNextRepaymentAmount(); final LoanTransactionEnumData transactionType = LoanEnumerations.transactionType(LoanTransactionType.REPAYMENT); - final Collection paymentOptions = codeValueReadPlatformService + final Collection paymentOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(PaymentDetailConstants.paymentTypeCodeName); return new LoanTransactionData(null, null, null, transactionType, null, currencyData, earliestUnpaidInstallmentDate, - possibleNextRepaymentAmount.getAmount(), null, null, null, null, paymentOptions, null,null); + possibleNextRepaymentAmount.getAmount(), null, null, null, null, paymentOptions, null, null); } @Override public LoanTransactionData retrieveWaiveInterestDetails(final Long loanId) { - context.authenticatedUser(); + this.context.authenticatedUser(); // TODO - KW -OPTIMIZE - write simple sql query to fetch back overdue // interest that can be waived along with the date of repayment period @@ -360,7 +360,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public LoanTransactionData retrieveNewClosureDetails() { - context.authenticatedUser(); + this.context.authenticatedUser(); final LoanTransactionEnumData transactionType = LoanEnumerations.transactionType(LoanTransactionType.WRITEOFF); return new LoanTransactionData(null, null, null, transactionType, null, null, DateUtils.getLocalDateOfTenant(), null, null, null, @@ -372,16 +372,16 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final Loan loan = this.loanRepository.findOne(loanId); if (loan == null) { throw new LoanNotFoundException(loanId); } final LoanTransactionEnumData transactionType = LoanEnumerations.transactionType(LoanTransactionType.DISBURSEMENT); - final Collection paymentOptions = codeValueReadPlatformService + final Collection paymentOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(PaymentDetailConstants.paymentTypeCodeName); return new LoanTransactionData(null, null, null, transactionType, null, null, loan.getExpectedDisbursedOnLocalDate(), null, null, - null, null, null, paymentOptions, null,null); + null, null, null, paymentOptions, null, null); } @Override public LoanTransactionData retrieveLoanTransaction(final Long loanId, final Long transactionId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final Loan loan = this.loanRepository.findOne(loanId); if (loan == null) { throw new LoanNotFoundException(loanId); } @@ -394,13 +394,11 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { if (transaction == null) { throw new LoanTransactionNotFoundException(transactionId); } if (transaction.isNotBelongingToLoanOf(loan)) { throw new LoanTransactionNotFoundException(transactionId, loanId); } - - LoanTransactionsAccountTransferMapper trasfermapper = new LoanTransactionsAccountTransferMapper(); - String sql = "select " - + trasfermapper.accountTransferSchema() - + " where tr.loan_id = ? and tr.id = ?"; - AccountTransferData accountTransferData = this.jdbcTemplate.queryForObject(sql, trasfermapper, loanId, transactionId); - return transaction.toData(currencyData,accountTransferData); + + final LoanTransactionsAccountTransferMapper trasfermapper = new LoanTransactionsAccountTransferMapper(); + final String sql = "select " + trasfermapper.accountTransferSchema() + " where tr.loan_id = ? and tr.id = ?"; + final AccountTransferData accountTransferData = this.jdbcTemplate.queryForObject(sql, trasfermapper, loanId, transactionId); + return transaction.toData(currencyData, accountTransferData); } private static final class LoanMapper implements RowMapper { @@ -703,8 +701,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { this.currency = repaymentScheduleRelatedLoanData.getCurrency(); this.disbursement = repaymentScheduleRelatedLoanData.disbursementData(); this.totalFeeChargesDueAtDisbursement = repaymentScheduleRelatedLoanData.getTotalFeeChargesAtDisbursement(); - this.lastDueDate = disbursement.disbursementDate(); - this.outstandingLoanPrincipalBalance = disbursement.amount(); + this.lastDueDate = this.disbursement.disbursementDate(); + this.outstandingLoanPrincipalBalance = this.disbursement.amount(); } public String schema() { @@ -830,11 +828,11 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { if (fromDate == null) { fromDate = this.lastDueDate; } - final BigDecimal outstandingPrincipalBalanceOfLoan = outstandingLoanPrincipalBalance.subtract(principalDue); + final BigDecimal outstandingPrincipalBalanceOfLoan = this.outstandingLoanPrincipalBalance.subtract(principalDue); // update based on current period values this.lastDueDate = dueDate; - outstandingLoanPrincipalBalance = outstandingLoanPrincipalBalance.subtract(principalDue); + this.outstandingLoanPrincipalBalance = this.outstandingLoanPrincipalBalance.subtract(principalDue); final LoanSchedulePeriodData periodData = LoanSchedulePeriodData.repaymentPeriodWithPayments(loanId, period, fromDate, dueDate, obligationsMetOnDate, complete, principalDue, principalPaid, principalWrittenOff, principalOutstanding, @@ -873,8 +871,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { + " fromtran.description as fromTransferDescription," + " totran.id as toTransferId, totran.is_reversed as toTransferReversed," + " totran.transaction_date as toTransferDate, totran.amount as toTransferAmount," - + " totran.description as toTransferDescription " - + " from m_loan l join m_loan_transaction tr on tr.loan_id = l.id" + + " totran.description as toTransferDescription " + " from m_loan l join m_loan_transaction tr on tr.loan_id = l.id" + " join m_currency rc on rc.`code` = l.currency_code " + " left JOIN m_payment_detail pd ON tr.payment_detail_id = pd.id" + " left join m_code_value cv on pd.payment_type_cv_id = cv.id" @@ -907,7 +904,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final Long paymentTypeId = JdbcSupport.getLong(rs, "paymentType"); if (paymentTypeId != null) { final String typeName = rs.getString("paymentTypeName"); - CodeValueData paymentType = CodeValueData.instance(paymentTypeId, typeName); + final CodeValueData paymentType = CodeValueData.instance(paymentTypeId, typeName); final String accountNumber = rs.getString("accountNumber"); final String checkNumber = rs.getString("checkNumber"); final String routingCode = rs.getString("routingCode"); @@ -924,7 +921,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final BigDecimal feeChargesPortion = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "fees"); final BigDecimal penaltyChargesPortion = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "penalties"); final String externalId = rs.getString("externalId"); - + AccountTransferData transfer = null; final Long fromTransferId = JdbcSupport.getLong(rs, "fromTransferId"); final Long toTransferId = JdbcSupport.getLong(rs, "toTransferId"); @@ -946,7 +943,6 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { toTransferDescription, toTransferReversed); } - return new LoanTransactionData(id, officeId, officeName, transactionType, paymentDetailData, currencyData, date, totalAmount, principalPortion, interestPortion, feeChargesPortion, penaltyChargesPortion, externalId, transfer); } @@ -1006,22 +1002,22 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { } } - @Override public LoanAccountData retrieveLoanProductDetailsTemplate(final Long productId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final LoanProductData loanProduct = this.loanProductReadPlatformService.retrieveLoanProduct(productId); - final Collection loanTermFrequencyTypeOptions = loanDropdownReadPlatformService + final Collection loanTermFrequencyTypeOptions = this.loanDropdownReadPlatformService .retrieveLoanTermFrequencyTypeOptions(); - final Collection repaymentFrequencyTypeOptions = loanDropdownReadPlatformService + final Collection repaymentFrequencyTypeOptions = this.loanDropdownReadPlatformService .retrieveRepaymentFrequencyTypeOptions(); - final Collection interestRateFrequencyTypeOptions = loanDropdownReadPlatformService + final Collection interestRateFrequencyTypeOptions = this.loanDropdownReadPlatformService .retrieveInterestRateFrequencyTypeOptions(); - final Collection amortizationTypeOptions = loanDropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); - final Collection interestTypeOptions = loanDropdownReadPlatformService.retrieveLoanInterestTypeOptions(); - final Collection interestCalculationPeriodTypeOptions = loanDropdownReadPlatformService + final Collection amortizationTypeOptions = this.loanDropdownReadPlatformService + .retrieveLoanAmortizationTypeOptions(); + final Collection interestTypeOptions = this.loanDropdownReadPlatformService.retrieveLoanInterestTypeOptions(); + final Collection interestCalculationPeriodTypeOptions = this.loanDropdownReadPlatformService .retrieveLoanInterestRateCalculatedInPeriodOptions(); final Collection fundOptions = this.fundReadPlatformService.retrieveAllFunds(); final Collection repaymentStrategyOptions = this.loanDropdownReadPlatformService @@ -1040,7 +1036,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public LoanAccountData retrieveClientDetailsTemplate(final Long clientId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final ClientData clientAccount = this.clientReadPlatformService.retrieveOne(clientId); final LocalDate expectedDisbursementDate = DateUtils.getLocalDateOfTenant(); @@ -1051,7 +1047,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { @Override public LoanAccountData retrieveGroupDetailsTemplate(final Long groupId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final GroupGeneralData groupAccount = this.groupReadPlatformService.retrieveOne(groupId); final LocalDate expectedDisbursementDate = DateUtils.getLocalDateOfTenant(); return LoanAccountData.groupDefaults(groupAccount, expectedDisbursementDate); @@ -1063,7 +1059,7 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { final LocalDate expectedDisbursementDate = DateUtils.getLocalDateOfTenant(); // get group associations - Collection membersOfGroup = this.clientReadPlatformService.retrieveActiveClientMembersOfGroup(groupId); + final Collection membersOfGroup = this.clientReadPlatformService.retrieveActiveClientMembersOfGroup(groupId); if (!CollectionUtils.isEmpty(membersOfGroup)) { final Collection calendarsData = null; final CalendarData collectionMeetingCalendar = null; @@ -1087,8 +1083,8 @@ public class LoanReadPlatformServiceImpl implements LoanReadPlatformService { } @Override - public Collection retrieveAllowedLoanOfficers(Long selectedOfficeId, boolean staffInSelectedOfficeOnly) { - if (selectedOfficeId == null) return null; + public Collection retrieveAllowedLoanOfficers(final Long selectedOfficeId, final boolean staffInSelectedOfficeOnly) { + if (selectedOfficeId == null) { return null; } Collection allowedLoanOfficers = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformService.java index 7bc82239c..607e80e7f 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformService.java @@ -72,5 +72,4 @@ public interface LoanWritePlatformService { void transferFeeCharges() throws JobExecutionException; - } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java index a668a3ba3..5021d484a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanaccount/service/LoanWritePlatformServiceJpaRepositoryImpl.java @@ -1007,9 +1007,9 @@ public class LoanWritePlatformServiceJpaRepositoryImpl implements LoanWritePlatf if (chargeData.getDueDate() != null && !chargeData.getDueDate().isAfter(new LocalDate())) { final PortfolioAccountData portfolioAccountData = this.accountAssociationsReadPlatformService .retriveLoanAssociation(chargeData.getLoanId()); - final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(new LocalDate(), chargeData.getAmountOutstanding(), - PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN, portfolioAccountData.accountId(), - chargeData.getLoanId(), "Loan Charge Payment", null, null, null, null, + final AccountTransferDTO accountTransferDTO = new AccountTransferDTO(new LocalDate(), + chargeData.getAmountOutstanding(), PortfolioAccountType.SAVINGS, PortfolioAccountType.LOAN, + portfolioAccountData.accountId(), chargeData.getLoanId(), "Loan Charge Payment", null, null, null, null, LoanTransactionType.CHARGE_PAYMENT.getValue(), chargeData.getId()); try { this.accountTransfersWritePlatformService.transferFunds(accountTransferDTO); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/api/LoanProductsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/api/LoanProductsApiResource.java index 167fc2c69..375742baa 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/api/LoanProductsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/api/LoanProductsApiResource.java @@ -69,11 +69,12 @@ public class LoanProductsApiResource { "graceOnInterestPayment", "graceOnInterestCharged", "interestRatePerPeriod", "minInterestRatePerPeriod", "maxInterestRatePerPeriod", "interestRateFrequencyType", "annualInterestRate", "amortizationType", "interestType", "interestCalculationPeriodType", "inArrearsTolerance", "transactionProcessingStrategyId", "transactionProcessingStrategyName", - "charges", "accountingRule", "externalId", "accountingMappings", "paymentChannelToFundSourceMappings", "fundOptions", "paymentTypeOptions", - "currencyOptions", "repaymentFrequencyTypeOptions", "interestRateFrequencyTypeOptions", "amortizationTypeOptions", - "interestTypeOptions", "interestCalculationPeriodTypeOptions", "transactionProcessingStrategyOptions", "chargeOptions", - "accountingOptions", "accountingRuleOptions", "accountingMappingOptions")); - + "charges", "accountingRule", "externalId", "accountingMappings", "paymentChannelToFundSourceMappings", "fundOptions", + "paymentTypeOptions", "currencyOptions", "repaymentFrequencyTypeOptions", "interestRateFrequencyTypeOptions", + "amortizationTypeOptions", "interestTypeOptions", "interestCalculationPeriodTypeOptions", + "transactionProcessingStrategyOptions", "chargeOptions", "accountingOptions", "accountingRuleOptions", + "accountingMappingOptions")); + private final Set PRODUCT_MIX_DATA_PARAMETERS = new HashSet(Arrays.asList("productId", "productName", "restrictedProducts", "allowedProducts", "productOptions")); @@ -139,21 +140,21 @@ public class LoanProductsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllLoanProducts(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Set associationParameters = ApiParameterHelper.extractAssociationsForResponseIfProvided(uriInfo.getQueryParameters()); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + if (!associationParameters.isEmpty()) { if (associationParameters.contains("productMixes")) { - context.authenticatedUser().validateHasReadPermission("PRODUCTMIX"); - Collection productMixes = this.productMixReadPlatformService.retrieveAllProductMixes(); - return this.productMixDataApiJsonSerializer.serialize(settings, productMixes, PRODUCT_MIX_DATA_PARAMETERS); + this.context.authenticatedUser().validateHasReadPermission("PRODUCTMIX"); + final Collection productMixes = this.productMixReadPlatformService.retrieveAllProductMixes(); + return this.productMixDataApiJsonSerializer.serialize(settings, productMixes, this.PRODUCT_MIX_DATA_PARAMETERS); } } final Collection products = this.loanProductReadPlatformService.retrieveAllLoanProducts(); - return this.toApiJsonSerializer.serialize(settings, products, LOAN_PRODUCT_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, products, this.LOAN_PRODUCT_DATA_PARAMETERS); } @GET @@ -162,21 +163,21 @@ public class LoanProductsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveTemplate(@Context final UriInfo uriInfo, @QueryParam("isProductMixTemplate") final boolean isProductMixTemplate) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (isProductMixTemplate) { - context.authenticatedUser().validateHasReadPermission("PRODUCTMIX"); + this.context.authenticatedUser().validateHasReadPermission("PRODUCTMIX"); - Collection productOptions = this.loanProductReadPlatformService.retrieveAvailableLoanProductsForMix(); - ProductMixData productMixData = ProductMixData.template(productOptions); - return this.productMixDataApiJsonSerializer.serialize(settings, productMixData, PRODUCT_MIX_DATA_PARAMETERS); + final Collection productOptions = this.loanProductReadPlatformService.retrieveAvailableLoanProductsForMix(); + final ProductMixData productMixData = ProductMixData.template(productOptions); + return this.productMixDataApiJsonSerializer.serialize(settings, productMixData, this.PRODUCT_MIX_DATA_PARAMETERS); } LoanProductData loanProduct = this.loanProductReadPlatformService.retrieveNewLoanProductDetails(); loanProduct = handleTemplate(loanProduct); - return this.toApiJsonSerializer.serialize(settings, loanProduct, LOAN_PRODUCT_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, loanProduct, this.LOAN_PRODUCT_DATA_PARAMETERS); } @GET @@ -185,9 +186,9 @@ public class LoanProductsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveLoanProductDetails(@PathParam("productId") final Long productId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); LoanProductData loanProduct = this.loanProductReadPlatformService.retrieveLoanProduct(productId); @@ -196,12 +197,13 @@ public class LoanProductsApiResource { Collection feeToGLAccountMappings = null; Collection penaltyToGLAccountMappings = null; if (loanProduct.hasAccountingEnabled()) { - accountingMappings = accountMappingReadPlatformService.fetchAccountMappingDetailsForLoanProduct(productId, loanProduct + accountingMappings = this.accountMappingReadPlatformService.fetchAccountMappingDetailsForLoanProduct(productId, loanProduct .accountingRuleType().getId().intValue()); - paymentChannelToFundSourceMappings = accountMappingReadPlatformService + paymentChannelToFundSourceMappings = this.accountMappingReadPlatformService .fetchPaymentTypeToFundSourceMappingsForLoanProduct(productId); - feeToGLAccountMappings = accountMappingReadPlatformService.fetchFeeToIncomeAccountMappingsForLoanProduct(productId); - penaltyToGLAccountMappings = accountMappingReadPlatformService.fetchPenaltyToIncomeAccountMappingsForLoanProduct(productId); + feeToGLAccountMappings = this.accountMappingReadPlatformService.fetchFeeToIncomeAccountMappingsForLoanProduct(productId); + penaltyToGLAccountMappings = this.accountMappingReadPlatformService + .fetchPenaltyToIncomeAccountMappingsForLoanProduct(productId); loanProduct = LoanProductData.withAccountingDetails(loanProduct, accountingMappings, paymentChannelToFundSourceMappings, feeToGLAccountMappings, penaltyToGLAccountMappings); } @@ -209,7 +211,7 @@ public class LoanProductsApiResource { if (settings.isTemplate()) { loanProduct = handleTemplate(loanProduct); } - return this.toApiJsonSerializer.serialize(settings, loanProduct, LOAN_PRODUCT_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, loanProduct, this.LOAN_PRODUCT_DATA_PARAMETERS); } @PUT @@ -239,15 +241,15 @@ public class LoanProductsApiResource { penaltyOptions = null; } - final Collection currencyOptions = currencyReadPlatformService.retrieveAllowedCurrencies(); - final List amortizationTypeOptions = dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); - final List interestTypeOptions = dropdownReadPlatformService.retrieveLoanInterestTypeOptions(); - final List interestCalculationPeriodTypeOptions = dropdownReadPlatformService + final Collection currencyOptions = this.currencyReadPlatformService.retrieveAllowedCurrencies(); + final List amortizationTypeOptions = this.dropdownReadPlatformService.retrieveLoanAmortizationTypeOptions(); + final List interestTypeOptions = this.dropdownReadPlatformService.retrieveLoanInterestTypeOptions(); + final List interestCalculationPeriodTypeOptions = this.dropdownReadPlatformService .retrieveLoanInterestRateCalculatedInPeriodOptions(); - final List repaymentFrequencyTypeOptions = dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions(); - final List interestRateFrequencyTypeOptions = dropdownReadPlatformService + final List repaymentFrequencyTypeOptions = this.dropdownReadPlatformService.retrieveRepaymentFrequencyTypeOptions(); + final List interestRateFrequencyTypeOptions = this.dropdownReadPlatformService .retrieveInterestRateFrequencyTypeOptions(); - final Collection paymentTypeOptions = codeValueReadPlatformService + final Collection paymentTypeOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(PaymentDetailConstants.paymentTypeCodeName); Collection fundOptions = this.fundReadPlatformService.retrieveAllFunds(); @@ -257,10 +259,11 @@ public class LoanProductsApiResource { final Collection transactionProcessingStrategyOptions = this.dropdownReadPlatformService .retreiveTransactionProcessingStrategies(); - Map> accountOptions = accountingDropdownReadPlatformService + final Map> accountOptions = this.accountingDropdownReadPlatformService .retrieveAccountMappingOptionsForLoanProducts(); - List accountingRuleTypeOptions = accountingDropdownReadPlatformService.retrieveAccountingRuleTypeOptions(); + final List accountingRuleTypeOptions = this.accountingDropdownReadPlatformService + .retrieveAccountingRuleTypeOptions(); return new LoanProductData(productData, chargeOptions, penaltyOptions, paymentTypeOptions, currencyOptions, amortizationTypeOptions, interestTypeOptions, interestCalculationPeriodTypeOptions, repaymentFrequencyTypeOptions, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/data/LoanProductData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/data/LoanProductData.java index 57380472a..6fcc6be2a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/data/LoanProductData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/data/LoanProductData.java @@ -74,7 +74,7 @@ public class LoanProductData { private final Collection charges; // accounting - private EnumOptionData accountingRule; + private final EnumOptionData accountingRule; private Map accountingMappings; private Collection paymentChannelToFundSourceMappings; private Collection feeToIncomeAccountMappings; @@ -134,7 +134,7 @@ public class LoanProductData { final EnumOptionData accountingType = null; final boolean includeInBorrowerCycle = false; final LocalDate startDate = null; - final LocalDate closeDate = null; + final LocalDate closeDate = null; final String status = null; final String externalId = null; return new LoanProductData(id, name, description, currency, principal, minPrincipal, maxPrincipal, tolerance, numberOfRepayments, @@ -416,39 +416,39 @@ public class LoanProductData { } public Long getId() { - return id; + return this.id; } public String getName() { - return name; + return this.name; } public String getDescription() { - return description; + return this.description; } public Long getFundId() { - return fundId; + return this.fundId; } public String getFundName() { - return fundName; + return this.fundName; } public Long getTransactionProcessingStrategyId() { - return transactionProcessingStrategyId; + return this.transactionProcessingStrategyId; } public String getTransactionProcessingStrategyName() { - return transactionProcessingStrategyName; + return this.transactionProcessingStrategyName; } public CurrencyData getCurrency() { - return currency; + return this.currency; } public BigDecimal getPrincipal() { - return principal; + return this.principal; } public BigDecimal getMinPrincipal() { @@ -460,27 +460,27 @@ public class LoanProductData { } public BigDecimal getInArrearsTolerance() { - return inArrearsTolerance; + return this.inArrearsTolerance; } public Integer getNumberOfRepayments() { - return numberOfRepayments; + return this.numberOfRepayments; } public Integer getRepaymentEvery() { - return repaymentEvery; + return this.repaymentEvery; } public BigDecimal getInterestRatePerPeriod() { - return interestRatePerPeriod; + return this.interestRatePerPeriod; } public BigDecimal getAnnualInterestRate() { - return annualInterestRate; + return this.annualInterestRate; } public EnumOptionData getRepaymentFrequencyType() { - return repaymentFrequencyType; + return this.repaymentFrequencyType; } public Integer getGraceOnPrincipalPayment() { @@ -496,52 +496,52 @@ public class LoanProductData { } public EnumOptionData getInterestRateFrequencyType() { - return interestRateFrequencyType; + return this.interestRateFrequencyType; } public EnumOptionData getAmortizationType() { - return amortizationType; + return this.amortizationType; } public EnumOptionData getInterestType() { - return interestType; + return this.interestType; } public EnumOptionData getInterestCalculationPeriodType() { - return interestCalculationPeriodType; + return this.interestCalculationPeriodType; } public Collection getFundOptions() { - return fundOptions; + return this.fundOptions; } public List getAmortizationTypeOptions() { - return amortizationTypeOptions; + return this.amortizationTypeOptions; } public List getInterestTypeOptions() { - return interestTypeOptions; + return this.interestTypeOptions; } public List getInterestCalculationPeriodTypeOptions() { - return interestCalculationPeriodTypeOptions; + return this.interestCalculationPeriodTypeOptions; } public List getRepaymentFrequencyTypeOptions() { - return repaymentFrequencyTypeOptions; + return this.repaymentFrequencyTypeOptions; } public List getInterestRateFrequencyTypeOptions() { - return interestRateFrequencyTypeOptions; + return this.interestRateFrequencyTypeOptions; } public Collection getChargeOptions() { - return chargeOptions; + return this.chargeOptions; } @Override public boolean equals(final Object obj) { - LoanProductData loanProductData = (LoanProductData) obj; + final LoanProductData loanProductData = (LoanProductData) obj; return loanProductData.id.equals(this.id); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/AmortizationMethod.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/AmortizationMethod.java index 39aa2174e..7d87bddc8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/AmortizationMethod.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/AmortizationMethod.java @@ -23,7 +23,7 @@ public enum AmortizationMethod { } public String getCode() { - return code; + return this.code; } public static AmortizationMethod fromInt(final Integer selectedMethod) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/InterestCalculationPeriodMethod.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/InterestCalculationPeriodMethod.java index 3330124b1..5716c34cf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/InterestCalculationPeriodMethod.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/InterestCalculationPeriodMethod.java @@ -23,7 +23,7 @@ public enum InterestCalculationPeriodMethod { } public String getCode() { - return code; + return this.code; } public static InterestCalculationPeriodMethod fromInt(final Integer selectedMethod) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/InterestMethod.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/InterestMethod.java index c9c723a33..a202c84a9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/InterestMethod.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/InterestMethod.java @@ -21,7 +21,7 @@ public enum InterestMethod { } public String getCode() { - return code; + return this.code; } public static InterestMethod fromInt(final Integer selectedMethod) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LendingStrategy.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LendingStrategy.java index 8b9b35f48..3121ddf62 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LendingStrategy.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LendingStrategy.java @@ -9,13 +9,12 @@ import java.util.HashMap; import java.util.Map; /** - * INDIVIDUAL_LOAN: Individual loans are applicable only to clients. - * GROUP_LOAN: * Group loans are applicable only to groups. And tracked only at - * group level. - * JOINT_LIABILITY_LOAN: Joint liability loans are applicable only - * to clients within a group. - * LINKED_LOAN: Loan is given to group, then later loan amount is split into individual loans. Loan is tracked at both - * individual and group level + * INDIVIDUAL_LOAN: Individual loans are applicable only to clients. GROUP_LOAN: + * * Group loans are applicable only to groups. And tracked only at group level. + * JOINT_LIABILITY_LOAN: Joint liability loans are applicable only to clients + * within a group. LINKED_LOAN: Loan is given to group, then later loan amount + * is split into individual loans. Loan is tracked at both individual and group + * level * */ public enum LendingStrategy { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProduct.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProduct.java index df45afe13..1d47397b3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProduct.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProduct.java @@ -48,7 +48,7 @@ import com.google.gson.JsonArray; */ @Entity @Table(name = "m_product_loan", uniqueConstraints = { @UniqueConstraint(columnNames = { "name" }, name = "unq_name"), -@UniqueConstraint(columnNames = { "external_id" }, name = "external_id_UNIQUE") }) + @UniqueConstraint(columnNames = { "external_id" }, name = "external_id_UNIQUE") }) public class LoanProduct extends AbstractPersistable { @ManyToOne @@ -77,21 +77,21 @@ public class LoanProduct extends AbstractPersistable { @Column(name = "accounting_type", nullable = false) private Integer accountingRule; - + @Column(name = "include_in_borrower_cycle") private boolean includeInBorrowerCycle; @Column(name = "start_date", nullable = true) @Temporal(TemporalType.DATE) private Date startDate; - + @Column(name = "close_date", nullable = true) @Temporal(TemporalType.DATE) private Date closeDate; @Column(name = "external_id", length = 100, nullable = true, unique = true) private String externalId; - + public static LoanProduct assembleFromJson(final Fund fund, final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy, final List productCharges, final JsonCommand command, final AprCalculator aprCalculator) { @@ -100,8 +100,8 @@ public class LoanProduct extends AbstractPersistable { final String currencyCode = command.stringValueOfParameterNamed("currencyCode"); final Integer digitsAfterDecimal = command.integerValueOfParameterNamed("digitsAfterDecimal"); final Integer inMultiplesOf = command.integerValueOfParameterNamed("inMultiplesOf"); - - final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal,inMultiplesOf); + + final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf); final BigDecimal principal = command.bigDecimalValueOfParameterNamed("principal"); final BigDecimal minPrincipal = command.bigDecimalValueOfParameterNamed("minPrincipal"); final BigDecimal maxPrincipal = command.bigDecimalValueOfParameterNamed("maxPrincipal"); @@ -132,16 +132,17 @@ public class LoanProduct extends AbstractPersistable { final AccountingRuleType accountingRuleType = AccountingRuleType.fromInt(command.integerValueOfParameterNamed("accountingRule")); final boolean includeInBorrowerCycle = command.booleanPrimitiveValueOfParameterNamed("includeInBorrowerCycle"); - + final LocalDate startDate = command.localDateValueOfParameterNamed("startDate"); final LocalDate closeDate = command.localDateValueOfParameterNamed("closeDate"); final String externalId = command.stringValueOfParameterNamedAllowingNull("externalId"); - + return new LoanProduct(fund, loanTransactionProcessingStrategy, name, description, currency, principal, minPrincipal, maxPrincipal, interestRatePerPeriod, minInterestRatePerPeriod, maxInterestRatePerPeriod, interestFrequencyType, annualInterestRate, interestMethod, interestCalculationPeriodMethod, repaymentEvery, repaymentFrequencyType, numberOfRepayments, minNumberOfRepayments, maxNumberOfRepayments, graceOnPrincipalPayment, graceOnInterestPayment, graceOnInterestCharged, - amortizationMethod, inArrearsTolerance, productCharges, accountingRuleType, includeInBorrowerCycle, startDate, closeDate, externalId); + amortizationMethod, inArrearsTolerance, productCharges, accountingRuleType, includeInBorrowerCycle, startDate, closeDate, + externalId); } protected LoanProduct() { @@ -160,7 +161,7 @@ public class LoanProduct extends AbstractPersistable { final Integer defaultMinNumberOfInstallments, final Integer defaultMaxNumberOfInstallments, final Integer graceOnPrincipalPayment, final Integer graceOnInterestPayment, final Integer graceOnInterestCharged, final AmortizationMethod amortizationMethod, final BigDecimal inArrearsTolerance, final List charges, - final AccountingRuleType accountingRuleType, final boolean includeInBorrowerCycle, final LocalDate startDate, + final AccountingRuleType accountingRuleType, final boolean includeInBorrowerCycle, final LocalDate startDate, final LocalDate closeDate, final String externalId) { this.fund = fund; this.transactionProcessingStrategy = transactionProcessingStrategy; @@ -190,11 +191,11 @@ public class LoanProduct extends AbstractPersistable { this.accountingRule = accountingRuleType.getValue(); } this.includeInBorrowerCycle = includeInBorrowerCycle; - + if (startDate != null) { this.startDate = startDate.toDateMidnight().toDate(); } - + if (closeDate != null) { this.closeDate = closeDate.toDateMidnight().toDate(); } @@ -219,7 +220,7 @@ public class LoanProduct extends AbstractPersistable { } public boolean update(final List newProductCharges) { - if (newProductCharges == null) return false; + if (newProductCharges == null) { return false; } boolean updated = false; if (this.charges != null) { @@ -244,7 +245,7 @@ public class LoanProduct extends AbstractPersistable { public Map update(final JsonCommand command, final AprCalculator aprCalculator) { final Map actualChanges = this.loanProductRelatedDetail.update(command, aprCalculator); - actualChanges.putAll(this.loanProductMinMaxConstraints().update(command)); + actualChanges.putAll(loanProductMinMaxConstraints().update(command)); final String accountingTypeParamName = "accountingRule"; if (command.isChangeInIntegerParameterNamed(accountingTypeParamName, this.accountingRule)) { @@ -276,7 +277,7 @@ public class LoanProduct extends AbstractPersistable { final Long newValue = command.longValueOfParameterNamed(fundIdParamName); actualChanges.put(fundIdParamName, newValue); } - + Long existingStrategyId = null; if (this.transactionProcessingStrategy != null) { existingStrategyId = this.transactionProcessingStrategy.getId(); @@ -289,22 +290,22 @@ public class LoanProduct extends AbstractPersistable { final String chargesParamName = "charges"; if (command.hasParameter(chargesParamName)) { - JsonArray jsonArray = command.arrayOfParameterNamed(chargesParamName); + final JsonArray jsonArray = command.arrayOfParameterNamed(chargesParamName); if (jsonArray != null) { actualChanges.put(chargesParamName, command.jsonFragment(chargesParamName)); } } - + final String includeInBorrowerCycleParamName = "includeInBorrowerCycle"; if (command.isChangeInBooleanParameterNamed(includeInBorrowerCycleParamName, this.includeInBorrowerCycle)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(includeInBorrowerCycleParamName); actualChanges.put(includeInBorrowerCycleParamName, newValue); this.includeInBorrowerCycle = newValue; } - + final String dateFormatAsInput = command.dateFormat(); final String localeAsInput = command.locale(); - + final String localeParamName = "locale"; final String dateFormatParamName = "dateFormat"; @@ -319,7 +320,7 @@ public class LoanProduct extends AbstractPersistable { if (newValue != null) { this.startDate = newValue.toDate(); } else { - this.startDate = null; + this.startDate = null; } } @@ -334,7 +335,7 @@ public class LoanProduct extends AbstractPersistable { if (newValue != null) { this.closeDate = newValue.toDate(); } else { - this.closeDate = null; + this.closeDate = null; } } @@ -343,8 +344,8 @@ public class LoanProduct extends AbstractPersistable { final String newValue = command.stringValueOfParameterNamed(externalIdTypeParamName); actualChanges.put(accountingTypeParamName, newValue); this.externalId = newValue; - } - + } + return actualChanges; } @@ -361,11 +362,11 @@ public class LoanProduct extends AbstractPersistable { } public Money getMinPrincipalAmount() { - return Money.of(this.loanProductRelatedDetail.getCurrency(), this.loanProductMinMaxConstraints().getMinPrincipal()); + return Money.of(this.loanProductRelatedDetail.getCurrency(), loanProductMinMaxConstraints().getMinPrincipal()); } public Money getMaxPrincipalAmount() { - return Money.of(this.loanProductRelatedDetail.getCurrency(), this.loanProductMinMaxConstraints().getMaxPrincipal()); + return Money.of(this.loanProductRelatedDetail.getCurrency(), loanProductMinMaxConstraints().getMaxPrincipal()); } public BigDecimal getNominalInterestRatePerPeriod() { @@ -377,11 +378,11 @@ public class LoanProduct extends AbstractPersistable { } public BigDecimal getMinNominalInterestRatePerPeriod() { - return this.loanProductMinMaxConstraints().getMinNominalInterestRatePerPeriod(); + return loanProductMinMaxConstraints().getMinNominalInterestRatePerPeriod(); } public BigDecimal getMaxNominalInterestRatePerPeriod() { - return this.loanProductMinMaxConstraints().getMaxNominalInterestRatePerPeriod(); + return loanProductMinMaxConstraints().getMaxNominalInterestRatePerPeriod(); } public Integer getNumberOfRepayments() { @@ -389,11 +390,11 @@ public class LoanProduct extends AbstractPersistable { } public Integer getMinNumberOfRepayments() { - return this.loanProductMinMaxConstraints().getMinNumberOfRepayments(); + return loanProductMinMaxConstraints().getMinNumberOfRepayments(); } public Integer getMaxNumberOfRepayments() { - return this.loanProductMinMaxConstraints().getMaxNumberOfRepayments(); + return loanProductMinMaxConstraints().getMaxNumberOfRepayments(); } public LoanProductMinMaxConstraints loanProductMinMaxConstraints() { @@ -402,13 +403,13 @@ public class LoanProduct extends AbstractPersistable { // Reset LoanProductMinMaxConstraints with null values. this.loanProductMinMaxConstraints = (this.loanProductMinMaxConstraints == null) ? new LoanProductMinMaxConstraints(null, null, null, null, null, null) : this.loanProductMinMaxConstraints; - return loanProductMinMaxConstraints; + return this.loanProductMinMaxConstraints; } public boolean isIncludeInBorrowerCycle() { return this.includeInBorrowerCycle; } - + public LocalDate getStartDate() { LocalDate startLocalDate = null; if (this.startDate != null) { @@ -416,7 +417,7 @@ public class LoanProduct extends AbstractPersistable { } return startLocalDate; } - + public LocalDate getCloseDate() { LocalDate closeLocalDate = null; if (this.closeDate != null) { @@ -429,8 +430,8 @@ public class LoanProduct extends AbstractPersistable { return this.name; } - public String getExternalId() { - return externalId; - } - + public String getExternalId() { + return this.externalId; + } + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProductMinMaxConstraints.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProductMinMaxConstraints.java index e92ee3cb4..81dd77bdf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProductMinMaxConstraints.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProductMinMaxConstraints.java @@ -120,11 +120,11 @@ public class LoanProductMinMaxConstraints { return actualChanges; } - + public BigDecimal getMinPrincipal() { return this.minPrincipal; } - + public BigDecimal getMaxPrincipal() { return this.maxPrincipal; } @@ -140,11 +140,11 @@ public class LoanProductMinMaxConstraints { } public Integer getMinNumberOfRepayments() { - return minNumberOfRepayments; + return this.minNumberOfRepayments; } public Integer getMaxNumberOfRepayments() { - return maxNumberOfRepayments; + return this.maxNumberOfRepayments; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProductRelatedDetail.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProductRelatedDetail.java index 76d58ce9f..b87e60f5e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProductRelatedDetail.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanProductRelatedDetail.java @@ -164,7 +164,7 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche } public PeriodFrequencyType getInterestPeriodFrequencyType() { - return interestPeriodFrequencyType; + return this.interestPeriodFrequencyType; } public BigDecimal getAnnualNominalInterestRate() { @@ -172,30 +172,30 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche } public InterestMethod getInterestMethod() { - return interestMethod; + return this.interestMethod; } public InterestCalculationPeriodMethod getInterestCalculationPeriodMethod() { - return interestCalculationPeriodMethod; + return this.interestCalculationPeriodMethod; } @Override public Integer getRepayEvery() { - return repayEvery; + return this.repayEvery; } @Override public PeriodFrequencyType getRepaymentPeriodFrequencyType() { - return repaymentPeriodFrequencyType; + return this.repaymentPeriodFrequencyType; } @Override public Integer getNumberOfRepayments() { - return numberOfRepayments; + return this.numberOfRepayments; } public AmortizationMethod getAmortizationMethod() { - return amortizationMethod; + return this.amortizationMethod; } public Map update(final JsonCommand command, final AprCalculator aprCalculator) { @@ -214,7 +214,7 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche actualChanges.put(digitsAfterDecimalParamName, newValue); actualChanges.put("locale", localeAsInput); digitsAfterDecimal = newValue; - this.currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal,inMultiplesOf); + this.currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf); } final String currencyCodeParamName = "currencyCode"; @@ -222,7 +222,7 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche final String newValue = command.stringValueOfParameterNamed(currencyCodeParamName); actualChanges.put(currencyCodeParamName, newValue); currencyCode = newValue; - this.currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal,inMultiplesOf); + this.currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf); } final String inMultiplesOfParamName = "inMultiplesOf"; @@ -230,7 +230,7 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche final Integer newValue = command.integerValueOfParameterNamed(inMultiplesOfParamName); actualChanges.put(inMultiplesOfParamName, newValue); inMultiplesOf = newValue; - this.currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal,inMultiplesOf); + this.currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf); } final Map loanApplicationAttributeChanges = updateLoanApplicationAttributes(command, aprCalculator); @@ -362,17 +362,17 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanproduct"); if (this.numberOfRepayments <= defaultToZeroIfNull(this.graceOnPrincipalPayment)) { - baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment) + baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(this.graceOnPrincipalPayment) .failWithCode(".mustBeLessThan.numberOfRepayments"); } if (this.numberOfRepayments <= defaultToZeroIfNull(this.graceOnInterestPayment)) { - baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment) + baseDataValidator.reset().parameter("graceOnInterestPayment").value(this.graceOnInterestPayment) .failWithCode(".mustBeLessThan.numberOfRepayments"); } if (this.numberOfRepayments < defaultToZeroIfNull(this.graceOnInterestCharged)) { - baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged) + baseDataValidator.reset().parameter("graceOnInterestCharged").value(this.graceOnInterestCharged) .failWithCode(".mustBeLessThan.numberOfRepayments"); } @@ -394,7 +394,7 @@ public class LoanProductRelatedDetail implements LoanProductMinimumRepaymentSche public boolean hasCurrencyCodeOf(final String currencyCode) { return this.currency.getCode().equalsIgnoreCase(currencyCode); } - + public void updatenterestPeriodFrequencyType(final PeriodFrequencyType interestPeriodFrequencyType) { this.interestPeriodFrequencyType = interestPeriodFrequencyType; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanTransactionProcessingStrategy.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanTransactionProcessingStrategy.java index 91e0d0711..76377e836 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanTransactionProcessingStrategy.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/LoanTransactionProcessingStrategy.java @@ -27,7 +27,7 @@ public class LoanTransactionProcessingStrategy extends AbstractPersistable } public TransactionProcessingStrategyData toData() { - return new TransactionProcessingStrategyData(this.getId(), this.code, this.name); + return new TransactionProcessingStrategyData(getId(), this.code, this.name); } public boolean isStandardMifosStrategy() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/PeriodFrequencyType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/PeriodFrequencyType.java index 83bb83ea1..3d1213039 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/PeriodFrequencyType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/domain/PeriodFrequencyType.java @@ -25,7 +25,7 @@ public enum PeriodFrequencyType { } public String getCode() { - return code; + return this.code; } public static PeriodFrequencyType fromInt(final Integer frequency) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/InvalidCurrencyException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/InvalidCurrencyException.java index cdd273d38..1c9b1ea45 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/InvalidCurrencyException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/InvalidCurrencyException.java @@ -13,7 +13,8 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class InvalidCurrencyException extends AbstractPlatformDomainRuleException { - public InvalidCurrencyException(final String entity, final String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { + public InvalidCurrencyException(final String entity, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg." + entity + "." + postFix + ".invalid.currency", defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/InvalidLendingStrategy.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/InvalidLendingStrategy.java index e03b721b2..e87de7c3d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/InvalidLendingStrategy.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/InvalidLendingStrategy.java @@ -8,11 +8,12 @@ package org.mifosplatform.portfolio.loanproduct.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown when lending strategy mismatch - * occurs + * {@link AbstractPlatformDomainRuleException} thrown when lending strategy + * mismatch occurs */ public class InvalidLendingStrategy extends AbstractPlatformDomainRuleException { - public InvalidLendingStrategy(final Integer strategyId ) { - super("error.msg.unsupported.lending.strategy", "Stratagy code ["+ strategyId + "] passed is not valid."); + + public InvalidLendingStrategy(final Integer strategyId) { + super("error.msg.unsupported.lending.strategy", "Stratagy code [" + strategyId + "] passed is not valid."); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/LinkedAccountRequiredException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/LinkedAccountRequiredException.java index 932d1d8da..a845ed945 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/LinkedAccountRequiredException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/LinkedAccountRequiredException.java @@ -2,10 +2,9 @@ package org.mifosplatform.portfolio.loanproduct.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - public class LinkedAccountRequiredException extends AbstractPlatformDomainRuleException { - public LinkedAccountRequiredException(final String entity, String defaultUserMessage, Object... defaultUserMessageArgs) { + public LinkedAccountRequiredException(final String entity, final String defaultUserMessage, final Object... defaultUserMessageArgs) { super("error.msg." + entity + ".requires.linked.account", defaultUserMessage, defaultUserMessageArgs); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/LoanProductDateException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/LoanProductDateException.java index e55970bbc..a1f50ff27 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/LoanProductDateException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/LoanProductDateException.java @@ -2,10 +2,9 @@ package org.mifosplatform.portfolio.loanproduct.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - public class LoanProductDateException extends AbstractPlatformDomainRuleException { - public LoanProductDateException(Object... defaultUserMessageArgs) { + public LoanProductDateException(final Object... defaultUserMessageArgs) { super("error.msg.loan.product.close.date.cannot.be.before.start.date.close.date", "Loan product close date cannot be before the start date", defaultUserMessageArgs); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/NotInMinMaxRangeException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/NotInMinMaxRangeException.java index 502b2f30d..6e6c26346 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/NotInMinMaxRangeException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/exception/NotInMinMaxRangeException.java @@ -8,12 +8,14 @@ package org.mifosplatform.portfolio.loanproduct.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown when a value is not within minimum and maximum values. + * {@link AbstractPlatformDomainRuleException} thrown when a value is not within + * minimum and maximum values. * */ public class NotInMinMaxRangeException extends AbstractPlatformDomainRuleException { - public NotInMinMaxRangeException(final String entity, final String postFix, String defaultUserMessage, Object... defaultUserMessageArgs) { + public NotInMinMaxRangeException(final String entity, final String postFix, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("validation.msg." + entity + "." + postFix + ".is.not.within.min.max.range", defaultUserMessage, defaultUserMessageArgs); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/data/ProductMixData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/data/ProductMixData.java index 4fe07286d..16c61d165 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/data/ProductMixData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/data/ProductMixData.java @@ -31,13 +31,13 @@ public class ProductMixData { productMixData.allowedProducts, productOptions); } - public static ProductMixData withDetails(Long productId, String productName, Collection restrictedProducts, - Collection allowedProducts) { + public static ProductMixData withDetails(final Long productId, final String productName, + final Collection restrictedProducts, final Collection allowedProducts) { return new ProductMixData(productId, productName, restrictedProducts, allowedProducts, null); } - public static ProductMixData withRestrictedOptions(Collection restrictedProducts, - Collection allowedProducts) { + public static ProductMixData withRestrictedOptions(final Collection restrictedProducts, + final Collection allowedProducts) { return new ProductMixData(null, null, restrictedProducts, allowedProducts, null); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/domain/ProductMix.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/domain/ProductMix.java index bffc37936..2ffee3880 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/domain/ProductMix.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/domain/ProductMix.java @@ -32,7 +32,7 @@ public class ProductMix extends AbstractPersistable { public static ProductMix createNew(final LoanProduct product, final LoanProduct restrictedProduct) { return new ProductMix(product, restrictedProduct); } - + public Long getRestrictedProductId() { return this.restrictedProduct.getId(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/serialization/ProductMixDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/serialization/ProductMixDataValidator.java index 1230b8126..300524848 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/serialization/ProductMixDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/serialization/ProductMixDataValidator.java @@ -51,7 +51,6 @@ public final class ProductMixDataValidator { if (restrictedProducts != null) { validateRestrictedProducts(restrictedProducts, baseDataValidator); } - throwExceptionIfValidationWarningsExist(dataValidationErrors); } @@ -67,8 +66,8 @@ public final class ProductMixDataValidator { "Validation errors exist.", dataValidationErrors); } } - public void validateForUpdate(String json) { - + public void validateForUpdate(final String json) { + if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixReadPlatformService.java index a80fa9851..e3b221f48 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixReadPlatformService.java @@ -4,10 +4,9 @@ import java.util.Collection; import org.mifosplatform.portfolio.loanproduct.productmix.data.ProductMixData; - public interface ProductMixReadPlatformService { ProductMixData retrieveLoanProductMixDetails(Long productId); - + Collection retrieveAllProductMixes(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixReadPlatformServiceImpl.java index 19e2416bb..f03c561ad 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixReadPlatformServiceImpl.java @@ -86,9 +86,11 @@ public class ProductMixReadPlatformServiceImpl implements ProductMixReadPlatform final Map extractedData = new HashMap(); if (!rs.next()) { - final Collection restrictedProducts = this.loanProductReadPlatformService.retrieveRestrictedProductsForMix(this.productId); - final Collection allowedProducts = this.loanProductReadPlatformService.retrieveAllowedProductsForMix(this.productId); - ProductMixData productMixData = ProductMixData.withRestrictedOptions(restrictedProducts, allowedProducts); + final Collection restrictedProducts = this.loanProductReadPlatformService + .retrieveRestrictedProductsForMix(this.productId); + final Collection allowedProducts = this.loanProductReadPlatformService + .retrieveAllowedProductsForMix(this.productId); + final ProductMixData productMixData = ProductMixData.withRestrictedOptions(restrictedProducts, allowedProducts); extractedData.put(this.productId, productMixData); return extractedData; } @@ -97,8 +99,10 @@ public class ProductMixReadPlatformServiceImpl implements ProductMixReadPlatform while (rs.next()) { final Long productId = rs.getLong("productId"); final String name = rs.getString("name"); - final Collection restrictedProducts = this.loanProductReadPlatformService.retrieveRestrictedProductsForMix(productId); - final Collection allowedProducts = this.loanProductReadPlatformService.retrieveAllowedProductsForMix(productId); + final Collection restrictedProducts = this.loanProductReadPlatformService + .retrieveRestrictedProductsForMix(productId); + final Collection allowedProducts = this.loanProductReadPlatformService + .retrieveAllowedProductsForMix(productId); final ProductMixData productMixData = ProductMixData.withDetails(productId, name, restrictedProducts, allowedProducts); extractedData.put(productId, productMixData); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixWritePlatformServiceJpaRepositoryImpl.java index 8ddef46f1..1cb9c7240 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/productmix/service/ProductMixWritePlatformServiceJpaRepositoryImpl.java @@ -60,7 +60,8 @@ public class ProductMixWritePlatformServiceJpaRepositoryImpl implements ProductM final Set restrictedIds = new HashSet(Arrays.asList(command.arrayValueOfParameterNamed("restrictedProducts"))); - // remove the existed restriction if it is not exists in restrictedIds. + // remove the existed restriction if it is not exists in + // restrictedIds. final List removedRestrictions = updateRestrictionsForProduct(productId, restrictedIds); final Map restrictedProductsAsMap = getRestrictedProducts(restrictedIds); final List productMixes = new ArrayList(); @@ -137,7 +138,7 @@ public class ProductMixWritePlatformServiceJpaRepositoryImpl implements ProductM final Map restrictedProductsAsMap = getRestrictedProducts(restrictedIds); createNewProductMix(restrictedProductsAsMap, productId, existedProductMixes); - this.productMixRepository.save(existedProductMixes); + this.productMixRepository.save(existedProductMixes); changes.put("restrictedProductsForMix", getProductIdsFromCollection(existedProductMixes)); if (!CollectionUtils.isEmpty(productMixesToRemove)) { @@ -213,10 +214,10 @@ public class ProductMixWritePlatformServiceJpaRepositoryImpl implements ProductM return CommandProcessingResult.empty(); } } - + private List getProductIdsFromCollection(final List collection) { final List productIds = new ArrayList(); - for (ProductMix productMix : collection) { + for (final ProductMix productMix : collection) { productIds.add(productMix.getRestrictedProductId()); } return productIds; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/serialization/LoanProductDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/serialization/LoanProductDataValidator.java index 25ce489a2..fd018242d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/serialization/LoanProductDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/serialization/LoanProductDataValidator.java @@ -65,52 +65,52 @@ public final class LoanProductDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanproduct"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); - final String description = fromApiJsonHelper.extractStringNamed("description", element); + final String description = this.fromApiJsonHelper.extractStringNamed("description", element); baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500); - if (fromApiJsonHelper.parameterExists("fundId", element)) { - final Long fundId = fromApiJsonHelper.extractLongNamed("fundId", element); + if (this.fromApiJsonHelper.parameterExists("fundId", element)) { + final Long fundId = this.fromApiJsonHelper.extractLongNamed("fundId", element); baseDataValidator.reset().parameter("fundId").value(fundId).ignoreIfNull().integerGreaterThanZero(); } - final Boolean includeInBorrowerCycle = fromApiJsonHelper.extractBooleanNamed("includeInBorrowerCycle", element); + final Boolean includeInBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed("includeInBorrowerCycle", element); baseDataValidator.reset().parameter("includeInBorrowerCycle").value(includeInBorrowerCycle).ignoreIfNull() .validateForBooleanValue(); // terms - final String currencyCode = fromApiJsonHelper.extractStringNamed("currencyCode", element); + final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element); baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3); - final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, Locale.getDefault()); + final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, Locale.getDefault()); baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); - final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element, Locale.getDefault()); + final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element, Locale.getDefault()); baseDataValidator.reset().parameter("inMultiplesOf").value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); - final BigDecimal principal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); + final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); baseDataValidator.reset().parameter("principal").value(principal).notNull().positiveAmount(); - String minPrincipalParameterName = "minPrincipal"; + final String minPrincipalParameterName = "minPrincipal"; BigDecimal minPrincipalAmount = null; - if (fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) { - minPrincipalAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element); + if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) { + minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element); baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount).ignoreIfNull().positiveAmount(); } - String maxPrincipalParameterName = "maxPrincipal"; + final String maxPrincipalParameterName = "maxPrincipal"; BigDecimal maxPrincipalAmount = null; - if (fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) { - maxPrincipalAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element); + if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) { + maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element); baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).ignoreIfNull().positiveAmount(); } @@ -128,21 +128,21 @@ public final class LoanProductDataValidator { baseDataValidator.reset().parameter("principal").value(principal).notLessThanMin(minPrincipalAmount); } - final Integer numberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed("numberOfRepayments", element); + final Integer numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("numberOfRepayments", element); baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notNull().integerGreaterThanZero(); - String minNumberOfRepaymentsParameterName = "minNumberOfRepayments"; + final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments"; Integer minNumberOfRepayments = null; - if (fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) { - minNumberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element); + if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) { + minNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element); baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments).ignoreIfNull() .integerGreaterThanZero(); } - String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments"; + final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments"; Integer maxNumberOfRepayments = null; - if (fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) { - maxNumberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element); + if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) { + maxNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element); baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments).ignoreIfNull() .integerGreaterThanZero(); } @@ -163,28 +163,30 @@ public final class LoanProductDataValidator { baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notLessThanMin(minNumberOfRepayments); } - final Integer repaymentEvery = fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element); + final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element); baseDataValidator.reset().parameter("repaymentEvery").value(repaymentEvery).notNull().integerGreaterThanZero(); - final Integer repaymentFrequencyType = fromApiJsonHelper - .extractIntegerNamed("repaymentFrequencyType", element, Locale.getDefault()); + final Integer repaymentFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("repaymentFrequencyType", element, + Locale.getDefault()); baseDataValidator.reset().parameter("repaymentFrequencyType").value(repaymentFrequencyType).notNull().inMinMaxRange(0, 3); - final BigDecimal interestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element); + final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element); baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod).notNull().zeroOrPositiveAmount(); - String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod"; + final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod"; BigDecimal minInterestRatePerPeriod = null; - if (fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) { - minInterestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, element); + if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) { + minInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, + element); baseDataValidator.reset().parameter(minInterestRatePerPeriodParameterName).value(minInterestRatePerPeriod).ignoreIfNull() .zeroOrPositiveAmount(); } - String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod"; + final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod"; BigDecimal maxInterestRatePerPeriod = null; - if (fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) { - maxInterestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, element); + if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) { + maxInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, + element); baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName).value(maxInterestRatePerPeriod).ignoreIfNull() .zeroOrPositiveAmount(); } @@ -206,76 +208,77 @@ public final class LoanProductDataValidator { .notLessThanMin(minInterestRatePerPeriod); } - final Integer interestRateFrequencyType = fromApiJsonHelper.extractIntegerNamed("interestRateFrequencyType", element, + final Integer interestRateFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("interestRateFrequencyType", element, Locale.getDefault()); baseDataValidator.reset().parameter("interestRateFrequencyType").value(interestRateFrequencyType).notNull().inMinMaxRange(0, 3); // settings - final Integer amortizationType = fromApiJsonHelper.extractIntegerNamed("amortizationType", element, Locale.getDefault()); + final Integer amortizationType = this.fromApiJsonHelper.extractIntegerNamed("amortizationType", element, Locale.getDefault()); baseDataValidator.reset().parameter("amortizationType").value(amortizationType).notNull().inMinMaxRange(0, 1); - final Integer interestType = fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); + final Integer interestType = this.fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); baseDataValidator.reset().parameter("interestType").value(interestType).notNull().inMinMaxRange(0, 1); - final Integer interestCalculationPeriodType = fromApiJsonHelper.extractIntegerNamed("interestCalculationPeriodType", element, + final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerNamed("interestCalculationPeriodType", element, Locale.getDefault()); baseDataValidator.reset().parameter("interestCalculationPeriodType").value(interestCalculationPeriodType).notNull() .inMinMaxRange(0, 1); - final BigDecimal inArrearsTolerance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element); + final BigDecimal inArrearsTolerance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element); baseDataValidator.reset().parameter("inArrearsTolerance").value(inArrearsTolerance).ignoreIfNull().zeroOrPositiveAmount(); - final Long transactionProcessingStrategyId = fromApiJsonHelper.extractLongNamed("transactionProcessingStrategyId", element); + final Long transactionProcessingStrategyId = this.fromApiJsonHelper.extractLongNamed("transactionProcessingStrategyId", element); baseDataValidator.reset().parameter("transactionProcessingStrategyId").value(transactionProcessingStrategyId).notNull() .integerGreaterThanZero(); // grace validation - final Integer graceOnPrincipalPayment = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); + final Integer graceOnPrincipalPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment).zeroOrPositiveAmount(); - final Integer graceOnInterestPayment = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); + final Integer graceOnInterestPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment).zeroOrPositiveAmount(); - final Integer graceOnInterestCharged = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); + final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged).zeroOrPositiveAmount(); // accounting related data validation - final Integer accountingRuleType = fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault()); + final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault()); baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).notNull().inMinMaxRange(1, 3); if (isCashBasedAccounting(accountingRuleType) || isAccrualBasedAccounting(accountingRuleType)) { - final Long fundAccountId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), element); + final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), + element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).value(fundAccountId).notNull() .integerGreaterThanZero(); - final Long loanPortfolioAccountId = fromApiJsonHelper.extractLongNamed( + final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue()).value(loanPortfolioAccountId) .notNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero(); - final Long incomeFromInterestId = fromApiJsonHelper.extractLongNamed( + final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue()).value(incomeFromInterestId) .notNull().integerGreaterThanZero(); - final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), - element); + final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed( + LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .notNull().integerGreaterThanZero(); - final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( + final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .notNull().integerGreaterThanZero(); - final Long writeOffAccountId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), - element); + final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed( + LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue()).value(writeOffAccountId) .notNull().integerGreaterThanZero(); @@ -286,17 +289,17 @@ public final class LoanProductDataValidator { if (isAccrualBasedAccounting(accountingRuleType)) { - final Long receivableInterestAccountId = fromApiJsonHelper.extractLongNamed( + final Long receivableInterestAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue()) .value(receivableInterestAccountId).notNull().integerGreaterThanZero(); - final Long receivableFeeAccountId = fromApiJsonHelper.extractLongNamed( + final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue()).value(receivableFeeAccountId) .notNull().integerGreaterThanZero(); - final Long receivablePenaltyAccountId = fromApiJsonHelper.extractLongNamed( + final Long receivablePenaltyAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue()) .value(receivablePenaltyAccountId).notNull().integerGreaterThanZero(); @@ -309,219 +312,225 @@ public final class LoanProductDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("loanproduct"); - final JsonElement element = fromApiJsonHelper.parse(json); - if (fromApiJsonHelper.parameterExists("name", element)) { - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + if (this.fromApiJsonHelper.parameterExists("name", element)) { + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("description", element)) { - final String description = fromApiJsonHelper.extractStringNamed("description", element); + if (this.fromApiJsonHelper.parameterExists("description", element)) { + final String description = this.fromApiJsonHelper.extractStringNamed("description", element); baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500); } - if (fromApiJsonHelper.parameterExists("fundId", element)) { - final Long fundId = fromApiJsonHelper.extractLongNamed("fundId", element); + if (this.fromApiJsonHelper.parameterExists("fundId", element)) { + final Long fundId = this.fromApiJsonHelper.extractLongNamed("fundId", element); baseDataValidator.reset().parameter("fundId").value(fundId).ignoreIfNull().integerGreaterThanZero(); } - if (fromApiJsonHelper.parameterExists("includeInBorrowerCycle", element)) { - final Boolean includeInBorrowerCycle = fromApiJsonHelper.extractBooleanNamed("includeInBorrowerCycle", element); + if (this.fromApiJsonHelper.parameterExists("includeInBorrowerCycle", element)) { + final Boolean includeInBorrowerCycle = this.fromApiJsonHelper.extractBooleanNamed("includeInBorrowerCycle", element); baseDataValidator.reset().parameter("includeInBorrowerCycle").value(includeInBorrowerCycle).ignoreIfNull() .validateForBooleanValue(); } - if (fromApiJsonHelper.parameterExists("currencyCode", element)) { - final String currencyCode = fromApiJsonHelper.extractStringNamed("currencyCode", element); + if (this.fromApiJsonHelper.parameterExists("currencyCode", element)) { + final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element); baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank().notExceedingLengthOf(3); } - if (fromApiJsonHelper.parameterExists("digitsAfterDecimal", element)) { - final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, Locale.getDefault()); + if (this.fromApiJsonHelper.parameterExists("digitsAfterDecimal", element)) { + final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal", element, + Locale.getDefault()); baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } - if (fromApiJsonHelper.parameterExists("inMultiplesOf", element)) { - final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element, Locale.getDefault()); + if (this.fromApiJsonHelper.parameterExists("inMultiplesOf", element)) { + final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element, Locale.getDefault()); baseDataValidator.reset().parameter("inMultiplesOf").value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } - String minPrincipalParameterName = "minPrincipal"; + final String minPrincipalParameterName = "minPrincipal"; BigDecimal minPrincipalAmount = null; - if (fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) { - minPrincipalAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element); + if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) { + minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element); baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount).ignoreIfNull().positiveAmount(); } - String maxPrincipalParameterName = "maxPrincipal"; + final String maxPrincipalParameterName = "maxPrincipal"; BigDecimal maxPrincipalAmount = null; - if (fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) { - maxPrincipalAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element); + if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) { + maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element); baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).ignoreIfNull().positiveAmount(); } - if (fromApiJsonHelper.parameterExists("principal", element)) { - final BigDecimal principal = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); + if (this.fromApiJsonHelper.parameterExists("principal", element)) { + final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element); baseDataValidator.reset().parameter("principal").value(principal).notNull().positiveAmount(); } - if (fromApiJsonHelper.parameterExists("inArrearsTolerance", element)) { - final BigDecimal inArrearsTolerance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element); + if (this.fromApiJsonHelper.parameterExists("inArrearsTolerance", element)) { + final BigDecimal inArrearsTolerance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("inArrearsTolerance", element); baseDataValidator.reset().parameter("inArrearsTolerance").value(inArrearsTolerance).ignoreIfNull().zeroOrPositiveAmount(); } - String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod"; + final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod"; BigDecimal minInterestRatePerPeriod = null; - if (fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) { - minInterestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, element); + if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) { + minInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, + element); baseDataValidator.reset().parameter(minInterestRatePerPeriodParameterName).value(minInterestRatePerPeriod).ignoreIfNull() .zeroOrPositiveAmount(); } - String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod"; + final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod"; BigDecimal maxInterestRatePerPeriod = null; - if (fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) { - maxInterestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, element); + if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) { + maxInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, + element); baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName).value(maxInterestRatePerPeriod).ignoreIfNull() .zeroOrPositiveAmount(); } - if (fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) { - final BigDecimal interestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element); + if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) { + final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("interestRatePerPeriod", + element); baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod).notNull().zeroOrPositiveAmount(); } - String minNumberOfRepaymentsParameterName = "minNumberOfRepayments"; + final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments"; Integer minNumberOfRepayments = null; - if (fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) { - minNumberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element); + if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) { + minNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element); baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments).ignoreIfNull() .integerGreaterThanZero(); } - String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments"; + final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments"; Integer maxNumberOfRepayments = null; - if (fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) { - maxNumberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element); + if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) { + maxNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element); baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments).ignoreIfNull() .integerGreaterThanZero(); } - if (fromApiJsonHelper.parameterExists("numberOfRepayments", element)) { - final Integer numberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed("numberOfRepayments", element); + if (this.fromApiJsonHelper.parameterExists("numberOfRepayments", element)) { + final Integer numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("numberOfRepayments", element); baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notNull().integerGreaterThanZero(); } - if (fromApiJsonHelper.parameterExists("repaymentEvery", element)) { - final Integer repaymentEvery = fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element); + if (this.fromApiJsonHelper.parameterExists("repaymentEvery", element)) { + final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery", element); baseDataValidator.reset().parameter("repaymentEvery").value(repaymentEvery).notNull().integerGreaterThanZero(); } - if (fromApiJsonHelper.parameterExists("repaymentFrequencyType", element)) { - final Integer repaymentFrequencyType = fromApiJsonHelper.extractIntegerNamed("repaymentFrequencyType", element, + if (this.fromApiJsonHelper.parameterExists("repaymentFrequencyType", element)) { + final Integer repaymentFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("repaymentFrequencyType", element, Locale.getDefault()); baseDataValidator.reset().parameter("repaymentFrequencyType").value(repaymentFrequencyType).notNull().inMinMaxRange(0, 3); } - if (fromApiJsonHelper.parameterExists("transactionProcessingStrategyId", element)) { - final Long transactionProcessingStrategyId = fromApiJsonHelper.extractLongNamed("transactionProcessingStrategyId", element); + if (this.fromApiJsonHelper.parameterExists("transactionProcessingStrategyId", element)) { + final Long transactionProcessingStrategyId = this.fromApiJsonHelper + .extractLongNamed("transactionProcessingStrategyId", element); baseDataValidator.reset().parameter("transactionProcessingStrategyId").value(transactionProcessingStrategyId).notNull() .integerGreaterThanZero(); } // grace validation - if (fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) { - final Integer graceOnPrincipalPayment = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); + if (this.fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) { + final Integer graceOnPrincipalPayment = this.fromApiJsonHelper + .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element); baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment).zeroOrPositiveAmount(); } - if (fromApiJsonHelper.parameterExists("graceOnInterestPayment", element)) { - final Integer graceOnInterestPayment = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); + if (this.fromApiJsonHelper.parameterExists("graceOnInterestPayment", element)) { + final Integer graceOnInterestPayment = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestPayment", element); baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment).zeroOrPositiveAmount(); } - if (fromApiJsonHelper.parameterExists("graceOnInterestCharged", element)) { - final Integer graceOnInterestCharged = fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); + if (this.fromApiJsonHelper.parameterExists("graceOnInterestCharged", element)) { + final Integer graceOnInterestCharged = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("graceOnInterestCharged", element); baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged).zeroOrPositiveAmount(); } // - if (fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) { - final Integer interestRateFrequencyType = fromApiJsonHelper.extractIntegerNamed("interestRateFrequencyType", element, + if (this.fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) { + final Integer interestRateFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("interestRateFrequencyType", element, Locale.getDefault()); baseDataValidator.reset().parameter("interestRateFrequencyType").value(interestRateFrequencyType).notNull().inMinMaxRange(0, 3); } - if (fromApiJsonHelper.parameterExists("amortizationType", element)) { - final Integer amortizationType = fromApiJsonHelper.extractIntegerNamed("amortizationType", element, Locale.getDefault()); + if (this.fromApiJsonHelper.parameterExists("amortizationType", element)) { + final Integer amortizationType = this.fromApiJsonHelper.extractIntegerNamed("amortizationType", element, Locale.getDefault()); baseDataValidator.reset().parameter("amortizationType").value(amortizationType).notNull().inMinMaxRange(0, 1); } - if (fromApiJsonHelper.parameterExists("interestType", element)) { - final Integer interestType = fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); + if (this.fromApiJsonHelper.parameterExists("interestType", element)) { + final Integer interestType = this.fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault()); baseDataValidator.reset().parameter("interestType").value(interestType).notNull().inMinMaxRange(0, 1); } - if (fromApiJsonHelper.parameterExists("interestCalculationPeriodType", element)) { - final Integer interestCalculationPeriodType = fromApiJsonHelper.extractIntegerNamed("interestCalculationPeriodType", element, - Locale.getDefault()); + if (this.fromApiJsonHelper.parameterExists("interestCalculationPeriodType", element)) { + final Integer interestCalculationPeriodType = this.fromApiJsonHelper.extractIntegerNamed("interestCalculationPeriodType", + element, Locale.getDefault()); baseDataValidator.reset().parameter("interestCalculationPeriodType").value(interestCalculationPeriodType).notNull() .inMinMaxRange(0, 1); } - final Integer accountingRuleType = fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault()); + final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault()); baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).ignoreIfNull().inMinMaxRange(1, 3); - final Long fundAccountId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), element); + final Long fundAccountId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue()).value(fundAccountId).ignoreIfNull() .integerGreaterThanZero(); - final Long loanPortfolioAccountId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), - element); + final Long loanPortfolioAccountId = this.fromApiJsonHelper.extractLongNamed( + LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue()).value(loanPortfolioAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); - final Long incomeFromInterestId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), - element); + final Long incomeFromInterestId = this.fromApiJsonHelper.extractLongNamed( + LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue()).value(incomeFromInterestId) .ignoreIfNull().integerGreaterThanZero(); - final Long incomeFromFeeId = fromApiJsonHelper - .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); + final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), + element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); - final Long incomeFromPenaltyId = fromApiJsonHelper.extractLongNamed( + final Long incomeFromPenaltyId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue()).value(incomeFromPenaltyId) .ignoreIfNull().integerGreaterThanZero(); - final Long writeOffAccountId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), - element); + final Long writeOffAccountId = this.fromApiJsonHelper.extractLongNamed( + LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue()).value(writeOffAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long receivableInterestAccountId = fromApiJsonHelper.extractLongNamed( + final Long receivableInterestAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue()) .value(receivableInterestAccountId).ignoreIfNull().integerGreaterThanZero(); - final Long receivableFeeAccountId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), - element); + final Long receivableFeeAccountId = this.fromApiJsonHelper.extractLongNamed( + LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue()).value(receivableFeeAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long receivablePenaltyAccountId = fromApiJsonHelper.extractLongNamed( + final Long receivablePenaltyAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element); baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue()) .value(receivablePenaltyAccountId).ignoreIfNull().integerGreaterThanZero(); @@ -538,16 +547,16 @@ public final class LoanProductDataValidator { * Validation for advanced accounting options */ private void validatePaymentChannelFundSourceMappings(final DataValidatorBuilder baseDataValidator, final JsonElement element) { - if (fromApiJsonHelper.parameterExists(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element)) { - JsonArray paymentChannelMappingArray = fromApiJsonHelper.extractJsonArrayNamed( + if (this.fromApiJsonHelper.parameterExists(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element)) { + final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); if (paymentChannelMappingArray != null && paymentChannelMappingArray.size() > 0) { int i = 0; do { final JsonObject jsonObject = paymentChannelMappingArray.get(i).getAsJsonObject(); - final Long paymentTypeId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.getValue(), - jsonObject); - final Long paymentSpecificFundAccountId = fromApiJsonHelper.extractLongNamed( + final Long paymentTypeId = this.fromApiJsonHelper.extractLongNamed( + LOAN_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_TYPE.getValue(), jsonObject); + final Long paymentSpecificFundAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), jsonObject); baseDataValidator @@ -575,7 +584,7 @@ public final class LoanProductDataValidator { } private void validateChargeToIncomeAccountMappings(final DataValidatorBuilder baseDataValidator, final JsonElement element, - boolean isPenalty) { + final boolean isPenalty) { String parameterName; if (isPenalty) { parameterName = LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTY_INCOME_ACCOUNT_MAPPING.getValue(); @@ -583,15 +592,15 @@ public final class LoanProductDataValidator { parameterName = LOAN_PRODUCT_ACCOUNTING_PARAMS.FEE_INCOME_ACCOUNT_MAPPING.getValue(); } - if (fromApiJsonHelper.parameterExists(parameterName, element)) { - JsonArray chargeToIncomeAccountMappingArray = fromApiJsonHelper.extractJsonArrayNamed(parameterName, element); + if (this.fromApiJsonHelper.parameterExists(parameterName, element)) { + final JsonArray chargeToIncomeAccountMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed(parameterName, element); if (chargeToIncomeAccountMappingArray != null && chargeToIncomeAccountMappingArray.size() > 0) { int i = 0; do { final JsonObject jsonObject = chargeToIncomeAccountMappingArray.get(i).getAsJsonObject(); - final Long chargeId = fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.CHARGE_ID.getValue(), + final Long chargeId = this.fromApiJsonHelper.extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.CHARGE_ID.getValue(), jsonObject); - final Long incomeAccountId = fromApiJsonHelper.extractLongNamed( + final Long incomeAccountId = this.fromApiJsonHelper.extractLongNamed( LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_ACCOUNT_ID.getValue(), jsonObject); baseDataValidator.reset() .parameter(parameterName + "[" + i + "]." + LOAN_PRODUCT_ACCOUNTING_PARAMS.CHARGE_ID.getValue()) @@ -621,28 +630,28 @@ public final class LoanProductDataValidator { boolean principalUpdated = false; boolean minPrincipalUpdated = false; boolean maxPrincipalUpdated = false; - String principalParameterName = "principal"; + final String principalParameterName = "principal"; BigDecimal principalAmount = null; - if (fromApiJsonHelper.parameterExists(principalParameterName, element)) { - principalAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName, element); + if (this.fromApiJsonHelper.parameterExists(principalParameterName, element)) { + principalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(principalParameterName, element); principalUpdated = true; } else { principalAmount = loanProduct.getPrincipalAmount().getAmount(); } - String minPrincipalParameterName = "minPrincipal"; + final String minPrincipalParameterName = "minPrincipal"; BigDecimal minPrincipalAmount = null; - if (fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) { - minPrincipalAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element); + if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) { + minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName, element); minPrincipalUpdated = true; } else { minPrincipalAmount = loanProduct.getMinPrincipalAmount().getAmount(); } - String maxPrincipalParameterName = "maxPrincipal"; + final String maxPrincipalParameterName = "maxPrincipal"; BigDecimal maxPrincipalAmount = null; - if (fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) { - maxPrincipalAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element); + if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) { + maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName, element); maxPrincipalUpdated = true; } else { maxPrincipalAmount = loanProduct.getMaxPrincipalAmount().getAmount(); @@ -679,28 +688,28 @@ public final class LoanProductDataValidator { boolean minNumberOfRepaymentsUpdated = false; boolean maxNumberOfRepaymentsUpdated = false; - String numberOfRepaymentsParameterName = "numberOfRepayments"; + final String numberOfRepaymentsParameterName = "numberOfRepayments"; Integer numberOfRepayments = null; - if (fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) { - numberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element); + if (this.fromApiJsonHelper.parameterExists(numberOfRepaymentsParameterName, element)) { + numberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element); numberOfRepaymentsUpdated = true; } else { numberOfRepayments = loanProduct.getNumberOfRepayments(); } - String minNumberOfRepaymentsParameterName = "minNumberOfRepayments"; + final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments"; Integer minNumberOfRepayments = null; - if (fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) { - minNumberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element); + if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) { + minNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element); minNumberOfRepaymentsUpdated = true; } else { minNumberOfRepayments = loanProduct.getMinNumberOfRepayments(); } - String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments"; + final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments"; Integer maxNumberOfRepayments = null; - if (fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) { - maxNumberOfRepayments = fromApiJsonHelper.extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element); + if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) { + maxNumberOfRepayments = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element); maxNumberOfRepaymentsUpdated = true; } else { maxNumberOfRepayments = loanProduct.getMaxNumberOfRepayments(); @@ -738,29 +747,31 @@ public final class LoanProductDataValidator { boolean iRPUpdated = false; boolean minIRPUpdated = false; boolean maxIRPUpdated = false; - String interestRatePerPeriodParameterName = "interestRatePerPeriod"; + final String interestRatePerPeriodParameterName = "interestRatePerPeriod"; BigDecimal interestRatePerPeriod = null; - if (fromApiJsonHelper.parameterExists(interestRatePerPeriodParameterName, element)) { - interestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, element); + if (this.fromApiJsonHelper.parameterExists(interestRatePerPeriodParameterName, element)) { + interestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, element); iRPUpdated = true; } else { interestRatePerPeriod = loanProduct.getNominalInterestRatePerPeriod(); } - String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod"; + final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod"; BigDecimal minInterestRatePerPeriod = null; - if (fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) { - minInterestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, element); + if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) { + minInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, + element); minIRPUpdated = true; } else { minInterestRatePerPeriod = loanProduct.getMinNominalInterestRatePerPeriod(); } - String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod"; + final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod"; BigDecimal maxInterestRatePerPeriod = null; - if (fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) { - maxInterestRatePerPeriod = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, element); + if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) { + maxInterestRatePerPeriod = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, + element); maxIRPUpdated = true; } else { maxInterestRatePerPeriod = loanProduct.getMaxNominalInterestRatePerPeriod(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LendingStrategyEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LendingStrategyEnumerations.java index e8c4dd5a8..b2b8c1fc9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LendingStrategyEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LendingStrategyEnumerations.java @@ -31,7 +31,7 @@ public class LendingStrategyEnumerations { break; default: - optionData = new EnumOptionData(LendingStrategy.INVALID.getId().longValue(), LendingStrategy.INVALID.getCode() , "Invalid"); + optionData = new EnumOptionData(LendingStrategy.INVALID.getId().longValue(), LendingStrategy.INVALID.getCode(), "Invalid"); break; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanDropdownReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanDropdownReadPlatformServiceImpl.java index 96918f64f..333485583 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanDropdownReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanDropdownReadPlatformServiceImpl.java @@ -41,7 +41,7 @@ public class LoanDropdownReadPlatformServiceImpl implements LoanDropdownReadPlat @Override public List retrieveLoanAmortizationTypeOptions() { - List allowedAmortizationMethods = Arrays.asList(amortizationType(AmortizationMethod.EQUAL_INSTALLMENTS), + final List allowedAmortizationMethods = Arrays.asList(amortizationType(AmortizationMethod.EQUAL_INSTALLMENTS), amortizationType(AmortizationMethod.EQUAL_PRINCIPAL)); return allowedAmortizationMethods; @@ -49,7 +49,7 @@ public class LoanDropdownReadPlatformServiceImpl implements LoanDropdownReadPlat @Override public List retrieveLoanInterestTypeOptions() { - List allowedRepaymentScheduleCalculationMethods = Arrays.asList(interestType(InterestMethod.FLAT), + final List allowedRepaymentScheduleCalculationMethods = Arrays.asList(interestType(InterestMethod.FLAT), interestType(InterestMethod.DECLINING_BALANCE)); return allowedRepaymentScheduleCalculationMethods; @@ -58,7 +58,7 @@ public class LoanDropdownReadPlatformServiceImpl implements LoanDropdownReadPlat @Override public List retrieveLoanInterestRateCalculatedInPeriodOptions() { - List allowedOptions = Arrays.asList(interestCalculationPeriodType(InterestCalculationPeriodMethod.DAILY), + final List allowedOptions = Arrays.asList(interestCalculationPeriodType(InterestCalculationPeriodMethod.DAILY), interestCalculationPeriodType(InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD)); return allowedOptions; @@ -66,7 +66,7 @@ public class LoanDropdownReadPlatformServiceImpl implements LoanDropdownReadPlat @Override public List retrieveLoanTermFrequencyTypeOptions() { - List loanTermFrequencyOptions = Arrays.asList(loanTermFrequencyType(PeriodFrequencyType.DAYS), + final List loanTermFrequencyOptions = Arrays.asList(loanTermFrequencyType(PeriodFrequencyType.DAYS), loanTermFrequencyType(PeriodFrequencyType.WEEKS), loanTermFrequencyType(PeriodFrequencyType.MONTHS), loanTermFrequencyType(PeriodFrequencyType.YEARS)); return loanTermFrequencyOptions; @@ -75,7 +75,7 @@ public class LoanDropdownReadPlatformServiceImpl implements LoanDropdownReadPlat @Override public List retrieveRepaymentFrequencyTypeOptions() { - List repaymentFrequencyOptions = Arrays.asList(repaymentFrequencyType(PeriodFrequencyType.DAYS), + final List repaymentFrequencyOptions = Arrays.asList(repaymentFrequencyType(PeriodFrequencyType.DAYS), repaymentFrequencyType(PeriodFrequencyType.WEEKS), repaymentFrequencyType(PeriodFrequencyType.MONTHS)); return repaymentFrequencyOptions; } @@ -83,7 +83,7 @@ public class LoanDropdownReadPlatformServiceImpl implements LoanDropdownReadPlat @Override public List retrieveInterestRateFrequencyTypeOptions() { // support for monthly and annual percentage rate (MPR) and (APR) - List interestRateFrequencyTypeOptions = Arrays.asList(interestRateFrequencyType(PeriodFrequencyType.MONTHS), + final List interestRateFrequencyTypeOptions = Arrays.asList(interestRateFrequencyType(PeriodFrequencyType.MONTHS), interestRateFrequencyType(PeriodFrequencyType.YEARS)); return interestRateFrequencyTypeOptions; } @@ -91,10 +91,10 @@ public class LoanDropdownReadPlatformServiceImpl implements LoanDropdownReadPlat @Override public Collection retreiveTransactionProcessingStrategies() { - Collection strategyOptions = new ArrayList(); + final Collection strategyOptions = new ArrayList(); - List strategies = this.loanTransactionProcessingStrategyRepository.findAll(); - for (LoanTransactionProcessingStrategy strategy : strategies) { + final List strategies = this.loanTransactionProcessingStrategyRepository.findAll(); + for (final LoanTransactionProcessingStrategy strategy : strategies) { strategyOptions.add(strategy.toData()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductReadPlatformService.java index 5f33ab8d2..43cf5b293 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductReadPlatformService.java @@ -22,6 +22,6 @@ public interface LoanProductReadPlatformService { Collection retrieveAvailableLoanProductsForMix(); Collection retrieveRestrictedProductsForMix(Long productId); - + Collection retrieveAllowedProductsForMix(Long productId); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductReadPlatformServiceImpl.java index 44ba1e579..d603dec03 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductReadPlatformServiceImpl.java @@ -54,7 +54,7 @@ public class LoanProductReadPlatformServiceImpl implements LoanProductReadPlatfo return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { loanProductId }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new LoanProductNotFoundException(loanProductId); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductWritePlatformServiceJpaRepositoryImpl.java index 197ab221b..7cebc8070 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/loanproduct/service/LoanProductWritePlatformServiceJpaRepositoryImpl.java @@ -81,14 +81,14 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro this.fromApiJsonDeserializer.validateForCreate(command.json()); validateInputDates(command); - + final Fund fund = findFundByIdIfProvided(command.longValueOfParameterNamed("fundId")); final Long transactionProcessingStrategyId = command.longValueOfParameterNamed("transactionProcessingStrategyId"); final LoanTransactionProcessingStrategy loanTransactionProcessingStrategy = findStrategyByIdIfProvided(transactionProcessingStrategyId); final String currencyCode = command.stringValueOfParameterNamed("currencyCode"); - final List charges = this.assembleListOfProductCharges(command, currencyCode); + final List charges = assembleListOfProductCharges(command, currencyCode); final LoanProduct loanproduct = LoanProduct.assembleFromJson(fund, loanTransactionProcessingStrategy, charges, command, this.aprCalculator); @@ -96,14 +96,14 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro this.loanProductRepository.save(loanproduct); // save accounting mappings - accountMappingWritePlatformService.createLoanProductToGLAccountMapping(loanproduct.getId(), command); + this.accountMappingWritePlatformService.createLoanProductToGLAccountMapping(loanproduct.getId(), command); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(loanproduct.getId()) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -137,10 +137,10 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro final LoanProduct product = this.loanProductRepository.findOne(loanProductId); if (product == null) { throw new LoanProductNotFoundException(loanProductId); } - + this.fromApiJsonDeserializer.validateForUpdate(command.json(), product); validateInputDates(command); - + final Map changes = product.update(command, this.aprCalculator); if (changes.containsKey("fundId")) { @@ -156,17 +156,17 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro } if (changes.containsKey("charges")) { - final List productCharges = this.assembleListOfProductCharges(command, product.getCurrency().getCode()); - boolean updated = product.update(productCharges); + final List productCharges = assembleListOfProductCharges(command, product.getCurrency().getCode()); + final boolean updated = product.update(productCharges); if (!updated) { changes.remove("charges"); } } // accounting related changes - boolean accountingTypeChanged = changes.containsKey("accountingRule"); - final Map accountingMappingChanges = accountMappingWritePlatformService.updateLoanProductToGLAccountMapping( - product.getId(), command, accountingTypeChanged, product.getAccountingType()); + final boolean accountingTypeChanged = changes.containsKey("accountingRule"); + final Map accountingMappingChanges = this.accountMappingWritePlatformService + .updateLoanProductToGLAccountMapping(product.getId(), command, accountingTypeChanged, product.getAccountingType()); changes.putAll(accountingMappingChanges); if (!changes.isEmpty()) { @@ -179,7 +179,7 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro .with(changes) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return new CommandProcessingResult(Long.valueOf(-1)); } @@ -196,7 +196,7 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro } if (command.parameterExists("charges")) { - JsonArray chargesArray = command.arrayOfParameterNamed("charges"); + final JsonArray chargesArray = command.arrayOfParameterNamed("charges"); if (chargesArray != null) { for (int i = 0; i < chargesArray.size(); i++) { @@ -207,7 +207,7 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro final Charge charge = this.chargeRepository.findOneWithNotFoundDetection(id); if (!loanProductCurrencyCode.equals(charge.getCurrencyCode())) { - String errorMessage = "Charge and Loan Product must have the same currency."; + final String errorMessage = "Charge and Loan Product must have the same currency."; throw new InvalidCurrencyException("charge", "attach.to.loan.product", errorMessage); } charges.add(charge); @@ -225,20 +225,20 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro */ private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("external_id")) { final String externalId = command.stringValueOfParameterNamed("externalId"); - throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.externalId", "Loan Product with externalId `" + externalId - + "` already exists", "externalId", externalId); + throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.externalId", "Loan Product with externalId `" + + externalId + "` already exists", "externalId", externalId); } else if (realCause.getMessage().contains("unq_name")) { final String name = command.stringValueOfParameterNamed("name"); throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.name", "Loan product with name `" + name + "` already exists", "name", name); } else if (realCause.getMessage().contains("Duplicate entry")) { - Object[] args = null; + final Object[] args = null; throw new PlatformDataIntegrityException("error.msg.product.loan.duplicate.charge", "Loan product may only have one charge of each type.`", "charges", args); } @@ -247,15 +247,13 @@ public class LoanProductWritePlatformServiceJpaRepositoryImpl implements LoanPro throw new PlatformDataIntegrityException("error.msg.product.loan.unknown.data.integrity.issue", "Unknown data integrity issue with resource."); } - + private void validateInputDates(final JsonCommand command) { final LocalDate startDate = command.localDateValueOfParameterNamed("startDate"); final LocalDate closeDate = command.localDateValueOfParameterNamed("closeDate"); if (startDate != null && closeDate != null) { - if (closeDate.isBefore(startDate)) { - throw new LoanProductDateException(startDate.toString(), closeDate.toString()); - } + if (closeDate.isBefore(startDate)) { throw new LoanProductDateException(startDate.toString(), closeDate.toString()); } } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/api/MeetingsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/api/MeetingsApiResource.java index e69c70753..cc6e831bf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/api/MeetingsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/api/MeetingsApiResource.java @@ -65,12 +65,12 @@ public class MeetingsApiResource { private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired - public MeetingsApiResource(PlatformSecurityContext context, MeetingReadPlatformService readPlatformService, - ClientAttendanceReadPlatformService attendanceReadPlatformService, final ClientReadPlatformService clientReadPlatformService, - final CalendarReadPlatformService calendarReadPlatformService, + public MeetingsApiResource(final PlatformSecurityContext context, final MeetingReadPlatformService readPlatformService, + final ClientAttendanceReadPlatformService attendanceReadPlatformService, + final ClientReadPlatformService clientReadPlatformService, final CalendarReadPlatformService calendarReadPlatformService, final AttendanceDropdownReadPlatformService attendanceDropdownReadPlatformService, - DefaultToApiJsonSerializer toApiJsonSerializer, ApiRequestParameterHelper apiRequestParameterHelper, - PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { + final DefaultToApiJsonSerializer toApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, + final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.context = context; this.readPlatformService = readPlatformService; this.attendanceReadPlatformService = attendanceReadPlatformService; @@ -87,7 +87,7 @@ public class MeetingsApiResource { @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) public String template(@PathParam("entityType") final String entityType, @PathParam("entityId") final Long entityId, - @QueryParam("calendarId") Long calendarId, @Context final UriInfo uriInfo) { + @QueryParam("calendarId") final Long calendarId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(MEETING_RESOURCE_NAME); final Integer entityTypeId = CalendarEntityType.valueOf(entityType.toUpperCase()).getValue(); @@ -101,16 +101,17 @@ public class MeetingsApiResource { } else { final String defaultUserMessage = "Meeting attendance is not supported for the resource " + entityType + ". The supported resources are [" + CalendarEntityType.GROUPS.name() + ", " + CalendarEntityType.CENTERS.name() + "]"; - throw new MeetingNotSupportedResourceException(defaultUserMessage, CalendarEntityType.GROUPS.name(), CalendarEntityType.CENTERS.name()); + throw new MeetingNotSupportedResourceException(defaultUserMessage, CalendarEntityType.GROUPS.name(), + CalendarEntityType.CENTERS.name()); } if (calendarId != null) { calendarData = this.calendarReadPlatformService.retrieveCalendar(calendarId, entityId, entityTypeId); calendarData = this.calendarReadPlatformService.generateRecurringDate(calendarData, DateUtils.getLocalDateOfTenant()); } - + final MeetingData meetingData = MeetingData.template(clients, calendarData, - attendanceDropdownReadPlatformService.retrieveAttendanceTypeOptions()); + this.attendanceDropdownReadPlatformService.retrieveAttendanceTypeOptions()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, meetingData, MEETING_RESPONSE_DATA_PARAMETERS); @@ -144,7 +145,7 @@ public class MeetingsApiResource { final Collection clientsAttendance = this.attendanceReadPlatformService .retrieveClientAttendanceByMeetingId(meetingId); meetingData = MeetingData.withClientsAttendanceAndAttendanceTypeOptions(meetingData, clientsAttendance, - attendanceDropdownReadPlatformService.retrieveAttendanceTypeOptions()); + this.attendanceDropdownReadPlatformService.retrieveAttendanceTypeOptions()); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, meetingData, MEETING_RESPONSE_DATA_PARAMETERS); } @@ -158,7 +159,7 @@ public class MeetingsApiResource { final CommandWrapper commandRequest = new CommandWrapperBuilder().createMeeting(entityType, entityId) .withJson(apiRequestBodyAsJson).build(); - CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); + final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/AttendanceType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/AttendanceType.java index 92fc1383b..58b34be16 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/AttendanceType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/AttendanceType.java @@ -32,7 +32,7 @@ public enum AttendanceType { } public String getCode() { - return code; + return this.code; } public static AttendanceType fromInt(final Integer attendanceTypeId) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/data/ClientAttendanceData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/data/ClientAttendanceData.java index 4533d4eb7..a8763698b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/data/ClientAttendanceData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/data/ClientAttendanceData.java @@ -20,16 +20,17 @@ public class ClientAttendanceData { private final String clientName; @SuppressWarnings("unused") private final EnumOptionData attendanceType; - - public static ClientAttendanceData instance(Long id, Long clientId, String clientName, EnumOptionData attendanceType){ + + public static ClientAttendanceData instance(final Long id, final Long clientId, final String clientName, + final EnumOptionData attendanceType) { return new ClientAttendanceData(id, clientId, clientName, attendanceType); } - - private ClientAttendanceData(Long id, Long clientId, String clientName, EnumOptionData attendanceType) { + + private ClientAttendanceData(final Long id, final Long clientId, final String clientName, final EnumOptionData attendanceType) { this.id = id; this.clientId = clientId; this.clientName = clientName; this.attendanceType = attendanceType; } - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/domain/ClientAttendance.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/domain/ClientAttendance.java index e7c07ae75..dcebc22a5 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/domain/ClientAttendance.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/domain/ClientAttendance.java @@ -41,7 +41,7 @@ public class ClientAttendance extends AbstractPersistable { } public Long clientId() { - return client.getId(); + return this.client.getId(); } public void updateAttendanceTypeId(final Integer attendanceTypeId) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/AttendanceDropdownReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/AttendanceDropdownReadPlatformService.java index ee99387c8..b2d7712ad 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/AttendanceDropdownReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/AttendanceDropdownReadPlatformService.java @@ -10,5 +10,6 @@ import java.util.List; import org.mifosplatform.infrastructure.core.data.EnumOptionData; public interface AttendanceDropdownReadPlatformService { + List retrieveAttendanceTypeOptions(); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/AttendanceEnumerations.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/AttendanceEnumerations.java index 258739ab9..2aff82593 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/AttendanceEnumerations.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/AttendanceEnumerations.java @@ -45,11 +45,13 @@ public class AttendanceEnumerations { } return optionData; } - + public static List attendanceType(final AttendanceType[] attendanceTypes) { final List optionDatas = new ArrayList(); for (final AttendanceType attendanceType : attendanceTypes) { - if(attendanceType.getValue().equals(AttendanceType.INVALID.getValue())) continue; + if (attendanceType.getValue().equals(AttendanceType.INVALID.getValue())) { + continue; + } optionDatas.add(attendanceType(attendanceType)); } return optionDatas; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformService.java index 77a22ea54..ab705526c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformService.java @@ -10,5 +10,6 @@ import java.util.Collection; import org.mifosplatform.portfolio.meeting.attendance.data.ClientAttendanceData; public interface ClientAttendanceReadPlatformService { + Collection retrieveClientAttendanceByMeetingId(final Long meetingId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformServiceImpl.java index a28c7365e..9452fee83 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/attendance/service/ClientAttendanceReadPlatformServiceImpl.java @@ -31,9 +31,9 @@ public class ClientAttendanceReadPlatformServiceImpl implements ClientAttendance public String schema() { - return " select ca.id as id, ca.client_id as clientId, ca.attendance_type_enum as attendanceTypeId, " + - " c.display_name as clientName from m_meeting m inner join m_client_attendance ca on m.id = ca.meeting_id " + - " inner join m_client c on ca.client_id=c.id "; + return " select ca.id as id, ca.client_id as clientId, ca.attendance_type_enum as attendanceTypeId, " + + " c.display_name as clientName from m_meeting m inner join m_client_attendance ca on m.id = ca.meeting_id " + + " inner join m_client c on ca.client_id=c.id "; } @Override diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/data/MeetingData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/data/MeetingData.java index 8fd10081f..05420b548 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/data/MeetingData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/data/MeetingData.java @@ -57,7 +57,7 @@ public class MeetingData { meetingData.calendarData, attendanceTypeOptions); } - private MeetingData(Long id, LocalDate meetingDate, Collection clientsAttendance, + private MeetingData(final Long id, final LocalDate meetingDate, final Collection clientsAttendance, final Collection clients, final CalendarData calendarData, final List attendanceTypeOptions) { this.id = id; this.meetingDate = meetingDate; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/data/MeetingDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/data/MeetingDataValidator.java index aab73bdaf..a5f6a2947 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/data/MeetingDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/data/MeetingDataValidator.java @@ -7,10 +7,10 @@ package org.mifosplatform.portfolio.meeting.data; import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.MEETING_REQUEST_DATA_PARAMETERS; import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.MEETING_RESOURCE_NAME; -import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.clientsAttendanceParamName; import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.attendanceTypeParamName; import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.calendarIdParamName; import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.clientIdParamName; +import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.clientsAttendanceParamName; import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.meetingDateParamName; import java.lang.reflect.Type; @@ -49,58 +49,56 @@ public class MeetingDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, MEETING_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, MEETING_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(MEETING_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); - + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(MEETING_RESOURCE_NAME); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final String meetingDateStr = this.fromApiJsonHelper.extractStringNamed(meetingDateParamName, element); baseDataValidator.reset().parameter(meetingDateParamName).value(meetingDateStr).notBlank(); - - if(!StringUtils.isBlank(meetingDateStr)){ + + if (!StringUtils.isBlank(meetingDateStr)) { final LocalDate meetingDate = this.fromApiJsonHelper.extractLocalDateNamed(meetingDateParamName, element); baseDataValidator.reset().parameter(meetingDateParamName).value(meetingDate).notNull(); } - + final Long calendarId = this.fromApiJsonHelper.extractLongNamed(calendarIdParamName, element); baseDataValidator.reset().parameter(calendarIdParamName).value(calendarId).notNull(); - + validateAttendanceDetails(element, baseDataValidator); - + throwExceptionIfValidationWarningsExist(dataValidationErrors); } - + public void validateForUpdate(final JsonCommand command) { final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, MEETING_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, MEETING_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(MEETING_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(MEETING_RESOURCE_NAME); + final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists(meetingDateParamName, element)) { final String meetingDateStr = this.fromApiJsonHelper.extractStringNamed(meetingDateParamName, element); baseDataValidator.reset().parameter(meetingDateParamName).value(meetingDateStr).notBlank(); - - if(!StringUtils.isBlank(meetingDateStr)){ + + if (!StringUtils.isBlank(meetingDateStr)) { final LocalDate meetingDate = this.fromApiJsonHelper.extractLocalDateNamed(meetingDateParamName, element); baseDataValidator.reset().parameter(meetingDateParamName).value(meetingDate).notNull(); } } - if(this.fromApiJsonHelper.parameterExists(calendarIdParamName, element)){ + if (this.fromApiJsonHelper.parameterExists(calendarIdParamName, element)) { final Long calendarId = this.fromApiJsonHelper.extractLongNamed(calendarIdParamName, element); baseDataValidator.reset().parameter(calendarIdParamName).value(calendarId).notNull(); } - + validateAttendanceDetails(element, baseDataValidator); - + throwExceptionIfValidationWarningsExist(dataValidationErrors); } @@ -109,36 +107,36 @@ public class MeetingDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, MEETING_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, MEETING_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(MEETING_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(MEETING_RESOURCE_NAME); + final JsonElement element = this.fromApiJsonHelper.parse(json); validateAttendanceDetails(element, baseDataValidator); - + throwExceptionIfValidationWarningsExist(dataValidationErrors); } - + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - private void validateAttendanceDetails(final JsonElement element, final DataValidatorBuilder baseDataValidator){ + private void validateAttendanceDetails(final JsonElement element, final DataValidatorBuilder baseDataValidator) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); if (element.isJsonObject()) { - if (topLevelJsonElement.has(clientsAttendanceParamName) - && topLevelJsonElement.get(clientsAttendanceParamName).isJsonArray()) { - final JsonArray array = topLevelJsonElement.get(clientsAttendanceParamName).getAsJsonArray(); - for (int i = 0; i < array.size(); i++) { - final JsonObject attendanceElement = array.get(i).getAsJsonObject(); - final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, attendanceElement); - final Long attendanceType = this.fromApiJsonHelper.extractLongNamed(attendanceTypeParamName, attendanceElement); - baseDataValidator.reset().parameter(clientsAttendanceParamName + "[" + i + "]." + clientIdParamName).value(clientId).notNull().integerGreaterThanZero(); - baseDataValidator.reset().parameter(clientsAttendanceParamName + "[" + i + "]." + attendanceTypeParamName).value(attendanceType).notNull().integerGreaterThanZero(); - } + if (topLevelJsonElement.has(clientsAttendanceParamName) && topLevelJsonElement.get(clientsAttendanceParamName).isJsonArray()) { + final JsonArray array = topLevelJsonElement.get(clientsAttendanceParamName).getAsJsonArray(); + for (int i = 0; i < array.size(); i++) { + final JsonObject attendanceElement = array.get(i).getAsJsonObject(); + final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, attendanceElement); + final Long attendanceType = this.fromApiJsonHelper.extractLongNamed(attendanceTypeParamName, attendanceElement); + baseDataValidator.reset().parameter(clientsAttendanceParamName + "[" + i + "]." + clientIdParamName).value(clientId) + .notNull().integerGreaterThanZero(); + baseDataValidator.reset().parameter(clientsAttendanceParamName + "[" + i + "]." + attendanceTypeParamName) + .value(attendanceType).notNull().integerGreaterThanZero(); } + } } } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/Meeting.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/Meeting.java index b4dff3b83..365fe0457 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/Meeting.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/Meeting.java @@ -6,9 +6,9 @@ package org.mifosplatform.portfolio.meeting.domain; -import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.clientsAttendanceParamName; import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.attendanceTypeParamName; import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.clientIdParamName; +import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.clientsAttendanceParamName; import static org.mifosplatform.portfolio.meeting.MeetingApiConstants.meetingDateParamName; import java.util.Collection; @@ -61,7 +61,7 @@ public class Meeting extends AbstractPersistable { // } - private Meeting(CalendarInstance calendarInstance, Date meetingDate) { + private Meeting(final CalendarInstance calendarInstance, final Date meetingDate) { this.calendarInstance = calendarInstance; this.meetingDate = meetingDate; } @@ -96,7 +96,7 @@ public class Meeting extends AbstractPersistable { this.meetingDate = newValue.toDate(); if (!isValidMeetingDate(this.calendarInstance, this.meetingDate)) { throw new NotValidRecurringDateException("meeting", - "Not a valid meeting date", meetingDate); } + "Not a valid meeting date", this.meetingDate); } } @@ -107,11 +107,11 @@ public class Meeting extends AbstractPersistable { final Map actualChanges = new LinkedHashMap(1); final Map clientAttendanceChanges = new LinkedHashMap(clientsAttendance.size()); - updateAttendanceLoop: for (ClientAttendance clientAttendance : clientsAttendance) { + updateAttendanceLoop: for (final ClientAttendance clientAttendance : clientsAttendance) { if (this.clientsAttendance == null) { this.clientsAttendance = new HashSet(); } - for (ClientAttendance clientAttendanceOriginal : this.clientsAttendance) { + for (final ClientAttendance clientAttendanceOriginal : this.clientsAttendance) { if (clientAttendanceOriginal.clientId().equals(clientAttendance.clientId())) { final Integer newValue = clientAttendance.getAttendanceTypeId(); if (!newValue.equals(clientAttendanceOriginal.getAttendanceTypeId())) { @@ -139,15 +139,15 @@ public class Meeting extends AbstractPersistable { } public Long entityId() { - return calendarInstance.getEntityId(); + return this.calendarInstance.getEntityId(); } public boolean isCenterEntity() { - return CalendarEntityType.isCenter(calendarInstance.getEntityTypeId()); + return CalendarEntityType.isCenter(this.calendarInstance.getEntityTypeId()); } public boolean isGroupEntity() { - return CalendarEntityType.isGroup(calendarInstance.getEntityTypeId()); + return CalendarEntityType.isGroup(this.calendarInstance.getEntityTypeId()); } public LocalDate getMeetingDateLocalDate() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/MeetingRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/MeetingRepository.java index 74547ad8a..0273ac0df 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/MeetingRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/MeetingRepository.java @@ -11,5 +11,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface MeetingRepository extends JpaRepository, JpaSpecificationExecutor { + Meeting findByCalendarInstanceIdAndMeetingDate(Long calendarInstanceId, Date meetingDate); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/MeetingRepositoryWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/MeetingRepositoryWrapper.java index e80292a62..f905e5324 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/MeetingRepositoryWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/domain/MeetingRepositoryWrapper.java @@ -11,9 +11,9 @@ import org.springframework.stereotype.Service; /** *

- * Wrapper for {@link MeetingRepository} that is responsible for checking - * if {@link Meeting} is returned when using findOne - * repository method and throwing an appropriate not found exception. + * Wrapper for {@link MeetingRepository} that is responsible for checking if + * {@link Meeting} is returned when using findOne repository method + * and throwing an appropriate not found exception. *

* *

diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/exception/MeetingNotSupportedResourceException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/exception/MeetingNotSupportedResourceException.java index e240aeea5..8b27f7bb9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/exception/MeetingNotSupportedResourceException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/exception/MeetingNotSupportedResourceException.java @@ -8,11 +8,12 @@ package org.mifosplatform.portfolio.meeting.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; /** - * {@link AbstractPlatformDomainRuleException} thrown when meeting is captured against not supported resource. + * {@link AbstractPlatformDomainRuleException} thrown when meeting is captured + * against not supported resource. */ public class MeetingNotSupportedResourceException extends AbstractPlatformDomainRuleException { - public MeetingNotSupportedResourceException(String defaultUserMessage, Object... defaultUserMessageArgs) { - super("error.msg.meeting.not.supported.resource", defaultUserMessage, defaultUserMessageArgs); - } + public MeetingNotSupportedResourceException(final String defaultUserMessage, final Object... defaultUserMessageArgs) { + super("error.msg.meeting.not.supported.resource", defaultUserMessage, defaultUserMessageArgs); + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingReadPlatformServiceImpl.java index 9904e5b7f..60dbadd79 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingReadPlatformServiceImpl.java @@ -50,7 +50,7 @@ public class MeetingReadPlatformServiceImpl implements MeetingReadPlatformServic } @Override - public MeetingData retrieveMeeting(final Long meetingId, Long entityId, Integer entityTypeId) { + public MeetingData retrieveMeeting(final Long meetingId, final Long entityId, final Integer entityTypeId) { try { final MeetingDataMapper rm = new MeetingDataMapper(); @@ -64,24 +64,24 @@ public class MeetingReadPlatformServiceImpl implements MeetingReadPlatformServic } @Override - public Collection retrieveMeetingsByEntity(Long entityId, Integer entityTypeId, Integer limit) { + public Collection retrieveMeetingsByEntity(final Long entityId, final Integer entityTypeId, final Integer limit) { final MeetingDataMapper rm = new MeetingDataMapper(); String sql = rm.schema() + " where ci.entity_id = ? and ci.entity_type_enum = ? "; - if(limit != null && limit > 0){ - sql = sql + " order by m.meeting_date desc " + " limit " + limit; + if (limit != null && limit > 0) { + sql = sql + " order by m.meeting_date desc " + " limit " + limit; } return this.jdbcTemplate.query(sql, rm, new Object[] { entityId, entityTypeId }); } @Override - public Collection retrieveMeetingsByEntityByCalendarType(Long entityId, Integer entityTypeId, - List calendarTypeOptions) { + public Collection retrieveMeetingsByEntityByCalendarType(final Long entityId, final Integer entityTypeId, + final List calendarTypeOptions) { final MeetingDataMapper rm = new MeetingDataMapper(); - String sqlCalendarTypeOptions = CalendarUtils.getSqlCalendarTypeOptionsInString(calendarTypeOptions); + final String sqlCalendarTypeOptions = CalendarUtils.getSqlCalendarTypeOptionsInString(calendarTypeOptions); final String sql = rm.schema() + " inner join m_calendar c on ci.calendar_id=c.id where ci.entity_id = ? and ci.entity_type_enum = ? and c.calendar_type_enum in (" - + sqlCalendarTypeOptions + ") order by c.start_date "; + + sqlCalendarTypeOptions + ") order by c.start_date "; return this.jdbcTemplate.query(sql, rm, new Object[] { entityId, entityTypeId }); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingWritePlatformService.java index f423b9586..bd94f7fdd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingWritePlatformService.java @@ -11,12 +11,12 @@ import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; public interface MeetingWritePlatformService { CommandProcessingResult createMeeting(JsonCommand command); - + void updateCollectionSheetAttendance(JsonCommand command); CommandProcessingResult updateMeeting(JsonCommand command); CommandProcessingResult deleteMeeting(Long meetingId); - + CommandProcessingResult saveOrUpdateAttendance(JsonCommand command); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingWritePlatformServiceJpaRepositoryImpl.java index b77230a86..2d422ba0c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/meeting/service/MeetingWritePlatformServiceJpaRepositoryImpl.java @@ -111,10 +111,11 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit final Calendar calendarForUpdate = this.calendarRepository.findOne(calendarId); if (calendarForUpdate == null) { throw new CalendarNotFoundException(calendarId); } CalendarEntityType entityType = CalendarEntityType.valueOf(command.getSupportedEntityType().toUpperCase()); - //If group is within a center then center entityType should be passed for retrieving CalendarInstance. - if(CalendarEntityType.isGroup(command.getSupportedEntityType().toUpperCase())){ + // If group is within a center then center entityType should be passed + // for retrieving CalendarInstance. + if (CalendarEntityType.isGroup(command.getSupportedEntityType().toUpperCase())) { final Group group = this.groupRepository.findOne(entityId); - if(group.isChildGroup()){ + if (group.isChildGroup()) { entityType = CalendarEntityType.CENTERS; entityId = group.getParent().getId(); } @@ -234,9 +235,10 @@ public class MeetingWritePlatformServiceJpaRepositoryImpl implements MeetingWrit private void handleMeetingDataIntegrityIssues(final Date meetingDate, final DataIntegrityViolationException dve) { final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("unique_calendar_instance_id_meeting_date")) { - final LocalDate meetingDateLocal = LocalDate.fromDateFields(meetingDate); - throw new PlatformDataIntegrityException("error.msg.meeting.duplicate", "A meeting with date '" + meetingDateLocal + "' already exists", - meetingDateParamName, meetingDateLocal); } + final LocalDate meetingDateLocal = LocalDate.fromDateFields(meetingDate); + throw new PlatformDataIntegrityException("error.msg.meeting.duplicate", "A meeting with date '" + meetingDateLocal + + "' already exists", meetingDateParamName, meetingDateLocal); + } throw new PlatformDataIntegrityException("error.msg.meeting.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage()); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/Note.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/Note.java index daa5144bb..cbdce2685 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/Note.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/domain/Note.java @@ -75,7 +75,7 @@ public class Note extends AbstractAuditableCustom { public static Note savingNote(final SavingsAccount account, final String note) { return new Note(account, note); } - + public Note(final Client client, final String note) { this.client = client; this.note = note; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/serialization/NoteCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/serialization/NoteCommandFromApiJsonDeserializer.java index ceab45a88..8dffbce48 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/serialization/NoteCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/serialization/NoteCommandFromApiJsonDeserializer.java @@ -29,8 +29,7 @@ import com.google.gson.JsonElement; import com.google.gson.reflect.TypeToken; /** - * Implementation of {@link FromApiJsonDeserializer} for {@link NoteCommand} - * 's. + * Implementation of {@link FromApiJsonDeserializer} for {@link NoteCommand} 's. */ @Component public final class NoteCommandFromApiJsonDeserializer extends AbstractFromApiJsonDeserializer { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteReadPlatformServiceImpl.java index cb0cac204..9b952dd06 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/note/service/NoteReadPlatformServiceImpl.java @@ -63,8 +63,8 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { final Long lastModifiedById = JdbcSupport.getLong(rs, "lastModifiedById"); final String createdByUsername = rs.getString("createdBy"); final String updatedByUsername = rs.getString("modifiedBy"); - return new NoteData(id, clientId, groupId, loanId, transactionId, null, null, noteType, note, - createdDate, createdById, createdByUsername, lastModifiedDate, lastModifiedById, updatedByUsername); + return new NoteData(id, clientId, groupId, loanId, transactionId, null, null, noteType, note, createdDate, createdById, + createdByUsername, lastModifiedDate, lastModifiedById, updatedByUsername); } } @@ -90,11 +90,11 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { public Collection retrieveNotesByResource(final Long resourceId, final Integer noteTypeId) { final NoteType noteType = NoteType.fromInt(noteTypeId); final NoteMapper rm = new NoteMapper(); - String conditionSql = getResourceCondition(noteType); + final String conditionSql = getResourceCondition(noteType); final String sql = rm.schema() + " where " + conditionSql + " order by n.created_date DESC"; - return this.jdbcTemplate.query(sql, rm, new Object[] { resourceId}); + return this.jdbcTemplate.query(sql, rm, new Object[] { resourceId }); } public static String getResourceCondition(final NoteType noteType) { @@ -104,7 +104,8 @@ public class NoteReadPlatformServiceImpl implements NoteReadPlatformService { conditionSql = " n.client_id = ? and note_type_enum = " + NoteType.CLIENT.getValue(); break; case LOAN: - conditionSql = " n.loan_id = ? and ( n.note_type_enum = " + NoteType.LOAN.getValue()+ " or n.note_type_enum = " + NoteType.LOAN_TRANSACTION.getValue() + " )"; + conditionSql = " n.loan_id = ? and ( n.note_type_enum = " + NoteType.LOAN.getValue() + " or n.note_type_enum = " + + NoteType.LOAN_TRANSACTION.getValue() + " )"; break; case LOAN_TRANSACTION: conditionSql = " n.loan_transaction_id = ? "; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/data/PaymentDetailData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/data/PaymentDetailData.java index 6739acc8d..7bd675cab 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/data/PaymentDetailData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/data/PaymentDetailData.java @@ -27,8 +27,8 @@ public class PaymentDetailData { @SuppressWarnings("unused") private final String bankNumber; - public PaymentDetailData(Long id, CodeValueData paymentType, String accountNumber, String checkNumber, String routingCode, - String receiptNumber, String bankNumber) { + public PaymentDetailData(final Long id, final CodeValueData paymentType, final String accountNumber, final String checkNumber, + final String routingCode, final String receiptNumber, final String bankNumber) { this.id = id; this.paymentType = paymentType; this.accountNumber = accountNumber; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/domain/PaymentDetail.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/domain/PaymentDetail.java index 730d5f0ba..470e47c73 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/domain/PaymentDetail.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/domain/PaymentDetail.java @@ -71,7 +71,8 @@ public final class PaymentDetail extends AbstractPersistable { if (StringUtils.isNotBlank(bankNumber)) { changes.put(PaymentDetailConstants.bankNumberParamName, bankNumber); } - PaymentDetail paymentDetail = new PaymentDetail(paymentType, accountNumber, checkNumber, routingCode, receiptNumber, bankNumber); + final PaymentDetail paymentDetail = new PaymentDetail(paymentType, accountNumber, checkNumber, routingCode, receiptNumber, + bankNumber); return paymentDetail; } @@ -86,7 +87,7 @@ public final class PaymentDetail extends AbstractPersistable { } public PaymentDetailData toData() { - CodeValueData paymentTypeData = paymentType.toData(); + final CodeValueData paymentTypeData = this.paymentType.toData(); final PaymentDetailData paymentDetailData = new PaymentDetailData(getId(), paymentTypeData, this.accountNumber, this.checkNumber, this.routingCode, this.receiptNumber, this.bankNumber); return paymentDetailData; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/service/PaymentDetailWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/service/PaymentDetailWritePlatformServiceJpaRepositoryImpl.java index a6667f10e..7c71d6a61 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/service/PaymentDetailWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/paymentdetail/service/PaymentDetailWritePlatformServiceJpaRepositoryImpl.java @@ -32,27 +32,27 @@ public class PaymentDetailWritePlatformServiceJpaRepositoryImpl implements Payme @Override @Transactional - public PaymentDetail createPaymentDetail(JsonCommand command, Map changes) { + public PaymentDetail createPaymentDetail(final JsonCommand command, final Map changes) { final Long paymentTypeId = command.longValueOfParameterNamed(PaymentDetailConstants.paymentTypeParamName); if (paymentTypeId == null) { return null; } - CodeValue paymentType = codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( + final CodeValue paymentType = this.codeValueRepositoryWrapper.findOneByCodeNameAndIdWithNotFoundDetection( PaymentDetailConstants.paymentTypeCodeName, paymentTypeId); - PaymentDetail paymentDetail = PaymentDetail.generatePaymentDetail(paymentType, command, changes); + final PaymentDetail paymentDetail = PaymentDetail.generatePaymentDetail(paymentType, command, changes); return paymentDetail; } @Override @Transactional - public PaymentDetail persistPaymentDetail(PaymentDetail paymentDetail) { - return paymentDetailRepository.save(paymentDetail); + public PaymentDetail persistPaymentDetail(final PaymentDetail paymentDetail) { + return this.paymentDetailRepository.save(paymentDetail); } @Override @Transactional - public PaymentDetail createAndPersistPaymentDetail(JsonCommand command, Map changes) { - PaymentDetail paymentDetail = createPaymentDetail(command, changes); + public PaymentDetail createAndPersistPaymentDetail(final JsonCommand command, final Map changes) { + final PaymentDetail paymentDetail = createPaymentDetail(command, changes); if (paymentDetail != null) { return persistPaymentDetail(paymentDetail); } return paymentDetail; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsAccountTransactionType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsAccountTransactionType.java index bef3f6570..42c827f72 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsAccountTransactionType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsAccountTransactionType.java @@ -19,9 +19,8 @@ public enum SavingsAccountTransactionType { INTEREST_POSTING(3, "savingsAccountTransactionType.interestPosting"), // WITHDRAWAL_FEE(4, "savingsAccountTransactionType.withdrawalFee"), // ANNUAL_FEE(5, "savingsAccountTransactionType.annualFee"), // - WAIVE_CHARGES(6, "savingsAccountTransactionType.waiveCharges"), - APPLY_CHARGES(7, "savingsAccountTransactionType.applyCharges"), - INITIATE_TRANSFER(12, "savingsAccountTransactionType.initiateTransfer"), // + WAIVE_CHARGES(6, "savingsAccountTransactionType.waiveCharges"), APPLY_CHARGES(7, "savingsAccountTransactionType.applyCharges"), INITIATE_TRANSFER( + 12, "savingsAccountTransactionType.initiateTransfer"), // APPROVE_TRANSFER(13, "savingsAccountTransactionType.approveTransfer"), // WITHDRAW_TRANSFER(14, "savingsAccountTransactionType.withdrawTransfer"), // REJECT_TRANSFER(15, "savingsAccountTransactionType.rejectTransfer"); @@ -39,7 +38,7 @@ public enum SavingsAccountTransactionType { } public String getCode() { - return code; + return this.code; } public static SavingsAccountTransactionType fromInt(final Integer transactionType) { @@ -104,11 +103,11 @@ public enum SavingsAccountTransactionType { public boolean isAnnualFee() { return this.value.equals(SavingsAccountTransactionType.ANNUAL_FEE.getValue()); } - + public boolean isCharge() { return this.value.equals(SavingsAccountTransactionType.APPLY_CHARGES.getValue()); } - + public boolean isWaiveCharge() { return this.value.equals(SavingsAccountTransactionType.WAIVE_CHARGES.getValue()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsApiConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsApiConstants.java index 5fb159e92..fd9cab5d9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsApiConstants.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsApiConstants.java @@ -19,7 +19,6 @@ public class SavingsApiConstants { public static final String SAVINGS_ACCOUNT_RESOURCE_NAME = "savingsaccount"; public static final String SAVINGS_ACCOUNT_TRANSACTION_RESOURCE_NAME = "savingsaccount.transaction"; public static final String SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME = "savingsaccountcharge"; - // actions public static String summitalAction = ".summital"; @@ -39,8 +38,8 @@ public class SavingsApiConstants { // command public static String COMMAND_UNDO_TRANSACTION = "undo"; public static String COMMAND_ADJUST_TRANSACTION = "modify"; - public static String COMMAND_WAIVE_CHARGE= "waive"; - public static String COMMAND_PAY_CHARGE= "paycharge"; + public static String COMMAND_WAIVE_CHARGE = "waive"; + public static String COMMAND_PAY_CHARGE = "paycharge"; // general public static final String localeParamName = "locale"; @@ -98,8 +97,8 @@ public class SavingsApiConstants { public static final String runningBalanceParamName = "runningBalance"; public static final String reversedParamName = "reversed"; public static final String dateParamName = "date"; - - //charges parameters + + // charges parameters public static final String chargeIdParamName = "chargeId"; public static final String chargesParamName = "charges"; public static final String savingsAccountChargeIdParamName = "savingsAccountChargeId"; @@ -117,7 +116,7 @@ public class SavingsApiConstants { public static final String amountOrPercentageParamName = "amountOrPercentage"; public static final String amountParamName = "amount"; public static final String amountPaidParamName = "amountPaid"; - public static final String chargeOptionsParamName = "chargeOptions"; + public static final String chargeOptionsParamName = "chargeOptions"; public static final String noteParamName = "note"; @@ -184,13 +183,13 @@ public class SavingsApiConstants { public static final Set SAVINGS_ACCOUNT_CLOSE_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList(localeParamName, dateFormatParamName, closedOnDateParamName, noteParamName)); - + public static final Set SAVINGS_ACCOUNT_CHARGES_RESPONSE_DATA_PARAMETERS = new HashSet(Arrays.asList(chargeIdParamName, savingsAccountChargeIdParamName, chargeNameParamName, penaltyParamName, chargeTimeTypeParamName, dueAsOfDateParamName, chargeCalculationTypeParamName, percentageParamName, amountPercentageAppliedToParamName, currencyParamName, - amountWaivedParamName, amountWrittenOffParamName, amountOutstandingParamName, amountOrPercentageParamName, amountParamName, amountPaidParamName, - chargeOptionsParamName)); - + amountWaivedParamName, amountWrittenOffParamName, amountOutstandingParamName, amountOrPercentageParamName, amountParamName, + amountPaidParamName, chargeOptionsParamName)); + public static final Set SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS = new HashSet(Arrays.asList( chargeIdParamName, amountParamName, dueAsOfDateParamName, dateFormatParamName, localeParamName)); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsCompoundingInterestPeriodType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsCompoundingInterestPeriodType.java index 5bfafea3a..1d6088bd6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsCompoundingInterestPeriodType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsCompoundingInterestPeriodType.java @@ -8,7 +8,6 @@ package org.mifosplatform.portfolio.savings; import java.util.ArrayList; import java.util.List; - /** *

* The compounding interest period is the span of time at the end of which @@ -19,13 +18,15 @@ public enum SavingsCompoundingInterestPeriodType { INVALID(0, "savingsCompoundingInterestPeriodType.invalid"), // DAILY(1, "savingsCompoundingInterestPeriodType.daily"), // -// WEEKLY(2, "savingsCompoundingInterestPeriodType.weekly"), // -// BIWEEKLY(3, "savingsCompoundingInterestPeriodType.biweekly"), // + // WEEKLY(2, "savingsCompoundingInterestPeriodType.weekly"), // + // BIWEEKLY(3, "savingsCompoundingInterestPeriodType.biweekly"), // MONTHLY(4, "savingsCompoundingInterestPeriodType.monthly"); -// QUATERLY(5, "savingsCompoundingInterestPeriodType.quarterly"), // -// BI_ANNUAL(6, "savingsCompoundingInterestPeriodType.biannual"), // -// ANNUAL(7, "savingsCompoundingInterestPeriodType.annual"), // -// NO_COMPOUNDING_SIMPLE_INTEREST(8, "savingsCompoundingInterestPeriodType.nocompounding"); + + // QUATERLY(5, "savingsCompoundingInterestPeriodType.quarterly"), // + // BI_ANNUAL(6, "savingsCompoundingInterestPeriodType.biannual"), // + // ANNUAL(7, "savingsCompoundingInterestPeriodType.annual"), // + // NO_COMPOUNDING_SIMPLE_INTEREST(8, + // "savingsCompoundingInterestPeriodType.nocompounding"); private final Integer value; private final String code; @@ -40,12 +41,12 @@ public enum SavingsCompoundingInterestPeriodType { } public String getCode() { - return code; + return this.code; } public static Object[] integerValues() { - List values = new ArrayList(); - for (SavingsCompoundingInterestPeriodType enumType : values()) { + final List values = new ArrayList(); + for (final SavingsCompoundingInterestPeriodType enumType : values()) { if (enumType.getValue() > 0) { values.add(enumType.getValue()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsInterestCalculationDaysInYearType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsInterestCalculationDaysInYearType.java index 23ba5a0c2..71ad54a12 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsInterestCalculationDaysInYearType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsInterestCalculationDaysInYearType.java @@ -35,12 +35,12 @@ public enum SavingsInterestCalculationDaysInYearType { } public String getCode() { - return code; + return this.code; } public static Object[] integerValues() { - List values = new ArrayList(); - for (SavingsInterestCalculationDaysInYearType enumType : values()) { + final List values = new ArrayList(); + for (final SavingsInterestCalculationDaysInYearType enumType : values()) { if (enumType.getValue() > 0) { values.add(enumType.getValue()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsInterestCalculationType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsInterestCalculationType.java index 03d810f05..00c45dc38 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsInterestCalculationType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsInterestCalculationType.java @@ -49,12 +49,12 @@ public enum SavingsInterestCalculationType { } public String getCode() { - return code; + return this.code; } public static Object[] integerValues() { - List values = new ArrayList(); - for (SavingsInterestCalculationType enumType : values()) { + final List values = new ArrayList(); + for (final SavingsInterestCalculationType enumType : values()) { if (enumType.getValue() > 0) { values.add(enumType.getValue()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsPeriodFrequencyType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsPeriodFrequencyType.java index 785a85049..7323071a0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsPeriodFrequencyType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsPeriodFrequencyType.java @@ -28,7 +28,7 @@ public enum SavingsPeriodFrequencyType { } public String getCode() { - return code; + return this.code; } public static SavingsPeriodFrequencyType fromInt(final Integer type) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsPostingInterestPeriodType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsPostingInterestPeriodType.java index e0f8a8ad6..d2e829eaf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsPostingInterestPeriodType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsPostingInterestPeriodType.java @@ -32,12 +32,12 @@ public enum SavingsPostingInterestPeriodType { } public String getCode() { - return code; + return this.code; } public static Object[] integerValues() { - List values = new ArrayList(); - for (SavingsPostingInterestPeriodType enumType : values()) { + final List values = new ArrayList(); + for (final SavingsPostingInterestPeriodType enumType : values()) { if (enumType.getValue() > 0) { values.add(enumType.getValue()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsWithdrawalFeesType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsWithdrawalFeesType.java index 43b3ded1d..808c1e37b 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsWithdrawalFeesType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/SavingsWithdrawalFeesType.java @@ -27,12 +27,12 @@ public enum SavingsWithdrawalFeesType { } public String getCode() { - return code; + return this.code; } public static Object[] integerValues() { - List values = new ArrayList(); - for (SavingsWithdrawalFeesType enumType : values()) { + final List values = new ArrayList(); + for (final SavingsWithdrawalFeesType enumType : values()) { if (enumType.getValue() > 0) { values.add(enumType.getValue()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountChargesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountChargesApiResource.java index 8c95bdafe..97c3f343c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountChargesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountChargesApiResource.java @@ -5,10 +5,10 @@ */ package org.mifosplatform.portfolio.savings.api; +import static org.mifosplatform.portfolio.savings.SavingsApiConstants.COMMAND_PAY_CHARGE; +import static org.mifosplatform.portfolio.savings.SavingsApiConstants.COMMAND_WAIVE_CHARGE; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.SAVINGS_ACCOUNT_CHARGES_RESPONSE_DATA_PARAMETERS; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME; -import static org.mifosplatform.portfolio.savings.SavingsApiConstants.COMMAND_WAIVE_CHARGE; -import static org.mifosplatform.portfolio.savings.SavingsApiConstants.COMMAND_PAY_CHARGE; import java.util.Collection; @@ -81,12 +81,12 @@ public class SavingsAccountChargesApiResource { public String retrieveAllSavingsAccountCharges(@PathParam("savingsAccountId") final Long savingsAccountId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); final Collection savingsAccountCharges = this.savingsAccountChargeReadPlatformService .retrieveSavingsAccountCharges(savingsAccountId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, savingsAccountCharges, SavingsApiConstants.SAVINGS_ACCOUNT_CHARGES_RESPONSE_DATA_PARAMETERS); } @@ -97,13 +97,13 @@ public class SavingsAccountChargesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveTemplate(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); final boolean feeChargesOnly = false; final Collection chargeOptions = this.chargeReadPlatformService.retrieveSavingsAccountApplicableCharges(feeChargesOnly); final SavingsAccountChargeData savingsAccountChargeTemplate = SavingsAccountChargeData.template(chargeOptions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, savingsAccountChargeTemplate, SAVINGS_ACCOUNT_CHARGES_RESPONSE_DATA_PARAMETERS); } @@ -114,12 +114,12 @@ public class SavingsAccountChargesApiResource { public String retrieveSavingsAccountCharge(@PathParam("savingsAccountId") final Long savingsAccountId, @PathParam("savingsAccountChargeId") final Long savingsAccountChargeId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); final SavingsAccountChargeData savingsAccountCharge = this.savingsAccountChargeReadPlatformService .retrieveSavingsAccountChargeDetails(savingsAccountChargeId, savingsAccountId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, savingsAccountCharge, SAVINGS_ACCOUNT_CHARGES_RESPONSE_DATA_PARAMETERS); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountTransactionsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountTransactionsApiResource.java index 8a4f9f87e..d4d5cca96 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountTransactionsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountTransactionsApiResource.java @@ -77,16 +77,16 @@ public class SavingsAccountTransactionsApiResource { // @QueryParam("command") final String commandParam, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); // FIXME - KW - for now just send back generic default information for // both deposit/withdrawal templates SavingsAccountTransactionData savingsAccount = this.savingsAccountReadPlatformService.retrieveDepositTransactionTemplate(savingsId); - final Collection paymentTypeOptions = codeValueReadPlatformService + final Collection paymentTypeOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(PaymentDetailConstants.paymentTypeCodeName); savingsAccount = SavingsAccountTransactionData.templateOnTop(savingsAccount, paymentTypeOptions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, savingsAccount, SavingsApiConstants.SAVINGS_TRANSACTION_RESPONSE_DATA_PARAMETERS); } @@ -98,12 +98,12 @@ public class SavingsAccountTransactionsApiResource { public String retrieveOne(@PathParam("savingsId") final Long savingsId, @PathParam("transactionId") final Long transactionId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); SavingsAccountTransactionData transactionData = this.savingsAccountReadPlatformService.retrieveSavingsTransaction(savingsId, transactionId); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (settings.isTemplate()) { - final Collection paymentTypeOptions = codeValueReadPlatformService + final Collection paymentTypeOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(PaymentDetailConstants.paymentTypeCodeName); transactionData = SavingsAccountTransactionData.templateOnTop(transactionData, paymentTypeOptions); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountsApiResource.java index a53ccc6af..2834c5946 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsAccountsApiResource.java @@ -64,7 +64,8 @@ public class SavingsAccountsApiResource { public SavingsAccountsApiResource(final SavingsAccountReadPlatformService savingsAccountReadPlatformService, final PlatformSecurityContext context, final DefaultToApiJsonSerializer toApiJsonSerializer, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService, - final ApiRequestParameterHelper apiRequestParameterHelper, final SavingsAccountChargeReadPlatformService savingsAccountChargeReadPlatformService) { + final ApiRequestParameterHelper apiRequestParameterHelper, + final SavingsAccountChargeReadPlatformService savingsAccountChargeReadPlatformService) { this.savingsAccountReadPlatformService = savingsAccountReadPlatformService; this.context = context; this.toApiJsonSerializer = toApiJsonSerializer; @@ -82,12 +83,12 @@ public class SavingsAccountsApiResource { @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); final SavingsAccountData savingsAccount = this.savingsAccountReadPlatformService.retrieveTemplate(clientId, groupId, productId, staffInSelectedOfficeOnly); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, savingsAccount, SavingsApiConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); } @@ -99,13 +100,13 @@ public class SavingsAccountsApiResource { @QueryParam("offset") final Integer offset, @QueryParam("limit") final Integer limit, @QueryParam("orderBy") final String orderBy, @QueryParam("sortOrder") final String sortOrder) { - context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); final SearchParameters searchParameters = SearchParameters.forLoans(sqlSearch, externalId, offset, limit, orderBy, sortOrder); final Page products = this.savingsAccountReadPlatformService.retrieveAll(searchParameters); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, products, SavingsApiConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); } @@ -129,15 +130,15 @@ public class SavingsAccountsApiResource { @DefaultValue("false") @QueryParam("staffInSelectedOfficeOnly") final boolean staffInSelectedOfficeOnly, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); final SavingsAccountData savingsAccount = this.savingsAccountReadPlatformService.retrieveOne(accountId); final Set mandatoryResponseParameters = new HashSet(); - SavingsAccountData savingsAccountTemplate = populateTemplateAndAssociations(accountId, savingsAccount, staffInSelectedOfficeOnly, - uriInfo, mandatoryResponseParameters); + final SavingsAccountData savingsAccountTemplate = populateTemplateAndAssociations(accountId, savingsAccount, + staffInSelectedOfficeOnly, uriInfo, mandatoryResponseParameters); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters(), + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters(), mandatoryResponseParameters); return this.toApiJsonSerializer.serialize(settings, savingsAccountTemplate, SavingsApiConstants.SAVINGS_ACCOUNT_RESPONSE_DATA_PARAMETERS); @@ -164,7 +165,7 @@ public class SavingsAccountsApiResource { transactions = currentTransactions; } } - + if (associationParameters.contains("charges")) { mandatoryResponseParameters.add("charges"); final Collection currentCharges = this.savingsAccountChargeReadPlatformService @@ -176,7 +177,7 @@ public class SavingsAccountsApiResource { } SavingsAccountData templateData = null; - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (settings.isTemplate()) { templateData = this.savingsAccountReadPlatformService.retrieveTemplate(savingsAccount.clientId(), savingsAccount.groupId(), savingsAccount.productId(), staffInSelectedOfficeOnly); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsProductsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsProductsApiResource.java index 191aa1623..d9cebb180 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsProductsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/api/SavingsProductsApiResource.java @@ -130,11 +130,11 @@ public class SavingsProductsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAll(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); final Collection products = this.savingProductReadPlatformService.retrieveAll(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, products, SavingsApiConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); } @@ -144,20 +144,20 @@ public class SavingsProductsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveOne(@PathParam("productId") final Long productId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); SavingsProductData savingProductData = this.savingProductReadPlatformService.retrieveOne(productId); - + final Collection charges = this.chargeReadPlatformService.retrieveSavingsProductCharges(productId); - + savingProductData = SavingsProductData.withCharges(savingProductData, charges); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); if (savingProductData.hasAccountingEnabled()) { - Map accountingMappings = accountMappingReadPlatformService.fetchAccountMappingDetailsForSavingsProduct( - productId, savingProductData.accountingRuleTypeId()); - Collection paymentChannelToFundSourceMappings = accountMappingReadPlatformService + final Map accountingMappings = this.accountMappingReadPlatformService + .fetchAccountMappingDetailsForSavingsProduct(productId, savingProductData.accountingRuleTypeId()); + final Collection paymentChannelToFundSourceMappings = this.accountMappingReadPlatformService .fetchPaymentTypeToFundSourceMappingsForSavingsProduct(productId); savingProductData = SavingsProductData.withAccountingDetails(savingProductData, accountingMappings, paymentChannelToFundSourceMappings); @@ -177,11 +177,11 @@ public class SavingsProductsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveTemplate(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); + this.context.authenticatedUser().validateHasReadPermission(SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME); - SavingsProductData savingProduct = handleTemplateRelatedData(null); + final SavingsProductData savingProduct = handleTemplateRelatedData(null); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, savingProduct, SavingsApiConstants.SAVINGS_PRODUCT_RESPONSE_DATA_PARAMETERS); } @@ -224,21 +224,21 @@ public class SavingsProductsApiResource { final Collection withdrawalFeeTypeOptions = this.dropdownReadPlatformService.retrievewithdrawalFeeTypeOptions(); - final Collection paymentTypeOptions = codeValueReadPlatformService + final Collection paymentTypeOptions = this.codeValueReadPlatformService .retrieveCodeValuesByCode(PaymentDetailConstants.paymentTypeCodeName); final Collection accountingRuleOptions = this.accountingDropdownReadPlatformService .retrieveAccountingRuleTypeOptions(); - final Map> accountingMappingOptions = accountingDropdownReadPlatformService + final Map> accountingMappingOptions = this.accountingDropdownReadPlatformService .retrieveAccountMappingOptionsForSavingsProducts(); - - //charges + + // charges final boolean feeChargesOnly = true; Collection chargeOptions = this.chargeReadPlatformService.retrieveSavingsAccountApplicableCharges(feeChargesOnly); chargeOptions = CollectionUtils.isEmpty(chargeOptions) ? null : chargeOptions; - + Collection penaltyOptions = this.chargeReadPlatformService.retrieveSavingsAccountApplicablePenalties(); penaltyOptions = CollectionUtils.isEmpty(penaltyOptions) ? null : penaltyOptions; - + SavingsProductData savingsProductToReturn = null; if (savingsProduct != null) { savingsProductToReturn = SavingsProductData.withTemplate(savingsProduct, currencyOptions, interestCompoundingPeriodTypeOptions, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountChargeData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountChargeData.java index 1b35ce6f4..d7db3d3f9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountChargeData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountChargeData.java @@ -83,9 +83,11 @@ public class SavingsAccountChargeData { final boolean penalty = false; final LocalDate dueAsOfDate = null; - return new SavingsAccountChargeData(id, chargeId, name, chargeTimeType, dueAsOfDate, chargeCalculationType, percentage, amountPercentageAppliedTo, currency, amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, chargeOptions, penalty); + return new SavingsAccountChargeData(id, chargeId, name, chargeTimeType, dueAsOfDate, chargeCalculationType, percentage, + amountPercentageAppliedTo, currency, amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, chargeOptions, + penalty); } - + public static SavingsAccountChargeData instance(final Long id, final Long chargeId, final String name, final CurrencyData currency, final BigDecimal amount, final BigDecimal amountPaid, final BigDecimal amountWaived, final BigDecimal amountWrittenOff, final BigDecimal amountOutstanding, final EnumOptionData chargeTimeType, final LocalDate dueAsOfDate, @@ -93,14 +95,15 @@ public class SavingsAccountChargeData { final Collection chargeOptions, final boolean penalty) { return new SavingsAccountChargeData(id, chargeId, name, chargeTimeType, dueAsOfDate, chargeCalculationType, percentage, - amountPercentageAppliedTo, currency, amount, amountPaid, amountWaived, amountWrittenOff, - amountOutstanding, chargeOptions, penalty); + amountPercentageAppliedTo, currency, amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, chargeOptions, + penalty); } - private SavingsAccountChargeData(Long id, Long chargeId, String name, EnumOptionData chargeTimeType, LocalDate dueAsOfDate, - EnumOptionData chargeCalculationType, BigDecimal percentage, BigDecimal amountPercentageAppliedTo, CurrencyData currency, - BigDecimal amount, BigDecimal amountPaid, BigDecimal amountWaived, BigDecimal amountWrittenOff, BigDecimal amountOutstanding, - Collection chargeOptions, boolean penalty) { + private SavingsAccountChargeData(final Long id, final Long chargeId, final String name, final EnumOptionData chargeTimeType, + final LocalDate dueAsOfDate, final EnumOptionData chargeCalculationType, final BigDecimal percentage, + final BigDecimal amountPercentageAppliedTo, final CurrencyData currency, final BigDecimal amount, final BigDecimal amountPaid, + final BigDecimal amountWaived, final BigDecimal amountWrittenOff, final BigDecimal amountOutstanding, + final Collection chargeOptions, final boolean penalty) { this.id = id; this.chargeId = chargeId; this.name = name; @@ -115,13 +118,13 @@ public class SavingsAccountChargeData { this.amountWaived = amountWaived; this.amountWrittenOff = amountWrittenOff; this.amountOutstanding = amountOutstanding; - this.amountOrPercentage = this.getAmountOrPercentage(); + this.amountOrPercentage = getAmountOrPercentage(); this.chargeOptions = chargeOptions; this.penalty = penalty; } private BigDecimal getAmountOrPercentage() { - return (this.chargeCalculationType != null) && (chargeCalculationType.getId().intValue() > 1) ? this.percentage : this.amount; + return (this.chargeCalculationType != null) && (this.chargeCalculationType.getId().intValue() > 1) ? this.percentage : this.amount; } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountChargeDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountChargeDataValidator.java index a2bb1c388..7949ad3a2 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountChargeDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountChargeDataValidator.java @@ -43,46 +43,48 @@ public class SavingsAccountChargeDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); - final Long chargeId = fromApiJsonHelper.extractLongNamed(chargeIdParamName, element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final Long chargeId = this.fromApiJsonHelper.extractLongNamed(chargeIdParamName, element); baseDataValidator.reset().parameter(chargeIdParamName).value(chargeId).notNull().integerGreaterThanZero(); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(amountParamName, element); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(amountParamName, element); baseDataValidator.reset().parameter(amountParamName).value(amount).notNull().positiveAmount(); - if (fromApiJsonHelper.parameterExists(dueAsOfDateParamName, element)) { - fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, element); + if (this.fromApiJsonHelper.parameterExists(dueAsOfDateParamName, element)) { + this.fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, element); } throwExceptionIfValidationWarningsExist(dataValidationErrors); } - + public void validateUpdate(final String json) { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_ACCOUNT_CHARGES_ADD_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); - final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); + final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) + .resource(SAVINGS_ACCOUNT_CHARGE_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(amountParamName, element); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(amountParamName, element); baseDataValidator.reset().parameter(amountParamName).value(amount).notNull().positiveAmount(); - if (fromApiJsonHelper.parameterExists(dueAsOfDateParamName, element)) { - fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, element); + if (this.fromApiJsonHelper.parameterExists(dueAsOfDateParamName, element)) { + this.fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, element); } throwExceptionIfValidationWarningsExist(dataValidationErrors); } - + private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java index 1fcb80ac0..7aba28190 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountData.java @@ -99,7 +99,8 @@ public class SavingsAccountData { lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, withdrawalFeeForTransfers, annualFeeAmount, annualFeeOnMonthDay, annualFeeNextDueDate, summary, transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, - interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions); + interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, + chargeOptions); } public static SavingsAccountData lookup(final Long accountId, final String accountNo) { @@ -148,9 +149,10 @@ public class SavingsAccountData { account.fieldOfficerName, account.status, account.timeline, account.currency, account.nominalAnnualInterestRate, account.interestCompoundingPeriodType, account.interestPostingPeriodType, account.interestCalculationType, account.interestCalculationDaysInYearType, account.minRequiredOpeningBalance, account.lockinPeriodFrequency, - account.lockinPeriodFrequencyType, account.withdrawalFeeAmount, account.withdrawalFeeType, account.withdrawalFeeForTransfers, - account.annualFeeAmount, account.annualFeeOnMonthDay, account.annualFeeNextDueDate, account.summary, transactions, template.productOptions, - template.fieldOfficerOptions, template.interestCompoundingPeriodTypeOptions, template.interestPostingPeriodTypeOptions, + account.lockinPeriodFrequencyType, account.withdrawalFeeAmount, account.withdrawalFeeType, + account.withdrawalFeeForTransfers, account.annualFeeAmount, account.annualFeeOnMonthDay, account.annualFeeNextDueDate, + account.summary, transactions, template.productOptions, template.fieldOfficerOptions, + template.interestCompoundingPeriodTypeOptions, template.interestPostingPeriodTypeOptions, template.interestCalculationTypeOptions, template.interestCalculationDaysInYearTypeOptions, template.lockinPeriodFrequencyTypeOptions, template.withdrawalFeeTypeOptions, charges, template.chargeOptions); } @@ -162,18 +164,19 @@ public class SavingsAccountData { final Collection interestCalculationTypeOptions, final Collection interestCalculationDaysInYearTypeOptions, final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, - final Collection transactions, final Collection charges, final Collection chargeOptions) { + final Collection transactions, final Collection charges, + final Collection chargeOptions) { return new SavingsAccountData(account.id, account.accountNo, account.externalId, account.groupId, account.groupName, account.clientId, account.clientName, account.savingsProductId, account.savingsProductName, account.fieldOfficerId, account.fieldOfficerName, account.status, account.timeline, account.currency, account.nominalAnnualInterestRate, account.interestCompoundingPeriodType, account.interestPostingPeriodType, account.interestCalculationType, account.interestCalculationDaysInYearType, account.minRequiredOpeningBalance, account.lockinPeriodFrequency, - account.lockinPeriodFrequencyType, account.withdrawalFeeAmount, account.withdrawalFeeType,account.withdrawalFeeForTransfers, - account.annualFeeAmount, account.annualFeeOnMonthDay, account.annualFeeNextDueDate, account.summary, transactions, productOptions, - fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, - interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, - withdrawalFeeTypeOptions, charges, chargeOptions); + account.lockinPeriodFrequencyType, account.withdrawalFeeAmount, account.withdrawalFeeType, + account.withdrawalFeeForTransfers, account.annualFeeAmount, account.annualFeeOnMonthDay, account.annualFeeNextDueDate, + account.summary, transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, + interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, + lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions); } public static SavingsAccountData withClientTemplate(final Long clientId, final String clientName, final Long groupId, @@ -222,10 +225,11 @@ public class SavingsAccountData { return new SavingsAccountData(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldOfficerId, fieldOfficerName, status, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, - lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType,withdrawalFeeForTransfers, + lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, withdrawalFeeForTransfers, annualFeeAmount, annualFeeOnMonthDay, annualFeeNextDueDate, summary, transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, - interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions); + interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, + chargeOptions); } private SavingsAccountData(final Long id, final String accountNo, final String externalId, final Long groupId, final String groupName, @@ -235,14 +239,15 @@ public class SavingsAccountData { final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, final BigDecimal withdrawalFeeAmount, - final EnumOptionData withdrawalFeeType,final boolean withdrawalFeeForTransfers, final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay, - final LocalDate annualFeeNextDueDate, final SavingsAccountSummaryData summary, + final EnumOptionData withdrawalFeeType, final boolean withdrawalFeeForTransfers, final BigDecimal annualFeeAmount, + final MonthDay annualFeeOnMonthDay, final LocalDate annualFeeNextDueDate, final SavingsAccountSummaryData summary, final Collection transactions, final Collection productOptions, final Collection fieldOfficerOptions, final Collection interestCompoundingPeriodTypeOptions, final Collection interestPostingPeriodTypeOptions, final Collection interestCalculationTypeOptions, final Collection interestCalculationDaysInYearTypeOptions, - final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, final Collection charges, final Collection chargeOptions) { + final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, + final Collection charges, final Collection chargeOptions) { this.id = id; this.accountNo = accountNo; this.externalId = externalId; @@ -284,8 +289,9 @@ public class SavingsAccountData { this.lockinPeriodFrequencyTypeOptions = lockinPeriodFrequencyTypeOptions; this.withdrawalFeeTypeOptions = withdrawalFeeTypeOptions; - this.charges = charges;//charges associated with Savings account - this.chargeOptions = chargeOptions;//charges available for adding to Savings account + this.charges = charges;// charges associated with Savings account + this.chargeOptions = chargeOptions;// charges available for adding to + // Savings account } public Long id() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountDataValidator.java index 6ae84b284..2cd1510bc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountDataValidator.java @@ -23,8 +23,8 @@ import static org.mifosplatform.portfolio.savings.SavingsApiConstants.nominalAnn import static org.mifosplatform.portfolio.savings.SavingsApiConstants.productIdParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.submittedOnDateParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeAmountParamName; -import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeTypeParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeForTransfersParamName; +import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeTypeParamName; import java.lang.reflect.Type; import java.math.BigDecimal; @@ -67,19 +67,19 @@ public class SavingsAccountDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsApiConstants.SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsApiConstants.SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); - final Long clientId = fromApiJsonHelper.extractLongNamed(clientIdParamName, element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); if (clientId != null) { baseDataValidator.reset().parameter(clientIdParamName).value(clientId).longGreaterThanZero(); } - final Long groupId = fromApiJsonHelper.extractLongNamed(groupIdParamName, element); + final Long groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParamName, element); if (groupId != null) { baseDataValidator.reset().parameter(groupIdParamName).value(groupId).longGreaterThanZero(); } @@ -88,73 +88,75 @@ public class SavingsAccountDataValidator { baseDataValidator.reset().parameter(clientIdParamName).value(clientId).notNull().integerGreaterThanZero(); } - final Long productId = fromApiJsonHelper.extractLongNamed(productIdParamName, element); + final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParamName, element); baseDataValidator.reset().parameter(productIdParamName).value(productId).notNull().integerGreaterThanZero(); - if (fromApiJsonHelper.parameterExists(fieldOfficerIdParamName, element)) { - final Long fieldOfficerId = fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); + if (this.fromApiJsonHelper.parameterExists(fieldOfficerIdParamName, element)) { + final Long fieldOfficerId = this.fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); baseDataValidator.reset().parameter(fieldOfficerIdParamName).value(fieldOfficerId).ignoreIfNull().integerGreaterThanZero(); } - final LocalDate submittedOnDate = fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); + final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); baseDataValidator.reset().parameter(submittedOnDateParamName).value(submittedOnDate).notNull(); - if (fromApiJsonHelper.parameterExists(accountNoParamName, element)) { - final String accountNo = fromApiJsonHelper.extractStringNamed(accountNoParamName, element); + if (this.fromApiJsonHelper.parameterExists(accountNoParamName, element)) { + final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParamName, element); baseDataValidator.reset().parameter(accountNoParamName).value(accountNo).notBlank().notExceedingLengthOf(20); } - if (fromApiJsonHelper.parameterExists(externalIdParamName, element)) { - final String externalId = fromApiJsonHelper.extractStringNamed(externalIdParamName, element); + if (this.fromApiJsonHelper.parameterExists(externalIdParamName, element)) { + final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParamName, element); baseDataValidator.reset().parameter(externalIdParamName).value(externalId).notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { - final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); + if (this.fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { + final BigDecimal interestRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, + element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } - if (fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { - final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + if (this.fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } - if (fromApiJsonHelper.parameterExists(interestPostingPeriodTypeParamName, element)) { - final Integer interestPostingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestPostingPeriodTypeParamName, - element); + if (this.fromApiJsonHelper.parameterExists(interestPostingPeriodTypeParamName, element)) { + final Integer interestPostingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( + interestPostingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestPostingPeriodTypeParamName).value(interestPostingPeriodType).notNull() .isOneOfTheseValues(SavingsPostingInterestPeriodType.integerValues()); } - if (fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { - final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, + if (this.fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { + final Integer interestCalculationType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .isOneOfTheseValues(SavingsInterestCalculationType.integerValues()); } - if (fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { - final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + if (this.fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, - element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { - final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); + final Integer lockinPeriodFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, + element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).integerZeroOrGreater(); if (lockinPeriodFrequency != null) { - final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull() .inMinMaxRange(0, 3); @@ -162,12 +164,12 @@ public class SavingsAccountDataValidator { } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, - element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( + lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); if (lockinPeriodFrequencyType != null) { - final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, + final Integer lockinPeriodFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).notNull() .integerZeroOrGreater(); @@ -176,51 +178,53 @@ public class SavingsAccountDataValidator { if (this.fromApiJsonHelper.parameterExists(withdrawalFeeAmountParamName, element)) { - final BigDecimal withdrawalFeeAmount = fromApiJsonHelper - .extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, element); + final BigDecimal withdrawalFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, + element); baseDataValidator.reset().parameter(withdrawalFeeAmountParamName).value(withdrawalFeeAmount).zeroOrPositiveAmount(); if (withdrawalFeeAmount != null) { - final Integer withdrawalFeeType = fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); + final Integer withdrawalFeeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); baseDataValidator.reset().parameter(withdrawalFeeTypeParamName).value(withdrawalFeeType) .isOneOfTheseValues(SavingsWithdrawalFeesType.integerValues()); } } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeTypeParamName, element)) { - final Integer withdrawalFeeType = fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); + final Integer withdrawalFeeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); baseDataValidator.reset().parameter(withdrawalFeeTypeParamName).value(withdrawalFeeType).ignoreIfNull() .isOneOfTheseValues(1, 2); if (withdrawalFeeType != null) { - final BigDecimal withdrawalFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, - element); + final BigDecimal withdrawalFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + withdrawalFeeAmountParamName, element); baseDataValidator.reset().parameter(withdrawalFeeAmountParamName).value(withdrawalFeeAmount).notNull() .zeroOrPositiveAmount(); } } - - if(this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { - final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); - baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers).ignoreIfNull() - .validateForBooleanValue(); + + if (this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { + final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper.extractBooleanNamed( + withdrawalFeeForTransfersParamName, element); + baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) + .ignoreIfNull().validateForBooleanValue(); } if (this.fromApiJsonHelper.parameterExists(annualFeeAmountParamName, element)) { - final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); + final BigDecimal annualFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); baseDataValidator.reset().parameter(annualFeeAmountParamName).value(annualFeeAmount).zeroOrPositiveAmount(); if (annualFeeAmount != null) { - MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); + final MonthDay monthDayOfAnnualFee = this.fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); baseDataValidator.reset().parameter(annualFeeOnMonthDayParamName).value(monthDayOfAnnualFee).notNull(); } } if (this.fromApiJsonHelper.parameterExists(annualFeeOnMonthDayParamName, element)) { - MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); + final MonthDay monthDayOfAnnualFee = this.fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); if (monthDayOfAnnualFee != null) { - final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); + final BigDecimal annualFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, + element); baseDataValidator.reset().parameter(annualFeeAmountParamName).value(annualFeeAmount).notNull().zeroOrPositiveAmount(); } } @@ -233,22 +237,22 @@ public class SavingsAccountDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsApiConstants.SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsApiConstants.SAVINGS_ACCOUNT_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SavingsApiConstants.SAVINGS_ACCOUNT_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); Long clientId = null; - if (fromApiJsonHelper.parameterExists(clientIdParamName, element)) { - clientId = fromApiJsonHelper.extractLongNamed(clientIdParamName, element); + if (this.fromApiJsonHelper.parameterExists(clientIdParamName, element)) { + clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); baseDataValidator.reset().parameter(clientIdParamName).value(clientId).ignoreIfNull().longGreaterThanZero(); Long groupId = null; - if (fromApiJsonHelper.parameterExists(productIdParamName, element)) { - groupId = fromApiJsonHelper.extractLongNamed(groupIdParamName, element); + if (this.fromApiJsonHelper.parameterExists(productIdParamName, element)) { + groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParamName, element); baseDataValidator.reset().parameter(groupIdParamName).value(groupId).ignoreIfNull().longGreaterThanZero(); } @@ -260,12 +264,12 @@ public class SavingsAccountDataValidator { } Long groupId = null; - if (fromApiJsonHelper.parameterExists(groupIdParamName, element)) { - groupId = fromApiJsonHelper.extractLongNamed(groupIdParamName, element); + if (this.fromApiJsonHelper.parameterExists(groupIdParamName, element)) { + groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParamName, element); baseDataValidator.reset().parameter(groupIdParamName).value(groupId).ignoreIfNull().longGreaterThanZero(); - if (fromApiJsonHelper.parameterExists(clientIdParamName, element)) { - clientId = fromApiJsonHelper.extractLongNamed(clientIdParamName, element); + if (this.fromApiJsonHelper.parameterExists(clientIdParamName, element)) { + clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); baseDataValidator.reset().parameter(clientIdParamName).value(clientId).ignoreIfNull().longGreaterThanZero(); } @@ -276,109 +280,112 @@ public class SavingsAccountDataValidator { } } - if (fromApiJsonHelper.parameterExists(productIdParamName, element)) { - final Long productId = fromApiJsonHelper.extractLongNamed(productIdParamName, element); + if (this.fromApiJsonHelper.parameterExists(productIdParamName, element)) { + final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParamName, element); baseDataValidator.reset().parameter(productIdParamName).value(productId).notNull().integerGreaterThanZero(); } - if (fromApiJsonHelper.parameterExists(fieldOfficerIdParamName, element)) { - final Long fieldOfficerId = fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); + if (this.fromApiJsonHelper.parameterExists(fieldOfficerIdParamName, element)) { + final Long fieldOfficerId = this.fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); baseDataValidator.reset().parameter(fieldOfficerIdParamName).value(fieldOfficerId).ignoreIfNull().integerGreaterThanZero(); } - if (fromApiJsonHelper.parameterExists(submittedOnDateParamName, element)) { - final LocalDate submittedOnDate = fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); + if (this.fromApiJsonHelper.parameterExists(submittedOnDateParamName, element)) { + final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); baseDataValidator.reset().parameter(submittedOnDateParamName).value(submittedOnDate).notNull(); } - if (fromApiJsonHelper.parameterExists(accountNoParamName, element)) { - final String accountNo = fromApiJsonHelper.extractStringNamed(accountNoParamName, element); + if (this.fromApiJsonHelper.parameterExists(accountNoParamName, element)) { + final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParamName, element); baseDataValidator.reset().parameter(accountNoParamName).value(accountNo).notBlank().notExceedingLengthOf(20); } - if (fromApiJsonHelper.parameterExists(externalIdParamName, element)) { - final String externalId = fromApiJsonHelper.extractStringNamed(externalIdParamName, element); + if (this.fromApiJsonHelper.parameterExists(externalIdParamName, element)) { + final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParamName, element); baseDataValidator.reset().parameter(externalIdParamName).value(externalId).notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { - final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); + if (this.fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { + final BigDecimal interestRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, + element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { - final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(interestPostingPeriodTypeParamName, element)) { - final Integer interestPostingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestPostingPeriodTypeParamName, - element); + final Integer interestPostingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( + interestPostingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestPostingPeriodTypeParamName).value(interestPostingPeriodType).notNull() .isOneOfTheseValues(SavingsPostingInterestPeriodType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { - final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, + final Integer interestCalculationType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .isOneOfTheseValues(SavingsInterestCalculationType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { - final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, - element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { - final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); + final Integer lockinPeriodFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, + element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, - element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( + lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeAmountParamName, element)) { - final BigDecimal withdrawalFeeAmount = fromApiJsonHelper - .extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, element); + final BigDecimal withdrawalFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, + element); baseDataValidator.reset().parameter(withdrawalFeeAmountParamName).value(withdrawalFeeAmount).ignoreIfNull() .zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeTypeParamName, element)) { - final Integer withdrawalFeeType = fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); + final Integer withdrawalFeeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); baseDataValidator.reset().parameter(withdrawalFeeTypeParamName).value(withdrawalFeeType).ignoreIfNull() .isOneOfTheseValues(SavingsWithdrawalFeesType.integerValues()); } - - if(this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { - final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, element); - baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers).ignoreIfNull() - .validateForBooleanValue(); + + if (this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { + final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper.extractBooleanNamed( + withdrawalFeeForTransfersParamName, element); + baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) + .ignoreIfNull().validateForBooleanValue(); } if (this.fromApiJsonHelper.parameterExists(annualFeeAmountParamName, element)) { - final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); + final BigDecimal annualFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); baseDataValidator.reset().parameter(annualFeeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(annualFeeOnMonthDayParamName, element)) { - MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); + final MonthDay monthDayOfAnnualFee = this.fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); baseDataValidator.reset().parameter(annualFeeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountTransactionDTO.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountTransactionDTO.java index cdaa9218c..e6d8b49de 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountTransactionDTO.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountTransactionDTO.java @@ -9,12 +9,12 @@ import org.mifosplatform.portfolio.paymentdetail.domain.PaymentDetail; public class SavingsAccountTransactionDTO { - private DateTimeFormatter formatter; - private LocalDate transactionDate; - private BigDecimal transactionAmount; - private List existingTransactionIds; - private List existingReversedTransactionIds; - private PaymentDetail paymentDetail; + private final DateTimeFormatter formatter; + private final LocalDate transactionDate; + private final BigDecimal transactionAmount; + private final List existingTransactionIds; + private final List existingReversedTransactionIds; + private final PaymentDetail paymentDetail; public SavingsAccountTransactionDTO(final DateTimeFormatter formatter, final LocalDate transactionDate, final BigDecimal transactionAmount, final List existingTransactionIds, final List existingReversedTransactionIds, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountTransactionDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountTransactionDataValidator.java index 4db68311d..379e22011 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountTransactionDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsAccountTransactionDataValidator.java @@ -57,7 +57,7 @@ public class SavingsAccountTransactionDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsApiConstants.SAVINGS_ACCOUNT_TRANSACTION_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); @@ -66,19 +66,19 @@ public class SavingsAccountTransactionDataValidator { final JsonElement element = command.parsedJson(); - final LocalDate transactionDate = fromApiJsonHelper.extractLocalDateNamed(transactionDateParamName, element); + final LocalDate transactionDate = this.fromApiJsonHelper.extractLocalDateNamed(transactionDateParamName, element); baseDataValidator.reset().parameter(transactionDateParamName).value(transactionDate).notNull(); - final BigDecimal transactionAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(transactionAmountParamName, element); + final BigDecimal transactionAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(transactionAmountParamName, element); baseDataValidator.reset().parameter(transactionAmountParamName).value(transactionAmount).notNull().positiveAmount(); // Validate all string payment detail fields for max length - final Integer paymentTypeId = fromApiJsonHelper.extractIntegerWithLocaleNamed(paymentTypeIdParamName, element); + final Integer paymentTypeId = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(paymentTypeIdParamName, element); baseDataValidator.reset().parameter(paymentTypeIdParamName).value(paymentTypeId).ignoreIfNull().integerGreaterThanZero(); - final Set paymentDetailParameters = new HashSet(Arrays.asList(transactionAccountNumberParamName, checkNumberParamName, - routingCodeParamName, receiptNumberParamName, bankNumberParamName)); - for (String paymentDetailParameterName : paymentDetailParameters) { - final String paymentDetailParameterValue = fromApiJsonHelper.extractStringNamed(paymentDetailParameterName, element); + final Set paymentDetailParameters = new HashSet(Arrays.asList(transactionAccountNumberParamName, + checkNumberParamName, routingCodeParamName, receiptNumberParamName, bankNumberParamName)); + for (final String paymentDetailParameterName : paymentDetailParameters) { + final String paymentDetailParameterValue = this.fromApiJsonHelper.extractStringNamed(paymentDetailParameterName, element); baseDataValidator.reset().parameter(paymentDetailParameterName).value(paymentDetailParameterValue).ignoreIfNull() .notExceedingLengthOf(50); } @@ -92,7 +92,7 @@ public class SavingsAccountTransactionDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsApiConstants.SAVINGS_ACCOUNT_ACTIVATION_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); @@ -101,19 +101,19 @@ public class SavingsAccountTransactionDataValidator { final JsonElement element = command.parsedJson(); - final LocalDate activationDate = fromApiJsonHelper.extractLocalDateNamed(activatedOnDateParamName, element); + final LocalDate activationDate = this.fromApiJsonHelper.extractLocalDateNamed(activatedOnDateParamName, element); baseDataValidator.reset().parameter(activatedOnDateParamName).value(activationDate).notNull(); throwExceptionIfValidationWarningsExist(dataValidationErrors); } - + public void validateClosing(final JsonCommand command) { final String json = command.json(); if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SavingsApiConstants.SAVINGS_ACCOUNT_CLOSE_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); @@ -122,13 +122,12 @@ public class SavingsAccountTransactionDataValidator { final JsonElement element = command.parsedJson(); - final LocalDate activationDate = fromApiJsonHelper.extractLocalDateNamed(closedOnDateParamName, element); + final LocalDate activationDate = this.fromApiJsonHelper.extractLocalDateNamed(closedOnDateParamName, element); baseDataValidator.reset().parameter(closedOnDateParamName).value(activationDate).notNull(); throwExceptionIfValidationWarningsExist(dataValidationErrors); } - private void throwExceptionIfValidationWarningsExist(final List dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { // diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductData.java index d54596758..73221a561 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductData.java @@ -49,7 +49,7 @@ public class SavingsProductData { // charges private final Collection charges; - + // template private final Collection currencyOptions; private final Collection interestCompoundingPeriodTypeOptions; @@ -63,7 +63,7 @@ public class SavingsProductData { private final Map> accountingMappingOptions; private final Collection chargeOptions; private final Collection penaltyOptions; - + public static SavingsProductData template(final CurrencyData currency, final EnumOptionData interestCompoundingPeriodType, final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, final EnumOptionData accountingRule, @@ -73,7 +73,8 @@ public class SavingsProductData { final Collection interestCalculationDaysInYearTypeOptions, final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, final Collection paymentTypeOptions, final Collection accountingRuleOptions, - final Map> accountingMappingOptions, final Collection chargeOptions, final Collection penaltyOptions) { + final Map> accountingMappingOptions, final Collection chargeOptions, + final Collection penaltyOptions) { final Long id = null; final String name = null; @@ -93,9 +94,9 @@ public class SavingsProductData { return new SavingsProductData(id, name, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, - lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType,withdrawalFeeForTransfers, - accountingRule, annualFeeAmount, annualFeeMonthDay, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions, - interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, + lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, withdrawalFeeForTransfers, + accountingRule, annualFeeAmount, annualFeeMonthDay, accountingMappings, paymentChannelToFundSourceMappings, + currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, penaltyOptions); } @@ -112,7 +113,7 @@ public class SavingsProductData { product.lockinPeriodFrequencyTypeOptions, product.withdrawalFeeTypeOptions, product.paymentTypeOptions, product.accountingRuleOptions, product.accountingMappingOptions, charges, product.chargeOptions, product.penaltyOptions); } - + /** * Returns a {@link SavingsProductData} that contains and exist * {@link SavingsProductData} data with further template data for dropdowns. @@ -124,15 +125,16 @@ public class SavingsProductData { final Collection interestCalculationDaysInYearTypeOptions, final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, final Collection paymentTypeOptions, final Collection accountingRuleOptions, - final Map> accountingMappingOptions, final Collection chargeOptions, final Collection penaltyOptions) { + final Map> accountingMappingOptions, final Collection chargeOptions, + final Collection penaltyOptions) { return new SavingsProductData(existingProduct.id, existingProduct.name, existingProduct.description, existingProduct.currency, existingProduct.nominalAnnualInterestRate, existingProduct.interestCompoundingPeriodType, existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, existingProduct.minRequiredOpeningBalance, existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, existingProduct.withdrawalFeeAmount, - existingProduct.withdrawalFeeType,existingProduct.withdrawalFeeForTransfers, existingProduct.accountingRule, existingProduct.annualFeeAmount, - existingProduct.annualFeeOnMonthDay, existingProduct.accountingMappings, + existingProduct.withdrawalFeeType, existingProduct.withdrawalFeeForTransfers, existingProduct.accountingRule, + existingProduct.annualFeeAmount, existingProduct.annualFeeOnMonthDay, existingProduct.accountingMappings, existingProduct.paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, @@ -160,11 +162,12 @@ public class SavingsProductData { existingProduct.interestPostingPeriodType, existingProduct.interestCalculationType, existingProduct.interestCalculationDaysInYearType, existingProduct.minRequiredOpeningBalance, existingProduct.lockinPeriodFrequency, existingProduct.lockinPeriodFrequencyType, existingProduct.withdrawalFeeAmount, - existingProduct.withdrawalFeeType,existingProduct.withdrawalFeeForTransfers, existingProduct.accountingRule, existingProduct.annualFeeAmount, - existingProduct.annualFeeOnMonthDay, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions, - interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, - interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, - accountingRuleOptions, accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions); + existingProduct.withdrawalFeeType, existingProduct.withdrawalFeeForTransfers, existingProduct.accountingRule, + existingProduct.annualFeeAmount, existingProduct.annualFeeOnMonthDay, accountingMappings, + paymentChannelToFundSourceMappings, currencyOptions, interestCompoundingPeriodTypeOptions, + interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, + lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, + accountingMappingOptions, existingProduct.charges, chargeOptions, penaltyOptions); } public static SavingsProductData instance(final Long id, final String name, final String description, final CurrencyData currency, @@ -172,7 +175,7 @@ public class SavingsProductData { final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, final BigDecimal withdrawalFeeAmount, - final EnumOptionData withdrawalFeeType, boolean withdrawalFeeForTransfers, final BigDecimal annualFeeAmount, + final EnumOptionData withdrawalFeeType, final boolean withdrawalFeeForTransfers, final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay, final EnumOptionData accountingType) { final Map accountingMappings = null; @@ -194,9 +197,9 @@ public class SavingsProductData { return new SavingsProductData(id, name, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, - lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType,withdrawalFeeForTransfers, accountingType, - annualFeeAmount, annualFeeOnMonthDay, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions, - interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, + lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, withdrawalFeeForTransfers, + accountingType, annualFeeAmount, annualFeeOnMonthDay, accountingMappings, paymentChannelToFundSourceMappings, + currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, penaltyOptions); } @@ -238,9 +241,9 @@ public class SavingsProductData { return new SavingsProductData(id, name, description, currency, nominalAnnualInterestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, - lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType,withdrawalFeeForTransfers, accountingType, - annualFeeAmount, annualFeeMonthDay, accountingMappings, paymentChannelToFundSourceMappings, currencyOptions, - interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, + lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, withdrawalFeeForTransfers, + accountingType, annualFeeAmount, annualFeeMonthDay, accountingMappings, paymentChannelToFundSourceMappings, + currencyOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, paymentTypeOptions, accountingRuleOptions, accountingMappingOptions, charges, chargeOptions, penaltyOptions); } @@ -250,7 +253,7 @@ public class SavingsProductData { final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType, final BigDecimal withdrawalFeeAmount, - final EnumOptionData withdrawalFeeType,final boolean withdrawalFeeForTransfers, final EnumOptionData accountingType, + final EnumOptionData withdrawalFeeType, final boolean withdrawalFeeForTransfers, final EnumOptionData accountingType, final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay, final Map accountingMappings, final Collection paymentChannelToFundSourceMappings, final Collection currencyOptions, final Collection interestCompoundingPeriodTypeOptions, @@ -259,7 +262,8 @@ public class SavingsProductData { final Collection interestCalculationDaysInYearTypeOptions, final Collection lockinPeriodFrequencyTypeOptions, final Collection withdrawalFeeTypeOptions, final Collection paymentTypeOptions, final Collection accountingRuleOptions, - final Map> accountingMappingOptions, final Collection charges, final Collection chargeOptions, final Collection penaltyOptions) { + final Map> accountingMappingOptions, final Collection charges, + final Collection chargeOptions, final Collection penaltyOptions) { this.id = id; this.name = name; this.description = description; @@ -296,10 +300,12 @@ public class SavingsProductData { this.accountingMappings = accountingMappings; } this.paymentChannelToFundSourceMappings = paymentChannelToFundSourceMappings; - - this.charges = charges;//charges associated with Savings product - this.chargeOptions = chargeOptions;//charges available for adding to Savings product - this.penaltyOptions = penaltyOptions;//penalties available for adding to Savings product + + this.charges = charges;// charges associated with Savings product + this.chargeOptions = chargeOptions;// charges available for adding to + // Savings product + this.penaltyOptions = penaltyOptions;// penalties available for adding + // to Savings product } public boolean hasAccountingEnabled() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductDataValidator.java index 91420f8ab..0cadc5f04 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/data/SavingsProductDataValidator.java @@ -70,66 +70,68 @@ public class SavingsProductDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_PRODUCT_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); + final String name = this.fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); - final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); + final String description = this.fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); - final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); + final String currencyCode = this.fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); - final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); + final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); if (this.fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { - final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); + final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } - final BigDecimal nominalAnnualInterestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, - element); + final BigDecimal nominalAnnualInterestRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + nominalAnnualInterestRateParamName, element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(nominalAnnualInterestRate).notNull() .zeroOrPositiveAmount(); - final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); - final Integer interestPostingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestPostingPeriodTypeParamName, + final Integer interestPostingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(interestPostingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestPostingPeriodTypeParamName).value(interestPostingPeriodType).notNull() .isOneOfTheseValues(SavingsPostingInterestPeriodType.integerValues()); - final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); + final Integer interestCalculationType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, + element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .isOneOfTheseValues(SavingsInterestCalculationType.integerValues()); - final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType).notNull() .isOneOfTheseValues(SavingsInterestCalculationDaysInYearType.integerValues()); if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, - element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { - final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); + final Integer lockinPeriodFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, + element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).integerZeroOrGreater(); if (lockinPeriodFrequency != null) { - final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).notNull() .inMinMaxRange(0, 3); @@ -137,12 +139,12 @@ public class SavingsProductDataValidator { } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, - element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( + lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); if (lockinPeriodFrequencyType != null) { - final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, + final Integer lockinPeriodFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).notNull() .integerZeroOrGreater(); @@ -151,84 +153,85 @@ public class SavingsProductDataValidator { if (this.fromApiJsonHelper.parameterExists(withdrawalFeeAmountParamName, element)) { - final BigDecimal withdrawalFeeAmount = fromApiJsonHelper - .extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, element); + final BigDecimal withdrawalFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, + element); baseDataValidator.reset().parameter(withdrawalFeeAmountParamName).value(withdrawalFeeAmount).zeroOrPositiveAmount(); if (withdrawalFeeAmount != null) { - final Integer withdrawalFeeType = fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); + final Integer withdrawalFeeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); baseDataValidator.reset().parameter(withdrawalFeeTypeParamName).value(withdrawalFeeType) .isOneOfTheseValues(SavingsWithdrawalFeesType.integerValues()); } } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeTypeParamName, element)) { - final Integer withdrawalFeeType = fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); + final Integer withdrawalFeeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); baseDataValidator.reset().parameter(withdrawalFeeTypeParamName).value(withdrawalFeeType).ignoreIfNull() .isOneOfTheseValues(1, 2); if (withdrawalFeeType != null) { - final BigDecimal withdrawalFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, - element); + final BigDecimal withdrawalFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + withdrawalFeeAmountParamName, element); baseDataValidator.reset().parameter(withdrawalFeeAmountParamName).value(withdrawalFeeAmount).notNull() .zeroOrPositiveAmount(); } } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { - final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, - element); + final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper.extractBooleanNamed( + withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (this.fromApiJsonHelper.parameterExists(annualFeeAmountParamName, element)) { - final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); + final BigDecimal annualFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); baseDataValidator.reset().parameter(annualFeeAmountParamName).value(annualFeeAmount).zeroOrPositiveAmount(); if (annualFeeAmount != null) { - MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); + final MonthDay monthDayOfAnnualFee = this.fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); baseDataValidator.reset().parameter(annualFeeOnMonthDayParamName).value(monthDayOfAnnualFee).notNull(); } } if (this.fromApiJsonHelper.parameterExists(annualFeeOnMonthDayParamName, element)) { - MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); + final MonthDay monthDayOfAnnualFee = this.fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); if (monthDayOfAnnualFee != null) { - final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); + final BigDecimal annualFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, + element); baseDataValidator.reset().parameter(annualFeeAmountParamName).value(annualFeeAmount).notNull().zeroOrPositiveAmount(); } } // accounting related data validation - final Integer accountingRuleType = fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault()); + final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element, Locale.getDefault()); baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).notNull().inMinMaxRange(1, 3); if (isCashBasedAccounting(accountingRuleType)) { - final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( + final Long savingsControlAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()) .value(savingsControlAccountId).notNull().integerGreaterThanZero(); - final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( + final Long savingsReferenceAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).notNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).notNull().integerGreaterThanZero(); - final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( + final Long interestOnSavingsAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).notNull().integerGreaterThanZero(); - final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), - element); + final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed( + SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .notNull().integerGreaterThanZero(); @@ -243,134 +246,136 @@ public class SavingsProductDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, SAVINGS_PRODUCT_REQUEST_DATA_PARAMETERS); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(SAVINGS_PRODUCT_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists(nameParamName, element)) { - final String name = fromApiJsonHelper.extractStringNamed(nameParamName, element); + final String name = this.fromApiJsonHelper.extractStringNamed(nameParamName, element); baseDataValidator.reset().parameter(nameParamName).value(name).notBlank().notExceedingLengthOf(100); } if (this.fromApiJsonHelper.parameterExists(descriptionParamName, element)) { - final String description = fromApiJsonHelper.extractStringNamed(descriptionParamName, element); + final String description = this.fromApiJsonHelper.extractStringNamed(descriptionParamName, element); baseDataValidator.reset().parameter(descriptionParamName).value(description).notBlank().notExceedingLengthOf(500); } if (this.fromApiJsonHelper.parameterExists(currencyCodeParamName, element)) { - final String currencyCode = fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); + final String currencyCode = this.fromApiJsonHelper.extractStringNamed(currencyCodeParamName, element); baseDataValidator.reset().parameter(currencyCodeParamName).value(currencyCode).notBlank(); } if (this.fromApiJsonHelper.parameterExists(digitsAfterDecimalParamName, element)) { - final Integer digitsAfterDecimal = fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); + final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(digitsAfterDecimalParamName, element); baseDataValidator.reset().parameter(digitsAfterDecimalParamName).value(digitsAfterDecimal).notNull().inMinMaxRange(0, 6); } if (this.fromApiJsonHelper.parameterExists(inMultiplesOfParamName, element)) { - final Integer inMultiplesOf = fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); + final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed(inMultiplesOfParamName, element, Locale.getDefault()); baseDataValidator.reset().parameter(inMultiplesOfParamName).value(inMultiplesOf).ignoreIfNull().integerZeroOrGreater(); } if (this.fromApiJsonHelper.parameterExists(nominalAnnualInterestRateParamName, element)) { - final BigDecimal interestRate = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, element); + final BigDecimal interestRate = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(nominalAnnualInterestRateParamName, + element); baseDataValidator.reset().parameter(nominalAnnualInterestRateParamName).value(interestRate).notNull().zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(interestCompoundingPeriodTypeParamName, element)) { - final Integer interestCompoundingPeriodType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + final Integer interestCompoundingPeriodType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCompoundingPeriodTypeParamName, element); baseDataValidator.reset().parameter(interestCompoundingPeriodTypeParamName).value(interestCompoundingPeriodType).notNull() .isOneOfTheseValues(SavingsCompoundingInterestPeriodType.integerValues()); } if (this.fromApiJsonHelper.parameterExists(interestCalculationTypeParamName, element)) { - final Integer interestCalculationType = fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, + final Integer interestCalculationType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(interestCalculationTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationTypeParamName).value(interestCalculationType).notNull() .inMinMaxRange(1, 2); } if (this.fromApiJsonHelper.parameterExists(interestCalculationDaysInYearTypeParamName, element)) { - final Integer interestCalculationDaysInYearType = fromApiJsonHelper.extractIntegerSansLocaleNamed( + final Integer interestCalculationDaysInYearType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( interestCalculationDaysInYearTypeParamName, element); baseDataValidator.reset().parameter(interestCalculationDaysInYearTypeParamName).value(interestCalculationDaysInYearType) .notNull().isOneOfTheseValues(360, 365); } if (this.fromApiJsonHelper.parameterExists(minRequiredOpeningBalanceParamName, element)) { - final BigDecimal minOpeningBalance = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minRequiredOpeningBalanceParamName, - element); + final BigDecimal minOpeningBalance = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed( + minRequiredOpeningBalanceParamName, element); baseDataValidator.reset().parameter(minRequiredOpeningBalanceParamName).value(minOpeningBalance).ignoreIfNull() .zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyParamName, element)) { - final Integer lockinPeriodFrequency = fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, element); + final Integer lockinPeriodFrequency = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(lockinPeriodFrequencyParamName, + element); baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(lockinPeriodFrequency).ignoreIfNull() .integerZeroOrGreater(); } if (this.fromApiJsonHelper.parameterExists(lockinPeriodFrequencyTypeParamName, element)) { - final Integer lockinPeriodFrequencyType = fromApiJsonHelper.extractIntegerSansLocaleNamed(lockinPeriodFrequencyTypeParamName, - element); + final Integer lockinPeriodFrequencyType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed( + lockinPeriodFrequencyTypeParamName, element); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(lockinPeriodFrequencyType).inMinMaxRange(0, 3); } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeAmountParamName, element)) { - final BigDecimal withdrawalFeeAmount = fromApiJsonHelper - .extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, element); + final BigDecimal withdrawalFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(withdrawalFeeAmountParamName, + element); baseDataValidator.reset().parameter(withdrawalFeeAmountParamName).value(withdrawalFeeAmount).ignoreIfNull() .zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeTypeParamName, element)) { - final Integer withdrawalFeeType = fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); + final Integer withdrawalFeeType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(withdrawalFeeTypeParamName, element); baseDataValidator.reset().parameter(withdrawalFeeTypeParamName).value(withdrawalFeeType).ignoreIfNull() .isOneOfTheseValues(1, 2); } if (this.fromApiJsonHelper.parameterExists(withdrawalFeeForTransfersParamName, element)) { - final Boolean isWithdrawalFeeApplicableForTransfers = fromApiJsonHelper.extractBooleanNamed(withdrawalFeeForTransfersParamName, - element); + final Boolean isWithdrawalFeeApplicableForTransfers = this.fromApiJsonHelper.extractBooleanNamed( + withdrawalFeeForTransfersParamName, element); baseDataValidator.reset().parameter(withdrawalFeeForTransfersParamName).value(isWithdrawalFeeApplicableForTransfers) .ignoreIfNull().validateForBooleanValue(); } if (this.fromApiJsonHelper.parameterExists(annualFeeAmountParamName, element)) { - final BigDecimal annualFeeAmount = fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); + final BigDecimal annualFeeAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(annualFeeAmountParamName, element); baseDataValidator.reset().parameter(annualFeeAmountParamName).value(annualFeeAmount).ignoreIfNull().zeroOrPositiveAmount(); } if (this.fromApiJsonHelper.parameterExists(annualFeeOnMonthDayParamName, element)) { - MonthDay monthDayOfAnnualFee = fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); + final MonthDay monthDayOfAnnualFee = this.fromApiJsonHelper.extractMonthDayNamed(annualFeeOnMonthDayParamName, element); baseDataValidator.reset().parameter(annualFeeOnMonthDayParamName).value(monthDayOfAnnualFee).ignoreIfNull(); } - final Long savingsControlAccountId = fromApiJsonHelper.extractLongNamed( + final Long savingsControlAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_CONTROL.getValue()).value(savingsControlAccountId) .ignoreIfNull().integerGreaterThanZero(); - final Long savingsReferenceAccountId = fromApiJsonHelper.extractLongNamed( + final Long savingsReferenceAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.SAVINGS_REFERENCE.getValue()) .value(savingsReferenceAccountId).ignoreIfNull().integerGreaterThanZero(); - final Long transfersInSuspenseAccountId = fromApiJsonHelper.extractLongNamed( + final Long transfersInSuspenseAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue()) .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero(); - final Long interestOnSavingsAccountId = fromApiJsonHelper.extractLongNamed( + final Long interestOnSavingsAccountId = this.fromApiJsonHelper.extractLongNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_SAVINGS.getValue()) .value(interestOnSavingsAccountId).ignoreIfNull().integerGreaterThanZero(); - final Long incomeFromFeeId = fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), + final Long incomeFromFeeId = this.fromApiJsonHelper.extractLongNamed(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element); baseDataValidator.reset().parameter(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue()).value(incomeFromFeeId) .ignoreIfNull().integerGreaterThanZero(); @@ -392,8 +397,9 @@ public class SavingsProductDataValidator { * Validation for advanced accounting options */ private void validatePaymentChannelFundSourceMappings(final DataValidatorBuilder baseDataValidator, final JsonElement element) { - if (fromApiJsonHelper.parameterExists(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element)) { - JsonArray paymentChannelMappingArray = fromApiJsonHelper.extractJsonArrayNamed( + if (this.fromApiJsonHelper.parameterExists(SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), + element)) { + final JsonArray paymentChannelMappingArray = this.fromApiJsonHelper.extractJsonArrayNamed( SAVINGS_PRODUCT_ACCOUNTING_PARAMS.PAYMENT_CHANNEL_FUND_SOURCE_MAPPING.getValue(), element); if (paymentChannelMappingArray != null && paymentChannelMappingArray.size() > 0) { int i = 0; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccount.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccount.java index 34b4948ee..6cd2e34db 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccount.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccount.java @@ -1104,7 +1104,7 @@ public class SavingsAccount extends AbstractPersistable { // charges final String chargesParamName = "charges"; if (command.hasParameter(chargesParamName)) { - JsonArray jsonArray = command.arrayOfParameterNamed(chargesParamName); + final JsonArray jsonArray = command.arrayOfParameterNamed(chargesParamName); if (jsonArray != null) { actualChanges.put(chargesParamName, command.jsonFragment(chargesParamName)); } @@ -1499,9 +1499,9 @@ public class SavingsAccount extends AbstractPersistable { } else if (transactionToUndo.isCharge()) { // undo charge final Set chargesPaidBy = transactionToUndo.getSavingsAccountChargesPaid(); - for (SavingsAccountChargePaidBy savingsAccountChargePaidBy : chargesPaidBy) { + for (final SavingsAccountChargePaidBy savingsAccountChargePaidBy : chargesPaidBy) { final SavingsAccountCharge chargeToUndo = savingsAccountChargePaidBy.getSavingsAccountCharge(); - chargeToUndo.resetPaidAmount(currency); + chargeToUndo.resetPaidAmount(this.currency); } } @@ -1807,15 +1807,15 @@ public class SavingsAccount extends AbstractPersistable { return actualChanges; } - private void validateActivityNotBeforeClientOrGroupTransferDate(SavingsEvent event, LocalDate activityDate) { + private void validateActivityNotBeforeClientOrGroupTransferDate(final SavingsEvent event, final LocalDate activityDate) { if (this.client != null && this.client.getOfficeJoiningLocalDate() != null) { - LocalDate clientOfficeJoiningDate = client.getOfficeJoiningLocalDate(); + final LocalDate clientOfficeJoiningDate = this.client.getOfficeJoiningLocalDate(); if (activityDate.isBefore(clientOfficeJoiningDate)) { throw new SavingsActivityPriorToClientTransferException(event.toString(), clientOfficeJoiningDate); } } } - private void validateAttemptToUndoTransferRelatedTransactions(SavingsAccountTransaction savingsAccountTransaction) { + private void validateAttemptToUndoTransferRelatedTransactions(final SavingsAccountTransaction savingsAccountTransaction) { if (savingsAccountTransaction.isTransferRelatedTransaction()) { throw new SavingsTransferTransactionsCannotBeUndoneException( savingsAccountTransaction.getId()); } } @@ -1882,9 +1882,11 @@ public class SavingsAccount extends AbstractPersistable { } public boolean update(final Set newSavingsAccountCharges) { - if (newSavingsAccountCharges == null) return false; + if (newSavingsAccountCharges == null) { return false; } - if (this.charges == null) this.charges = new HashSet(); + if (this.charges == null) { + this.charges = new HashSet(); + } this.charges.clear(); this.charges.addAll(associateChargesWithThisSavingsAccount(newSavingsAccountCharges)); return true; @@ -1892,7 +1894,7 @@ public class SavingsAccount extends AbstractPersistable { public boolean hasCurrencyCodeOf(final String matchingCurrencyCode) { // TODO AA: revisit - if (this.currency == null) return false; + if (this.currency == null) { return false; } return this.currency.getCode().equalsIgnoreCase(matchingCurrencyCode); } @@ -1917,7 +1919,7 @@ public class SavingsAccount extends AbstractPersistable { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - final SavingsAccountCharge savingsAccountCharge = this.getCharge(savingsAccountChargeId); + final SavingsAccountCharge savingsAccountCharge = getCharge(savingsAccountChargeId); // validate charge is not already paid or waived if (savingsAccountCharge.isWaived()) { @@ -1932,7 +1934,7 @@ public class SavingsAccount extends AbstractPersistable { existingReversedTransactionIds.addAll(findExistingReversedTransactionIds()); // waive charge - final Money amountWaived = savingsAccountCharge.waive(this.getCurrency()); + final Money amountWaived = savingsAccountCharge.waive(getCurrency()); // TODO : AA revisit the code /* * Money feeChargesWaived = amountWaived; Money penaltyChargesWaived = @@ -1942,7 +1944,7 @@ public class SavingsAccount extends AbstractPersistable { */ // persist an entry in transaction details - SavingsAccountTransaction chargeTransaction = SavingsAccountTransaction.charge(this, this.office(), + final SavingsAccountTransaction chargeTransaction = SavingsAccountTransaction.charge(this, office(), savingsAccountCharge.getDueLocalDate(), amountWaived); this.transactions.add(chargeTransaction); @@ -1968,7 +1970,7 @@ public class SavingsAccount extends AbstractPersistable { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - if (!this.hasCurrencyCodeOf(chargeDefinition.getCurrencyCode())) { + if (!hasCurrencyCodeOf(chargeDefinition.getCurrencyCode())) { baseDataValidator.reset().failWithCodeNoParameterAddedToErrorCode( "transaction.invalid.account.currency.and.charge.currency.not.same"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } @@ -2006,7 +2008,7 @@ public class SavingsAccount extends AbstractPersistable { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } - final SavingsAccountCharge savingsAccountCharge = this.getCharge(savingsAccountChargeId); + final SavingsAccountCharge savingsAccountCharge = getCharge(savingsAccountChargeId); // validate charge is not already paid or waived if (savingsAccountCharge.isWaived()) { @@ -2020,14 +2022,14 @@ public class SavingsAccount extends AbstractPersistable { existingTransactionIds.addAll(findExistingTransactionIds()); existingReversedTransactionIds.addAll(findExistingReversedTransactionIds()); - final Money chargePaid = savingsAccountCharge.pay(this.getCurrency(), amountPaid); + final Money chargePaid = savingsAccountCharge.pay(getCurrency(), amountPaid); // If null reset to current date final LocalDate transactionDate = (savingsAccountCharge.getDueLocalDate() == null) ? DateUtils.getLocalDateOfTenant() : savingsAccountCharge.getDueLocalDate(); // persist an entry in transaction details - SavingsAccountTransaction chargeTransaction = SavingsAccountTransaction.charge(this, this.office(), transactionDate, chargePaid); + final SavingsAccountTransaction chargeTransaction = SavingsAccountTransaction.charge(this, office(), transactionDate, chargePaid); final SavingsAccountChargePaidBy chargePaidBy = SavingsAccountChargePaidBy.instance(chargeTransaction, savingsAccountCharge, amountPaid); @@ -2049,9 +2051,9 @@ public class SavingsAccount extends AbstractPersistable { } - private SavingsAccountCharge getCharge(Long savingsAccountChargeId) { + private SavingsAccountCharge getCharge(final Long savingsAccountChargeId) { SavingsAccountCharge charge = null; - for (SavingsAccountCharge existingCharge : this.charges) { + for (final SavingsAccountCharge existingCharge : this.charges) { if (existingCharge.getId().equals(savingsAccountChargeId)) { charge = existingCharge; break; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountAssembler.java index b10dc9e0d..a5e25328e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountAssembler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountAssembler.java @@ -23,8 +23,8 @@ import static org.mifosplatform.portfolio.savings.SavingsApiConstants.nominalAnn import static org.mifosplatform.portfolio.savings.SavingsApiConstants.productIdParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.submittedOnDateParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeAmountParamName; -import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeTypeParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeForTransfersParamName; +import static org.mifosplatform.portfolio.savings.SavingsApiConstants.withdrawalFeeTypeParamName; import java.math.BigDecimal; import java.util.Set; @@ -42,8 +42,8 @@ import org.mifosplatform.portfolio.client.domain.ClientRepositoryWrapper; import org.mifosplatform.portfolio.client.exception.ClientNotActiveException; import org.mifosplatform.portfolio.group.domain.Group; import org.mifosplatform.portfolio.group.domain.GroupRepositoryWrapper; -import org.mifosplatform.portfolio.group.exception.ClientNotInGroupException; import org.mifosplatform.portfolio.group.exception.CenterNotActiveException; +import org.mifosplatform.portfolio.group.exception.ClientNotInGroupException; import org.mifosplatform.portfolio.group.exception.GroupNotActiveException; import org.mifosplatform.portfolio.savings.SavingsCompoundingInterestPeriodType; import org.mifosplatform.portfolio.savings.SavingsInterestCalculationDaysInYearType; @@ -95,9 +95,9 @@ public class SavingsAccountAssembler { final JsonElement element = command.parsedJson(); - final String accountNo = fromApiJsonHelper.extractStringNamed(accountNoParamName, element); - final String externalId = fromApiJsonHelper.extractStringNamed(externalIdParamName, element); - final Long productId = fromApiJsonHelper.extractLongNamed(productIdParamName, element); + final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParamName, element); + final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParamName, element); + final Long productId = this.fromApiJsonHelper.extractLongNamed(productIdParamName, element); final SavingsProduct product = this.savingProductRepository.findOne(productId); if (product == null) { throw new SavingsProductNotFoundException(productId); } @@ -106,14 +106,14 @@ public class SavingsAccountAssembler { Group group = null; Staff fieldOfficer = null; AccountType accountType = AccountType.INVALID; - final Long clientId = fromApiJsonHelper.extractLongNamed(clientIdParamName, element); + final Long clientId = this.fromApiJsonHelper.extractLongNamed(clientIdParamName, element); if (clientId != null) { client = this.clientRepository.findOneWithNotFoundDetection(clientId); accountType = AccountType.INDIVIDUAL; if (client.isNotActive()) { throw new ClientNotActiveException(clientId); } } - final Long groupId = fromApiJsonHelper.extractLongNamed(groupIdParamName, element); + final Long groupId = this.fromApiJsonHelper.extractLongNamed(groupIdParamName, element); if (groupId != null) { group = this.groupRepository.findOneWithNotFoundDetection(groupId); accountType = AccountType.GROUP; @@ -128,12 +128,12 @@ public class SavingsAccountAssembler { } } - final Long fieldOfficerId = fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); + final Long fieldOfficerId = this.fromApiJsonHelper.extractLongNamed(fieldOfficerIdParamName, element); if (fieldOfficerId != null) { fieldOfficer = this.staffRepository.findOneWithNotFoundDetection(fieldOfficerId); } - final LocalDate submittedOnDate = fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); + final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParamName, element); BigDecimal interestRate = null; if (command.parameterExists(nominalAnnualInterestRateParamName)) { @@ -216,9 +216,9 @@ public class SavingsAccountAssembler { } else { withdrawalFeeType = product.withdrawalFeeType(); } - + boolean iswithdrawalFeeApplicableForTransfer = false; - if(command.parameterExists(withdrawalFeeForTransfersParamName)){ + if (command.parameterExists(withdrawalFeeForTransfersParamName)) { iswithdrawalFeeApplicableForTransfer = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); } @@ -235,7 +235,7 @@ public class SavingsAccountAssembler { } else { monthDayOfAnnualFee = product.monthDayOfAnnualFee(); } - + final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(element); final SavingsAccount account = SavingsAccount.createNewApplicationForSubmittal(client, group, product, fieldOfficer, accountNo, @@ -251,13 +251,13 @@ public class SavingsAccountAssembler { } public SavingsAccount assembleFrom(final Long savingsId) { - SavingsAccount account = this.savingsAccountRepository.findOneWithNotFoundDetection(savingsId); - account.setHelpers(this.savingsAccountTransactionSummaryWrapper, savingsHelper); + final SavingsAccount account = this.savingsAccountRepository.findOneWithNotFoundDetection(savingsId); + account.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); return account; } - - public void assignSavingAccountHelpers(SavingsAccount savingsAccount){ + + public void assignSavingAccountHelpers(final SavingsAccount savingsAccount) { savingsAccount.setHelpers(this.savingsAccountTransactionSummaryWrapper, this.savingsHelper); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountCharge.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountCharge.java index 21f0c92a1..33c5efa66 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountCharge.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountCharge.java @@ -6,8 +6,8 @@ package org.mifosplatform.portfolio.savings.domain; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.amountParamName; -import static org.mifosplatform.portfolio.savings.SavingsApiConstants.dueAsOfDateParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.dateFormatParamName; +import static org.mifosplatform.portfolio.savings.SavingsApiConstants.dueAsOfDateParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.localeParamName; import java.math.BigDecimal; @@ -89,7 +89,8 @@ public class SavingsAccountCharge extends AbstractPersistable { @Column(name = "waived", nullable = false) private boolean waived = false; - public static SavingsAccountCharge createNewFromJson(final SavingsAccount savingsAccount, final Charge chargeDefinition, final JsonCommand command) { + public static SavingsAccountCharge createNewFromJson(final SavingsAccount savingsAccount, final Charge chargeDefinition, + final JsonCommand command) { final BigDecimal amount = command.bigDecimalValueOfParameterNamed(amountParamName); final LocalDate dueDate = command.localDateValueOfParameterNamed(dueAsOfDateParamName); @@ -99,7 +100,7 @@ public class SavingsAccountCharge extends AbstractPersistable { return new SavingsAccountCharge(savingsAccount, chargeDefinition, amount, chargeTime, chargeCalculation, dueDate); } - //TODO AA: refactor method signature + // TODO AA: refactor method signature public static SavingsAccountCharge createNewWithoutSavingsAccount(final Charge chargeDefinition, final BigDecimal amount, final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculation, final LocalDate dueDate) { return new SavingsAccountCharge(null, chargeDefinition, amount, chargeTime, chargeCalculation, dueDate); @@ -111,7 +112,7 @@ public class SavingsAccountCharge extends AbstractPersistable { public SavingsAccountCharge(final SavingsAccount savingsAccount, final Charge chargeDefinition, final BigDecimal amount, final ChargeTimeType chargeTime, final ChargeCalculationType chargeCalculation, final LocalDate dueDate) { - + this.savingsAccount = savingsAccount; this.charge = chargeDefinition; this.penaltyCharge = chargeDefinition.isPenalty(); @@ -120,10 +121,10 @@ public class SavingsAccountCharge extends AbstractPersistable { if (isOnSpecifiedDueDate()) { if (dueDate == null) { final String defaultUserMessage = "Savings Account charge is missing due date."; - throw new SavingsAccountChargeWithoutMandatoryFieldException("savingsaccount.charge", dueAsOfDateParamName, defaultUserMessage, chargeDefinition.getId(), - chargeDefinition.getName()); + throw new SavingsAccountChargeWithoutMandatoryFieldException("savingsaccount.charge", dueAsOfDateParamName, + defaultUserMessage, chargeDefinition.getId(), chargeDefinition.getName()); } - + } this.dueDate = (dueDate == null) ? null : dueDate.toDate(); @@ -137,8 +138,12 @@ public class SavingsAccountCharge extends AbstractPersistable { if (amount != null) { chargeAmount = amount; } - - final BigDecimal transactionAmount = new BigDecimal(0);//percentage based fee is not yet supported for savings + + final BigDecimal transactionAmount = new BigDecimal(0);// percentage + // based fee is + // not yet + // supported for + // savings populateDerivedFields(transactionAmount, chargeAmount); this.paid = determineIfFullyPaid(); } @@ -222,11 +227,11 @@ public class SavingsAccountCharge extends AbstractPersistable { this.waived = true; return getAmountWaived(currency); } - + public Money pay(final MonetaryCurrency currency, final BigDecimal chargePaid) { - + Money amountPaidToDate = Money.of(currency, this.amountPaid); - Money amountPaid = Money.of(currency, chargePaid); + final Money amountPaid = Money.of(currency, chargePaid); Money amountOutstanding = Money.of(currency, this.amountOutstanding); amountPaidToDate = amountPaidToDate.plus(amountPaid); amountOutstanding = amountOutstanding.minus(chargePaid); @@ -245,7 +250,11 @@ public class SavingsAccountCharge extends AbstractPersistable { } public void update(final BigDecimal amount, final LocalDate dueDate) { - final BigDecimal transactionAmount = BigDecimal.ZERO;//percentage based fee calculation is not yet supported for Savings + final BigDecimal transactionAmount = BigDecimal.ZERO;// percentage based + // fee calculation + // is not yet + // supported for + // Savings if (dueDate != null) { this.dueDate = dueDate.toDate(); } @@ -286,7 +295,6 @@ public class SavingsAccountCharge extends AbstractPersistable { final String dateFormatAsInput = command.dateFormat(); final String localeAsInput = command.locale(); - if (command.isChangeInLocalDateParameterNamed(dueAsOfDateParamName, getDueLocalDate())) { final String valueAsInput = command.stringValueOfParameterNamed(dueAsOfDateParamName); actualChanges.put(dueAsOfDateParamName, valueAsInput); @@ -379,7 +387,7 @@ public class SavingsAccountCharge extends AbstractPersistable { if (isGreaterThanZero(value)) { final MathContext mc = new MathContext(8, RoundingMode.HALF_EVEN); - BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc); + final BigDecimal multiplicand = percentage.divide(BigDecimal.valueOf(100l), mc); percentageOf = value.multiply(multiplicand, mc); } @@ -440,7 +448,7 @@ public class SavingsAccountCharge extends AbstractPersistable { public Money updatePaidAmountBy(final Money incrementBy) { Money amountPaidToDate = Money.of(incrementBy.getCurrency(), this.amountPaid); - Money amountOutstanding = Money.of(incrementBy.getCurrency(), this.amountOutstanding); + final Money amountOutstanding = Money.of(incrementBy.getCurrency(), this.amountOutstanding); Money amountPaidOnThisCharge = Money.zero(incrementBy.getCurrency()); if (incrementBy.isGreaterThanOrEqualTo(amountOutstanding)) { @@ -453,7 +461,7 @@ public class SavingsAccountCharge extends AbstractPersistable { amountPaidToDate = amountPaidToDate.plus(incrementBy); this.amountPaid = amountPaidToDate.getAmount(); - Money amountExpected = Money.of(incrementBy.getCurrency(), this.amount); + final Money amountExpected = Money.of(incrementBy.getCurrency(), this.amount); this.amountOutstanding = amountExpected.minus(amountPaidToDate).getAmount(); } @@ -473,8 +481,8 @@ public class SavingsAccountCharge extends AbstractPersistable { public Charge getCharge() { return this.charge; } - - public boolean isOnSpecifiedDueDate(){ + + public boolean isOnSpecifiedDueDate() { return ChargeTimeType.fromInt(this.chargeTime).isOnSpecifiedDueDate(); } @@ -483,21 +491,21 @@ public class SavingsAccountCharge extends AbstractPersistable { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } - SavingsAccountCharge rhs = (SavingsAccountCharge) obj; + final SavingsAccountCharge rhs = (SavingsAccountCharge) obj; return new EqualsBuilder().appendSuper(super.equals(obj)) // - .append(this.getId(), rhs.getId()) // + .append(getId(), rhs.getId()) // .append(this.charge.getId(), rhs.charge.getId()) // .append(this.amount, rhs.amount) // - .append(this.getDueLocalDate(), rhs.getDueLocalDate()) // + .append(getDueLocalDate(), rhs.getDueLocalDate()) // .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(3, 5) // - .append(this.getId()) // + .append(getId()) // .append(this.charge.getId()) // - .append(this.amount).append(this.getDueLocalDate()) // + .append(this.amount).append(getDueLocalDate()) // .toHashCode(); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeAssembler.java index ea72111d1..4da5cc734 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeAssembler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeAssembler.java @@ -54,44 +54,48 @@ public class SavingsAccountChargeAssembler { if (element.isJsonObject()) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final String dateFormat = fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); - final Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.has(chargesParamName) && topLevelJsonElement.get(chargesParamName).isJsonArray()) { final JsonArray array = topLevelJsonElement.get(chargesParamName).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject savingsChargeElement = array.get(i).getAsJsonObject(); - final Long id = fromApiJsonHelper.extractLongNamed(idParamName, savingsChargeElement); - final Long chargeId = fromApiJsonHelper.extractLongNamed(chargeIdParamName, savingsChargeElement); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalNamed(amountParamName, savingsChargeElement, locale); - final Integer chargeTimeType = fromApiJsonHelper.extractIntegerNamed(chargeTimeTypeParamName, savingsChargeElement, locale); - final Integer chargeCalculationType = fromApiJsonHelper.extractIntegerNamed(chargeCalculationTypeParamName, savingsChargeElement, - locale); - final LocalDate dueDate = fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, savingsChargeElement, + final Long id = this.fromApiJsonHelper.extractLongNamed(idParamName, savingsChargeElement); + final Long chargeId = this.fromApiJsonHelper.extractLongNamed(chargeIdParamName, savingsChargeElement); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed(amountParamName, savingsChargeElement, locale); + final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed(chargeTimeTypeParamName, + savingsChargeElement, locale); + final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed(chargeCalculationTypeParamName, + savingsChargeElement, locale); + final LocalDate dueDate = this.fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, savingsChargeElement, dateFormat, locale); if (id == null) { final Charge chargeDefinition = this.chargeRepository.findOneWithNotFoundDetection(chargeId); - - if(!chargeDefinition.isSavingsCharge()){ - String errorMessage = "Charge with identifier " + chargeDefinition.getId() + " cannot be applied to Savings product."; - throw new ChargeCannotBeAppliedToException("savings.product", errorMessage, chargeDefinition.getId()); + + if (!chargeDefinition.isSavingsCharge()) { + final String errorMessage = "Charge with identifier " + chargeDefinition.getId() + + " cannot be applied to Savings product."; + throw new ChargeCannotBeAppliedToException("savings.product", errorMessage, chargeDefinition.getId()); } - - ChargeTimeType chargeTime = null; + + final ChargeTimeType chargeTime = null; if (chargeTimeType != null) { ChargeTimeType.fromInt(chargeTimeType); } - ChargeCalculationType chargeCalculation = null; + final ChargeCalculationType chargeCalculation = null; if (chargeCalculationType != null) { ChargeCalculationType.fromInt(chargeCalculationType); } - final SavingsAccountCharge savingsAccountCharge = SavingsAccountCharge.createNewWithoutSavingsAccount(chargeDefinition, amount, chargeTime, chargeCalculation, dueDate); + final SavingsAccountCharge savingsAccountCharge = SavingsAccountCharge.createNewWithoutSavingsAccount( + chargeDefinition, amount, chargeTime, chargeCalculation, dueDate); savingsAccountCharges.add(savingsAccountCharge); } else { final Long savingsAccountChargeId = id; - final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOne(savingsAccountChargeId); + final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository + .findOne(savingsAccountChargeId); if (savingsAccountCharge == null) { throw new SavingsAccountChargeNotFoundException(savingsAccountChargeId); } savingsAccountCharge.update(amount, dueDate); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargePaidBy.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargePaidBy.java index 25393cadf..e29b2ac40 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargePaidBy.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargePaidBy.java @@ -29,29 +29,31 @@ public class SavingsAccountChargePaidBy extends AbstractPersistable { } - public static SavingsAccountChargePaidBy instance(final SavingsAccountTransaction savingsAccountTransaction, final SavingsAccountCharge savingsAccountCharge, final BigDecimal amount){ + public static SavingsAccountChargePaidBy instance(final SavingsAccountTransaction savingsAccountTransaction, + final SavingsAccountCharge savingsAccountCharge, final BigDecimal amount) { return new SavingsAccountChargePaidBy(savingsAccountTransaction, savingsAccountCharge, amount); } - - private SavingsAccountChargePaidBy(SavingsAccountTransaction savingsAccountTransaction, SavingsAccountCharge savingsAccountCharge, BigDecimal amount) { + + private SavingsAccountChargePaidBy(final SavingsAccountTransaction savingsAccountTransaction, + final SavingsAccountCharge savingsAccountCharge, final BigDecimal amount) { this.savingsAccountTransaction = savingsAccountTransaction; this.savingsAccountCharge = savingsAccountCharge; this.amount = amount; } - + public SavingsAccountTransaction getSavingsAccountTransaction() { return this.savingsAccountTransaction; } - - public void setSavingsAccountTransaction(SavingsAccountTransaction savingsAccountTransaction) { + + public void setSavingsAccountTransaction(final SavingsAccountTransaction savingsAccountTransaction) { this.savingsAccountTransaction = savingsAccountTransaction; } - + public SavingsAccountCharge getSavingsAccountCharge() { return this.savingsAccountCharge; } - - public void setSavingsAccountCharge(SavingsAccountCharge savingsAccountCharge) { + + public void setSavingsAccountCharge(final SavingsAccountCharge savingsAccountCharge) { this.savingsAccountCharge = savingsAccountCharge; } @@ -59,15 +61,15 @@ public class SavingsAccountChargePaidBy extends AbstractPersistable { return this.amount; } - public void setAmount(BigDecimal amount) { + public void setAmount(final BigDecimal amount) { this.amount = amount; } - - public boolean isFeeCharge(){ + + public boolean isFeeCharge() { return (this.savingsAccountCharge == null) ? false : this.savingsAccountCharge.isFeeCharge(); } - - public boolean isPenaltyCharge(){ + + public boolean isPenaltyCharge() { return (this.savingsAccountCharge == null) ? false : this.savingsAccountCharge.isPenaltyCharge(); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeRepository.java index 236496e1c..38e007ffa 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeRepository.java @@ -8,6 +8,8 @@ package org.mifosplatform.portfolio.savings.domain; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; -public interface SavingsAccountChargeRepository extends JpaRepository, JpaSpecificationExecutor { +public interface SavingsAccountChargeRepository extends JpaRepository, + JpaSpecificationExecutor { + SavingsAccountCharge findByIdAndSavingsAccountId(Long id, Long savingsAccountId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeRepositoryWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeRepositoryWrapper.java index 41bc230d8..87bebc69e 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeRepositoryWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountChargeRepositoryWrapper.java @@ -11,8 +11,8 @@ import org.springframework.stereotype.Service; /** *

- * Wrapper for {@link SavingsAccountChargeRepository} that adds NULL checking and Error - * handling capabilities + * Wrapper for {@link SavingsAccountChargeRepository} that adds NULL checking + * and Error handling capabilities *

*/ @Service @@ -30,13 +30,13 @@ public class SavingsAccountChargeRepositoryWrapper { if (savingsAccountCharge == null) { throw new SavingsAccountChargeNotFoundException(id); } return savingsAccountCharge; } - + public SavingsAccountCharge findOneWithNotFoundDetection(final Long id, final Long savingsAccountId) { final SavingsAccountCharge savingsAccountCharge = this.repository.findByIdAndSavingsAccountId(id, savingsAccountId); if (savingsAccountCharge == null) { throw new SavingsAccountChargeNotFoundException(id); } return savingsAccountCharge; } - + public void save(final SavingsAccountCharge savingsAccountCharge) { this.repository.save(savingsAccountCharge); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountDomainServiceJpa.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountDomainServiceJpa.java index 8bd651172..ac76d853c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountDomainServiceJpa.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountDomainServiceJpa.java @@ -46,13 +46,14 @@ public class SavingsAccountDomainServiceJpa implements SavingsAccountDomainServi @Transactional @Override public SavingsAccountTransaction handleWithdrawal(final SavingsAccount account, final DateTimeFormatter fmt, - final LocalDate transactionDate, final BigDecimal transactionAmount, final PaymentDetail paymentDetail, boolean applyWithdrawFee) { + final LocalDate transactionDate, final BigDecimal transactionAmount, final PaymentDetail paymentDetail, + final boolean applyWithdrawFee) { final List existingTransactionIds = new ArrayList(); final List existingReversedTransactionIds = new ArrayList(); - SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, - existingTransactionIds,existingReversedTransactionIds, paymentDetail); - final SavingsAccountTransaction withdrawal = account.withdraw(transactionDTO , applyWithdrawFee); + final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, + existingTransactionIds, existingReversedTransactionIds, paymentDetail); + final SavingsAccountTransaction withdrawal = account.withdraw(transactionDTO, applyWithdrawFee); final MathContext mc = MathContext.DECIMAL64; if (account.isBeforeLastPostingPeriod(transactionDate)) { @@ -78,7 +79,7 @@ public class SavingsAccountDomainServiceJpa implements SavingsAccountDomainServi final List existingTransactionIds = new ArrayList(); final List existingReversedTransactionIds = new ArrayList(); - SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, + final SavingsAccountTransactionDTO transactionDTO = new SavingsAccountTransactionDTO(fmt, transactionDate, transactionAmount, existingTransactionIds, existingReversedTransactionIds, paymentDetail); final SavingsAccountTransaction deposit = account.deposit(transactionDTO); @@ -113,6 +114,6 @@ public class SavingsAccountDomainServiceJpa implements SavingsAccountDomainServi final Map accountingBridgeData = savingsAccount.deriveAccountingBridgeData(applicationCurrency.toData(), existingTransactionIds, existingReversedTransactionIds); - journalEntryWritePlatformService.createJournalEntriesForSavings(accountingBridgeData); + this.journalEntryWritePlatformService.createJournalEntriesForSavings(accountingBridgeData); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountRepository.java index 49d714bd2..c716d5abd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountRepository.java @@ -25,7 +25,7 @@ public interface SavingsAccountRepository extends JpaRepository 0) then true else false end from SavingsAccount saving where saving.client.id = :clientId and saving.status in (100,200,300,303,304)") boolean doNonClosedSavingAccountsExistForClient(@Param("clientId") Long clientId); - + @Query("from SavingsAccount sa where sa.client.id is null and sa.group.id = :groupId") List findByGroupId(@Param("groupId") Long groupId); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountStatusType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountStatusType.java index 2f09829c8..e28457092 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountStatusType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountStatusType.java @@ -69,7 +69,7 @@ public enum SavingsAccountStatusType { } public String getCode() { - return code; + return this.code; } public boolean isSubmittedAndPendingApproval() { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountSummary.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountSummary.java index 6c66e818e..91e26bcdd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountSummary.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountSummary.java @@ -36,10 +36,10 @@ public final class SavingsAccountSummary { @Column(name = "total_withdrawal_fees_derived", scale = 6, precision = 19) private BigDecimal totalWithdrawalFees; - + @Column(name = "total_fees_charge_derived", scale = 6, precision = 19) private BigDecimal totalFeeCharge; - + @Column(name = "total_penalty_charge_derived", scale = 6, precision = 19) private BigDecimal totalPenaltyCharge; @@ -65,7 +65,8 @@ public final class SavingsAccountSummary { this.totalPenaltyCharge = wrapper.calculateTotalPenaltyCharge(currency, transactions); this.accountBalance = Money.of(currency, this.totalDeposits).plus(this.totalInterestPosted).minus(this.totalWithdrawals) - .minus(this.totalWithdrawalFees).minus(this.totalAnnualFees).minus(totalFeeCharge).minus(totalPenaltyCharge).getAmount(); + .minus(this.totalWithdrawalFees).minus(this.totalAnnualFees).minus(this.totalFeeCharge).minus(this.totalPenaltyCharge) + .getAmount(); } public void updateFromInterestPeriodSummaries(final MonetaryCurrency currency, final List allPostingPeriods) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountTransaction.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountTransaction.java index 283d39995..f5b8d6035 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountTransaction.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountTransaction.java @@ -83,11 +83,11 @@ public final class SavingsAccountTransaction extends AbstractPersistable { @Column(name = "balance_number_of_days_derived", nullable = false) private Integer balanceNumberOfDays; - + @LazyCollection(LazyCollectionOption.FALSE) @OneToMany(cascade = CascadeType.ALL, mappedBy = "savingsAccountTransaction", orphanRemoval = true) - private Set savingsAccountChargesPaid = new HashSet(); - + private final Set savingsAccountChargesPaid = new HashSet(); + protected SavingsAccountTransaction() { this.dateOf = null; this.typeOf = null; @@ -127,14 +127,14 @@ public final class SavingsAccountTransaction extends AbstractPersistable { return new SavingsAccountTransaction(savingsAccount, office, SavingsAccountTransactionType.ANNUAL_FEE.getValue(), date, amount, isReversed); } - + public static SavingsAccountTransaction charge(final SavingsAccount savingsAccount, final Office office, final LocalDate date, final Money amount) { final boolean isReversed = false; return new SavingsAccountTransaction(savingsAccount, office, SavingsAccountTransactionType.APPLY_CHARGES.getValue(), date, amount, isReversed); } - + public static SavingsAccountTransaction waiver(final SavingsAccount savingsAccount, final Office office, final LocalDate date, final Money amount) { final boolean isReversed = false; @@ -433,11 +433,11 @@ public final class SavingsAccountTransaction extends AbstractPersistable { public boolean isDebit() { return isWithdrawal() || isWithdrawalFeeAndNotReversed() || isAnnualFeeAndNotReversed() || isCharge(); } - + public boolean isCharge() { return SavingsAccountTransactionType.fromInt(this.typeOf).isCharge(); } - + public boolean isFeeCharge() { final SavingsAccountChargePaidBy chargePaidBy = getSavingsAccountChargePaidBy(); return (isCharge() && chargePaidBy != null) ? chargePaidBy.isFeeCharge() : false; @@ -447,24 +447,22 @@ public final class SavingsAccountTransaction extends AbstractPersistable { final SavingsAccountChargePaidBy chargePaidBy = getSavingsAccountChargePaidBy(); return (isCharge() && chargePaidBy != null) ? chargePaidBy.isPenaltyCharge() : false; } - - public boolean isFeeChargeAndNotReversed(){ + + public boolean isFeeChargeAndNotReversed() { return isFeeCharge() && isNotReversed(); } - - public boolean isPenaltyChargeAndNotReversed(){ + + public boolean isPenaltyChargeAndNotReversed() { return isPenaltyCharge() && isNotReversed(); } - - private SavingsAccountChargePaidBy getSavingsAccountChargePaidBy(){ - if(!CollectionUtils.isEmpty(this.savingsAccountChargesPaid)){ - return this.savingsAccountChargesPaid.iterator().next(); - } + + private SavingsAccountChargePaidBy getSavingsAccountChargePaidBy() { + if (!CollectionUtils.isEmpty(this.savingsAccountChargesPaid)) { return this.savingsAccountChargesPaid.iterator().next(); } return null; } - + public Set getSavingsAccountChargesPaid() { return this.savingsAccountChargesPaid; } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountTransactionSummaryWrapper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountTransactionSummaryWrapper.java index bafe459dc..b75caf58a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountTransactionSummaryWrapper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsAccountTransactionSummaryWrapper.java @@ -21,7 +21,7 @@ public final class SavingsAccountTransactionSummaryWrapper { public BigDecimal calculateTotalDeposits(final MonetaryCurrency currency, final List transactions) { Money total = Money.zero(currency); - for (SavingsAccountTransaction transaction : transactions) { + for (final SavingsAccountTransaction transaction : transactions) { if (transaction.isDeposit() && transaction.isNotReversed()) { total = total.plus(transaction.getAmount(currency)); } @@ -31,7 +31,7 @@ public final class SavingsAccountTransactionSummaryWrapper { public BigDecimal calculateTotalWithdrawals(final MonetaryCurrency currency, final List transactions) { Money total = Money.zero(currency); - for (SavingsAccountTransaction transaction : transactions) { + for (final SavingsAccountTransaction transaction : transactions) { if (transaction.isWithdrawal() && transaction.isNotReversed()) { total = total.plus(transaction.getAmount(currency)); } @@ -41,7 +41,7 @@ public final class SavingsAccountTransactionSummaryWrapper { public BigDecimal calculateTotalInterestPosted(final MonetaryCurrency currency, final List transactions) { Money total = Money.zero(currency); - for (SavingsAccountTransaction transaction : transactions) { + for (final SavingsAccountTransaction transaction : transactions) { if (transaction.isInterestPostingAndNotReversed() && transaction.isNotReversed()) { total = total.plus(transaction.getAmount(currency)); } @@ -51,7 +51,7 @@ public final class SavingsAccountTransactionSummaryWrapper { public BigDecimal calculateTotalWithdrawalFees(final MonetaryCurrency currency, final List transactions) { Money total = Money.zero(currency); - for (SavingsAccountTransaction transaction : transactions) { + for (final SavingsAccountTransaction transaction : transactions) { if (transaction.isWithdrawalFeeAndNotReversed() && transaction.isNotReversed()) { total = total.plus(transaction.getAmount(currency)); } @@ -61,32 +61,32 @@ public final class SavingsAccountTransactionSummaryWrapper { public BigDecimal calculateTotalAnnualFees(final MonetaryCurrency currency, final List transactions) { Money total = Money.zero(currency); - for (SavingsAccountTransaction transaction : transactions) { + for (final SavingsAccountTransaction transaction : transactions) { if (transaction.isAnnualFeeAndNotReversed() && transaction.isNotReversed()) { total = total.plus(transaction.getAmount(currency)); } } return total.getAmountDefaultedToNullIfZero(); } - + public BigDecimal calculateTotalFeesCharge(final MonetaryCurrency currency, final List transactions) { Money total = Money.zero(currency); - for (SavingsAccountTransaction transaction : transactions) { + for (final SavingsAccountTransaction transaction : transactions) { if (transaction.isFeeChargeAndNotReversed() && transaction.isNotReversed()) { total = total.plus(transaction.getAmount(currency)); } } return total.getAmountDefaultedToNullIfZero(); } - + public BigDecimal calculateTotalPenaltyCharge(final MonetaryCurrency currency, final List transactions) { Money total = Money.zero(currency); - for (SavingsAccountTransaction transaction : transactions) { + for (final SavingsAccountTransaction transaction : transactions) { if (transaction.isPenaltyChargeAndNotReversed() && transaction.isNotReversed()) { total = total.plus(transaction.getAmount(currency)); } } return total.getAmountDefaultedToNullIfZero(); } - + } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsHelper.java index f87d72e4d..836f04ce1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsHelper.java @@ -20,7 +20,7 @@ public final class SavingsHelper { public List determineInterestPostingPeriods(final LocalDate activationLocalDate, final LocalDate interestPostingUpToDate, final SavingsPostingInterestPeriodType postingPeriodType) { - List postingPeriods = new ArrayList(); + final List postingPeriods = new ArrayList(); LocalDate periodStartDate = activationLocalDate; LocalDate periodEndDate = periodStartDate; @@ -58,8 +58,8 @@ public final class SavingsHelper { case QUATERLY: // jan 1st to mar 31st, 1st apr to jun 30, jul 1st to sept 30, // oct 1st to dec 31 - int year = periodStartDate.getYearOfEra(); - int monthofYear = periodStartDate.getMonthOfYear(); + final int year = periodStartDate.getYearOfEra(); + final int monthofYear = periodStartDate.getMonthOfYear(); if (monthofYear <= 3) { periodEndDate = new DateTime().withDate(year, 3, 31).toLocalDate(); } else if (monthofYear <= 6) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProduct.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProduct.java index 976b9ea66..6aff92596 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProduct.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProduct.java @@ -5,7 +5,6 @@ */ package org.mifosplatform.portfolio.savings.domain; - import static org.mifosplatform.portfolio.savings.SavingsApiConstants.SAVINGS_PRODUCT_RESOURCE_NAME; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.accountingRuleParamName; import static org.mifosplatform.portfolio.savings.SavingsApiConstants.annualFeeAmountParamName; @@ -83,7 +82,7 @@ public class SavingsProduct extends AbstractPersistable { /** * The interest period is the span of time at the end of which savings in a * client's account earn interest. - * + * * A value from the {@link SavingsCompoundingInterestPeriodType} * enumeration. */ @@ -141,7 +140,7 @@ public class SavingsProduct extends AbstractPersistable { @Column(name = "annual_fee_on_day", nullable = true) private Integer annualFeeOnDay; - + @ManyToMany @JoinTable(name = "m_savings_product_charge", joinColumns = @JoinColumn(name = "savings_product_id"), inverseJoinColumns = @JoinColumn(name = "charge_id")) private Set charges; @@ -151,12 +150,13 @@ public class SavingsProduct extends AbstractPersistable { final SavingsPostingInterestPeriodType interestPostingPeriodType, final SavingsInterestCalculationType interestCalculationType, final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType, - final BigDecimal withdrawalFeeAmount, final SavingsWithdrawalFeesType withdrawalFeeType, final boolean withdrawalFeeApplicableForTransfer, - final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay, final AccountingRuleType accountingRuleType, final Set charges) { + final BigDecimal withdrawalFeeAmount, final SavingsWithdrawalFeesType withdrawalFeeType, + final boolean withdrawalFeeApplicableForTransfer, final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay, + final AccountingRuleType accountingRuleType, final Set charges) { return new SavingsProduct(name, description, currency, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency, - lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType,withdrawalFeeApplicableForTransfer, annualFeeAmount, + lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, withdrawalFeeApplicableForTransfer, annualFeeAmount, annualFeeOnMonthDay, accountingRuleType, charges); } @@ -170,8 +170,9 @@ public class SavingsProduct extends AbstractPersistable { final SavingsPostingInterestPeriodType interestPostingPeriodType, final SavingsInterestCalculationType interestCalculationType, final SavingsInterestCalculationDaysInYearType interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final SavingsPeriodFrequencyType lockinPeriodFrequencyType, - final BigDecimal withdrawalFeeAmount, final SavingsWithdrawalFeesType withdrawalFeeType, final boolean withdrawalFeeApplicableForTransfer, - final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay, final AccountingRuleType accountingRuleType, final Set charges) { + final BigDecimal withdrawalFeeAmount, final SavingsWithdrawalFeesType withdrawalFeeType, + final boolean withdrawalFeeApplicableForTransfer, final BigDecimal annualFeeAmount, final MonthDay annualFeeOnMonthDay, + final AccountingRuleType accountingRuleType, final Set charges) { this.name = name; this.description = description; @@ -304,7 +305,7 @@ public class SavingsProduct extends AbstractPersistable { actualChanges.put(digitsAfterDecimalParamName, newValue); actualChanges.put(localeParamName, localeAsInput); digitsAfterDecimal = newValue; - this.currency = new MonetaryCurrency(this.currency.getCode(), digitsAfterDecimal,this.currency.getCurrencyInMultiplesOf()); + this.currency = new MonetaryCurrency(this.currency.getCode(), digitsAfterDecimal, this.currency.getCurrencyInMultiplesOf()); } String currencyCode = this.currency.getCode(); @@ -312,7 +313,8 @@ public class SavingsProduct extends AbstractPersistable { final String newValue = command.stringValueOfParameterNamed(currencyCodeParamName); actualChanges.put(currencyCodeParamName, newValue); currencyCode = newValue; - this.currency = new MonetaryCurrency(currencyCode, this.currency.getDigitsAfterDecimal(),this.currency.getCurrencyInMultiplesOf()); + this.currency = new MonetaryCurrency(currencyCode, this.currency.getDigitsAfterDecimal(), + this.currency.getCurrencyInMultiplesOf()); } Integer inMultiplesOf = this.currency.getCurrencyInMultiplesOf(); @@ -321,7 +323,7 @@ public class SavingsProduct extends AbstractPersistable { actualChanges.put(inMultiplesOfParamName, newValue); actualChanges.put(localeParamName, localeAsInput); inMultiplesOf = newValue; - this.currency = new MonetaryCurrency(this.currency.getCode(), this.currency.getDigitsAfterDecimal(),inMultiplesOf); + this.currency = new MonetaryCurrency(this.currency.getCode(), this.currency.getDigitsAfterDecimal(), inMultiplesOf); } if (command.isChangeInBigDecimalParameterNamed(nominalAnnualInterestRateParamName, this.nominalAnnualInterestRate)) { @@ -394,7 +396,7 @@ public class SavingsProduct extends AbstractPersistable { this.withdrawalFeeType = newValue != null ? SavingsWithdrawalFeesType.fromInt(newValue).getValue() : newValue; } - if(command.isChangeInBooleanParameterNamed(withdrawalFeeForTransfersParamName, this.withdrawalFeeApplicableForTransfer)){ + if (command.isChangeInBooleanParameterNamed(withdrawalFeeForTransfersParamName, this.withdrawalFeeApplicableForTransfer)) { final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); actualChanges.put(withdrawalFeeForTransfersParamName, newValue); this.withdrawalFeeApplicableForTransfer = newValue; @@ -441,10 +443,10 @@ public class SavingsProduct extends AbstractPersistable { actualChanges.put(accountingRuleParamName, newValue); this.accountingRule = newValue; } - - //charges + + // charges if (command.hasParameter(chargesParamName)) { - JsonArray jsonArray = command.arrayOfParameterNamed(chargesParamName); + final JsonArray jsonArray = command.arrayOfParameterNamed(chargesParamName); if (jsonArray != null) { actualChanges.put(chargesParamName, command.jsonFragment(chargesParamName)); } @@ -517,12 +519,12 @@ public class SavingsProduct extends AbstractPersistable { .integerZeroOrGreater(); } } else { - baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(this.lockinPeriodFrequencyType).integerZeroOrGreater(); + baseDataValidator.reset().parameter(lockinPeriodFrequencyParamName).value(this.lockinPeriodFrequencyType) + .integerZeroOrGreater(); baseDataValidator.reset().parameter(lockinPeriodFrequencyTypeParamName).value(this.lockinPeriodFrequencyType).notNull() .inMinMaxRange(0, 3); } - if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } @@ -537,9 +539,9 @@ public class SavingsProduct extends AbstractPersistable { public Integer getAccountingType() { return this.accountingRule; } - + public boolean update(final Set newSavingsProductCharges) { - if (newSavingsProductCharges == null) return false; + if (newSavingsProductCharges == null) { return false; } boolean updated = false; if (this.charges != null) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java index 6594a1d9c..efaf39812 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductAssembler.java @@ -68,7 +68,7 @@ public class SavingsProductAssembler { final String currencyCode = command.stringValueOfParameterNamed(currencyCodeParamName); final Integer digitsAfterDecimal = command.integerValueOfParameterNamed(digitsAfterDecimalParamName); final Integer inMultiplesOf = command.integerValueOfParameterNamed(inMultiplesOfParamName); - final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal,inMultiplesOf); + final MonetaryCurrency currency = new MonetaryCurrency(currencyCode, digitsAfterDecimal, inMultiplesOf); final BigDecimal interestRate = command.bigDecimalValueOfParameterNamed(nominalAnnualInterestRateParamName); @@ -115,7 +115,7 @@ public class SavingsProductAssembler { } boolean iswithdrawalFeeApplicableForTransfer = false; - if(command.parameterExists(withdrawalFeeForTransfersParamName)){ + if (command.parameterExists(withdrawalFeeForTransfersParamName)) { iswithdrawalFeeApplicableForTransfer = command.booleanPrimitiveValueOfParameterNamed(withdrawalFeeForTransfersParamName); } @@ -123,13 +123,13 @@ public class SavingsProductAssembler { final MonthDay monthDayOfAnnualFee = command.extractMonthDayNamed(annualFeeOnMonthDayParamName); final AccountingRuleType accountingRuleType = AccountingRuleType.fromInt(command.integerValueOfParameterNamed("accountingRule")); - //Savings product charges + // Savings product charges final Set charges = assembleListOfSavingsProductCharges(command, currencyCode); return SavingsProduct.createNew(name, description, currency, interestRate, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, - lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, iswithdrawalFeeApplicableForTransfer, - annualFeeAmount, monthDayOfAnnualFee, accountingRuleType, charges); + lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeAmount, withdrawalFeeType, + iswithdrawalFeeApplicableForTransfer, annualFeeAmount, monthDayOfAnnualFee, accountingRuleType, charges); } public Set assembleListOfSavingsProductCharges(final JsonCommand command, final String savingsProductCurrencyCode) { @@ -147,8 +147,9 @@ public class SavingsProductAssembler { final Charge charge = this.chargeRepository.findOneWithNotFoundDetection(id); - if(!charge.isSavingsCharge()){ - final String errorMessage = "Charge with identifier " + charge.getId() + " cannot be applied to Savings product."; + if (!charge.isSavingsCharge()) { + final String errorMessage = "Charge with identifier " + charge.getId() + + " cannot be applied to Savings product."; throw new ChargeCannotBeAppliedToException("savings.product", errorMessage, charge.getId()); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductChargeAssembler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductChargeAssembler.java index d92f793e2..a23fc8caa 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductChargeAssembler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/SavingsProductChargeAssembler.java @@ -53,38 +53,41 @@ public class SavingsProductChargeAssembler { if (element.isJsonObject()) { final JsonObject topLevelJsonElement = element.getAsJsonObject(); - final String dateFormat = fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); - final Locale locale = fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); + final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement); + final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement); if (topLevelJsonElement.has(chargesParamName) && topLevelJsonElement.get(chargesParamName).isJsonArray()) { final JsonArray array = topLevelJsonElement.get(chargesParamName).getAsJsonArray(); for (int i = 0; i < array.size(); i++) { final JsonObject savingsChargeElement = array.get(i).getAsJsonObject(); - final Long id = fromApiJsonHelper.extractLongNamed(idParamName, savingsChargeElement); - final Long chargeId = fromApiJsonHelper.extractLongNamed(chargeIdParamName, savingsChargeElement); - final BigDecimal amount = fromApiJsonHelper.extractBigDecimalNamed(amountParamName, savingsChargeElement, locale); - final Integer chargeTimeType = fromApiJsonHelper.extractIntegerNamed(chargeTimeTypeParamName, savingsChargeElement, locale); - final Integer chargeCalculationType = fromApiJsonHelper.extractIntegerNamed(chargeCalculationTypeParamName, savingsChargeElement, - locale); - final LocalDate dueDate = fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, savingsChargeElement, + final Long id = this.fromApiJsonHelper.extractLongNamed(idParamName, savingsChargeElement); + final Long chargeId = this.fromApiJsonHelper.extractLongNamed(chargeIdParamName, savingsChargeElement); + final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed(amountParamName, savingsChargeElement, locale); + final Integer chargeTimeType = this.fromApiJsonHelper.extractIntegerNamed(chargeTimeTypeParamName, + savingsChargeElement, locale); + final Integer chargeCalculationType = this.fromApiJsonHelper.extractIntegerNamed(chargeCalculationTypeParamName, + savingsChargeElement, locale); + final LocalDate dueDate = this.fromApiJsonHelper.extractLocalDateNamed(dueAsOfDateParamName, savingsChargeElement, dateFormat, locale); if (id == null) { final Charge chargeDefinition = this.chargeRepository.findOneWithNotFoundDetection(chargeId); - ChargeTimeType chargeTime = null; + final ChargeTimeType chargeTime = null; if (chargeTimeType != null) { ChargeTimeType.fromInt(chargeTimeType); } - ChargeCalculationType chargeCalculation = null; + final ChargeCalculationType chargeCalculation = null; if (chargeCalculationType != null) { ChargeCalculationType.fromInt(chargeCalculationType); } - final SavingsAccountCharge savingsAccountCharge = SavingsAccountCharge.createNewWithoutSavingsAccount(chargeDefinition, amount, chargeTime, chargeCalculation, dueDate); + final SavingsAccountCharge savingsAccountCharge = SavingsAccountCharge.createNewWithoutSavingsAccount( + chargeDefinition, amount, chargeTime, chargeCalculation, dueDate); savingsAccountCharges.add(savingsAccountCharge); } else { final Long savingsAccountChargeId = id; - final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOne(savingsAccountChargeId); + final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository + .findOne(savingsAccountChargeId); if (savingsAccountCharge == null) { throw new SavingsAccountChargeNotFoundException(savingsAccountChargeId); } savingsAccountCharge.update(amount, dueDate); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/CompoundInterestHelper.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/CompoundInterestHelper.java index f13b0d1fb..4bdd187dc 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/CompoundInterestHelper.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/CompoundInterestHelper.java @@ -12,14 +12,14 @@ public class CompoundInterestHelper { // sum up the 'rounded' values that are posted each posting period Money interestEarned = Money.zero(currency); - + // total interest earned in previous periods but not yet recognised BigDecimal interestEarnedButNotPosted = BigDecimal.ZERO; - for (PostingPeriod postingPeriod : allPeriods) { + for (final PostingPeriod postingPeriod : allPeriods) { final BigDecimal interestEarnedThisPeriod = postingPeriod.calculateInterest(interestEarnedButNotPosted); - Money moneyToBePostedForPeriod = Money.of(currency, interestEarnedThisPeriod); + final Money moneyToBePostedForPeriod = Money.of(currency, interestEarnedThisPeriod); interestEarned = interestEarned.plus(moneyToBePostedForPeriod); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/DailyCompoundingPeriod.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/DailyCompoundingPeriod.java index 7be30730f..3d29c4b9d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/DailyCompoundingPeriod.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/DailyCompoundingPeriod.java @@ -26,18 +26,18 @@ public class DailyCompoundingPeriod implements CompoundingPeriod { private static List endOfDayBalancesWithinPeriodInterval(final LocalDateInterval compoundingPeriodInterval, final List allEndOfDayBalances) { - List endOfDayBalancesForPeriodInterval = new ArrayList(); + final List endOfDayBalancesForPeriodInterval = new ArrayList(); EndOfDayBalance cappedToPeriodEndDate = null; - for (EndOfDayBalance endOfDayBalance : allEndOfDayBalances) { + for (final EndOfDayBalance endOfDayBalance : allEndOfDayBalances) { if (compoundingPeriodInterval.contains(endOfDayBalance.date())) { cappedToPeriodEndDate = endOfDayBalance.upTo(compoundingPeriodInterval); } else if (endOfDayBalance.contains(compoundingPeriodInterval)) { cappedToPeriodEndDate = endOfDayBalance.upTo(compoundingPeriodInterval); } else { - LocalDateInterval latestPeriod = LocalDateInterval.create(compoundingPeriodInterval.startDate(), + final LocalDateInterval latestPeriod = LocalDateInterval.create(compoundingPeriodInterval.startDate(), DateUtils.getLocalDateOfTenant()); cappedToPeriodEndDate = endOfDayBalance.upTo(latestPeriod); } @@ -60,8 +60,9 @@ public class DailyCompoundingPeriod implements CompoundingPeriod { BigDecimal interestEarned = BigDecimal.ZERO; - for (EndOfDayBalance balance : this.endOfDayBalances) { - BigDecimal interestOnBalanceUnrounded = balance.calculateInterestOnBalance(BigDecimal.ZERO, interestRateAsFraction, daysInYear); + for (final EndOfDayBalance balance : this.endOfDayBalances) { + final BigDecimal interestOnBalanceUnrounded = balance.calculateInterestOnBalance(BigDecimal.ZERO, interestRateAsFraction, + daysInYear); interestEarned = interestEarned.add(interestOnBalanceUnrounded); } @@ -78,8 +79,8 @@ public class DailyCompoundingPeriod implements CompoundingPeriod { // for daily compounding - each interest calculated from previous daily // calculations is 'compounded' BigDecimal interestToCompound = interestFromPreviousPostingPeriod; - for (EndOfDayBalance balance : this.endOfDayBalances) { - BigDecimal interestOnBalanceUnrounded = balance.calculateInterestOnBalanceAndInterest(interestToCompound, + for (final EndOfDayBalance balance : this.endOfDayBalances) { + final BigDecimal interestOnBalanceUnrounded = balance.calculateInterestOnBalanceAndInterest(interestToCompound, interestRateAsFraction, daysInYear); interestToCompound = interestToCompound.add(interestOnBalanceUnrounded, MathContext.DECIMAL64).setScale(9); interestEarned = interestEarned.add(interestOnBalanceUnrounded); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/EndOfDayBalance.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/EndOfDayBalance.java index 078bca10b..095d523f1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/EndOfDayBalance.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/EndOfDayBalance.java @@ -44,11 +44,11 @@ public class EndOfDayBalance { public BigDecimal calculateInterestOnBalance(final BigDecimal interestToCompound, final BigDecimal interestRateAsFraction, final long daysInYear) { - BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); - BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(this.numberOfDays), MathContext.DECIMAL64); + final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); + final BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(this.numberOfDays), MathContext.DECIMAL64); - BigDecimal realBalanceForInterestCalculation = this.endOfDayBalance.getAmount().add(interestToCompound); + final BigDecimal realBalanceForInterestCalculation = this.endOfDayBalance.getAmount().add(interestToCompound); return realBalanceForInterestCalculation.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, RoundingMode.HALF_EVEN); } @@ -62,42 +62,42 @@ public class EndOfDayBalance { */ public BigDecimal calculateInterestOnBalanceAndInterest(final BigDecimal interestToCompound, final BigDecimal interestRateAsFraction, final long daysInYear) { - BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); + final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); - BigDecimal presentValue = endOfDayBalance.getAmount().add(interestToCompound); + final BigDecimal presentValue = this.endOfDayBalance.getAmount().add(interestToCompound); - BigDecimal r = interestRateAsFraction.multiply(multiplicand); + final BigDecimal r = interestRateAsFraction.multiply(multiplicand); - BigDecimal interestRateForCompoundingPeriodPlusOne = BigDecimal.ONE.add(r); + final BigDecimal interestRateForCompoundingPeriodPlusOne = BigDecimal.ONE.add(r); - double interestRateForCompoundingPeriodPowered = Math.pow(interestRateForCompoundingPeriodPlusOne.doubleValue(), - Integer.valueOf(this.numberOfDays).doubleValue()); + final double interestRateForCompoundingPeriodPowered = Math.pow(interestRateForCompoundingPeriodPlusOne.doubleValue(), Integer + .valueOf(this.numberOfDays).doubleValue()); - BigDecimal futureValue = presentValue.multiply(BigDecimal.valueOf(interestRateForCompoundingPeriodPowered), MathContext.DECIMAL64) - .setScale(9, RoundingMode.HALF_EVEN); + final BigDecimal futureValue = presentValue.multiply(BigDecimal.valueOf(interestRateForCompoundingPeriodPowered), + MathContext.DECIMAL64).setScale(9, RoundingMode.HALF_EVEN); return futureValue.subtract(presentValue); } public EndOfDayBalance upTo(final LocalDateInterval compoundingPeriodInterval) { - Money startingBalance = openingBalance; + Money startingBalance = this.openingBalance; LocalDate balanceStartDate = this.date; if (this.date.isBefore(compoundingPeriodInterval.startDate())) { balanceStartDate = compoundingPeriodInterval.startDate(); - startingBalance = endOfDayBalance; + startingBalance = this.endOfDayBalance; } int daysOfBalance = this.numberOfDays; LocalDate balanceEndDate = balanceStartDate.plusDays(this.numberOfDays); if (balanceEndDate.isAfter(compoundingPeriodInterval.endDate())) { balanceEndDate = compoundingPeriodInterval.endDate(); - LocalDateInterval balancePeriodInterval = LocalDateInterval.create(balanceStartDate, balanceEndDate); + final LocalDateInterval balancePeriodInterval = LocalDateInterval.create(balanceStartDate, balanceEndDate); daysOfBalance = balancePeriodInterval.daysInPeriodInclusiveOfEndDate(); } if (balanceEndDate.isAfter(DateUtils.getLocalDateOfTenant())) { balanceEndDate = DateUtils.getLocalDateOfTenant(); - LocalDateInterval balancePeriodInterval = LocalDateInterval.create(balanceStartDate, balanceEndDate); + final LocalDateInterval balancePeriodInterval = LocalDateInterval.create(balanceStartDate, balanceEndDate); daysOfBalance = balancePeriodInterval.daysInPeriodInclusiveOfEndDate(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/MonthlyCompoundingPeriod.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/MonthlyCompoundingPeriod.java index 60646a339..5b1ddcb64 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/MonthlyCompoundingPeriod.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/MonthlyCompoundingPeriod.java @@ -28,8 +28,9 @@ public class MonthlyCompoundingPeriod implements CompoundingPeriod { BigDecimal interestEarned = BigDecimal.ZERO; - for (EndOfDayBalance balance : endOfDayBalances) { - BigDecimal interestOnBalanceUnrounded = balance.calculateInterestOnBalance(BigDecimal.ZERO, interestRateAsFraction, daysInYear); + for (final EndOfDayBalance balance : this.endOfDayBalances) { + final BigDecimal interestOnBalanceUnrounded = balance.calculateInterestOnBalance(BigDecimal.ZERO, interestRateAsFraction, + daysInYear); interestEarned = interestEarned.add(interestOnBalanceUnrounded); } @@ -64,22 +65,22 @@ public class MonthlyCompoundingPeriod implements CompoundingPeriod { BigDecimal cumulativeBalance = BigDecimal.ZERO; Integer numberOfDays = Integer.valueOf(0); - for (EndOfDayBalance balance : endOfDayBalances) { - BigDecimal endOfDayCumulativeBalance = balance.cumulativeBalance(interestToCompound); + for (final EndOfDayBalance balance : this.endOfDayBalances) { + final BigDecimal endOfDayCumulativeBalance = balance.cumulativeBalance(interestToCompound); cumulativeBalance = cumulativeBalance.add(endOfDayCumulativeBalance); - Integer balanceExistsForNumberOfDays = balance.getNumberOfDays(); + final Integer balanceExistsForNumberOfDays = balance.getNumberOfDays(); numberOfDays = numberOfDays + balanceExistsForNumberOfDays; } BigDecimal interestEarned = BigDecimal.ZERO; if (cumulativeBalance.compareTo(BigDecimal.ZERO) != 0 && numberOfDays > 0) { - BigDecimal averageDailyBalance = cumulativeBalance.divide(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64).setScale(9, - RoundingMode.HALF_EVEN); + final BigDecimal averageDailyBalance = cumulativeBalance.divide(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64) + .setScale(9, RoundingMode.HALF_EVEN); - BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); - BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); - BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); + final BigDecimal multiplicand = BigDecimal.ONE.divide(BigDecimal.valueOf(daysInYear), MathContext.DECIMAL64); + final BigDecimal dailyInterestRate = interestRateAsFraction.multiply(multiplicand, MathContext.DECIMAL64); + final BigDecimal periodicInterestRate = dailyInterestRate.multiply(BigDecimal.valueOf(numberOfDays), MathContext.DECIMAL64); interestEarned = averageDailyBalance.multiply(periodicInterestRate, MathContext.DECIMAL64).setScale(9, RoundingMode.HALF_EVEN); } @@ -92,7 +93,7 @@ public class MonthlyCompoundingPeriod implements CompoundingPeriod { BigDecimal interestEarned = BigDecimal.ZERO; BigDecimal interestOnBalanceUnrounded = BigDecimal.ZERO; - for (EndOfDayBalance balance : endOfDayBalances) { + for (final EndOfDayBalance balance : this.endOfDayBalances) { switch (compoundingInterestPeriodType) { case DAILY: @@ -126,9 +127,9 @@ public class MonthlyCompoundingPeriod implements CompoundingPeriod { private static List endOfDayBalancesWithinPeriodInterval(final LocalDateInterval compoundingPeriodInterval, final List allEndOfDayBalances) { - List endOfDayBalancesForPeriodInterval = new ArrayList(); + final List endOfDayBalancesForPeriodInterval = new ArrayList(); - for (EndOfDayBalance endOfDayBalance : allEndOfDayBalances) { + for (final EndOfDayBalance endOfDayBalance : allEndOfDayBalances) { if (compoundingPeriodInterval.contains(endOfDayBalance.date())) { final EndOfDayBalance cappedToPeriodEndDate = endOfDayBalance.upTo(compoundingPeriodInterval); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/PostingPeriod.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/PostingPeriod.java index 3da8b4300..1f0f28779 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/PostingPeriod.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/domain/interest/PostingPeriod.java @@ -39,21 +39,21 @@ public class PostingPeriod { final SavingsCompoundingInterestPeriodType interestCompoundingPeriodType, final SavingsInterestCalculationType interestCalculationType, final BigDecimal interestRateAsFraction, final long daysInYear) { - List accountEndOfDayBalances = new ArrayList(); + final List accountEndOfDayBalances = new ArrayList(); Money openingDayBalance = periodStartingBalance; Money closeOfDayBalance = openingDayBalance; - for (SavingsAccountTransaction transaction : orderedListOfTransactions) { + for (final SavingsAccountTransaction transaction : orderedListOfTransactions) { if (transaction.fallsWithin(periodInterval)) { // the balance of the transaction falls entirely within this // period so no need to do any cropping/bounding - EndOfDayBalance endOfDayBalance = transaction.toEndOfDayBalance(openingDayBalance); + final EndOfDayBalance endOfDayBalance = transaction.toEndOfDayBalance(openingDayBalance); accountEndOfDayBalances.add(endOfDayBalance); openingDayBalance = endOfDayBalance.closingBalance(); } else if (transaction.spansAnyPortionOf(periodInterval)) { - EndOfDayBalance endOfDayBalance = transaction.toEndOfDayBalanceBoundedBy(openingDayBalance, periodInterval); + final EndOfDayBalance endOfDayBalance = transaction.toEndOfDayBalanceBoundedBy(openingDayBalance, periodInterval); accountEndOfDayBalances.add(endOfDayBalance); closeOfDayBalance = endOfDayBalance.closingBalance(); @@ -62,7 +62,7 @@ public class PostingPeriod { } if (accountEndOfDayBalances.isEmpty()) { - EndOfDayBalance endOfDayBalance = EndOfDayBalance.from(periodInterval.startDate(), openingDayBalance, closeOfDayBalance, + final EndOfDayBalance endOfDayBalance = EndOfDayBalance.from(periodInterval.startDate(), openingDayBalance, closeOfDayBalance, periodInterval.daysInPeriodInclusiveOfEndDate()); accountEndOfDayBalances.add(endOfDayBalance); @@ -112,10 +112,10 @@ public class PostingPeriod { // for each compounding period accumulate the amount of interest // to be applied to the balanced for interest calculation BigDecimal interestCompounded = interestFromPreviousPostingPeriod; - for (CompoundingPeriod compoundingPeriod : this.compoundingPeriods) { + for (final CompoundingPeriod compoundingPeriod : this.compoundingPeriods) { - BigDecimal interestUnrounded = compoundingPeriod.calculateInterest(this.interestCompoundingType, this.interestCalculationType, - interestCompounded, this.interestRateAsFraction, this.daysInYear); + final BigDecimal interestUnrounded = compoundingPeriod.calculateInterest(this.interestCompoundingType, + this.interestCalculationType, interestCompounded, this.interestRateAsFraction, this.daysInYear); interestCompounded = interestCompounded.add(interestUnrounded); interestEarned = interestEarned.add(interestUnrounded); } @@ -133,7 +133,7 @@ public class PostingPeriod { private static List compoundingPeriodsInPostingPeriod(final LocalDateInterval postingPeriodInterval, final SavingsCompoundingInterestPeriodType interestPeriodType, final List allEndOfDayBalances) { - List compoundingPeriods = new ArrayList(); + final List compoundingPeriods = new ArrayList(); CompoundingPeriod compoundingPeriod = null; switch (interestPeriodType) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsAccountClosingNotAllowedException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsAccountClosingNotAllowedException.java index 5f7db3bbf..3f1a6e28f 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsAccountClosingNotAllowedException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsAccountClosingNotAllowedException.java @@ -2,10 +2,10 @@ package org.mifosplatform.portfolio.savings.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRuleException; - public class SavingsAccountClosingNotAllowedException extends AbstractPlatformDomainRuleException { - public SavingsAccountClosingNotAllowedException(final String entity, String defaultUserMessage, Object... defaultUserMessageArgs) { + public SavingsAccountClosingNotAllowedException(final String entity, final String defaultUserMessage, + final Object... defaultUserMessageArgs) { super("error.msg." + entity + ".saving.account.close.notallowed", defaultUserMessage, defaultUserMessageArgs); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsActivityPriorToClientTransferException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsActivityPriorToClientTransferException.java index 9eabc50e5..1ff33f071 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsActivityPriorToClientTransferException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsActivityPriorToClientTransferException.java @@ -13,7 +13,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class SavingsActivityPriorToClientTransferException extends AbstractPlatformDomainRuleException { - public SavingsActivityPriorToClientTransferException(final String action, Object... defaultUserMessageArgs) { + public SavingsActivityPriorToClientTransferException(final String action, final Object... defaultUserMessageArgs) { super("error.msg.savings." + action + "." + "not.permitted.before.client.transfer.date", "Transactions on savings account prior to the customer joining date are not permitted", defaultUserMessageArgs); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsTransferTransactionsCannotBeUndoneException.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsTransferTransactionsCannotBeUndoneException.java index c29a35fb9..655b92adb 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsTransferTransactionsCannotBeUndoneException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/exception/SavingsTransferTransactionsCannotBeUndoneException.java @@ -13,7 +13,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformDomainRul */ public class SavingsTransferTransactionsCannotBeUndoneException extends AbstractPlatformDomainRuleException { - public SavingsTransferTransactionsCannotBeUndoneException(Long transactionId) { + public SavingsTransferTransactionsCannotBeUndoneException(final Long transactionId) { super("error.msg.savings.transfer.transactions.cannot.be.undone", "Transactions related to savings account transfers cannot be undone", transactionId); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/ApplyAnnualFeeSavingsAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/ApplyAnnualFeeSavingsAccountCommandHandler.java index 226e97814..1e0cf8ee6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/ApplyAnnualFeeSavingsAccountCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/ApplyAnnualFeeSavingsAccountCommandHandler.java @@ -28,7 +28,7 @@ public class ApplyAnnualFeeSavingsAccountCommandHandler implements NewCommandSou @Override public CommandProcessingResult processCommand(final JsonCommand command) { - LocalDate annualFeeTransactionDate = command.localDateValueOfParameterNamed("annualFeeTransactionDate"); + final LocalDate annualFeeTransactionDate = command.localDateValueOfParameterNamed("annualFeeTransactionDate"); return this.writePlatformService.applyAnnualFee(command.getSavingsId(), annualFeeTransactionDate); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CalculateInterestSavingsAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CalculateInterestSavingsAccountCommandHandler.java index f12498d12..1c389a6cd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CalculateInterestSavingsAccountCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CalculateInterestSavingsAccountCommandHandler.java @@ -19,8 +19,7 @@ public class CalculateInterestSavingsAccountCommandHandler implements NewCommand private final SavingsAccountWritePlatformService writePlatformService; @Autowired - public CalculateInterestSavingsAccountCommandHandler( - final SavingsAccountWritePlatformService writePlatformService) { + public CalculateInterestSavingsAccountCommandHandler(final SavingsAccountWritePlatformService writePlatformService) { this.writePlatformService = writePlatformService; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CloseSavingsAccountCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CloseSavingsAccountCommandHandler.java index 221782427..47ec2dfe8 100755 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CloseSavingsAccountCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/CloseSavingsAccountCommandHandler.java @@ -9,7 +9,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service -public class CloseSavingsAccountCommandHandler implements NewCommandSourceHandler{ +public class CloseSavingsAccountCommandHandler implements NewCommandSourceHandler { private final SavingsAccountWritePlatformService writePlatformService; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationDeletionCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationDeletionCommandHandler.java index f0d835872..b83b87cc8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationDeletionCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationDeletionCommandHandler.java @@ -19,7 +19,8 @@ public class SavingsAccountApplicationDeletionCommandHandler implements NewComma private final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService; @Autowired - public SavingsAccountApplicationDeletionCommandHandler(final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { + public SavingsAccountApplicationDeletionCommandHandler( + final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { this.savingAccountWritePlatformService = savingAccountWritePlatformService; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationModificationCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationModificationCommandHandler.java index 1afe21684..9bf4671fb 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationModificationCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationModificationCommandHandler.java @@ -19,7 +19,8 @@ public class SavingsAccountApplicationModificationCommandHandler implements NewC private final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService; @Autowired - public SavingsAccountApplicationModificationCommandHandler(final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { + public SavingsAccountApplicationModificationCommandHandler( + final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { this.savingAccountWritePlatformService = savingAccountWritePlatformService; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationSubmittalCommandHandler.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationSubmittalCommandHandler.java index f746185dc..a0df7564c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationSubmittalCommandHandler.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/handler/SavingsAccountApplicationSubmittalCommandHandler.java @@ -19,7 +19,8 @@ public class SavingsAccountApplicationSubmittalCommandHandler implements NewComm private final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService; @Autowired - public SavingsAccountApplicationSubmittalCommandHandler(final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { + public SavingsAccountApplicationSubmittalCommandHandler( + final SavingsApplicationProcessWritePlatformService savingAccountWritePlatformService) { this.savingAccountWritePlatformService = savingAccountWritePlatformService; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountApplicationTransitionApiJsonValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountApplicationTransitionApiJsonValidator.java index 243f13435..b570222ca 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountApplicationTransitionApiJsonValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountApplicationTransitionApiJsonValidator.java @@ -47,16 +47,16 @@ public final class SavingsAccountApplicationTransitionApiJsonValidator { final Set disbursementParameters = new HashSet(Arrays.asList("approvedOnDate", "note", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("savingsaccountapplication"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate approvedOnDate = fromApiJsonHelper.extractLocalDateNamed("approvedOnDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate approvedOnDate = this.fromApiJsonHelper.extractLocalDateNamed("approvedOnDate", element); baseDataValidator.reset().parameter("approvedOnDate").value(approvedOnDate).notNull(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -69,16 +69,16 @@ public final class SavingsAccountApplicationTransitionApiJsonValidator { final Set disbursementParameters = new HashSet(Arrays.asList("rejectedOnDate", "note", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("savingsaccountapplication"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate rejectedOnDate = fromApiJsonHelper.extractLocalDateNamed("rejectedOnDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate rejectedOnDate = this.fromApiJsonHelper.extractLocalDateNamed("rejectedOnDate", element); baseDataValidator.reset().parameter("rejectedOnDate").value(rejectedOnDate).notNull(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -91,16 +91,16 @@ public final class SavingsAccountApplicationTransitionApiJsonValidator { final Set disbursementParameters = new HashSet(Arrays.asList("withdrawnOnDate", "note", "locale", "dateFormat")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, disbursementParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("savingsaccountapplication"); - final JsonElement element = fromApiJsonHelper.parse(json); - final LocalDate withdrawnOnDate = fromApiJsonHelper.extractLocalDateNamed("withdrawnOnDate", element); + final JsonElement element = this.fromApiJsonHelper.parse(json); + final LocalDate withdrawnOnDate = this.fromApiJsonHelper.extractLocalDateNamed("withdrawnOnDate", element); baseDataValidator.reset().parameter("withdrawnOnDate").value(withdrawnOnDate).notNull(); - final String note = fromApiJsonHelper.extractStringNamed("note", element); + final String note = this.fromApiJsonHelper.extractStringNamed("note", element); baseDataValidator.reset().parameter("note").value(note).notExceedingLengthOf(1000); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -111,16 +111,16 @@ public final class SavingsAccountApplicationTransitionApiJsonValidator { final Set undoSupportedParameters = new HashSet(Arrays.asList("note")); final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, undoSupportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, undoSupportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("savingsaccountapplication.undo"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); final String note = "note"; - if (fromApiJsonHelper.parameterExists(note, element)) { - final String noteText = fromApiJsonHelper.extractStringNamed(note, element); + if (this.fromApiJsonHelper.parameterExists(note, element)) { + final String noteText = this.fromApiJsonHelper.extractStringNamed(note, element); baseDataValidator.reset().parameter(note).value(noteText).notExceedingLengthOf(1000); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountChargeReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountChargeReadPlatformServiceImpl.java index 41ff245a0..656ad16b1 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountChargeReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountChargeReadPlatformServiceImpl.java @@ -97,10 +97,12 @@ public class SavingsAccountChargeReadPlatformServiceImpl implements SavingsAccou final int chargeCalculation = rs.getInt("chargeCalculation"); final EnumOptionData chargeCalculationType = ChargeEnumerations.chargeCalculationType(chargeCalculation); final boolean penalty = rs.getBoolean("penalty"); - + final Collection chargeOptions = null; - - return SavingsAccountChargeData.instance(id, chargeId, name, currency, amount, amountPaid, amountWaived, amountWrittenOff, amountOutstanding, chargeTimeType, dueAsOfDate, chargeCalculationType, percentageOf, amountPercentageAppliedTo, chargeOptions, penalty); + + return SavingsAccountChargeData.instance(id, chargeId, name, currency, amount, amountPaid, amountWaived, amountWrittenOff, + amountOutstanding, chargeTimeType, dueAsOfDate, chargeCalculationType, percentageOf, amountPercentageAppliedTo, + chargeOptions, penalty); } } @@ -111,7 +113,7 @@ public class SavingsAccountChargeReadPlatformServiceImpl implements SavingsAccou final List allowedChargeCalculationTypeOptions = this.chargeDropdownReadPlatformService.retrieveCalculationTypes(); final List allowedChargeTimeOptions = this.chargeDropdownReadPlatformService.retrieveCollectionTimeTypes(); - //TODO AA : revisit for merge conflict - Not sure method signature + // TODO AA : revisit for merge conflict - Not sure method signature return ChargeData.template(null, allowedChargeCalculationTypeOptions, null, allowedChargeTimeOptions, null); } @@ -125,7 +127,7 @@ public class SavingsAccountChargeReadPlatformServiceImpl implements SavingsAccou final String sql = "select " + rm.schema() + " where sc.id=? and sc.savings_account_id=?"; return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { id, savingsAccountId }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new SavingsAccountChargeNotFoundException(savingsAccountId); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java index 9e1ed2f34..62cef05c7 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountReadPlatformServiceImpl.java @@ -102,23 +102,23 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead @Override public Collection retrieveAllForLookup(final Long clientId) { - StringBuilder sqlBuilder = new StringBuilder("select " + this.savingAccountMapper.schema()); + final StringBuilder sqlBuilder = new StringBuilder("select " + this.savingAccountMapper.schema()); sqlBuilder.append(" where sa.client_id = ? and sa.status_enum = 300"); - Object[] queryParameters = new Object[] { clientId }; + final Object[] queryParameters = new Object[] { clientId }; return this.jdbcTemplate.query(sqlBuilder.toString(), this.savingAccountMapper, queryParameters); } @Override public Page retrieveAll(final SearchParameters searchParameters) { - final AppUser currentUser = context.authenticatedUser(); + final AppUser currentUser = this.context.authenticatedUser(); final String hierarchy = currentUser.getOffice().getHierarchy(); final String hierarchySearchString = hierarchy + "%"; - StringBuilder sqlBuilder = new StringBuilder(200); + final StringBuilder sqlBuilder = new StringBuilder(200); sqlBuilder.append("select SQL_CALC_FOUND_ROWS "); - sqlBuilder.append(savingAccountMapper.schema()); + sqlBuilder.append(this.savingAccountMapper.schema()); sqlBuilder.append(" join m_office o on o.id = c.office_id"); sqlBuilder.append(" where o.hierarchy like ?"); @@ -167,7 +167,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final String sql = "select " + this.savingAccountMapper.schema() + " where sa.id = ?"; return this.jdbcTemplate.queryForObject(sql, this.savingAccountMapper, new Object[] { accountId }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new SavingsAccountNotFoundException(accountId); } } @@ -358,7 +358,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead if (withdrawalFeeTypeValue != null) { withdrawalFeeType = SavingsEnumerations.withdrawalFeeType(withdrawalFeeTypeValue); } - + final boolean withdrawalFeeForTransfers = rs.getBoolean("withdrawalFeeForTransfers"); final BigDecimal annualFeeAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "annualFeeAmount"); @@ -382,7 +382,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final BigDecimal accountBalance = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "accountBalance"); final BigDecimal totalFeeCharge = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalFeeCharge"); final BigDecimal totalPenaltyCharge = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "totalPenaltyCharge"); - + final SavingsAccountSummaryData summary = new SavingsAccountSummaryData(currency, totalDeposits, totalWithdrawals, totalWithdrawalFees, totalAnnualFees, totalInterestEarned, totalInterestPosted, accountBalance, totalFeeCharge, totalPenaltyCharge); @@ -399,7 +399,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead public SavingsAccountData retrieveTemplate(final Long clientId, final Long groupId, final Long productId, final boolean staffInSelectedOfficeOnly) { - AppUser loggedInUser = context.authenticatedUser(); + final AppUser loggedInUser = this.context.authenticatedUser(); Long officeId = loggedInUser.getOffice().getId(); ClientData client = null; @@ -418,7 +418,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead SavingsAccountData template = null; if (productId != null) { - SavingAccountTemplateMapper mapper = new SavingAccountTemplateMapper(client, group); + final SavingAccountTemplateMapper mapper = new SavingAccountTemplateMapper(client, group); final String sql = "select " + mapper.schema() + " where sp.id = ?"; template = this.jdbcTemplate.queryForObject(sql, mapper, new Object[] { productId }); @@ -442,11 +442,12 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final Collection transactions = null; final Collection productCharges = this.chargeReadPlatformService.retrieveSavingsProductCharges(productId); - //update charges from Product charges + // update charges from Product charges final Collection charges = fromChargesToSavingsCharges(productCharges); - + final boolean feeChargesOnly = false; - final Collection chargeOptions = this.chargeReadPlatformService.retrieveSavingsAccountApplicableCharges(feeChargesOnly); + final Collection chargeOptions = this.chargeReadPlatformService + .retrieveSavingsAccountApplicableCharges(feeChargesOnly); Collection fieldOfficerOptions = null; @@ -454,7 +455,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead if (staffInSelectedOfficeOnly) { // only bring back loan officers in selected branch/office - Collection fieldOfficersInBranch = this.staffReadPlatformService + final Collection fieldOfficersInBranch = this.staffReadPlatformService .retrieveAllLoanOfficersInOfficeById(officeId); if (!CollectionUtils.isEmpty(fieldOfficersInBranch)) { @@ -465,7 +466,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead // branch/office as well as officers in office above // this office final boolean restrictToLoanOfficersOnly = true; - Collection loanOfficersInHierarchy = this.staffReadPlatformService + final Collection loanOfficersInHierarchy = this.staffReadPlatformService .retrieveAllStaffInOfficeAndItsParentOfficeHierarchy(officeId, restrictToLoanOfficersOnly); if (!CollectionUtils.isEmpty(loanOfficersInHierarchy)) { @@ -476,7 +477,8 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead template = SavingsAccountData.withTemplateOptions(template, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, - interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, transactions, charges, chargeOptions); + interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, transactions, + charges, chargeOptions); } else { String clientName = null; @@ -501,21 +503,23 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final Collection transactions = null; final Collection charges = null; - + final boolean feeChargesOnly = true; - final Collection chargeOptions = this.chargeReadPlatformService.retrieveSavingsAccountApplicableCharges(feeChargesOnly); + final Collection chargeOptions = this.chargeReadPlatformService + .retrieveSavingsAccountApplicableCharges(feeChargesOnly); template = SavingsAccountData.withTemplateOptions(template, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions, - interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, transactions, charges, chargeOptions); + interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, transactions, + charges, chargeOptions); } return template; } - private Collection fromChargesToSavingsCharges(Collection productCharges) { + private Collection fromChargesToSavingsCharges(final Collection productCharges) { final Collection savingsCharges = new ArrayList(); - for (ChargeData chargeData : productCharges) { + for (final ChargeData chargeData : productCharges) { final SavingsAccountChargeData savingsCharge = chargeData.toSavingsAccountChargeData(); savingsCharges.add(savingsCharge); } @@ -526,10 +530,10 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead public SavingsAccountTransactionData retrieveDepositTransactionTemplate(final Long savingsId) { try { - final String sql = "select " + transactionTemplateMapper.schema() + " where sa.id = ?"; + final String sql = "select " + this.transactionTemplateMapper.schema() + " where sa.id = ?"; - return this.jdbcTemplate.queryForObject(sql, transactionTemplateMapper, new Object[] { savingsId }); - } catch (EmptyResultDataAccessException e) { + return this.jdbcTemplate.queryForObject(sql, this.transactionTemplateMapper, new Object[] { savingsId }); + } catch (final EmptyResultDataAccessException e) { throw new SavingsAccountNotFoundException(savingsId); } } @@ -552,7 +556,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead @Override public Collection retrieveAccountsWithAnnualFeeDue() { - final String sql = "select " + annualFeeMapper.schema() + final String sql = "select " + this.annualFeeMapper.schema() + " where sa.annual_fee_next_due_date is not null and sa.annual_fee_next_due_date <= NOW()"; return this.jdbcTemplate.query(sql, this.annualFeeMapper, new Object[] {}); @@ -616,7 +620,7 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final Long paymentTypeId = JdbcSupport.getLong(rs, "paymentType"); if (paymentTypeId != null) { final String typeName = rs.getString("paymentTypeName"); - CodeValueData paymentType = CodeValueData.instance(paymentTypeId, typeName); + final CodeValueData paymentType = CodeValueData.instance(paymentTypeId, typeName); final String accountNumber = rs.getString("accountNumber"); final String checkNumber = rs.getString("checkNumber"); final String routingCode = rs.getString("routingCode"); @@ -761,17 +765,17 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead final BigDecimal nominalAnnualIterestRate = rs.getBigDecimal("nominalAnnualIterestRate"); - EnumOptionData interestCompoundingPeriodType = SavingsEnumerations + final EnumOptionData interestCompoundingPeriodType = SavingsEnumerations .compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.fromInt(JdbcSupport.getInteger(rs, "interestCompoundingPeriodType"))); final EnumOptionData interestPostingPeriodType = SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType .fromInt(JdbcSupport.getInteger(rs, "interestPostingPeriodType"))); - EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType + final EnumOptionData interestCalculationType = SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType .fromInt(JdbcSupport.getInteger(rs, "interestCalculationType"))); - EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations + final EnumOptionData interestCalculationDaysInYearType = SavingsEnumerations .interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.fromInt(JdbcSupport.getInteger(rs, "interestCalculationDaysInYearType"))); @@ -792,9 +796,9 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead if (withdrawalFeeTypeValue != null) { withdrawalFeeType = SavingsEnumerations.withdrawalFeeType(withdrawalFeeTypeValue); } - + final boolean withdrawalFeeForTransfers = rs.getBoolean("withdrawalFeeForTransfers"); - + final BigDecimal annualFeeAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "annualFeeAmount"); MonthDay annualFeeOnMonthDay = null; @@ -806,16 +810,16 @@ public class SavingsAccountReadPlatformServiceImpl implements SavingsAccountRead Long clientId = null; String clientName = null; - if (client != null) { - clientId = client.id(); - clientName = client.displayName(); + if (this.client != null) { + clientId = this.client.id(); + clientName = this.client.displayName(); } Long groupId = null; String groupName = null; - if (group != null) { - groupId = group.getId(); - groupName = group.getName(); + if (this.group != null) { + groupId = this.group.getId(); + groupName = this.group.getName(); } final Long fieldOfficerId = null; diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformService.java index e2c46cf5d..d9f75c0ee 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformService.java @@ -41,7 +41,7 @@ public interface SavingsAccountWritePlatformService { void rejectSavingsTransfer(Long accountId); SavingsAccountTransaction acceptSavingsTransfer(Long accountId, LocalDate transferDate, Office acceptedInOffice, Staff staff); - + CommandProcessingResult addSavingsAccountCharge(JsonCommand command); CommandProcessingResult updateSavingsAccountCharge(JsonCommand command); @@ -49,6 +49,6 @@ public interface SavingsAccountWritePlatformService { CommandProcessingResult deleteSavingsAccountCharge(Long savingsAccountId, Long savingsAccountChargeId, JsonCommand command); CommandProcessingResult waiveCharge(Long savingsAccountId, Long savingsAccountChargeId, JsonCommand command); - + CommandProcessingResult payCharge(Long savingsAccountId, Long savingsAccountChargeId, JsonCommand command); } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java index e23a1e2fe..8083a4f42 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsAccountWritePlatformServiceJpaRepositoryImpl.java @@ -319,18 +319,20 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi } @Override - public CommandProcessingResult undoTransaction(final Long savingsId, final Long transactionId, final boolean allowAccountTransferModification) { + public CommandProcessingResult undoTransaction(final Long savingsId, final Long transactionId, + final boolean allowAccountTransferModification) { final List newTransactionIds = new ArrayList(); final List reversedTransactionIds = new ArrayList(); - final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository.findOneByIdAndSavingsAccountId( - transactionId, savingsId); + final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository + .findOneByIdAndSavingsAccountId(transactionId, savingsId); if (savingsAccountTransaction == null) { throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId); } - if(!allowAccountTransferModification && this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)){ - throw new PlatformServiceUnavailableException("error.msg.saving.account.transfer.transaction.update.not.allowed","Savings account transaction:"+transactionId+" update not allowed as it involves in account transfer",transactionId); - } + if (!allowAccountTransferModification + && this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)) { throw new PlatformServiceUnavailableException( + "error.msg.saving.account.transfer.transaction.update.not.allowed", "Savings account transaction:" + transactionId + + " update not allowed as it involves in account transfer", transactionId); } final LocalDate today = DateUtils.getLocalDateOfTenant(); final MathContext mc = new MathContext(15, RoundingMode.HALF_EVEN); @@ -363,16 +365,16 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi @Override public CommandProcessingResult adjustSavingsTransaction(final Long savingsId, final Long transactionId, final JsonCommand command) { - final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository.findOneByIdAndSavingsAccountId( - transactionId, savingsId); + final SavingsAccountTransaction savingsAccountTransaction = this.savingsAccountTransactionRepository + .findOneByIdAndSavingsAccountId(transactionId, savingsId); if (savingsAccountTransaction == null) { throw new SavingsAccountTransactionNotFoundException(savingsId, transactionId); } if (!(savingsAccountTransaction.isDeposit() || savingsAccountTransaction.isWithdrawal()) || savingsAccountTransaction.isReversed()) { throw new TransactionUpdateNotAllowedException( savingsId, transactionId); } - if(this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)){ - throw new PlatformServiceUnavailableException("error.msg.saving.account.transfer.transaction.update.not.allowed","Savings account transaction:"+transactionId+" update not allowed as it involves in account transfer",transactionId); - } + if (this.accountTransfersReadPlatformService.isAccountTransfer(transactionId, PortfolioAccountType.SAVINGS)) { throw new PlatformServiceUnavailableException( + "error.msg.saving.account.transfer.transaction.update.not.allowed", "Savings account transaction:" + transactionId + + " update not allowed as it involves in account transfer", transactionId); } this.savingsAccountTransactionDataValidator.validate(command); final LocalDate today = DateUtils.getLocalDateOfTenant(); @@ -395,10 +397,10 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi account.undoTransaction(transactionId, existingReversedTransactionIds); // for undo withdrawal fee - final SavingsAccountTransaction nextSavingsAccountTransaction = this.savingsAccountTransactionRepository.findOneByIdAndSavingsAccountId( - transactionId+1, savingsId); - if(nextSavingsAccountTransaction!=null && nextSavingsAccountTransaction.isWithdrawalFeeAndNotReversed()){ - account.undoTransaction(transactionId+1, existingReversedTransactionIds); + final SavingsAccountTransaction nextSavingsAccountTransaction = this.savingsAccountTransactionRepository + .findOneByIdAndSavingsAccountId(transactionId + 1, savingsId); + if (nextSavingsAccountTransaction != null && nextSavingsAccountTransaction.isWithdrawalFeeAndNotReversed()) { + account.undoTransaction(transactionId + 1, existingReversedTransactionIds); } SavingsAccountTransaction transaction = null; @@ -472,8 +474,9 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi this.savingsAccountTransactionDataValidator.validateClosing(command); final SavingsAccount account = this.savingAccountAssembler.assembleFrom(savingsId); final boolean isLinkedWithAnyActiveLoan = this.accountAssociationsReadPlatformService.isLinkedWithAnyActiveLoan(savingsId); - if(isLinkedWithAnyActiveLoan){ - final String defaultUserMessage = "Closing savings account with id:"+savingsId+" is not allowed, since it is linked with one of the active loans"; + if (isLinkedWithAnyActiveLoan) { + final String defaultUserMessage = "Closing savings account with id:" + savingsId + + " is not allowed, since it is linked with one of the active loans"; throw new SavingsAccountClosingNotAllowedException("linked", defaultUserMessage, savingsId); } @@ -546,8 +549,8 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi } @Override - public SavingsAccountTransaction acceptSavingsTransfer(final Long accountId, final LocalDate transferDate, final Office acceptedInOffice, - final Staff fieldOfficer) { + public SavingsAccountTransaction acceptSavingsTransfer(final Long accountId, final LocalDate transferDate, + final Office acceptedInOffice, final Staff fieldOfficer) { final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(accountId); final List existingTransactionIds = new ArrayList(savingsAccount.findExistingTransactionIds()); @@ -608,34 +611,38 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi this.savingsAccountChargeDataValidator.validateUpdate(command.json()); final Long savingsAccountId = command.getSavingsId(); - final Long savingsChargeId = command.entityId();//SavingsAccount Charge entity + final Long savingsChargeId = command.entityId();// SavingsAccount Charge + // entity final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(savingsAccountId); checkClientOrGroupActive(savingsAccount); - final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection(savingsChargeId, savingsAccountId); + final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection(savingsChargeId, + savingsAccountId); final Map changes = savingsAccountCharge.update(command); this.savingsAccountChargeRepository.saveAndFlush(savingsAccountCharge); - //TODO AA: revisit the code + // TODO AA: revisit the code /* - // Charges may be edited only when the loan associated with them are - // yet to be approved (are in submitted and pending status) - if (!loan.status().isSubmittedAndPendingApproval()) { throw new LoanChargeCannotBeUpdatedException( - LOAN_CHARGE_CANNOT_BE_UPDATED_REASON.LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, loanCharge.getId()); } -*/ + * // Charges may be edited only when the loan associated with them are + * // yet to be approved (are in submitted and pending status) if + * (!loan.status().isSubmittedAndPendingApproval()) { throw new + * LoanChargeCannotBeUpdatedException( + * LOAN_CHARGE_CANNOT_BE_UPDATED_REASON + * .LOAN_NOT_IN_SUBMITTED_AND_PENDING_APPROVAL_STAGE, + * loanCharge.getId()); } + */ return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(savingsChargeId) // - //.withOfficeId(savings) // - //.withClientId(loan.getClientId()) // - //.withGroupId(loan.getGroupId()) // - //.withLoanId(savingsAccountId) // + // .withOfficeId(savings) // + // .withClientId(loan.getClientId()) // + // .withGroupId(loan.getGroupId()) // + // .withLoanId(savingsAccountId) // .with(changes) // .build(); } - @Transactional @Override public CommandProcessingResult waiveCharge(final Long savingsAccountId, final Long savingsAccountChargeId, final JsonCommand command) { @@ -653,36 +660,38 @@ public class SavingsAccountWritePlatformServiceJpaRepositoryImpl implements Savi this.savingAccountRepository.saveAndFlush(savingsAccount); return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(savingsAccountChargeId) // - .withOfficeId(savingsAccount.officeId()) // - .withClientId(savingsAccount.clientId()) // - .withGroupId(savingsAccount.groupId()) // - .withSavingsId(savingsAccountId) // - .build(); + .withCommandId(command.commandId()) // + .withEntityId(savingsAccountChargeId) // + .withOfficeId(savingsAccount.officeId()) // + .withClientId(savingsAccount.clientId()) // + .withGroupId(savingsAccount.groupId()) // + .withSavingsId(savingsAccountId) // + .build(); } @Transactional @Override - public CommandProcessingResult deleteSavingsAccountCharge(final Long savingsAccountId, final Long savingsAccountChargeId, @SuppressWarnings("unused") final JsonCommand command) { + public CommandProcessingResult deleteSavingsAccountCharge(final Long savingsAccountId, final Long savingsAccountChargeId, + @SuppressWarnings("unused") final JsonCommand command) { this.context.authenticatedUser(); final SavingsAccount savingsAccount = this.savingAccountAssembler.assembleFrom(savingsAccountId); checkClientOrGroupActive(savingsAccount); - final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection(savingsAccountChargeId, savingsAccountId); + final SavingsAccountCharge savingsAccountCharge = this.savingsAccountChargeRepository.findOneWithNotFoundDetection( + savingsAccountChargeId, savingsAccountId); - //TODO AA: validate before deleting a charge + // TODO AA: validate before deleting a charge savingsAccount.removeCharge(savingsAccountCharge); this.savingAccountRepository.saveAndFlush(savingsAccount); return new CommandProcessingResultBuilder() // - .withEntityId(savingsAccountChargeId) // - .withOfficeId(savingsAccount.officeId()) // - .withClientId(savingsAccount.clientId()) // - .withGroupId(savingsAccount.groupId()) // - .withSavingsId(savingsAccountId) // - .build(); + .withEntityId(savingsAccountChargeId) // + .withOfficeId(savingsAccount.officeId()) // + .withClientId(savingsAccount.clientId()) // + .withGroupId(savingsAccount.groupId()) // + .withSavingsId(savingsAccountId) // + .build(); } @Transactional diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java index 12e28f6b3..8454a6ad4 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl.java @@ -157,13 +157,13 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl final Long savingsId = account.getId(); return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(savingsId) // - .withOfficeId(account.officeId()) // - .withClientId(account.clientId()) // - .withGroupId(account.groupId()) // - .withSavingsId(savingsId) // - .build(); + .withCommandId(command.commandId()) // + .withEntityId(savingsId) // + .withOfficeId(account.officeId()) // + .withClientId(account.clientId()) // + .withGroupId(account.groupId()) // + .withSavingsId(savingsId) // + .build(); } catch (final DataAccessException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); @@ -233,7 +233,9 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } if (changes.containsKey("charges")) { - //final Set savingsProductCharges = this.savi.assembleListOfSavingsProductCharges(command, product.currency().getCode()); + // final Set savingsProductCharges = + // this.savi.assembleListOfSavingsProductCharges(command, + // product.currency().getCode()); final Set charges = this.savingsAccountChargeAssembler.fromParsedJson(command.parsedJson()); final boolean updated = account.update(charges); if (!updated) { @@ -245,14 +247,14 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(savingsId) // - .withOfficeId(account.officeId()) // - .withClientId(account.clientId()) // - .withGroupId(account.groupId()) // - .withSavingsId(savingsId) // - .with(changes) // - .build(); + .withCommandId(command.commandId()) // + .withEntityId(savingsId) // + .withOfficeId(account.officeId()) // + .withClientId(account.clientId()) // + .withGroupId(account.groupId()) // + .withSavingsId(savingsId) // + .with(changes) // + .build(); } catch (final DataAccessException dve) { handleDataIntegrityIssues(command, dve); return new CommandProcessingResult(Long.valueOf(-1)); @@ -269,10 +271,10 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl if (account.isNotSubmittedAndPendingApproval()) { final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) - .resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.deleteApplicationAction); + .resource(SAVINGS_ACCOUNT_RESOURCE_NAME + SavingsApiConstants.deleteApplicationAction); baseDataValidator.reset().parameter(SavingsApiConstants.activatedOnDateParamName) - .failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state"); + .failWithCodeNoParameterAddedToErrorCode("not.in.submittedandpendingapproval.state"); if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } @@ -283,12 +285,12 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl this.savingAccountRepository.delete(account); return new CommandProcessingResultBuilder() // - .withEntityId(savingsId) // - .withOfficeId(account.officeId()) // - .withClientId(account.clientId()) // - .withGroupId(account.groupId()) // - .withSavingsId(savingsId) // - .build(); + .withEntityId(savingsId) // + .withOfficeId(account.officeId()) // + .withClientId(account.clientId()) // + .withGroupId(account.groupId()) // + .withSavingsId(savingsId) // + .build(); } @Transactional @@ -315,14 +317,14 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(savingsId) // - .withOfficeId(savingsAccount.officeId()) // - .withClientId(savingsAccount.clientId()) // - .withGroupId(savingsAccount.groupId()) // - .withSavingsId(savingsId) // - .with(changes) // - .build(); + .withCommandId(command.commandId()) // + .withEntityId(savingsId) // + .withOfficeId(savingsAccount.officeId()) // + .withClientId(savingsAccount.clientId()) // + .withGroupId(savingsAccount.groupId()) // + .withSavingsId(savingsId) // + .with(changes) // + .build(); } @Transactional @@ -349,14 +351,14 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(savingsId) // - .withOfficeId(savingsAccount.officeId()) // - .withClientId(savingsAccount.clientId()) // - .withGroupId(savingsAccount.groupId()) // - .withSavingsId(savingsId) // - .with(changes) // - .build(); + .withCommandId(command.commandId()) // + .withEntityId(savingsId) // + .withOfficeId(savingsAccount.officeId()) // + .withClientId(savingsAccount.clientId()) // + .withGroupId(savingsAccount.groupId()) // + .withSavingsId(savingsId) // + .with(changes) // + .build(); } @Transactional @@ -383,14 +385,14 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(savingsId) // - .withOfficeId(savingsAccount.officeId()) // - .withClientId(savingsAccount.clientId()) // - .withGroupId(savingsAccount.groupId()) // - .withSavingsId(savingsId) // - .with(changes) // - .build(); + .withCommandId(command.commandId()) // + .withEntityId(savingsId) // + .withOfficeId(savingsAccount.officeId()) // + .withClientId(savingsAccount.clientId()) // + .withGroupId(savingsAccount.groupId()) // + .withSavingsId(savingsId) // + .with(changes) // + .build(); } @Transactional @@ -417,14 +419,14 @@ public class SavingsApplicationProcessWritePlatformServiceJpaRepositoryImpl impl } return new CommandProcessingResultBuilder() // - .withCommandId(command.commandId()) // - .withEntityId(savingsId) // - .withOfficeId(savingsAccount.officeId()) // - .withClientId(savingsAccount.clientId()) // - .withGroupId(savingsAccount.groupId()) // - .withSavingsId(savingsId) // - .with(changes) // - .build(); + .withCommandId(command.commandId()) // + .withEntityId(savingsId) // + .withOfficeId(savingsAccount.officeId()) // + .withClientId(savingsAccount.clientId()) // + .withGroupId(savingsAccount.groupId()) // + .withSavingsId(savingsId) // + .with(changes) // + .build(); } private void postJournalEntries(final SavingsAccount savingsAccount, final List existingTransactionIds, diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java index 8e884d64c..c3daa0a16 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsDropdownReadPlatformServiceImpl.java @@ -23,7 +23,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe @Override public Collection retrievewithdrawalFeeTypeOptions() { - List allowedOptions = Arrays.asList( // + final List allowedOptions = Arrays.asList( // SavingsEnumerations.withdrawalFeeType(SavingsWithdrawalFeesType.FLAT), // SavingsEnumerations.withdrawalFeeType(SavingsWithdrawalFeesType.PERCENT_OF_AMOUNT) // ); @@ -33,7 +33,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe @Override public List retrieveLockinPeriodFrequencyTypeOptions() { - List allowedLockinPeriodFrequencyTypeOptions = Arrays.asList( // + final List allowedLockinPeriodFrequencyTypeOptions = Arrays.asList( // SavingsEnumerations.lockinPeriodFrequencyType(SavingsPeriodFrequencyType.DAYS), // SavingsEnumerations.lockinPeriodFrequencyType(SavingsPeriodFrequencyType.WEEKS), // SavingsEnumerations.lockinPeriodFrequencyType(SavingsPeriodFrequencyType.MONTHS), // @@ -45,15 +45,21 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe @Override public Collection retrieveCompoundingInterestPeriodTypeOptions() { - List allowedOptions = Arrays.asList( // + final List allowedOptions = Arrays.asList( // SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.DAILY), // -// SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.WEEKLY), // -// SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.BIWEEKLY), // + // SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.WEEKLY), + // // + // SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.BIWEEKLY), + // // SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.MONTHLY) -// SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.QUATERLY), // -// SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.BI_ANNUAL), // -// SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.ANNUAL), // -// SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.NO_COMPOUNDING_SIMPLE_INTEREST) // + // SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.QUATERLY), + // // + // SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.BI_ANNUAL), + // // + // SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.ANNUAL), + // // + // SavingsEnumerations.compoundingInterestPeriodType(SavingsCompoundingInterestPeriodType.NO_COMPOUNDING_SIMPLE_INTEREST) + // // ); return allowedOptions; @@ -61,7 +67,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe @Override public Collection retrieveInterestPostingPeriodTypeOptions() { - List allowedOptions = Arrays.asList( // + final List allowedOptions = Arrays.asList( // SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType.MONTHLY), // SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType.QUATERLY), // SavingsEnumerations.interestPostingPeriodType(SavingsPostingInterestPeriodType.ANNUAL) // @@ -72,7 +78,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe @Override public Collection retrieveInterestCalculationTypeOptions() { - List allowedOptions = Arrays.asList( // + final List allowedOptions = Arrays.asList( // SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType.DAILY_BALANCE), // SavingsEnumerations.interestCalculationType(SavingsInterestCalculationType.AVERAGE_DAILY_BALANCE) // ); @@ -82,7 +88,7 @@ public class SavingsDropdownReadPlatformServiceImpl implements SavingsDropdownRe @Override public Collection retrieveInterestCalculationDaysInYearTypeOptions() { - List allowedOptions = Arrays.asList( // + final List allowedOptions = Arrays.asList( // SavingsEnumerations.interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.DAYS_360), // SavingsEnumerations.interestCalculationDaysInYearType(SavingsInterestCalculationDaysInYearType.DAYS_365) // ); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java index 7dddf9fec..1316ccd2d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/savings/service/SavingsProductWritePlatformServiceJpaRepositoryImpl.java @@ -73,7 +73,7 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi } private void logAsErrorUnexpectedDataIntegrityException(final DataAccessException dae) { - logger.error(dae.getMessage(), dae); + this.logger.error(dae.getMessage(), dae); } @Transactional @@ -88,12 +88,12 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi this.savingProductRepository.save(product); // save accounting mappings - accountMappingWritePlatformService.createSavingProductToGLAccountMapping(product.getId(), command); + this.accountMappingWritePlatformService.createSavingProductToGLAccountMapping(product.getId(), command); return new CommandProcessingResultBuilder() // .withEntityId(product.getId()) // .build(); - } catch (DataAccessException e) { + } catch (final DataAccessException e) { handleDataIntegrityIssues(command, e); return CommandProcessingResult.empty(); } @@ -113,17 +113,18 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi final Map changes = product.update(command); if (changes.containsKey(chargesParamName)) { - final Set savingsProductCharges = this.savingsProductAssembler.assembleListOfSavingsProductCharges(command, product.currency().getCode()); - boolean updated = product.update(savingsProductCharges); + final Set savingsProductCharges = this.savingsProductAssembler.assembleListOfSavingsProductCharges(command, product + .currency().getCode()); + final boolean updated = product.update(savingsProductCharges); if (!updated) { changes.remove(chargesParamName); } } - + // accounting related changes - boolean accountingTypeChanged = changes.containsKey(accountingRuleParamName); - final Map accountingMappingChanges = accountMappingWritePlatformService.updateSavingsProductToGLAccountMapping( - product.getId(), command, accountingTypeChanged, product.getAccountingType()); + final boolean accountingTypeChanged = changes.containsKey(accountingRuleParamName); + final Map accountingMappingChanges = this.accountMappingWritePlatformService + .updateSavingsProductToGLAccountMapping(product.getId(), command, accountingTypeChanged, product.getAccountingType()); changes.putAll(accountingMappingChanges); if (!changes.isEmpty()) { @@ -133,7 +134,7 @@ public class SavingsProductWritePlatformServiceJpaRepositoryImpl implements Savi return new CommandProcessingResultBuilder() // .withEntityId(product.getId()) // .with(changes).build(); - } catch (DataAccessException e) { + } catch (final DataAccessException e) { handleDataIntegrityIssues(command, e); return CommandProcessingResult.empty(); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/SearchConstants.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/SearchConstants.java index a34284ed1..b76e42180 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/SearchConstants.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/SearchConstants.java @@ -22,7 +22,7 @@ public class SearchConstants { private static final Set values = new HashSet(); static { - for (SEARCH_RESPONSE_PARAMETERS param : SEARCH_RESPONSE_PARAMETERS.values()) { + for (final SEARCH_RESPONSE_PARAMETERS param : SEARCH_RESPONSE_PARAMETERS.values()) { values.add(param.value); } } @@ -40,7 +40,7 @@ public class SearchConstants { return this.value; } } - + public static enum SEARCH_SUPPORTED_PARAMETERS { QUERY("query"), RESOURCE("resource"); @@ -52,7 +52,7 @@ public class SearchConstants { private static final Set values = new HashSet(); static { - for (SEARCH_SUPPORTED_PARAMETERS param : SEARCH_SUPPORTED_PARAMETERS.values()) { + for (final SEARCH_SUPPORTED_PARAMETERS param : SEARCH_SUPPORTED_PARAMETERS.values()) { values.add(param.value); } } @@ -82,7 +82,7 @@ public class SearchConstants { private static final Set values = new HashSet(); static { - for (SEARCH_SUPPORTED_RESOURCES param : SEARCH_SUPPORTED_RESOURCES.values()) { + for (final SEARCH_SUPPORTED_RESOURCES param : SEARCH_SUPPORTED_RESOURCES.values()) { values.add(param.value); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/api/SearchApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/api/SearchApiResource.java index e336e4425..da4e57a74 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/api/SearchApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/api/SearchApiResource.java @@ -59,7 +59,7 @@ public class SearchApiResource { final Collection searchResults = this.searchReadPlatformService.retriveMatchingData(searchConditions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, searchResults, searchResponseParameters); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, searchResults, this.searchResponseParameters); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/data/SearchConditions.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/data/SearchConditions.java index ec0b7be4a..b8c0f5fb9 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/data/SearchConditions.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/data/SearchConditions.java @@ -7,24 +7,30 @@ package org.mifosplatform.portfolio.search.data; import org.mifosplatform.portfolio.search.SearchConstants.SEARCH_SUPPORTED_RESOURCES; - public class SearchConditions { - + private final String searchQuery; private final String searchResource; private final Boolean clientSearch; private final Boolean groupSearch; private final Boolean loanSeach; private final Boolean clientIdentifierSearch; - public SearchConditions(String searchQueryParam, String searchResource) { + + public SearchConditions(final String searchQueryParam, final String searchResource) { this.searchQuery = searchQueryParam; this.searchResource = searchResource; - this.clientSearch = (null == searchResource || searchResource.toLowerCase().contains(SEARCH_SUPPORTED_RESOURCES.CLIENTS.name().toLowerCase()))? true : false; - this.groupSearch = (null == searchResource || searchResource.toLowerCase().contains(SEARCH_SUPPORTED_RESOURCES.GROUPS.name().toLowerCase()))? true : false; - this.loanSeach = (null == searchResource || searchResource.toLowerCase().contains(SEARCH_SUPPORTED_RESOURCES.LOANS.name().toLowerCase()))? true : false; - this.clientIdentifierSearch = (null == searchResource || searchResource.toLowerCase().contains(SEARCH_SUPPORTED_RESOURCES.CLIENTIDENTIFIERS.name().toLowerCase()))? true : false; + this.clientSearch = (null == searchResource || searchResource.toLowerCase().contains( + SEARCH_SUPPORTED_RESOURCES.CLIENTS.name().toLowerCase())) ? true : false; + this.groupSearch = (null == searchResource || searchResource.toLowerCase().contains( + SEARCH_SUPPORTED_RESOURCES.GROUPS.name().toLowerCase())) ? true : false; + this.loanSeach = (null == searchResource || searchResource.toLowerCase().contains( + SEARCH_SUPPORTED_RESOURCES.LOANS.name().toLowerCase())) ? true : false; + this.clientIdentifierSearch = (null == searchResource || searchResource.toLowerCase().contains( + SEARCH_SUPPORTED_RESOURCES.CLIENTIDENTIFIERS.name().toLowerCase())) ? true : false; } - public SearchConditions(String searchQueryParam, String searchResource, Boolean clientSearch, Boolean groupSearch, Boolean loanSeach, Boolean clientIdentifierSearch) { + + public SearchConditions(final String searchQueryParam, final String searchResource, final Boolean clientSearch, + final Boolean groupSearch, final Boolean loanSeach, final Boolean clientIdentifierSearch) { this.searchQuery = searchQueryParam; this.searchResource = searchResource; this.clientSearch = clientSearch; @@ -32,30 +38,29 @@ public class SearchConditions { this.loanSeach = loanSeach; this.clientIdentifierSearch = clientIdentifierSearch; } - + public String getSearchQuery() { return this.searchQuery; } - + public String getSearchResource() { return this.searchResource; } - + public Boolean isClientSearch() { return this.clientSearch; } - + public Boolean isGroupSearch() { return this.groupSearch; } - + public Boolean isLoanSeach() { return this.loanSeach; } - + public Boolean isClientIdentifierSearch() { return this.clientIdentifierSearch; } - } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/data/SearchData.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/data/SearchData.java index 66351944b..7dd4a4458 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/data/SearchData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/data/SearchData.java @@ -5,9 +5,8 @@ */ package org.mifosplatform.portfolio.search.data; - public class SearchData { - + private final Long entityId; private final String entityAccountNo; private final String entityExternalId; @@ -15,9 +14,10 @@ public class SearchData { private final String entityType; private final Long parentId; private final String parentName; - - public SearchData(Long entityId, String entityAccountNo, String entityExternalId, String entityName, String entityType, Long parentId, String parentName) { - + + public SearchData(final Long entityId, final String entityAccountNo, final String entityExternalId, final String entityName, + final String entityType, final Long parentId, final String parentName) { + this.entityId = entityId; this.entityAccountNo = entityAccountNo; this.entityExternalId = entityExternalId; @@ -27,41 +27,32 @@ public class SearchData { this.parentName = parentName; } - public Long getEntityId() { return this.entityId; } - public String getEntityAccountNo() { return this.entityAccountNo; } - public String getEntityExternalId() { return this.entityExternalId; } - public String getEntityName() { return this.entityName; } - public String getEntityType() { return this.entityType; } - - public Long getParentId() { return this.parentId; } - - public String getParentName() { return this.parentName; } - + } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java index fb6edb452..7db4df4df 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/search/service/SearchReadPlatformServiceImpl.java @@ -35,12 +35,12 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService @Override public Collection retriveMatchingData(final SearchConditions searchConditions) { - AppUser currentUser = context.authenticatedUser(); - String hierarchy = currentUser.getOffice().getHierarchy(); + final AppUser currentUser = this.context.authenticatedUser(); + final String hierarchy = currentUser.getOffice().getHierarchy(); - SearchMapper rm = new SearchMapper(); + final SearchMapper rm = new SearchMapper(); - MapSqlParameterSource params = new MapSqlParameterSource(); + final MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("hierarchy", hierarchy + "%"); params.addValue("search", searchConditions.getSearchQuery()); params.addValue("partialSearch", "%" + searchConditions.getSearchQuery() + "%"); @@ -52,44 +52,44 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService public String searchSchema(final SearchConditions searchConditions) { - String union = " union "; - String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + final String union = " union "; + final String clientExactMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + " , c.office_id as parentId, o.name as parentName " + " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :search or c.display_name like :search or c.external_id like :search)) "; - String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + final String clientMatchSql = " (select 'CLIENT' as entityType, c.id as entityId, c.display_name as entityName, c.external_id as entityExternalId, c.account_no as entityAccountNo " + " , c.office_id as parentId, o.name as parentName " + " from m_client c join m_office o on o.id = c.office_id where o.hierarchy like :hierarchy and (c.account_no like :partialSearch and c.account_no not like :search) or " + "(c.display_name like :partialSearch and c.display_name not like :search) or " + "(c.external_id like :partialSearch and c.external_id not like :search))"; - String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + final String loanExactMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + " , c.id as parentId, c.display_name as parentName " + " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :search) "; - String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + final String loanMatchSql = " (select 'LOAN' as entityType, l.id as entityId, pl.name as entityName, l.external_id as entityExternalId, l.account_no as entityAccountNo " + " , c.id as parentId, c.display_name as parentName " + " from m_loan l join m_client c on l.client_id = c.id join m_office o on o.id = c.office_id join m_product_loan pl on pl.id=l.product_id where o.hierarchy like :hierarchy and l.account_no like :partialSearch and l.account_no not like :search) "; - String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + final String clientIdentifierExactMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName " + " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id " + " where o.hierarchy like :hierarchy and ci.document_key like :search) "; - - String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + + final String clientIdentifierMatchSql = " (select 'CLIENTIDENTIFIER' as entityType, ci.id as entityId, ci.document_key as entityName, " + " null as entityExternalId, null as entityAccountNo, c.id as parentId, c.display_name as parentName " + " from m_client_identifier ci join m_client c on ci.client_id=c.id join m_office o on o.id = c.office_id " + " where o.hierarchy like :hierarchy and ci.document_key like :partialSearch and ci.document_key not like :search) "; - String groupExactMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + final String groupExactMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + " , g.office_id as parentId, o.name as parentName " + " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :search) "; - String groupMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + final String groupMatchSql = " (select IF(g.level_id=1,'CENTER','GROUP') as entityType, g.id as entityId, g.display_name as entityName, g.external_id as entityExternalId, NULL as entityAccountNo " + " , g.office_id as parentId, o.name as parentName " + " from m_group g join m_office o on o.id = g.office_id where o.hierarchy like :hierarchy and g.display_name like :partialSearch and g.display_name not like :search) "; - StringBuffer sql = new StringBuffer(); + final StringBuffer sql = new StringBuffer(); // first include all exact matches if (searchConditions.isClientSearch()) { @@ -100,10 +100,10 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService sql.append(loanExactMatchSql).append(union); } - if(searchConditions.isClientIdentifierSearch()){ + if (searchConditions.isClientIdentifierSearch()) { sql.append(clientIdentifierExactMatchSql).append(union); } - + if (searchConditions.isGroupSearch()) { sql.append(groupExactMatchSql).append(union); } @@ -116,8 +116,8 @@ public class SearchReadPlatformServiceImpl implements SearchReadPlatformService if (searchConditions.isLoanSeach()) { sql.append(loanMatchSql).append(union); } - - if(searchConditions.isClientIdentifierSearch()){ + + if (searchConditions.isClientIdentifierSearch()) { sql.append(clientIdentifierMatchSql).append(union); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/data/TransfersDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/data/TransfersDataValidator.java index 70bb54a5a..1ea8a16ca 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/data/TransfersDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/data/TransfersDataValidator.java @@ -105,7 +105,7 @@ public final class TransfersDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(ClientApiConstants.CLIENT_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); if (this.fromApiJsonHelper.parameterExists(TransferApiConstants.newStaffIdParamName, element)) { final Long newStaffId = this.fromApiJsonHelper.extractLongNamed(TransferApiConstants.newStaffIdParamName, element); @@ -134,7 +134,7 @@ public final class TransfersDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(ClientApiConstants.CLIENT_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); validateNote(baseDataValidator, element); @@ -151,7 +151,7 @@ public final class TransfersDataValidator { final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource(ClientApiConstants.CLIENT_RESOURCE_NAME); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); validateNote(baseDataValidator, element); @@ -159,7 +159,7 @@ public final class TransfersDataValidator { } private void validateNote(final DataValidatorBuilder baseDataValidator, final JsonElement element) { - final String note = fromApiJsonHelper.extractStringNamed(TransferApiConstants.note, element); + final String note = this.fromApiJsonHelper.extractStringNamed(TransferApiConstants.note, element); baseDataValidator.reset().parameter(TransferApiConstants.note).value(note).notExceedingLengthOf(1000); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/service/TransferEventType.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/service/TransferEventType.java index 9c365cd43..e101fe2c8 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/service/TransferEventType.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/service/TransferEventType.java @@ -5,7 +5,6 @@ */ package org.mifosplatform.portfolio.transfer.service; - public enum TransferEventType { PROPOSAL(1, "transferEvent.proposal"), ACCEPTANCE(2, "transferEvent.acceptance"), WITHDRAWAL(3, "transferEvent.withdrawal"), REJECTION( 4, "transferEvent.rejection"); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/service/TransferWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/service/TransferWritePlatformServiceJpaRepositoryImpl.java index 6467b1fbf..255afe106 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/service/TransferWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/portfolio/transfer/service/TransferWritePlatformServiceJpaRepositoryImpl.java @@ -90,7 +90,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr @Override @Transactional - public CommandProcessingResult transferClientsBetweenGroups(Long sourceGroupId, JsonCommand jsonCommand) { + public CommandProcessingResult transferClientsBetweenGroups(final Long sourceGroupId, final JsonCommand jsonCommand) { this.transfersDataValidator.validateForClientsTransferBetweenGroups(jsonCommand.json()); final Group sourceGroup = this.groupRepository.findOneWithNotFoundDetection(sourceGroupId); @@ -105,7 +105,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr staff = this.staffRepositoryWrapper.findByOfficeHierarchyWithNotFoundDetection(staffId, sourceOffice.getHierarchy()); } - final List clients = this.assembleListOfClients(jsonCommand); + final List clients = assembleListOfClients(jsonCommand); if (sourceGroupId == destinationGroupId) { throw new TransferNotSupportedException( TRANSFER_NOT_SUPPORTED_REASON.SOURCE_AND_DESTINATION_GROUP_CANNOT_BE_SAME, sourceGroupId, destinationGroupId); } @@ -114,7 +114,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr if (!(sourceOffice.getId() == destinationGroup.getOffice().getId())) { throw new TransferNotSupportedException( TRANSFER_NOT_SUPPORTED_REASON.BULK_CLIENT_TRANSFER_ACROSS_BRANCHES, sourceGroupId, destinationGroupId); } - for (Client client : clients) { + for (final Client client : clients) { transferClientBetweenGroups(sourceGroup, client, destinationGroup, inheritDestinationGroupLoanOfficer, staff); } @@ -165,8 +165,8 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr TRANSFER_NOT_SUPPORTED_REASON.DESTINATION_GROUP_HAS_NO_MEETING, destinationGroup.getId()); } - Calendar sourceGroupCalendar = sourceGroupCalendarInstance.getCalendar(); - Calendar destinationGroupCalendar = destinationGroupCalendarInstance.getCalendar(); + final Calendar sourceGroupCalendar = sourceGroupCalendarInstance.getCalendar(); + final Calendar destinationGroupCalendar = destinationGroupCalendarInstance.getCalendar(); /*** * Ensure that the recurrence pattern are same for collection @@ -178,7 +178,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr destinationGroup.getId()); } /** map all JLG loans for this client to the destinationGroup **/ - for (CalendarInstance calendarInstance : activeLoanCalendarInstances) { + for (final CalendarInstance calendarInstance : activeLoanCalendarInstances) { calendarInstance.updateCalendar(destinationGroupCalendar); this.calendarInstanceRepository.save(calendarInstance); } @@ -190,7 +190,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr * Now Change the loan officer for this client and all his active JLG * loans **/ - Staff destinationGroupLoanOfficer = destinationGroup.getStaff(); + final Staff destinationGroupLoanOfficer = destinationGroup.getStaff(); if (destinationGroupLoanOfficer != null) { client.updateStaff(destinationGroupLoanOfficer); } @@ -201,8 +201,8 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr /** * Active JLG loans are now linked to the new Group and Loan officer **/ - List allClientJLGLoans = loanRepository.findByClientIdAndGroupId(client.getId(), sourceGroup.getId()); - for (Loan loan : allClientJLGLoans) { + final List allClientJLGLoans = this.loanRepository.findByClientIdAndGroupId(client.getId(), sourceGroup.getId()); + for (final Loan loan : allClientJLGLoans) { if (loan.status().isActiveOrAwaitingApprovalOrDisbursal()) { loan.updateGroup(destinationGroup); if (inheritDestinationGroupLoanOfficer != null && inheritDestinationGroupLoanOfficer == true @@ -281,7 +281,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr @Override @Transactional - public CommandProcessingResult withdrawClientTransfer(Long clientId, JsonCommand jsonCommand) { + public CommandProcessingResult withdrawClientTransfer(final Long clientId, final JsonCommand jsonCommand) { // validation this.transfersDataValidator.validateForWithdrawClientTransfer(jsonCommand.json()); final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId); @@ -298,7 +298,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr @Override @Transactional - public CommandProcessingResult rejectClientTransfer(Long clientId, JsonCommand jsonCommand) { + public CommandProcessingResult rejectClientTransfer(final Long clientId, final JsonCommand jsonCommand) { // validation this.transfersDataValidator.validateForRejectClientTransfer(jsonCommand.json()); final Client client = this.clientRepository.findOneWithNotFoundDetection(clientId); @@ -312,8 +312,8 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr } private void handleClientTransferLifecycleEvent(final Client client, final Office destinationOffice, - TransferEventType transferEventType, JsonCommand jsonCommand) { - Date todaysDate = DateUtils.getDateOfTenant(); + final TransferEventType transferEventType, final JsonCommand jsonCommand) { + final Date todaysDate = DateUtils.getDateOfTenant(); /** Get destination loan officer if exists **/ Staff staff = null; Group destinationGroup = null; @@ -327,9 +327,9 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr } /*** Handle Active Loans ***/ - if (loanRepository.doNonClosedLoanAccountsExistForClient(client.getId())) { + if (this.loanRepository.doNonClosedLoanAccountsExistForClient(client.getId())) { // get each individual loan for the client - for (Loan loan : loanRepository.findLoanByClientId(client.getId())) { + for (final Loan loan : this.loanRepository.findLoanByClientId(client.getId())) { /** * We need to create transactions etc only for loans which are * disbursed and not yet closed @@ -354,9 +354,9 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr } /*** Handle Active Savings (Currently throw and exception) ***/ - if (savingsAccountRepository.doNonClosedSavingAccountsExistForClient(client.getId())) { + if (this.savingsAccountRepository.doNonClosedSavingAccountsExistForClient(client.getId())) { // get each individual saving account for the client - for (SavingsAccount savingsAccount : savingsAccountRepository.findSavingAccountByClientId(client.getId())) { + for (final SavingsAccount savingsAccount : this.savingsAccountRepository.findSavingAccountByClientId(client.getId())) { if (!savingsAccount.isClosed()) { switch (transferEventType) { case ACCEPTANCE: @@ -411,7 +411,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr client.updateTransferToOffice(null); } - noteWritePlatformService.createAndPersistClientNote(client, jsonCommand); + this.noteWritePlatformService.createAndPersistClientNote(client, jsonCommand); } private List assembleListOfClients(final JsonCommand command) { @@ -419,7 +419,7 @@ public class TransferWritePlatformServiceJpaRepositoryImpl implements TransferWr final List clients = new ArrayList(); if (command.parameterExists(TransferApiConstants.clients)) { - JsonArray clientsArray = command.arrayOfParameterNamed(TransferApiConstants.clients); + final JsonArray clientsArray = command.arrayOfParameterNamed(TransferApiConstants.clients); if (clientsArray != null) { for (int i = 0; i < clientsArray.size(); i++) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/scheduledjobs/service/ScheduledJobRunnerServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/scheduledjobs/service/ScheduledJobRunnerServiceImpl.java index 88e1449b1..c71632ddb 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/scheduledjobs/service/ScheduledJobRunnerServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/scheduledjobs/service/ScheduledJobRunnerServiceImpl.java @@ -47,9 +47,9 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService @CronTarget(jobName = JobName.UPDATE_LOAN_SUMMARY) public void updateLoanSummaryDetails() { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceServiceFactory.determineDataSourceService().retrieveDataSource()); + final JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSourceServiceFactory.determineDataSourceService().retrieveDataSource()); - StringBuilder updateSqlBuilder = new StringBuilder(900); + final StringBuilder updateSqlBuilder = new StringBuilder(900); updateSqlBuilder.append("update m_loan "); updateSqlBuilder.append("join ("); updateSqlBuilder.append("SELECT ml.id AS loanId,"); @@ -118,7 +118,7 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService updateSqlBuilder .append(" (x.penalty_charges_charged_derived - (x.penalty_charges_repaid_derived + x.penalty_charges_waived_derived + x.penalty_charges_writtenoff_derived))"); - int result = jdbcTemplate.update(updateSqlBuilder.toString()); + final int result = jdbcTemplate.update(updateSqlBuilder.toString()); logger.info(ThreadLocalContextUtil.getTenant().getName() + ": Results affected by update: " + result); } @@ -128,11 +128,11 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService @CronTarget(jobName = JobName.UPDATE_LOAN_ARREARS_AGEING) public void updateLoanArrearsAgeingDetails() { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceServiceFactory.determineDataSourceService().retrieveDataSource()); + final JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSourceServiceFactory.determineDataSourceService().retrieveDataSource()); jdbcTemplate.execute("truncate table m_loan_arrears_aging"); - StringBuilder updateSqlBuilder = new StringBuilder(900); + final StringBuilder updateSqlBuilder = new StringBuilder(900); updateSqlBuilder .append("INSERT INTO m_loan_arrears_aging(`loan_id`,`principal_overdue_derived`,`interest_overdue_derived`,`fee_charges_overdue_derived`,`penalty_charges_overdue_derived`,`total_overdue_derived`,`overdue_since_date_derived`)"); @@ -158,7 +158,7 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService updateSqlBuilder.append(" and mr.duedate < CURDATE() "); updateSqlBuilder.append(" GROUP BY ml.id"); - int result = jdbcTemplate.update(updateSqlBuilder.toString()); + final int result = jdbcTemplate.update(updateSqlBuilder.toString()); logger.info(ThreadLocalContextUtil.getTenant().getName() + ": Results affected by update: " + result); } @@ -168,11 +168,11 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService @CronTarget(jobName = JobName.UPDATE_LOAN_PAID_IN_ADVANCE) public void updateLoanPaidInAdvance() { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceServiceFactory.determineDataSourceService().retrieveDataSource()); + final JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSourceServiceFactory.determineDataSourceService().retrieveDataSource()); jdbcTemplate.execute("truncate table m_loan_paid_in_advance"); - StringBuilder updateSqlBuilder = new StringBuilder(900); + final StringBuilder updateSqlBuilder = new StringBuilder(900); updateSqlBuilder .append("INSERT INTO m_loan_paid_in_advance(loan_id, principal_in_advance_derived, interest_in_advance_derived, fee_charges_in_advance_derived, penalty_charges_in_advance_derived, total_in_advance_derived)"); @@ -193,7 +193,7 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService updateSqlBuilder .append(" SUM(ifnull(mr.fee_charges_completed_derived, 0)) + SUM(ifnull(mr.penalty_charges_completed_derived, 0))) > 0.0"); - int result = jdbcTemplate.update(updateSqlBuilder.toString()); + final int result = jdbcTemplate.update(updateSqlBuilder.toString()); logger.info(ThreadLocalContextUtil.getTenant().getName() + ": Results affected by update: " + result); } @@ -202,18 +202,19 @@ public class ScheduledJobRunnerServiceImpl implements ScheduledJobRunnerService @Override @CronTarget(jobName = JobName.APPLY_ANNUAL_FEE_FOR_SAVINGS) public void applyAnnualFeeForSavings() { - + final Collection annualFeeData = this.savingsAccountReadPlatformService .retrieveAccountsWithAnnualFeeDue(); - for (SavingsAccountAnnualFeeData savingsAccountReference : annualFeeData) { - try{ + for (final SavingsAccountAnnualFeeData savingsAccountReference : annualFeeData) { + try { this.savingsAccountWritePlatformService.applyAnnualFee(savingsAccountReference.getId(), savingsAccountReference.getNextAnnualFeeDueDate()); - } catch (PlatformApiDataValidationException e) { - List errors = e.getErrors(); - for(ApiParameterError error : errors){ - logger.error("Apply annual fee failed for account:"+savingsAccountReference.getAccountNo()+" with message "+error.getDeveloperMessage()); + } catch (final PlatformApiDataValidationException e) { + final List errors = e.getErrors(); + for (final ApiParameterError error : errors) { + logger.error("Apply annual fee failed for account:" + savingsAccountReference.getAccountNo() + " with message " + + error.getDeveloperMessage()); } } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/api/PermissionsApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/api/PermissionsApiResource.java index 652b7ed3c..d010ab24c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/api/PermissionsApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/api/PermissionsApiResource.java @@ -65,9 +65,9 @@ public class PermissionsApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllPermissions(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); Collection permissions = null; if (settings.isMakerCheckerable()) { @@ -76,7 +76,7 @@ public class PermissionsApiResource { permissions = this.permissionReadPlatformService.retrieveAllPermissions(); } - return this.toApiJsonSerializer.serialize(settings, permissions, RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, permissions, this.RESPONSE_DATA_PARAMETERS); } @PUT diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/api/RolesApiResource.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/api/RolesApiResource.java index e2f56da4f..f4354b378 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/api/RolesApiResource.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/api/RolesApiResource.java @@ -86,12 +86,12 @@ public class RolesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveAllRoles(@Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); final Collection roles = this.roleReadPlatformService.retrieveAll(); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); - return this.toApiJsonSerializer.serialize(settings, roles, RESPONSE_DATA_PARAMETERS); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + return this.toApiJsonSerializer.serialize(settings, roles, this.RESPONSE_DATA_PARAMETERS); } @POST @@ -115,13 +115,13 @@ public class RolesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveRole(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final RoleData role = this.roleReadPlatformService.retrieveOne(roleId); - return this.toApiJsonSerializer.serialize(settings, role, RESPONSE_DATA_PARAMETERS); + return this.toApiJsonSerializer.serialize(settings, role, this.RESPONSE_DATA_PARAMETERS); } @PUT @@ -146,14 +146,14 @@ public class RolesApiResource { @Produces({ MediaType.APPLICATION_JSON }) public String retrieveRolePermissions(@PathParam("roleId") final Long roleId, @Context final UriInfo uriInfo) { - context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); + this.context.authenticatedUser().validateHasReadPermission(this.resourceNameForPermissions); - final ApiRequestJsonSerializationSettings settings = apiRequestParameterHelper.process(uriInfo.getQueryParameters()); + final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); final RoleData role = this.roleReadPlatformService.retrieveOne(roleId); final Collection permissionUsageData = this.permissionReadPlatformService.retrieveAllRolePermissions(roleId); final RolePermissionsData permissionsData = role.toRolePermissionData(permissionUsageData); - return this.permissionsToApiJsonSerializer.serialize(settings, permissionsData, PERMISSIONS_RESPONSE_DATA_PARAMETERS); + return this.permissionsToApiJsonSerializer.serialize(settings, permissionsData, this.PERMISSIONS_RESPONSE_DATA_PARAMETERS); } @PUT diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/data/AppUserData.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/data/AppUserData.java index 3959ade25..f30776389 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/data/AppUserData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/data/AppUserData.java @@ -27,7 +27,7 @@ public class AppUserData { private final Collection availableRoles; private final Collection selectedRoles; - public static AppUserData template(AppUserData user, Collection officesForDropdown) { + public static AppUserData template(final AppUserData user, final Collection officesForDropdown) { return new AppUserData(user.id, user.username, user.email, user.officeId, user.officeName, user.firstname, user.lastname, user.availableRoles, user.selectedRoles, officesForDropdown); } @@ -35,7 +35,7 @@ public class AppUserData { public static AppUserData template(final Collection offices, final Collection availableRoles) { return new AppUserData(null, null, null, null, null, null, null, availableRoles, null, offices); } - + public static AppUserData dropdown(final Long id, final String username) { return new AppUserData(id, username, null, null, null, null, null, null, null, null); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/data/RoleData.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/data/RoleData.java index cd3e70909..ef25de8af 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/data/RoleData.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/data/RoleData.java @@ -18,7 +18,7 @@ public class RoleData implements Serializable { private final String description; public RolePermissionsData toRolePermissionData(final Collection permissionUsageData) { - return new RolePermissionsData(id, name, description, permissionUsageData); + return new RolePermissionsData(this.id, this.name, this.description, permissionUsageData); } public RoleData(final Long id, final String name, final String description) { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUser.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUser.java index 4e1e6f55b..eb8deba31 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUser.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUser.java @@ -243,7 +243,7 @@ public class AppUser extends AbstractPersistable implements PlatformUser { /** * Delete is a soft delete. Updates flag so it wont appear in * query/report results. - * + * * Any fields with unique constraints and prepended with id of record. */ public void delete() { @@ -455,7 +455,8 @@ public class AppUser extends AbstractPersistable implements PlatformUser { public void validateHasReadPermission(final String function, final Long userId) { if ("USER".equalsIgnoreCase(function) && userId.equals(getId())) { - // abstain from validation as user allowed fetch their own data no matter what permissions they have. + // abstain from validation as user allowed fetch their own data no + // matter what permissions they have. } else { validateHasPermissionTo(function); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUserRepository.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUserRepository.java index 295e53b84..b15053cd3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUserRepository.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/AppUserRepository.java @@ -10,5 +10,5 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface AppUserRepository extends JpaRepository, JpaSpecificationExecutor, PlatformUserRepository { - // no behaviour added + // no behaviour added } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/JpaUserDomainService.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/JpaUserDomainService.java index 6ed40691a..0c5fcc40c 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/JpaUserDomainService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/JpaUserDomainService.java @@ -33,7 +33,7 @@ public class JpaUserDomainService implements UserDomainService { generateKeyUsedForPasswordSalting(appUser); - String unencodedPassword = appUser.getPassword(); + final String unencodedPassword = appUser.getPassword(); final String encodePassword = this.applicationPasswordEncoder.encode(appUser); appUser.updatePassword(encodePassword); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/Permission.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/Permission.java index aedfd1e77..0ebfcf270 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/Permission.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/Permission.java @@ -15,58 +15,57 @@ import org.springframework.data.jpa.domain.AbstractPersistable; @Table(name = "m_permission") public class Permission extends AbstractPersistable { - @Column(name = "grouping", nullable = false, length = 45) - private final String grouping; + @Column(name = "grouping", nullable = false, length = 45) + private final String grouping; - @Column(name = "code", nullable = false, length = 100) - private final String code; + @Column(name = "code", nullable = false, length = 100) + private final String code; - @Column(name = "entity_name", nullable = true, length = 100) - private final String entityName; + @Column(name = "entity_name", nullable = true, length = 100) + private final String entityName; - @Column(name = "action_name", nullable = true, length = 100) - private final String actionName; + @Column(name = "action_name", nullable = true, length = 100) + private final String actionName; - @Column(name = "can_maker_checker", nullable = false) - private boolean canMakerChecker; + @Column(name = "can_maker_checker", nullable = false) + private boolean canMakerChecker; - public Permission(final String grouping, final String entityName, - final String actionName) { - this.grouping = grouping; - this.entityName = entityName; - this.actionName = actionName; - this.code = actionName + "_" + entityName; - this.canMakerChecker = false; - } + public Permission(final String grouping, final String entityName, final String actionName) { + this.grouping = grouping; + this.entityName = entityName; + this.actionName = actionName; + this.code = actionName + "_" + entityName; + this.canMakerChecker = false; + } - protected Permission() { - this.grouping = null; - this.entityName = null; - this.actionName = null; - this.code = null; - this.canMakerChecker = false; - } + protected Permission() { + this.grouping = null; + this.entityName = null; + this.actionName = null; + this.code = null; + this.canMakerChecker = false; + } - public boolean hasCode(final String checkCode) { - return this.code.equalsIgnoreCase(checkCode); - } + public boolean hasCode(final String checkCode) { + return this.code.equalsIgnoreCase(checkCode); + } - public String getCode() { - return this.code; - } + public String getCode() { + return this.code; + } - public boolean hasMakerCheckerEnabled() { - return this.canMakerChecker; - } + public boolean hasMakerCheckerEnabled() { + return this.canMakerChecker; + } - public String getGrouping() { - return this.grouping; - } + public String getGrouping() { + return this.grouping; + } - public boolean enableMakerChecker(final boolean canMakerChecker) { - final boolean isUpdatedValueSame = this.canMakerChecker == canMakerChecker; - this.canMakerChecker = canMakerChecker; + public boolean enableMakerChecker(final boolean canMakerChecker) { + final boolean isUpdatedValueSame = this.canMakerChecker == canMakerChecker; + this.canMakerChecker = canMakerChecker; - return !isUpdatedValueSame; - } + return !isUpdatedValueSame; + } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/UserDomainService.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/UserDomainService.java index bd87b7a5b..27b7559d6 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/UserDomainService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/domain/UserDomainService.java @@ -7,5 +7,5 @@ package org.mifosplatform.useradministration.domain; public interface UserDomainService { - void create(AppUser appUser,Boolean sendPasswordToEmail); + void create(AppUser appUser, Boolean sendPasswordToEmail); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/PasswordMustBeDifferentException.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/PasswordMustBeDifferentException.java index dea3cc9f8..d03d4b3ab 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/PasswordMustBeDifferentException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/PasswordMustBeDifferentException.java @@ -6,5 +6,5 @@ package org.mifosplatform.useradministration.exception; public class PasswordMustBeDifferentException extends RuntimeException { - // basic runtime exception + // basic runtime exception } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/PermissionCantBeMakerCheckerableException.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/PermissionCantBeMakerCheckerableException.java index acf4b2b81..8ba70a659 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/PermissionCantBeMakerCheckerableException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/PermissionCantBeMakerCheckerableException.java @@ -8,7 +8,8 @@ package org.mifosplatform.useradministration.exception; import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceNotFoundException; /** - * A {@link RuntimeException} thrown when permission is attempted to be set as maker-checker enabled. + * A {@link RuntimeException} thrown when permission is attempted to be set as + * maker-checker enabled. */ public class PermissionCantBeMakerCheckerableException extends AbstractPlatformResourceNotFoundException { diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/RoleNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/RoleNotFoundException.java index c73854e9a..1c49634b0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/RoleNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/RoleNotFoundException.java @@ -12,7 +12,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN */ public class RoleNotFoundException extends AbstractPlatformResourceNotFoundException { - public RoleNotFoundException(Long id) { + public RoleNotFoundException(final Long id) { super("error.msg.role.id.invalid", "Role with identifier " + id + " does not exist", id); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/UserNotFoundException.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/UserNotFoundException.java index fa61b3815..27b565d7d 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/UserNotFoundException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/UserNotFoundException.java @@ -12,7 +12,7 @@ import org.mifosplatform.infrastructure.core.exception.AbstractPlatformResourceN */ public class UserNotFoundException extends AbstractPlatformResourceNotFoundException { - public UserNotFoundException(Long id) { + public UserNotFoundException(final Long id) { super("error.msg.user.id.invalid", "User with identifier " + id + " does not exist", id); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/UsernameMustBeDifferentException.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/UsernameMustBeDifferentException.java index 867d43ab2..f29489371 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/UsernameMustBeDifferentException.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/exception/UsernameMustBeDifferentException.java @@ -6,5 +6,5 @@ package org.mifosplatform.useradministration.exception; public class UsernameMustBeDifferentException extends RuntimeException { - // basic runtime exception + // basic runtime exception } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/serialization/PermissionsCommandFromApiJsonDeserializer.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/serialization/PermissionsCommandFromApiJsonDeserializer.java index 6bef43f5f..0ca24c447 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/serialization/PermissionsCommandFromApiJsonDeserializer.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/serialization/PermissionsCommandFromApiJsonDeserializer.java @@ -46,8 +46,8 @@ public final class PermissionsCommandFromApiJsonDeserializer extends AbstractFro if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); - return fromApiJsonHelper.fromJson(json, PermissionsCommand.class); + return this.fromApiJsonHelper.fromJson(json, PermissionsCommand.class); } } \ No newline at end of file diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/AppUserReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/AppUserReadPlatformServiceImpl.java index c0a9dd881..a41375553 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/AppUserReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/AppUserReadPlatformServiceImpl.java @@ -52,24 +52,24 @@ public class AppUserReadPlatformServiceImpl implements AppUserReadPlatformServic @Cacheable(value = "users", key = "T(org.mifosplatform.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat(#root.target.context.authenticatedUser().getOffice().getHierarchy())") public Collection retrieveAllUsers() { - AppUser currentUser = context.authenticatedUser(); - String hierarchy = currentUser.getOffice().getHierarchy(); - String hierarchySearchString = hierarchy + "%"; + final AppUser currentUser = this.context.authenticatedUser(); + final String hierarchy = currentUser.getOffice().getHierarchy(); + final String hierarchySearchString = hierarchy + "%"; - AppUserMapper mapper = new AppUserMapper(); - String sql = "select " + mapper.schema(); + final AppUserMapper mapper = new AppUserMapper(); + final String sql = "select " + mapper.schema(); return this.jdbcTemplate.query(sql, mapper, new Object[] { hierarchySearchString }); } @Override public Collection retrieveSearchTemplate() { - AppUser currentUser = context.authenticatedUser(); - String hierarchy = currentUser.getOffice().getHierarchy(); - String hierarchySearchString = hierarchy + "%"; + final AppUser currentUser = this.context.authenticatedUser(); + final String hierarchy = currentUser.getOffice().getHierarchy(); + final String hierarchySearchString = hierarchy + "%"; - AppUserLookupMapper mapper = new AppUserLookupMapper(); - String sql = "select " + mapper.schema(); + final AppUserLookupMapper mapper = new AppUserLookupMapper(); + final String sql = "select " + mapper.schema(); return this.jdbcTemplate.query(sql, mapper, new Object[] { hierarchySearchString }); } @@ -86,16 +86,16 @@ public class AppUserReadPlatformServiceImpl implements AppUserReadPlatformServic @Override public AppUserData retrieveUser(final Long userId) { - context.authenticatedUser(); + this.context.authenticatedUser(); final AppUser user = this.appUserRepository.findOne(userId); if (user == null || user.isDeleted()) { throw new UserNotFoundException(userId); } - Collection availableRoles = this.roleReadPlatformService.retrieveAll(); + final Collection availableRoles = this.roleReadPlatformService.retrieveAll(); - Collection selectedUserRoles = new ArrayList(); - Set userRoles = user.getRoles(); - for (Role role : userRoles) { + final Collection selectedUserRoles = new ArrayList(); + final Set userRoles = user.getRoles(); + for (final Role role : userRoles) { selectedUserRoles.add(role.toData()); } @@ -145,7 +145,7 @@ public class AppUserReadPlatformServiceImpl implements AppUserReadPlatformServic + " join m_office o on o.id = u.office_id where o.hierarchy like ? and u.is_deleted=0 order by u.username"; } } - + public PlatformSecurityContext getContext() { return this.context; } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/AppUserWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/AppUserWritePlatformServiceJpaRepositoryImpl.java index 393958914..b1802c506 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/AppUserWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/AppUserWritePlatformServiceJpaRepositoryImpl.java @@ -71,7 +71,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit public CommandProcessingResult createUser(final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForCreate(command.json()); @@ -86,22 +86,22 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit final AppUser appUser = AppUser.fromJson(userOffice, allRoles, command); final Boolean sendPasswordToEmail = command.booleanObjectValueOfParameterNamed("sendPasswordToEmail"); - this.userDomainService.create(appUser,sendPasswordToEmail); + this.userDomainService.create(appUser, sendPasswordToEmail); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // .withEntityId(appUser.getId()) // .withOfficeId(userOffice.getId()) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); - } catch (PlatformEmailSendException e) { + } catch (final PlatformEmailSendException e) { final List dataValidationErrors = new ArrayList(); final String email = command.stringValueOfParameterNamed("email"); - ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid", "The parameter email is invalid.", - "email", email); + final ApiParameterError error = ApiParameterError.parameterError("error.msg.user.email.invalid", + "The parameter email is invalid.", "email", email); dataValidationErrors.add(error); throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist", "Validation errors exist.", @@ -115,7 +115,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit public CommandProcessingResult updateUser(final Long userId, final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); @@ -148,7 +148,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit .withOfficeId(userToUpdate.getOffice().getId()) // .with(changes) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return CommandProcessingResult.empty(); } @@ -159,7 +159,7 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit final Set allRoles = new HashSet(); if (!ObjectUtils.isEmpty(rolesArray)) { - for (String roleId : rolesArray) { + for (final String roleId : rolesArray) { final Long id = Long.valueOf(roleId); final Role role = this.roleRepository.findOne(id); if (role == null) { throw new RoleNotFoundException(id); } @@ -190,10 +190,11 @@ public class AppUserWritePlatformServiceJpaRepositoryImpl implements AppUserWrit */ private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("username_org")) { final String username = command.stringValueOfParameterNamed("username"); - StringBuilder defaultMessageBuilder = new StringBuilder("User with username ").append(username).append(" already exists."); + final StringBuilder defaultMessageBuilder = new StringBuilder("User with username ").append(username) + .append(" already exists."); throw new PlatformDataIntegrityException("error.msg.user.duplicate.username", defaultMessageBuilder.toString(), "username", username); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionReadPlatformService.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionReadPlatformService.java index 89c6b9fed..c7363d1f0 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionReadPlatformService.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionReadPlatformService.java @@ -12,7 +12,7 @@ import org.mifosplatform.useradministration.data.PermissionData; public interface PermissionReadPlatformService { Collection retrieveAllPermissions(); - + Collection retrieveAllMakerCheckerablePermissions(); Collection retrieveAllRolePermissions(Long roleId); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionReadPlatformServiceImpl.java index 4668ad69b..5d7412fdd 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionReadPlatformServiceImpl.java @@ -36,7 +36,7 @@ public class PermissionReadPlatformServiceImpl implements PermissionReadPlatform @Override public Collection retrieveAllPermissions() { - context.authenticatedUser(); + this.context.authenticatedUser(); final PermissionUsageDataMapper mapper = new PermissionUsageDataMapper(); final String sql = mapper.permissionSchema(); @@ -47,7 +47,7 @@ public class PermissionReadPlatformServiceImpl implements PermissionReadPlatform @Override public Collection retrieveAllMakerCheckerablePermissions() { - context.authenticatedUser(); + this.context.authenticatedUser(); final PermissionUsageDataMapper mapper = new PermissionUsageDataMapper(); final String sql = mapper.makerCheckerablePermissionSchema(); diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionWritePlatformServiceJpaRepositoryImpl.java index cd9e0e6d9..715b8d49a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/PermissionWritePlatformServiceJpaRepositoryImpl.java @@ -31,8 +31,7 @@ public class PermissionWritePlatformServiceJpaRepositoryImpl implements Permissi @Autowired public PermissionWritePlatformServiceJpaRepositoryImpl(final PlatformSecurityContext context, - final PermissionRepository permissionRepository, - final PermissionsCommandFromApiJsonDeserializer fromApiJsonDeserializer) { + final PermissionRepository permissionRepository, final PermissionsCommandFromApiJsonDeserializer fromApiJsonDeserializer) { this.context = context; this.permissionRepository = permissionRepository; this.fromApiJsonDeserializer = fromApiJsonDeserializer; @@ -41,10 +40,10 @@ public class PermissionWritePlatformServiceJpaRepositoryImpl implements Permissi @Transactional @Override public CommandProcessingResult updateMakerCheckerPermissions(final JsonCommand command) { - context.authenticatedUser(); + this.context.authenticatedUser(); final Collection allPermissions = this.permissionRepository.findAll(); - + final PermissionsCommand permissionsCommand = this.fromApiJsonDeserializer.commandFromApiJson(command.json()); final Map commandPermissions = permissionsCommand.getPermissions(); @@ -58,13 +57,13 @@ public class PermissionWritePlatformServiceJpaRepositoryImpl implements Permissi || permission.getGrouping().equalsIgnoreCase("special")) { throw new PermissionNotFoundException(permissionCode); } final boolean isSelected = commandPermissions.get(permissionCode).booleanValue(); - boolean changed = permission.enableMakerChecker(isSelected); + final boolean changed = permission.enableMakerChecker(isSelected); if (changed) { changedPermissions.put(permissionCode, isSelected); this.permissionRepository.save(permission); } } - + if (!changedPermissions.isEmpty()) { changes.put("permissions", changedPermissions); } @@ -75,7 +74,7 @@ public class PermissionWritePlatformServiceJpaRepositoryImpl implements Permissi private Permission findPermissionInCollectionByCode(final Collection allPermissions, final String permissionCode) { if (allPermissions != null) { - for (Permission permission : allPermissions) { + for (final Permission permission : allPermissions) { if (permission.hasCode(permissionCode)) { return permission; } } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleDataValidator.java index 4dadab0ab..c5ce73c7a 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleDataValidator.java @@ -44,17 +44,17 @@ public final class RoleDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("role"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final String name = fromApiJsonHelper.extractStringNamed("name", element); + final String name = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100); - final String description = fromApiJsonHelper.extractStringNamed("description", element); + final String description = this.fromApiJsonHelper.extractStringNamed("description", element); baseDataValidator.reset().parameter("description").value(description).notBlank().notExceedingLengthOf(500); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -64,20 +64,20 @@ public final class RoleDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("role"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - if (fromApiJsonHelper.parameterExists("name", element)) { - final String username = fromApiJsonHelper.extractStringNamed("name", element); + if (this.fromApiJsonHelper.parameterExists("name", element)) { + final String username = this.fromApiJsonHelper.extractStringNamed("name", element); baseDataValidator.reset().parameter("name").value(username).notBlank().notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("description", element)) { - final String description = fromApiJsonHelper.extractStringNamed("description", element); + if (this.fromApiJsonHelper.parameterExists("description", element)) { + final String description = this.fromApiJsonHelper.extractStringNamed("description", element); baseDataValidator.reset().parameter("description").value(description).notBlank().notExceedingLengthOf(500); } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleReadPlatformServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleReadPlatformServiceImpl.java index 71e1769d2..48b2528cf 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleReadPlatformServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleReadPlatformServiceImpl.java @@ -33,7 +33,7 @@ public class RoleReadPlatformServiceImpl implements RoleReadPlatformService { @Override public Collection retrieveAll() { - final String sql = "select " + roleRowMapper.schema() + " order by r.id"; + final String sql = "select " + this.roleRowMapper.schema() + " order by r.id"; return this.jdbcTemplate.query(sql, this.roleRowMapper); } @@ -42,10 +42,10 @@ public class RoleReadPlatformServiceImpl implements RoleReadPlatformService { public RoleData retrieveOne(final Long id) { try { - final String sql = "select " + roleRowMapper.schema() + " where r.id=?"; + final String sql = "select " + this.roleRowMapper.schema() + " where r.id=?"; return this.jdbcTemplate.queryForObject(sql, this.roleRowMapper, new Object[] { id }); - } catch (EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException e) { throw new RoleNotFoundException(id); } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleWritePlatformServiceJpaRepositoryImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleWritePlatformServiceJpaRepositoryImpl.java index 39dc3a3e7..26eedce63 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleWritePlatformServiceJpaRepositoryImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/RoleWritePlatformServiceJpaRepositoryImpl.java @@ -55,7 +55,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf public CommandProcessingResult createRole(final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.roleCommandFromApiJsonDeserializer.validateForCreate(command.json()); @@ -64,7 +64,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf this.roleRepository.save(entity); return new CommandProcessingResultBuilder().withCommandId(command.commandId()).withEntityId(entity.getId()).build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -78,7 +78,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf */ private void handleDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) { - Throwable realCause = dve.getMostSpecificCause(); + final Throwable realCause = dve.getMostSpecificCause(); if (realCause.getMessage().contains("unq_name")) { final String name = command.stringValueOfParameterNamed("name"); @@ -99,7 +99,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf @Override public CommandProcessingResult updateRole(final Long roleId, final JsonCommand command) { try { - context.authenticatedUser(); + this.context.authenticatedUser(); this.roleCommandFromApiJsonDeserializer.validateForUpdate(command.json()); @@ -116,7 +116,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf .withEntityId(roleId) // .with(changes) // .build(); - } catch (DataIntegrityViolationException dve) { + } catch (final DataIntegrityViolationException dve) { handleDataIntegrityIssues(command, dve); return new CommandProcessingResultBuilder() // .withCommandId(command.commandId()) // @@ -127,7 +127,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf @Transactional @Override public CommandProcessingResult updateRolePermissions(final Long roleId, final JsonCommand command) { - context.authenticatedUser(); + this.context.authenticatedUser(); final Role role = this.roleRepository.findOne(roleId); if (role == null) { throw new RoleNotFoundException(roleId); } @@ -143,7 +143,7 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf final boolean isSelected = commandPermissions.get(permissionCode).booleanValue(); final Permission permission = findPermissionByCode(allPermissions, permissionCode); - boolean changed = role.updatePermission(permission, isSelected); + final boolean changed = role.updatePermission(permission, isSelected); if (changed) { changedPermissions.put(permissionCode, isSelected); } @@ -161,10 +161,10 @@ public class RoleWritePlatformServiceJpaRepositoryImpl implements RoleWritePlatf .build(); } - private Permission findPermissionByCode(Collection allPermissions, String permissionCode) { + private Permission findPermissionByCode(final Collection allPermissions, final String permissionCode) { if (allPermissions != null) { - for (Permission permission : allPermissions) { + for (final Permission permission : allPermissions) { if (permission.hasCode(permissionCode)) { return permission; } } } diff --git a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/UserDataValidator.java b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/UserDataValidator.java index 80e2a7e52..67b90a4f2 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/UserDataValidator.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/useradministration/service/UserDataValidator.java @@ -45,44 +45,43 @@ public final class UserDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("user"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - final String username = fromApiJsonHelper.extractStringNamed("username", element); + final String username = this.fromApiJsonHelper.extractStringNamed("username", element); baseDataValidator.reset().parameter("username").value(username).notBlank().notExceedingLengthOf(100); - final String firstname = fromApiJsonHelper.extractStringNamed("firstname", element); + final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element); baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(100); - final String lastname = fromApiJsonHelper.extractStringNamed("lastname", element); + final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element); baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(100); - final Boolean sendPasswordToEmail = this.fromApiJsonHelper.extractBooleanNamed("sendPasswordToEmail", element); - if (sendPasswordToEmail != null) { - if (sendPasswordToEmail.booleanValue()) { - final String email = fromApiJsonHelper.extractStringNamed("email", element); - baseDataValidator.reset().parameter("email").value(email).notBlank().notExceedingLengthOf(100); - } - else{ - final String password = fromApiJsonHelper.extractStringNamed("password", element); - final String repeatPassword = fromApiJsonHelper.extractStringNamed("repeatPassword", element); - baseDataValidator.reset().parameter("password").value(password).notBlank().notExceedingLengthOf(50); - if (StringUtils.isNotBlank(password)) { - baseDataValidator.reset().parameter("password").value(password).equalToParameter("repeatPassword", repeatPassword); - } - } - } else { + final Boolean sendPasswordToEmail = this.fromApiJsonHelper.extractBooleanNamed("sendPasswordToEmail", element); + if (sendPasswordToEmail != null) { + if (sendPasswordToEmail.booleanValue()) { + final String email = this.fromApiJsonHelper.extractStringNamed("email", element); + baseDataValidator.reset().parameter("email").value(email).notBlank().notExceedingLengthOf(100); + } else { + final String password = this.fromApiJsonHelper.extractStringNamed("password", element); + final String repeatPassword = this.fromApiJsonHelper.extractStringNamed("repeatPassword", element); + baseDataValidator.reset().parameter("password").value(password).notBlank().notExceedingLengthOf(50); + if (StringUtils.isNotBlank(password)) { + baseDataValidator.reset().parameter("password").value(password).equalToParameter("repeatPassword", repeatPassword); + } + } + } else { baseDataValidator.reset().parameter("sendPasswordToEmail").value(sendPasswordToEmail).trueOrFalseRequired(false); - } + } - final Long officeId = fromApiJsonHelper.extractLongNamed("officeId", element); + final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element); baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero(); - final String[] roles = fromApiJsonHelper.extractArrayNamed("roles", element); + final String[] roles = this.fromApiJsonHelper.extractArrayNamed("roles", element); baseDataValidator.reset().parameter("roles").value(roles).arrayNotEmpty(); throwExceptionIfValidationWarningsExist(dataValidationErrors); @@ -96,46 +95,46 @@ public final class UserDataValidator { if (StringUtils.isBlank(json)) { throw new InvalidJsonException(); } final Type typeOfMap = new TypeToken>() {}.getType(); - fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, supportedParameters); + this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters); final List dataValidationErrors = new ArrayList(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("user"); - final JsonElement element = fromApiJsonHelper.parse(json); + final JsonElement element = this.fromApiJsonHelper.parse(json); - if (fromApiJsonHelper.parameterExists("officeId", element)) { - final Long officeId = fromApiJsonHelper.extractLongNamed("officeId", element); + if (this.fromApiJsonHelper.parameterExists("officeId", element)) { + final Long officeId = this.fromApiJsonHelper.extractLongNamed("officeId", element); baseDataValidator.reset().parameter("officeId").value(officeId).notNull().integerGreaterThanZero(); } - if (fromApiJsonHelper.parameterExists("username", element)) { - final String username = fromApiJsonHelper.extractStringNamed("username", element); + if (this.fromApiJsonHelper.parameterExists("username", element)) { + final String username = this.fromApiJsonHelper.extractStringNamed("username", element); baseDataValidator.reset().parameter("username").value(username).notBlank().notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("firstname", element)) { - final String firstname = fromApiJsonHelper.extractStringNamed("firstname", element); + if (this.fromApiJsonHelper.parameterExists("firstname", element)) { + final String firstname = this.fromApiJsonHelper.extractStringNamed("firstname", element); baseDataValidator.reset().parameter("firstname").value(firstname).notBlank().notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("lastname", element)) { - final String lastname = fromApiJsonHelper.extractStringNamed("lastname", element); + if (this.fromApiJsonHelper.parameterExists("lastname", element)) { + final String lastname = this.fromApiJsonHelper.extractStringNamed("lastname", element); baseDataValidator.reset().parameter("lastname").value(lastname).notBlank().notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("email", element)) { - final String email = fromApiJsonHelper.extractStringNamed("email", element); + if (this.fromApiJsonHelper.parameterExists("email", element)) { + final String email = this.fromApiJsonHelper.extractStringNamed("email", element); baseDataValidator.reset().parameter("email").value(email).notBlank().notExceedingLengthOf(100); } - if (fromApiJsonHelper.parameterExists("roles", element)) { - final String[] roles = fromApiJsonHelper.extractArrayNamed("roles", element); + if (this.fromApiJsonHelper.parameterExists("roles", element)) { + final String[] roles = this.fromApiJsonHelper.extractArrayNamed("roles", element); baseDataValidator.reset().parameter("roles").value(roles).arrayNotEmpty(); } - if (fromApiJsonHelper.parameterExists("password", element)) { - final String password = fromApiJsonHelper.extractStringNamed("password", element); - final String repeatPassword = fromApiJsonHelper.extractStringNamed("repeatPassword", element); + if (this.fromApiJsonHelper.parameterExists("password", element)) { + final String password = this.fromApiJsonHelper.extractStringNamed("password", element); + final String repeatPassword = this.fromApiJsonHelper.extractStringNamed("repeatPassword", element); baseDataValidator.reset().parameter("password").value(password).notBlank().notExceedingLengthOf(50); if (StringUtils.isNotBlank(password)) { baseDataValidator.reset().parameter("password").value(password).equalToParameter("repeatPassword", repeatPassword); diff --git a/mifosng-provider/src/test/java/org/mifosplatform/mix/report/service/XBRLBuilderTest.java b/mifosng-provider/src/test/java/org/mifosplatform/mix/report/service/XBRLBuilderTest.java index 75029d2e1..cdc8c888e 100644 --- a/mifosng-provider/src/test/java/org/mifosplatform/mix/report/service/XBRLBuilderTest.java +++ b/mifosng-provider/src/test/java/org/mifosplatform/mix/report/service/XBRLBuilderTest.java @@ -21,6 +21,7 @@ import org.mifosplatform.mix.data.NamespaceData; import org.mifosplatform.mix.service.NamespaceReadPlatformServiceImpl; import org.mifosplatform.mix.service.XBRLBuilder; import org.mockito.InjectMocks; +import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; @@ -33,13 +34,13 @@ public class XBRLBuilderTest { @Mock private NamespaceReadPlatformServiceImpl readNamespaceService; @InjectMocks - private XBRLBuilder xbrlBuilder = new XBRLBuilder(); + private final XBRLBuilder xbrlBuilder = new XBRLBuilder(); @Before public void setUp() throws Exception { - readNamespaceService = Mockito.mock(NamespaceReadPlatformServiceImpl.class); - when(readNamespaceService.retrieveNamespaceByPrefix(Mockito.anyString())).thenReturn( + this.readNamespaceService = Mockito.mock(NamespaceReadPlatformServiceImpl.class); + when(this.readNamespaceService.retrieveNamespaceByPrefix(Matchers.anyString())).thenReturn( new NamespaceData(1l, "mockedprefix", "mockedurl")); } @@ -47,23 +48,23 @@ public class XBRLBuilderTest { @Test public void shouldCorrectlyBuildMap() { - HashMap map = new HashMap(); - MixTaxonomyData data1 = Mockito.mock(MixTaxonomyData.class); + final HashMap map = new HashMap(); + final MixTaxonomyData data1 = Mockito.mock(MixTaxonomyData.class); when(data1.getName()).thenReturn("Assets"); map.put(data1, new BigDecimal(10000)); - String result = xbrlBuilder.build(map, Date.valueOf("2005-11-11"), Date.valueOf("2013-07-17"), "USD"); + final String result = this.xbrlBuilder.build(map, Date.valueOf("2005-11-11"), Date.valueOf("2013-07-17"), "USD"); System.out.println(result); NodeList nodes = null; try { nodes = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(result.getBytes())) .getElementsByTagName("Assets"); - } catch (SAXException e) { + } catch (final SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); - } catch (IOException e) { + } catch (final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); - } catch (ParserConfigurationException e) { + } catch (final ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } diff --git a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/AdhikarLoanRepaymentScheduleTransactionProcessorTest.java b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/AdhikarLoanRepaymentScheduleTransactionProcessorTest.java index 6c2a93abf..93a7630b3 100644 --- a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/AdhikarLoanRepaymentScheduleTransactionProcessorTest.java +++ b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/AdhikarLoanRepaymentScheduleTransactionProcessorTest.java @@ -1,8 +1,5 @@ package org.mifosplatform.portfolio.loanaccount; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - import java.util.List; import org.joda.time.LocalDate; @@ -10,7 +7,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.organisation.monetary.domain.Money; import org.mifosplatform.portfolio.loanaccount.domain.LoanRepaymentScheduleInstallment; import org.mifosplatform.portfolio.loanaccount.domain.transactionprocessor.impl.RBILoanRepaymentScheduleTransactionProcessor; import org.mockito.runners.MockitoJUnitRunner; @@ -18,136 +14,189 @@ import org.mockito.runners.MockitoJUnitRunner; @SuppressWarnings("unused") @RunWith(MockitoJUnitRunner.class) public class AdhikarLoanRepaymentScheduleTransactionProcessorTest { - - // class under test - private RBILoanRepaymentScheduleTransactionProcessor processor; - - // - private LocalDate july2nd = new LocalDate(2012, 7, 2); - private MonetaryCurrency usDollars = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); - private List installments; - - @Before - public void setUpForEachTestCase() { - - installments = LoanScheduleTestDataHelper.createSimpleLoanSchedule(july2nd, usDollars); - - processor = new RBILoanRepaymentScheduleTransactionProcessor(); - } - /** - * Scenario 1: Given no overdue installments, current interest due is paid before principal. - */ - @Test - public void givenNoOverdueInstallmentsOnTimeRepaymentPaysOffInterestDueFirst() { - -// // setup -// Money repaymentAmount = new MoneyBuilder().with(usDollars).with("100.00").build(); -// LoanTransaction onTimePartialRepayment = new LoanTransactionBuilder().repayment().with(july2nd).with(repaymentAmount).build(); -// -// // execute test -// processor.handleTransaction(onTimePartialRepayment, usDollars, installments); -// -// // verification of derived fields on installments -// LoanRepaymentScheduleInstallment firstInstallment = this.installments.get(0); -// assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), interestOf("100.00"), interestWaivedOf("0.00"), firstInstallment, usDollars); -// -// assertThatLoanTransactionHasDerivedFieldsOf(principalOf("0.00"), interestOf("100.00"), onTimePartialRepayment, usDollars); - } - -// /** -// * Scenario 2: Given overdue interest exists on overdue installment, a late -// * repayment results in overdue interest and current interest being paid -// * before principal component for overdue or current installments. -// */ -// @Test -// public void givenOverdueInterestOnOverdueInstallmentsLateRepaymentPaysOffOverdueInterestAndCurrentInterestDue() { -// -// // setup -// Money repaymentAmount = new MoneyBuilder().with(usDollars).with("300.00").build(); -// LoanTransaction lateRepayment = new LoanTransactionBuilder().repayment().with(july2nd.plusMonths(1)).with(repaymentAmount).build(); -// -// // execute test -// processor.handleTransaction(lateRepayment, usDollars, installments); -// -// // verification of derived fields on installments -// LoanRepaymentScheduleInstallment firstInstallment = this.installments.get(0); -// assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), interestOf("200.00"), interestWaivedOf("0.00"), firstInstallment, usDollars); -// -// LoanRepaymentScheduleInstallment secondInstallment = this.installments.get(1); -// assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), interestOf("100.00"), interestWaivedOf("0.00"), secondInstallment, usDollars); -// -// LoanRepaymentScheduleInstallment thirdInstallment = this.installments.get(2); -// assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), interestOf("0.00"), interestWaivedOf("0.00"), thirdInstallment, usDollars); -// -// assertThatLoanTransactionHasDerivedFieldsOf(principalOf("0.00"), interestOf("300.00"), lateRepayment, usDollars); -// } -// -// /** -// * Scenario 3: Given an overdue installment with overdue interest and principal, a late -// * repayment results in overdue interest and current interest being paid -// * before principal component for overdue or current installments. -// */ -// @Test -// public void givenAFullyOverdueInstallmentALateRepaymentShouldPayOffOverdueInterestAndCurrentInterestDueFirstThenOverduePrincipal() { -// -// // setup -// Money repaymentAmount = new MoneyBuilder().with(usDollars).with("900.00").build(); -// LoanTransaction lateRepayment = new LoanTransactionBuilder().repayment().with(july2nd.plusMonths(1)).with(repaymentAmount).build(); -// -// // execute test -// processor.handleTransaction(lateRepayment, usDollars, installments); -// -// // verification of derived fields on installments -// LoanRepaymentScheduleInstallment firstInstallment = this.installments.get(0); -// assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("500.00"), interestOf("200.00"), interestWaivedOf("0.00"), firstInstallment, usDollars); -// -// LoanRepaymentScheduleInstallment secondInstallment = this.installments.get(1); -// assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), interestOf("200.00"), interestWaivedOf("0.00"), secondInstallment, usDollars); -// -// LoanRepaymentScheduleInstallment thirdInstallment = this.installments.get(2); -// assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), interestOf("0.00"), interestWaivedOf("0.00"), thirdInstallment, usDollars); -// -// assertThatLoanTransactionHasDerivedFieldsOf(principalOf("500.00"), interestOf("400.00"), lateRepayment, usDollars); -// } -// -// private void assertThatLoanTransactionHasDerivedFieldsOf( -// final String principal, -// final String interest, -// final LoanTransaction transaction, final MonetaryCurrency currency) { -// -// Money expectedPrincipalPortion = new MoneyBuilder().with(currency).with(principal).build(); -// assertThat("Principal portion of transaction not as expected: ", transaction.getPrincipalPortion(currency).toString(), is(expectedPrincipalPortion.toString())); -// -// Money expectedInterestPortion = new MoneyBuilder().with(currency).with(interest).build(); -// assertThat("Interest portion of transaction not as expected: ", transaction.getInterestPortion(currency).toString(), is(expectedInterestPortion.toString())); -// } -// -// private void assertThatLoanInstallmentHasDerivedFieldsOf( -// final String principal, -// final String interest, -// final String interestWaived, -// final LoanRepaymentScheduleInstallment installment, final MonetaryCurrency currency) { -// -// Money expectedPrincipalCompleted = new MoneyBuilder().with(currency).with(principal).build(); -// assertThat("principal not as expected", installment.getPrincipalCompleted(currency).toString(), is(expectedPrincipalCompleted.toString())); -// -// Money expectedInterestCompleted = new MoneyBuilder().with(currency).with(interest).build(); -// assertThat("interest completed not as expected: ",installment.getInterestCompleted(currency).toString(), is(expectedInterestCompleted.toString())); -// -// Money expectedInterestWaived = new MoneyBuilder().with(currency).with(interestWaived).build(); -// assertThat("interest waived not as expected: ", installment.getInterestWaived(currency).toString(), is(expectedInterestWaived.toString())); -// } -// -// private String principalOf(final String value) { -// return value; -// } -// -// private String interestOf(final String value) { -// return value; -// } -// -// private String interestWaivedOf(final String value) { -// return value; -// } + // class under test + private RBILoanRepaymentScheduleTransactionProcessor processor; + + // + private final LocalDate july2nd = new LocalDate(2012, 7, 2); + private final MonetaryCurrency usDollars = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); + private List installments; + + @Before + public void setUpForEachTestCase() { + + this.installments = LoanScheduleTestDataHelper.createSimpleLoanSchedule(this.july2nd, this.usDollars); + + this.processor = new RBILoanRepaymentScheduleTransactionProcessor(); + } + + /** + * Scenario 1: Given no overdue installments, current interest due is paid + * before principal. + */ + @Test + public void givenNoOverdueInstallmentsOnTimeRepaymentPaysOffInterestDueFirst() { + + // // setup + // Money repaymentAmount = new + // MoneyBuilder().with(usDollars).with("100.00").build(); + // LoanTransaction onTimePartialRepayment = new + // LoanTransactionBuilder().repayment().with(july2nd).with(repaymentAmount).build(); + // + // // execute test + // processor.handleTransaction(onTimePartialRepayment, usDollars, + // installments); + // + // // verification of derived fields on installments + // LoanRepaymentScheduleInstallment firstInstallment = + // this.installments.get(0); + // assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), + // interestOf("100.00"), interestWaivedOf("0.00"), firstInstallment, + // usDollars); + // + // assertThatLoanTransactionHasDerivedFieldsOf(principalOf("0.00"), + // interestOf("100.00"), onTimePartialRepayment, usDollars); + } + + // /** + // * Scenario 2: Given overdue interest exists on overdue installment, a + // late + // * repayment results in overdue interest and current interest being paid + // * before principal component for overdue or current installments. + // */ + // @Test + // public void + // givenOverdueInterestOnOverdueInstallmentsLateRepaymentPaysOffOverdueInterestAndCurrentInterestDue() + // { + // + // // setup + // Money repaymentAmount = new + // MoneyBuilder().with(usDollars).with("300.00").build(); + // LoanTransaction lateRepayment = new + // LoanTransactionBuilder().repayment().with(july2nd.plusMonths(1)).with(repaymentAmount).build(); + // + // // execute test + // processor.handleTransaction(lateRepayment, usDollars, installments); + // + // // verification of derived fields on installments + // LoanRepaymentScheduleInstallment firstInstallment = + // this.installments.get(0); + // assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), + // interestOf("200.00"), interestWaivedOf("0.00"), firstInstallment, + // usDollars); + // + // LoanRepaymentScheduleInstallment secondInstallment = + // this.installments.get(1); + // assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), + // interestOf("100.00"), interestWaivedOf("0.00"), secondInstallment, + // usDollars); + // + // LoanRepaymentScheduleInstallment thirdInstallment = + // this.installments.get(2); + // assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), + // interestOf("0.00"), interestWaivedOf("0.00"), thirdInstallment, + // usDollars); + // + // assertThatLoanTransactionHasDerivedFieldsOf(principalOf("0.00"), + // interestOf("300.00"), lateRepayment, usDollars); + // } + // + // /** + // * Scenario 3: Given an overdue installment with overdue interest and + // principal, a late + // * repayment results in overdue interest and current interest being paid + // * before principal component for overdue or current installments. + // */ + // @Test + // public void + // givenAFullyOverdueInstallmentALateRepaymentShouldPayOffOverdueInterestAndCurrentInterestDueFirstThenOverduePrincipal() + // { + // + // // setup + // Money repaymentAmount = new + // MoneyBuilder().with(usDollars).with("900.00").build(); + // LoanTransaction lateRepayment = new + // LoanTransactionBuilder().repayment().with(july2nd.plusMonths(1)).with(repaymentAmount).build(); + // + // // execute test + // processor.handleTransaction(lateRepayment, usDollars, installments); + // + // // verification of derived fields on installments + // LoanRepaymentScheduleInstallment firstInstallment = + // this.installments.get(0); + // assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("500.00"), + // interestOf("200.00"), interestWaivedOf("0.00"), firstInstallment, + // usDollars); + // + // LoanRepaymentScheduleInstallment secondInstallment = + // this.installments.get(1); + // assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), + // interestOf("200.00"), interestWaivedOf("0.00"), secondInstallment, + // usDollars); + // + // LoanRepaymentScheduleInstallment thirdInstallment = + // this.installments.get(2); + // assertThatLoanInstallmentHasDerivedFieldsOf(principalOf("0.00"), + // interestOf("0.00"), interestWaivedOf("0.00"), thirdInstallment, + // usDollars); + // + // assertThatLoanTransactionHasDerivedFieldsOf(principalOf("500.00"), + // interestOf("400.00"), lateRepayment, usDollars); + // } + // + // private void assertThatLoanTransactionHasDerivedFieldsOf( + // final String principal, + // final String interest, + // final LoanTransaction transaction, final MonetaryCurrency currency) { + // + // Money expectedPrincipalPortion = new + // MoneyBuilder().with(currency).with(principal).build(); + // assertThat("Principal portion of transaction not as expected: ", + // transaction.getPrincipalPortion(currency).toString(), + // is(expectedPrincipalPortion.toString())); + // + // Money expectedInterestPortion = new + // MoneyBuilder().with(currency).with(interest).build(); + // assertThat("Interest portion of transaction not as expected: ", + // transaction.getInterestPortion(currency).toString(), + // is(expectedInterestPortion.toString())); + // } + // + // private void assertThatLoanInstallmentHasDerivedFieldsOf( + // final String principal, + // final String interest, + // final String interestWaived, + // final LoanRepaymentScheduleInstallment installment, final + // MonetaryCurrency currency) { + // + // Money expectedPrincipalCompleted = new + // MoneyBuilder().with(currency).with(principal).build(); + // assertThat("principal not as expected", + // installment.getPrincipalCompleted(currency).toString(), + // is(expectedPrincipalCompleted.toString())); + // + // Money expectedInterestCompleted = new + // MoneyBuilder().with(currency).with(interest).build(); + // assertThat("interest completed not as expected: ",installment.getInterestCompleted(currency).toString(), + // is(expectedInterestCompleted.toString())); + // + // Money expectedInterestWaived = new + // MoneyBuilder().with(currency).with(interestWaived).build(); + // assertThat("interest waived not as expected: ", + // installment.getInterestWaived(currency).toString(), + // is(expectedInterestWaived.toString())); + // } + // + // private String principalOf(final String value) { + // return value; + // } + // + // private String interestOf(final String value) { + // return value; + // } + // + // private String interestWaivedOf(final String value) { + // return value; + // } } \ No newline at end of file diff --git a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/HeavensFamilyLoanRepaymentScheduleTransactionProcessorTest.java b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/HeavensFamilyLoanRepaymentScheduleTransactionProcessorTest.java index 1d2266551..e4f4eb2e2 100644 --- a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/HeavensFamilyLoanRepaymentScheduleTransactionProcessorTest.java +++ b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/HeavensFamilyLoanRepaymentScheduleTransactionProcessorTest.java @@ -1,8 +1,5 @@ package org.mifosplatform.portfolio.loanaccount; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - import java.util.List; import org.joda.time.LocalDate; @@ -10,7 +7,6 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency; -import org.mifosplatform.organisation.monetary.domain.Money; import org.mifosplatform.portfolio.loanaccount.domain.LoanRepaymentScheduleInstallment; import org.mifosplatform.portfolio.loanaccount.domain.transactionprocessor.impl.HeavensFamilyLoanRepaymentScheduleTransactionProcessor; import org.mockito.runners.MockitoJUnitRunner; @@ -23,16 +19,16 @@ public class HeavensFamilyLoanRepaymentScheduleTransactionProcessorTest { private HeavensFamilyLoanRepaymentScheduleTransactionProcessor processor; // - private LocalDate july2nd = new LocalDate(2012, 7, 2); - private MonetaryCurrency usDollars = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); + private final LocalDate july2nd = new LocalDate(2012, 7, 2); + private final MonetaryCurrency usDollars = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); private List installments; @Before public void setUpForEachTestCase() { - installments = LoanScheduleTestDataHelper.createSimpleLoanSchedule(july2nd, usDollars); + this.installments = LoanScheduleTestDataHelper.createSimpleLoanSchedule(this.july2nd, this.usDollars); - processor = new HeavensFamilyLoanRepaymentScheduleTransactionProcessor(); + this.processor = new HeavensFamilyLoanRepaymentScheduleTransactionProcessor(); } /** diff --git a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanProductRelatedDetailTestHelper.java b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanProductRelatedDetailTestHelper.java index f699fa9db..7083d4a3d 100644 --- a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanProductRelatedDetailTestHelper.java +++ b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanProductRelatedDetailTestHelper.java @@ -19,23 +19,23 @@ public class LoanProductRelatedDetailTestHelper { public static LoanProductRelatedDetail createSettingsForEqualPrincipalAmortizationQuarterly() { - MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); - BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("200000")); + final MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); + final BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("200000")); // 2% per month, 24% per year - BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2")); - PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS; - BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24")); + final BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2")); + final PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS; + final BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24")); - InterestMethod interestMethod = InterestMethod.DECLINING_BALANCE; - InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD; - Integer repayEvery = Integer.valueOf(3); - PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS; + final InterestMethod interestMethod = InterestMethod.DECLINING_BALANCE; + final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD; + final Integer repayEvery = Integer.valueOf(3); + final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS; - Integer defaultNumberOfRepayments = Integer.valueOf(4); - AmortizationMethod amortizationMethod = AmortizationMethod.EQUAL_PRINCIPAL; + final Integer defaultNumberOfRepayments = Integer.valueOf(4); + final AmortizationMethod amortizationMethod = AmortizationMethod.EQUAL_PRINCIPAL; - BigDecimal inArrearsTolerance = BigDecimal.ZERO; + final BigDecimal inArrearsTolerance = BigDecimal.ZERO; return createLoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, repayEvery, repaymentFrequencyType, @@ -43,23 +43,23 @@ public class LoanProductRelatedDetailTestHelper { } public static LoanProductRelatedDetail createSettingsForEqualInstallmentAmortizationQuarterly() { - MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); - BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("200000")); + final MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); + final BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("200000")); // 2% per month, 24% per year - BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2")); - PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS; - BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24")); + final BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2")); + final PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS; + final BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24")); - InterestMethod interestMethod = InterestMethod.DECLINING_BALANCE; - InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD; - Integer repayEvery = Integer.valueOf(3); - PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS; + final InterestMethod interestMethod = InterestMethod.DECLINING_BALANCE; + final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD; + final Integer repayEvery = Integer.valueOf(3); + final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS; - Integer defaultNumberOfRepayments = Integer.valueOf(4); - AmortizationMethod amortizationMethod = AmortizationMethod.EQUAL_INSTALLMENTS; + final Integer defaultNumberOfRepayments = Integer.valueOf(4); + final AmortizationMethod amortizationMethod = AmortizationMethod.EQUAL_INSTALLMENTS; - BigDecimal inArrearsTolerance = BigDecimal.ZERO; + final BigDecimal inArrearsTolerance = BigDecimal.ZERO; return createLoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, repayEvery, repaymentFrequencyType, @@ -68,22 +68,22 @@ public class LoanProductRelatedDetailTestHelper { public static LoanProductRelatedDetail createSettingsForFlatQuarterly(final AmortizationMethod amortizationMethod) { - MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); - BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("200000")); + final MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("USD").withDigitsAfterDecimal(2).build(); + final BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("200000")); // 2% per month, 24% per year - BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2")); - PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS; - BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24")); + final BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2")); + final PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS; + final BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24")); - InterestMethod interestMethod = InterestMethod.FLAT; - InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD; - Integer repayEvery = Integer.valueOf(3); - PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS; + final InterestMethod interestMethod = InterestMethod.FLAT; + final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD; + final Integer repayEvery = Integer.valueOf(3); + final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS; - Integer defaultNumberOfRepayments = Integer.valueOf(4); + final Integer defaultNumberOfRepayments = Integer.valueOf(4); - BigDecimal inArrearsTolerance = BigDecimal.ZERO; + final BigDecimal inArrearsTolerance = BigDecimal.ZERO; return createLoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, repayEvery, repaymentFrequencyType, @@ -92,36 +92,36 @@ public class LoanProductRelatedDetailTestHelper { public static LoanProductRelatedDetail createSettingsForIrregularFlatEveryFourMonths() { - MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("KSH").withDigitsAfterDecimal(0).build(); - BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("15000")); + final MonetaryCurrency currency = new MonetaryCurrencyBuilder().withCode("KSH").withDigitsAfterDecimal(0).build(); + final BigDecimal defaultPrincipal = BigDecimal.valueOf(Double.valueOf("15000")); // 2% per month, 24% per year - BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2")); - PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS; - BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24")); + final BigDecimal defaultNominalInterestRatePerPeriod = BigDecimal.valueOf(Double.valueOf("2")); + final PeriodFrequencyType interestPeriodFrequencyType = PeriodFrequencyType.MONTHS; + final BigDecimal defaultAnnualNominalInterestRate = BigDecimal.valueOf(Double.valueOf("24")); - InterestMethod interestMethod = InterestMethod.FLAT; - InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD; - Integer repayEvery = Integer.valueOf(3); - PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS; + final InterestMethod interestMethod = InterestMethod.FLAT; + final InterestCalculationPeriodMethod interestCalculationPeriodMethod = InterestCalculationPeriodMethod.SAME_AS_REPAYMENT_PERIOD; + final Integer repayEvery = Integer.valueOf(3); + final PeriodFrequencyType repaymentFrequencyType = PeriodFrequencyType.MONTHS; - Integer defaultNumberOfRepayments = Integer.valueOf(2); + final Integer defaultNumberOfRepayments = Integer.valueOf(2); - BigDecimal inArrearsTolerance = BigDecimal.ZERO; + final BigDecimal inArrearsTolerance = BigDecimal.ZERO; - AmortizationMethod amortizationMethod = AmortizationMethod.EQUAL_PRINCIPAL; + final AmortizationMethod amortizationMethod = AmortizationMethod.EQUAL_PRINCIPAL; return createLoanProductRelatedDetail(currency, defaultPrincipal, defaultNominalInterestRatePerPeriod, interestPeriodFrequencyType, defaultAnnualNominalInterestRate, interestMethod, interestCalculationPeriodMethod, repayEvery, repaymentFrequencyType, defaultNumberOfRepayments, amortizationMethod, inArrearsTolerance); } - private static LoanProductRelatedDetail createLoanProductRelatedDetail(final MonetaryCurrency currency, final BigDecimal defaultPrincipal, - final BigDecimal defaultNominalInterestRatePerPeriod, final PeriodFrequencyType interestPeriodFrequencyType, - final BigDecimal defaultAnnualNominalInterestRate, final InterestMethod interestMethod, - final InterestCalculationPeriodMethod interestCalculationPeriodMethod, final Integer repayEvery, - final PeriodFrequencyType repaymentFrequencyType, final Integer defaultNumberOfRepayments, final AmortizationMethod amortizationMethod, - final BigDecimal inArrearsTolerance) { + private static LoanProductRelatedDetail createLoanProductRelatedDetail(final MonetaryCurrency currency, + final BigDecimal defaultPrincipal, final BigDecimal defaultNominalInterestRatePerPeriod, + final PeriodFrequencyType interestPeriodFrequencyType, final BigDecimal defaultAnnualNominalInterestRate, + final InterestMethod interestMethod, final InterestCalculationPeriodMethod interestCalculationPeriodMethod, + final Integer repayEvery, final PeriodFrequencyType repaymentFrequencyType, final Integer defaultNumberOfRepayments, + final AmortizationMethod amortizationMethod, final BigDecimal inArrearsTolerance) { final Integer graceOnPrincipalPayment = Integer.valueOf(0); final Integer graceOnInterestPayment = Integer.valueOf(0); diff --git a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanRepaymentScheduleInstallmentBuilder.java b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanRepaymentScheduleInstallmentBuilder.java index 1b4b0b91c..d3e72eea3 100644 --- a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanRepaymentScheduleInstallmentBuilder.java +++ b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanRepaymentScheduleInstallmentBuilder.java @@ -27,22 +27,23 @@ public class LoanRepaymentScheduleInstallmentBuilder { } public LoanRepaymentScheduleInstallment build() { - LoanRepaymentScheduleInstallment installment = new LoanRepaymentScheduleInstallment(loan, installmentNumber, fromDate, dueDate, - principal.getAmount(), interest.getAmount(), feeCharges.getAmount(), penaltyCharges.getAmount()); - if (completed) { - installment.payPrincipalComponent(latestTransactionDate, principal); - installment.payInterestComponent(latestTransactionDate, interest); + final LoanRepaymentScheduleInstallment installment = new LoanRepaymentScheduleInstallment(this.loan, this.installmentNumber, + this.fromDate, this.dueDate, this.principal.getAmount(), this.interest.getAmount(), this.feeCharges.getAmount(), + this.penaltyCharges.getAmount()); + if (this.completed) { + installment.payPrincipalComponent(this.latestTransactionDate, this.principal); + installment.payInterestComponent(this.latestTransactionDate, this.interest); } return installment; } public LoanRepaymentScheduleInstallmentBuilder withPrincipal(final String withPrincipal) { - this.principal = new MoneyBuilder().with(currencyDetail).with(withPrincipal).build(); + this.principal = new MoneyBuilder().with(this.currencyDetail).with(withPrincipal).build(); return this; } public LoanRepaymentScheduleInstallmentBuilder withInterest(final String withInterest) { - this.interest = new MoneyBuilder().with(currencyDetail).with(withInterest).build(); + this.interest = new MoneyBuilder().with(this.currencyDetail).with(withInterest).build(); return this; } diff --git a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanScheduleTestDataHelper.java b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanScheduleTestDataHelper.java index 15d2bae4d..d6c246b01 100644 --- a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanScheduleTestDataHelper.java +++ b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanScheduleTestDataHelper.java @@ -12,81 +12,55 @@ import org.mifosplatform.portfolio.loanaccount.domain.LoanRepaymentScheduleInsta */ public class LoanScheduleTestDataHelper { - /** - * Creates brand new three installment loan: - * - * For example: - * with firstDueDate = 02 July 2011 - * - * Date Principal Interest Interest Waived - * ================================================================================== - * 02 July 2011 1,000 200 0 - * 02 August 2011 1,000 200 0 - * 02 September 2011 1,000 200 0 - */ - public static List createSimpleLoanSchedule(final LocalDate firstDueDate, final MonetaryCurrency currency) { - LoanRepaymentScheduleInstallment firstInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) - .withInstallmentNumber(1) - .withDueDate(firstDueDate) - .withPrincipal("1000.00") - .withInterest("200.00") - .build(); + /** + * Creates brand new three installment loan: + * + * For example: with firstDueDate = 02 July 2011 + * + * Date Principal Interest Interest Waived + * ================================== + * ================================================ 02 July 2011 1,000 200 0 + * 02 August 2011 1,000 200 0 02 September 2011 1,000 200 0 + */ + public static List createSimpleLoanSchedule(final LocalDate firstDueDate, + final MonetaryCurrency currency) { + final LoanRepaymentScheduleInstallment firstInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) + .withInstallmentNumber(1).withDueDate(firstDueDate).withPrincipal("1000.00").withInterest("200.00").build(); - LoanRepaymentScheduleInstallment secondInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) - .withInstallmentNumber(2) - .withDueDate(firstDueDate.plusMonths(1)) - .withPrincipal("1000.00") - .withInterest("200.00") - .build(); - - LoanRepaymentScheduleInstallment thirdInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) - .withInstallmentNumber(3) - .withDueDate(firstDueDate.plusMonths(2)) - .withPrincipal("1000.00") - .withInterest("200.00") - .build(); - - return Arrays.asList(firstInstallment, secondInstallment, thirdInstallment); - } + final LoanRepaymentScheduleInstallment secondInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) + .withInstallmentNumber(2).withDueDate(firstDueDate.plusMonths(1)).withPrincipal("1000.00").withInterest("200.00").build(); - - /** - * Creates three installment loan with first installment fully completed: - * - * For example: - * with firstDueDate = 02 July 2011 - * - * Date Principal Interest Interest Waived Completed - * ================================================================================================================ - * 02 July 2011 1,000 200 0 true (principal paid, interest paid) - * 02 August 2011 1,000 200 0 false - * 02 September 2011 1,000 200 0 false - */ - public static List createSimpleLoanScheduleWithFirstInstallmentFullyPaid(final LocalDate firstDueDate, final MonetaryCurrency currency) { - - LoanRepaymentScheduleInstallment firstInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) - .withInstallmentNumber(1) - .withDueDate(firstDueDate) - .withPrincipal("1000.00") - .withInterest("200.00") - .completed() - .build(); + final LoanRepaymentScheduleInstallment thirdInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) + .withInstallmentNumber(3).withDueDate(firstDueDate.plusMonths(2)).withPrincipal("1000.00").withInterest("200.00").build(); - LoanRepaymentScheduleInstallment secondInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) - .withInstallmentNumber(2) - .withDueDate(firstDueDate.plusMonths(1)) - .withPrincipal("1000.00") - .withInterest("200.00") - .build(); - - LoanRepaymentScheduleInstallment thirdInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) - .withInstallmentNumber(3) - .withDueDate(firstDueDate.plusMonths(2)) - .withPrincipal("1000.00") - .withInterest("200.00") - .build(); - - return Arrays.asList(firstInstallment, secondInstallment, thirdInstallment); - } + return Arrays.asList(firstInstallment, secondInstallment, thirdInstallment); + } + + /** + * Creates three installment loan with first installment fully completed: + * + * For example: with firstDueDate = 02 July 2011 + * + * Date Principal Interest Interest Waived Completed + * ======================== + * ================================================== + * ====================================== 02 July 2011 1,000 200 0 true + * (principal paid, interest paid) 02 August 2011 1,000 200 0 false 02 + * September 2011 1,000 200 0 false + */ + public static List createSimpleLoanScheduleWithFirstInstallmentFullyPaid( + final LocalDate firstDueDate, final MonetaryCurrency currency) { + + final LoanRepaymentScheduleInstallment firstInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) + .withInstallmentNumber(1).withDueDate(firstDueDate).withPrincipal("1000.00").withInterest("200.00").completed().build(); + + final LoanRepaymentScheduleInstallment secondInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) + .withInstallmentNumber(2).withDueDate(firstDueDate.plusMonths(1)).withPrincipal("1000.00").withInterest("200.00").build(); + + final LoanRepaymentScheduleInstallment thirdInstallment = new LoanRepaymentScheduleInstallmentBuilder(currency) + .withInstallmentNumber(3).withDueDate(firstDueDate.plusMonths(2)).withPrincipal("1000.00").withInterest("200.00").build(); + + return Arrays.asList(firstInstallment, secondInstallment, thirdInstallment); + } } diff --git a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanTransactionBuilder.java b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanTransactionBuilder.java index b75805d8d..ca10c20a7 100644 --- a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanTransactionBuilder.java +++ b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/LoanTransactionBuilder.java @@ -12,16 +12,16 @@ public class LoanTransactionBuilder { @SuppressWarnings("unused") private boolean repayment = false; - /** public LoanTransaction build() { - - LoanTransaction transaction = null; - - if (repayment) { - transaction = LoanTransaction.repayment(transactionAmount, transactionDate); - } - - return transaction; - }**/ + /** + * public LoanTransaction build() { + * + * LoanTransaction transaction = null; + * + * if (repayment) { transaction = + * LoanTransaction.repayment(transactionAmount, transactionDate); } + * + * return transaction; } + **/ public LoanTransactionBuilder with(final Money newAmount) { this.transactionAmount = newAmount; diff --git a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/MonetaryCurrencyBuilder.java b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/MonetaryCurrencyBuilder.java index 9c5e25b23..8259338a0 100644 --- a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/MonetaryCurrencyBuilder.java +++ b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/MonetaryCurrencyBuilder.java @@ -6,10 +6,10 @@ public class MonetaryCurrencyBuilder { private String code = "XOF"; private int digitsAfterDecimal = 0; - private Integer inMultiplesOf = null; + private final Integer inMultiplesOf = null; public MonetaryCurrency build() { - return new MonetaryCurrency(code, digitsAfterDecimal,inMultiplesOf); + return new MonetaryCurrency(this.code, this.digitsAfterDecimal, this.inMultiplesOf); } public MonetaryCurrencyBuilder withCode(final String withCode) { diff --git a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/MoneyBuilder.java b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/MoneyBuilder.java index cc762ec87..81244df38 100644 --- a/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/MoneyBuilder.java +++ b/mifosng-provider/src/test/java/org/mifosplatform/portfolio/loanaccount/MoneyBuilder.java @@ -11,7 +11,7 @@ public class MoneyBuilder { private BigDecimal newAmount = BigDecimal.ZERO; public Money build() { - return Money.of(currencyDetail, newAmount); + return Money.of(this.currencyDetail, this.newAmount); } public MoneyBuilder with(final MonetaryCurrency withDetail) { From 086fbcd0c99a757c2aa7dd63398692b6d3b3bf3c Mon Sep 17 00:00:00 2001 From: Vishwas Babu A J Date: Fri, 20 Sep 2013 23:12:47 +0530 Subject: [PATCH 7/8] resolve compilation issues generated by cleanup --- .../dataqueries/service/ReadWriteNonCoreDataServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java index a5fd1dd6c..ff54ad7c3 100644 --- a/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java +++ b/mifosng-provider/src/main/java/org/mifosplatform/infrastructure/dataqueries/service/ReadWriteNonCoreDataServiceImpl.java @@ -228,10 +228,10 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ this.jdbcTemplate.batchUpdate(sqlArray); } - final /*** + /*** * Strangely, a Hibernate contraint violation exception is thrown ****/ - catch (ConstraintViolationException cve) { + catch (final ConstraintViolationException cve) { final Throwable realCause = cve.getCause(); // even if duplicate is only due to permission duplicate, okay to // show duplicate datatable error msg From 3531e956fbec9b2c142ace7430310da6a437dc55 Mon Sep 17 00:00:00 2001 From: Vishwas Babu A J Date: Fri, 20 Sep 2013 23:30:40 +0530 Subject: [PATCH 8/8] Update CHANGELOG.md for 1.10.1 Release --- CHANGELOG.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4826327e..cbae7ac88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ See VERSIONING (https://github.com/openMF/mifosx/blob/master/VERSIONING.md) for Releases =============== +1. 20 Sep 2013 - 1.10.1.RELEASE 1. 19 Sep 2013 - 1.10.0.RELEASE 1. 18 Sep 2013 - 1.9.2.RELEASE 1. 10 Sep 2013 - 1.9.1.RELEASE @@ -37,6 +38,21 @@ Releases 1. 05 April 2013 - 0.11.1.beta 1. 05 April 2013 - 0.11.0.beta + +1.10.1.RELEASE +============= +Bug Release + +Platform & API + +Bug + - [MIFOSX-675] - Not able to create savings account with/without charges. + - [MIFOSX-680] - Duplicate entries for Payment channels to Fund source mapping + +Reference App + - [MIFOSX-683] - Update Reference UI to allow manual payments of Loan fees from savings + + 1.10.0.RELEASE ============= Feature Release