implementation of FINERACT-724 (Upgrade Spring Boot, Spring and Spring Security to their latest stable version)

This commit is contained in:
ibondarenko
2019-10-11 13:39:22 +03:00
parent 608317ef52
commit 1fbe75281c
182 changed files with 1113 additions and 832 deletions
+1 -1
View File
@@ -188,4 +188,4 @@
</Host> </Host>
</Engine> </Engine>
</Service> </Service>
</Server> </Server>
+7 -7
View File
@@ -21,15 +21,15 @@ Run as:
gradle clean tomcatrunwar gradle clean tomcatrunwar
''' '''
project.ext.springBootVersion = '1.2.8.RELEASE' project.ext.springBootVersion = '2.1.9.RELEASE'
project.ext.springVersion = '4.1.9.RELEASE' project.ext.springVersion = '5.1.10.RELEASE'
project.ext.springOauthVersion = '2.0.4.RELEASE' project.ext.springOauthVersion = '2.3.6.RELEASE'
project.ext.jerseyVersion = '1.17' project.ext.jerseyVersion = '1.17'
project.ext.springDataJpaVersion = '1.7.0.RELEASE' // also change spring-boot-gradle-plugin version below project.ext.springDataJpaVersion = '2.2.0.RELEASE' // also change spring-boot-gradle-plugin version below
buildscript { buildscript {
ext { ext {
openJPAVersion = '2.4.3' openJPAVersion = '3.1.0'
} }
repositories { repositories {
jcenter() jcenter()
@@ -41,9 +41,9 @@ buildscript {
classpath 'com.bmuschko:gradle-tomcat-plugin:2.5', classpath 'com.bmuschko:gradle-tomcat-plugin:2.5',
'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.0', 'nl.javadude.gradle.plugins:license-gradle-plugin:0.11.0',
'org.zeroturnaround:gradle-jrebel-plugin:1.1.2', 'org.zeroturnaround:gradle-jrebel-plugin:1.1.2',
'org.springframework.boot:spring-boot-gradle-plugin:2.1.3.RELEASE' // also change springDataJpaVersion below 'org.springframework.boot:spring-boot-gradle-plugin:2.1.9.RELEASE' // also change springDataJpaVersion below
classpath "org.apache.openjpa:openjpa:$openJPAVersion" classpath "org.apache.openjpa:openjpa:$openJPAVersion"
classpath 'com.radcortez.gradle:openjpa-gradle-plugin:3.0.0' classpath 'com.radcortez.gradle:openjpa-gradle-plugin:3.1.0'
classpath 'gradle.plugin.org.nosphere.apache:creadur-rat-gradle:0.2.2' classpath 'gradle.plugin.org.nosphere.apache:creadur-rat-gradle:0.2.2'
} }
} }
+4 -2
View File
@@ -66,7 +66,7 @@ dependencies {
//[group: 'mysql', name: 'mysql-connector-java', version: '5.1.27'], //[group: 'mysql', name: 'mysql-connector-java', version: '5.1.27'],
[group: 'org.drizzle.jdbc', name: 'drizzle-jdbc', version: '1.4'], [group: 'org.drizzle.jdbc', name: 'drizzle-jdbc', version: '1.4'],
// [group: 'org.apache.tomcat', name: 'tomcat-jdbc', version: tomcatVersion], [group: 'org.apache.tomcat', name: 'tomcat-jdbc', version: tomcatVersion],
[group: 'org.apache.poi',name: 'poi', version: '3.9'], [group: 'org.apache.poi',name: 'poi', version: '3.9'],
@@ -101,8 +101,10 @@ dependencies {
'junit:junit-dep:4.11', 'junit:junit-dep:4.11',
'org.mockito:mockito-core:1.9.5', 'org.mockito:mockito-core:1.9.5',
'com.jayway.restassured:rest-assured:2.3.3', 'com.jayway.restassured:rest-assured:2.3.3',
[group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: springBootVersion],
[group: 'com.mockrunner', name: 'mockrunner-jms', version: '1.0.6'], [group: 'com.mockrunner', name: 'mockrunner-jms', version: '1.0.6'],
[group: 'com.mockrunner', name: 'mockrunner-jdbc', version: '1.0.6'] [group: 'com.mockrunner', name: 'mockrunner-jdbc', version: '1.0.6']
testCompile ("org.springframework.boot:spring-boot-starter-test:$springBootVersion") {
exclude group: 'com.jayway.jsonpath', module: 'json-path'
}
} }
+10 -11
View File
@@ -17,7 +17,7 @@
* under the License. * under the License.
*/ */
dependencies { dependencies {
def tomcatVersion = '7.0.54' def tomcatVersion = '7.0.94'
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}", tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
"org.apache.tomcat.embed:tomcat-embed-logging-log4j:${tomcatVersion}" // NOT tomcat-embed-logging-juli (http://stackoverflow.com/questions/23963049/classcircularityerror-java-util-logging-logrecord-running-gradle-webapp-with-ja) "org.apache.tomcat.embed:tomcat-embed-logging-log4j:${tomcatVersion}" // NOT tomcat-embed-logging-juli (http://stackoverflow.com/questions/23963049/classcircularityerror-java-util-logging-logrecord-running-gradle-webapp-with-ja)
tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}") { tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}") {
@@ -27,22 +27,19 @@ dependencies {
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat:${springBootVersion}") providedRuntime("org.springframework.boot:spring-boot-starter-tomcat:${springBootVersion}")
providedCompile(
// [group: 'javax.servlet', name: 'servlet-api', version: '2.5'],
)
compile( compile(
[group: 'ch.vorburger.mariaDB4j', name: 'mariaDB4j', version: '2.1.3'], [group: 'ch.vorburger.mariaDB4j', name: 'mariaDB4j', version: '2.1.3'],
[group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springBootVersion], [group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springBootVersion],
[group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: springBootVersion], [group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: springBootVersion],
[group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: springBootVersion], [group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: springBootVersion],
[group: 'org.springframework.boot', name: 'spring-boot-starter-actuator', version: springBootVersion],
//[group: 'org.eclipse.persistence', name: 'javax.persistence', version: '2.0.0'], //[group: 'org.eclipse.persistence', name: 'javax.persistence', version: '2.0.0'],
[group: 'org.springframework', name: 'spring-context-support', version: springVersion], [group: 'org.springframework', name: 'spring-context-support', version: springVersion],
[group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: springOauthVersion], [group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: springOauthVersion],
[group: 'org.apache.openjpa', name:'openjpa-all', version:'2.4.1'], [group: 'org.apache.openjpa', name:'openjpa-all', version:openJPAVersion],
[group: 'org.apache.openjpa', name:'openjpa-maven-plugin', version:'2.4.1'], [group: 'org.apache.openjpa', name:'openjpa-maven-plugin', version:openJPAVersion],
[group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1'], [group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1'],
[group: 'com.sun.jersey', name: 'jersey-core', version: jerseyVersion], [group: 'com.sun.jersey', name: 'jersey-core', version: jerseyVersion],
[group: 'com.sun.jersey', name: 'jersey-servlet', version: jerseyVersion], [group: 'com.sun.jersey', name: 'jersey-servlet', version: jerseyVersion],
@@ -67,7 +64,7 @@ dependencies {
// no slf4j & logback here (anymore), as spring-boot-starter-logging already brings this now, better assembled (log4j-over-slf4j was originally forgotten here) // no slf4j & logback here (anymore), as spring-boot-starter-logging already brings this now, better assembled (log4j-over-slf4j was originally forgotten here)
//[group: 'mysql', name: 'mysql-connector-java', version: '5.1.27'], //[group: 'mysql', name: 'mysql-connector-java', version: '5.1.27'],
[group: 'org.drizzle.jdbc', name: 'drizzle-jdbc', version: '1.3'], [group: 'org.drizzle.jdbc', name: 'drizzle-jdbc', version: '1.4'],
[group: 'org.apache.tomcat', name: 'tomcat-jdbc', version: tomcatVersion], [group: 'org.apache.tomcat', name: 'tomcat-jdbc', version: tomcatVersion],
@@ -92,8 +89,8 @@ dependencies {
//[group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.0'] //[group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.0']
[group: 'io.swagger', name: 'swagger-jersey-jaxrs', version: '1.5.15'], [group: 'io.swagger', name: 'swagger-jersey-jaxrs', version: '1.5.15'],
[group: 'org.springframework', name:'spring-jms'], [group: 'org.springframework', name:'spring-jms', version: '4.0.7.RELEASE'],
[group: 'org.apache.activemq', name: 'activemq-broker'], [group: 'org.apache.activemq', name: 'activemq-broker', version: '5.9.1'],
[group: 'javax.validation', name: 'validation-api', version: '2.0.0.Final'] [group: 'javax.validation', name: 'validation-api', version: '2.0.0.Final']
) )
@@ -101,8 +98,10 @@ dependencies {
'junit:junit-dep:4.11', 'junit:junit-dep:4.11',
'org.mockito:mockito-core:1.9.5', 'org.mockito:mockito-core:1.9.5',
'com.jayway.restassured:rest-assured:2.3.3', 'com.jayway.restassured:rest-assured:2.3.3',
[group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: springBootVersion],
[group: 'com.mockrunner', name: 'mockrunner-jms', version: '1.0.6'], [group: 'com.mockrunner', name: 'mockrunner-jms', version: '1.0.6'],
[group: 'com.mockrunner', name: 'mockrunner-jdbc', version: '1.0.6'] [group: 'com.mockrunner', name: 'mockrunner-jdbc', version: '1.0.6']
testCompile ("org.springframework.boot:spring-boot-starter-test:$springBootVersion") {
exclude group: 'com.jayway.jsonpath', module: 'json-path'
}
} }
-2
View File
@@ -18,5 +18,3 @@
# #
releaseVersion=1.0.0 releaseVersion=1.0.0
buildType=BUILD buildType=BUILD
@@ -17,4 +17,8 @@
# under the License. # under the License.
# #
spring.profiles.default=basicauth spring.profiles.default=basicauth
management.health.jms.enabled=false
security.enable-csrf=false
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
@@ -18,4 +18,8 @@
# #
spring.profiles.default=basicauth spring.profiles.default=basicauth
spring.profiles.active=basicauth,twofactor spring.profiles.active=basicauth,twofactor
management.health.jms.enabled=false
security.enable-csrf=false
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
@@ -18,4 +18,8 @@
# #
spring.profiles.default=basicauth spring.profiles.default=basicauth
spring.profiles.active=oauth spring.profiles.active=oauth
management.health.jms.enabled=false
security.enable-csrf=false
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
@@ -18,4 +18,8 @@
# #
spring.profiles.default=basicauth spring.profiles.default=basicauth
spring.profiles.active=oauth,twofactor spring.profiles.active=oauth,twofactor
management.health.jms.enabled=false
security.enable-csrf=false
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
@@ -550,4 +550,4 @@ public class GroupSavingsIntegrationTest {
.withMinimumOpenningBalance(minOpenningBalance).build(); .withMinimumOpenningBalance(minOpenningBalance).build();
return SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec); return SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec);
} }
} }
@@ -175,4 +175,4 @@ public class GroupTest {
return this.loanTransactionHelper.getLoanId(loanApplicationJSON); return this.loanTransactionHelper.getLoanId(loanApplicationJSON);
} }
} }
@@ -403,4 +403,4 @@ public class LoanReschedulingWithinCenterTest {
return new ArrayList<>(Arrays.asList(date.get(Calendar.YEAR), date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH))); return new ArrayList<>(Arrays.asList(date.get(Calendar.YEAR), date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH)));
} }
} }
@@ -61,7 +61,7 @@ public class Utils {
public static final String TENANT_TIME_ZONE = "Asia/Kolkata"; public static final String TENANT_TIME_ZONE = "Asia/Kolkata";
private static final String HEALTH_URL = "/fineract-provider/health"; private static final String HEALTH_URL = "/fineract-provider/actuator/health";
private static final String LOGIN_URL = "/fineract-provider/api/v1/authentication?username=mifos&password=password&" + TENANT_IDENTIFIER; private static final String LOGIN_URL = "/fineract-provider/api/v1/authentication?username=mifos&password=password&" + TENANT_IDENTIFIER;
public static void initializeRESTAssured() { public static void initializeRESTAssured() {
@@ -102,8 +102,7 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure
closureCommand.validateForUpdate(); closureCommand.validateForUpdate();
// is the glClosure valid // is the glClosure valid
final GLClosure glClosure = this.glClosureRepository.findOne(glClosureId); final GLClosure glClosure = this.glClosureRepository.findById(glClosureId).orElseThrow(() -> new GLClosureNotFoundException(glClosureId));
if (glClosure == null) { throw new GLClosureNotFoundException(glClosureId); }
final Map<String, Object> changesOnly = glClosure.update(command); final Map<String, Object> changesOnly = glClosure.update(command);
@@ -118,9 +117,9 @@ public class GLClosureWritePlatformServiceJpaRepositoryImpl implements GLClosure
@Transactional @Transactional
@Override @Override
public CommandProcessingResult deleteGLClosure(final Long glClosureId) { public CommandProcessingResult deleteGLClosure(final Long glClosureId) {
final GLClosure glClosure = this.glClosureRepository.findOne(glClosureId); final GLClosure glClosure = this.glClosureRepository.findById(glClosureId)
.orElseThrow(() -> new GLClosureNotFoundException(glClosureId));
if (glClosure == null) { throw new GLClosureNotFoundException(glClosureId); }
/** /**
* check if any closures are present for this branch at a later date * check if any closures are present for this branch at a later date
@@ -41,9 +41,8 @@ public class FinancialActivityAccountRepositoryWrapper {
} }
public FinancialActivityAccount findOneWithNotFoundDetection(final Long id) { public FinancialActivityAccount findOneWithNotFoundDetection(final Long id) {
final FinancialActivityAccount financialActivityAccount = this.repository.findOne(id); return this.repository.findById(id)
if (financialActivityAccount == null) { throw new FinancialActivityAccountNotFoundException(id); } .orElseThrow(() -> new FinancialActivityAccountNotFoundException(id));
return financialActivityAccount;
} }
public FinancialActivityAccount findByFinancialActivityTypeWithNotFoundDetection(final int financialActivityType) { public FinancialActivityAccount findByFinancialActivityTypeWithNotFoundDetection(final int financialActivityType) {
@@ -67,4 +66,4 @@ public class FinancialActivityAccountRepositoryWrapper {
public void delete(final FinancialActivityAccount entity) { public void delete(final FinancialActivityAccount entity) {
this.repository.delete(entity); this.repository.delete(entity);
} }
} }
@@ -38,9 +38,7 @@ public class GLAccountRepositoryWrapper {
} }
public GLAccount findOneWithNotFoundDetection(final Long id) { public GLAccount findOneWithNotFoundDetection(final Long id) {
final GLAccount account = this.repository.findOne(id); return this.repository.findById(id).orElseThrow(() -> new GLAccountNotFoundException(id));
if (account == null) { throw new GLAccountNotFoundException(id); }
return account;
} }
} }
@@ -42,6 +42,6 @@ public class TrialBalanceRepositoryWrapper {
} }
public void save(final List<TrialBalance> tbRows){ public void save(final List<TrialBalance> tbRows){
this.repository.save(tbRows); this.repository.saveAll(tbRows);
} }
} }
@@ -131,8 +131,8 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
final Long parentId = command.longValueOfParameterNamed(GLAccountJsonInputParams.PARENT_ID.getValue()); final Long parentId = command.longValueOfParameterNamed(GLAccountJsonInputParams.PARENT_ID.getValue());
if (glAccountId.equals(parentId)) { throw new InvalidParentGLAccountHeadException(glAccountId, parentId); } if (glAccountId.equals(parentId)) { throw new InvalidParentGLAccountHeadException(glAccountId, parentId); }
// is the glAccount valid // is the glAccount valid
final GLAccount glAccount = this.glAccountRepository.findOne(glAccountId); final GLAccount glAccount = this.glAccountRepository.findById(glAccountId)
if (glAccount == null) { throw new GLAccountNotFoundException(glAccountId); } .orElseThrow(() -> new GLAccountNotFoundException(glAccountId));
final Map<String, Object> changesOnly = glAccount.update(command); final Map<String, Object> changesOnly = glAccount.update(command);
@@ -191,9 +191,8 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
@Transactional @Transactional
@Override @Override
public CommandProcessingResult deleteGLAccount(final Long glAccountId) { public CommandProcessingResult deleteGLAccount(final Long glAccountId) {
final GLAccount glAccount = this.glAccountRepository.findOne(glAccountId); final GLAccount glAccount = this.glAccountRepository.findById(glAccountId)
.orElseThrow(() -> new GLAccountNotFoundException(glAccountId));
if (glAccount == null) { throw new GLAccountNotFoundException(glAccountId); }
// validate this isn't a header account that has children // validate this isn't a header account that has children
if (glAccount.isHeaderAccount() && glAccount.getChildren().size() > 0) { throw new GLAccountInvalidDeleteException( if (glAccount.isHeaderAccount() && glAccount.getChildren().size() > 0) { throw new GLAccountInvalidDeleteException(
@@ -215,8 +214,8 @@ public class GLAccountWritePlatformServiceJpaRepositoryImpl implements GLAccount
private GLAccount validateParentGLAccount(final Long parentAccountId) { private GLAccount validateParentGLAccount(final Long parentAccountId) {
GLAccount parentGLAccount = null; GLAccount parentGLAccount = null;
if (parentAccountId != null) { if (parentAccountId != null) {
parentGLAccount = this.glAccountRepository.findOne(parentAccountId); parentGLAccount = this.glAccountRepository.findById(parentAccountId)
if (parentGLAccount == null) { throw new GLAccountNotFoundException(parentAccountId); } .orElseThrow(() -> new GLAccountNotFoundException(parentAccountId));
// ensure parent is not a detail account // ensure parent is not a detail account
if (parentGLAccount.isDetailAccount()) { throw new GLAccountInvalidParentException(parentAccountId); } if (parentGLAccount.isDetailAccount()) { throw new GLAccountInvalidParentException(parentAccountId); }
} }
@@ -774,11 +774,11 @@ public class AccountingProcessorHelper {
} }
public LoanTransaction getLoanTransactionById(final long loanTransactionId) { public LoanTransaction getLoanTransactionById(final long loanTransactionId) {
return this.loanTransactionRepository.findOne(loanTransactionId); return this.loanTransactionRepository.findById(loanTransactionId).get();
} }
public SavingsAccountTransaction getSavingsTransactionById(final long savingsTransactionId) { public SavingsAccountTransaction getSavingsTransactionById(final long savingsTransactionId) {
return this.savingsAccountTransactionRepository.findOne(savingsTransactionId); return this.savingsAccountTransactionRepository.findById(savingsTransactionId).get();
} }
private void createCreditJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final int accountMappingTypeId, private void createCreditJournalEntryOrReversalForLoan(final Office office, final String currencyCode, final int accountMappingTypeId,
@@ -828,7 +828,7 @@ public class AccountingProcessorHelper {
String modifiedTransactionId = transactionId; String modifiedTransactionId = transactionId;
if (StringUtils.isNumeric(transactionId)) { if (StringUtils.isNumeric(transactionId)) {
long id = Long.parseLong(transactionId); long id = Long.parseLong(transactionId);
savingsAccountTransaction = this.savingsAccountTransactionRepository.findOne(id); savingsAccountTransaction = this.savingsAccountTransactionRepository.findById(id).get();
modifiedTransactionId = SAVINGS_TRANSACTION_IDENTIFIER + transactionId; modifiedTransactionId = SAVINGS_TRANSACTION_IDENTIFIER + transactionId;
} }
final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId, final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId,
@@ -848,7 +848,7 @@ public class AccountingProcessorHelper {
String modifiedTransactionId = transactionId; String modifiedTransactionId = transactionId;
if (StringUtils.isNumeric(transactionId)) { if (StringUtils.isNumeric(transactionId)) {
long id = Long.parseLong(transactionId); long id = Long.parseLong(transactionId);
loanTransaction = this.loanTransactionRepository.findOne(id); loanTransaction = this.loanTransactionRepository.findById(id).get();
modifiedTransactionId = LOAN_TRANSACTION_IDENTIFIER + transactionId; modifiedTransactionId = LOAN_TRANSACTION_IDENTIFIER + transactionId;
} }
final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId, final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId,
@@ -898,7 +898,7 @@ public class AccountingProcessorHelper {
String modifiedTransactionId = transactionId; String modifiedTransactionId = transactionId;
if (StringUtils.isNumeric(transactionId)) { if (StringUtils.isNumeric(transactionId)) {
long id = Long.parseLong(transactionId); long id = Long.parseLong(transactionId);
loanTransaction = this.loanTransactionRepository.findOne(id); loanTransaction = this.loanTransactionRepository.findById(id).get();
modifiedTransactionId = LOAN_TRANSACTION_IDENTIFIER + transactionId; modifiedTransactionId = LOAN_TRANSACTION_IDENTIFIER + transactionId;
} }
final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId, final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId,
@@ -918,7 +918,7 @@ public class AccountingProcessorHelper {
String modifiedTransactionId = transactionId; String modifiedTransactionId = transactionId;
if (StringUtils.isNumeric(transactionId)) { if (StringUtils.isNumeric(transactionId)) {
long id = Long.parseLong(transactionId); long id = Long.parseLong(transactionId);
savingsAccountTransaction = this.savingsAccountTransactionRepository.findOne(id); savingsAccountTransaction = this.savingsAccountTransactionRepository.findById(id).get();
modifiedTransactionId = SAVINGS_TRANSACTION_IDENTIFIER + transactionId; modifiedTransactionId = SAVINGS_TRANSACTION_IDENTIFIER + transactionId;
} }
final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId, final JournalEntry journalEntry = JournalEntry.createNew(office, paymentDetail, account, currencyCode, modifiedTransactionId,
@@ -165,8 +165,8 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
if (accountRuleId != null) { if (accountRuleId != null) {
final AccountingRule accountingRule = this.accountingRuleRepository.findOne(accountRuleId); final AccountingRule accountingRule = this.accountingRuleRepository.findById(accountRuleId)
if (accountingRule == null) { throw new AccountingRuleNotFoundException(accountRuleId); } .orElseThrow(() -> new AccountingRuleNotFoundException(accountRuleId));
if (accountingRule.getAccountToCredit() == null) { if (accountingRule.getAccountToCredit() == null) {
if (journalEntryCommand.getCredits() == null) { throw new JournalEntryInvalidException( if (journalEntryCommand.getCredits() == null) { throw new JournalEntryInvalidException(
@@ -604,8 +604,8 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
final JournalEntryType type, final String referenceNumber) { final JournalEntryType type, final String referenceNumber) {
final boolean manualEntry = true; final boolean manualEntry = true;
for (final SingleDebitOrCreditEntryCommand singleDebitOrCreditEntryCommand : singleDebitOrCreditEntryCommands) { for (final SingleDebitOrCreditEntryCommand singleDebitOrCreditEntryCommand : singleDebitOrCreditEntryCommands) {
final GLAccount glAccount = this.glAccountRepository.findOne(singleDebitOrCreditEntryCommand.getGlAccountId()); final GLAccount glAccount = this.glAccountRepository.findById(singleDebitOrCreditEntryCommand.getGlAccountId())
if (glAccount == null) { throw new GLAccountNotFoundException(singleDebitOrCreditEntryCommand.getGlAccountId()); } .orElseThrow(() -> new GLAccountNotFoundException(singleDebitOrCreditEntryCommand.getGlAccountId()));
validateGLAccountForTransaction(glAccount); validateGLAccountForTransaction(glAccount);
@@ -703,8 +703,8 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
final JournalEntryType type, final Long contraAccountId) { final JournalEntryType type, final Long contraAccountId) {
final boolean manualEntry = true; final boolean manualEntry = true;
final GLAccount contraAccount = this.glAccountRepository.findOne(contraAccountId); final GLAccount contraAccount = this.glAccountRepository.findById(contraAccountId)
if (contraAccount == null) { throw new GLAccountNotFoundException(contraAccountId); } .orElseThrow(() -> new GLAccountNotFoundException(contraAccountId));
if (!GLAccountType.fromInt(contraAccount.getType()).isEquityType()) { throw new GeneralPlatformDomainRuleException( if (!GLAccountType.fromInt(contraAccount.getType()).isEquityType()) { throw new GeneralPlatformDomainRuleException(
"error.msg.configuration.opening.balance.contra.account.value.is.invalid.account.type", "error.msg.configuration.opening.balance.contra.account.value.is.invalid.account.type",
"Global configuration 'office-opening-balances-contra-account' value is not an equity type account", contraAccountId); } "Global configuration 'office-opening-balances-contra-account' value is not an equity type account", contraAccountId); }
@@ -716,8 +716,8 @@ public class JournalEntryWritePlatformServiceJpaRepositoryImpl implements Journa
this.organisationCurrencyRepository.findOneWithNotFoundDetection(currencyCode); this.organisationCurrencyRepository.findOneWithNotFoundDetection(currencyCode);
for (final SingleDebitOrCreditEntryCommand singleDebitOrCreditEntryCommand : singleDebitOrCreditEntryCommands) { for (final SingleDebitOrCreditEntryCommand singleDebitOrCreditEntryCommand : singleDebitOrCreditEntryCommands) {
final GLAccount glAccount = this.glAccountRepository.findOne(singleDebitOrCreditEntryCommand.getGlAccountId()); final GLAccount glAccount = this.glAccountRepository.findById(singleDebitOrCreditEntryCommand.getGlAccountId())
if (glAccount == null) { throw new GLAccountNotFoundException(singleDebitOrCreditEntryCommand.getGlAccountId()); } .orElseThrow(() -> new GLAccountNotFoundException(singleDebitOrCreditEntryCommand.getGlAccountId()));
validateGLAccountForTransaction(glAccount); validateGLAccountForTransaction(glAccount);
@@ -104,8 +104,8 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements
@Override @Override
public CommandProcessingResult createProvisioningJournalEntries(Long provisioningEntryId, JsonCommand command) { public CommandProcessingResult createProvisioningJournalEntries(Long provisioningEntryId, JsonCommand command) {
ProvisioningEntry requestedEntry = this.provisioningEntryRepository.findOne(provisioningEntryId); ProvisioningEntry requestedEntry = this.provisioningEntryRepository.findById(provisioningEntryId)
if (requestedEntry == null) { throw new ProvisioningEntryNotfoundException(provisioningEntryId); } .orElseThrow(() -> new ProvisioningEntryNotfoundException(provisioningEntryId));
ProvisioningEntryData exisProvisioningEntryData = this.provisioningEntriesReadPlatformService ProvisioningEntryData exisProvisioningEntryData = this.provisioningEntriesReadPlatformService
.retrieveExistingProvisioningIdDateWithJournals(); .retrieveExistingProvisioningIdDateWithJournals();
@@ -205,8 +205,8 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements
@Override @Override
public CommandProcessingResult reCreateProvisioningEntries(Long provisioningEntryId, JsonCommand command) { public CommandProcessingResult reCreateProvisioningEntries(Long provisioningEntryId, JsonCommand command) {
ProvisioningEntry requestedEntry = this.provisioningEntryRepository.findOne(provisioningEntryId); ProvisioningEntry requestedEntry = this.provisioningEntryRepository.findById(provisioningEntryId)
if (requestedEntry == null) { throw new ProvisioningEntryNotfoundException(provisioningEntryId); } .orElseThrow(() -> new ProvisioningEntryNotfoundException(provisioningEntryId));
requestedEntry.getLoanProductProvisioningEntries().clear(); requestedEntry.getLoanProductProvisioningEntries().clear();
this.provisioningEntryRepository.save(requestedEntry); this.provisioningEntryRepository.save(requestedEntry);
Collection<LoanProductProvisioningEntry> entries = generateLoanProvisioningEntry(requestedEntry, requestedEntry.getCreatedDate()); Collection<LoanProductProvisioningEntry> entries = generateLoanProvisioningEntry(requestedEntry, requestedEntry.getCreatedDate());
@@ -220,11 +220,11 @@ public class ProvisioningEntriesWritePlatformServiceJpaRepositoryImpl implements
.retrieveLoanProductsProvisioningData(date); .retrieveLoanProductsProvisioningData(date);
Map<LoanProductProvisioningEntry, LoanProductProvisioningEntry> provisioningEntries = new HashMap<>(); Map<LoanProductProvisioningEntry, LoanProductProvisioningEntry> provisioningEntries = new HashMap<>();
for (LoanProductProvisioningEntryData data : entries) { for (LoanProductProvisioningEntryData data : entries) {
LoanProduct loanProduct = this.loanProductRepository.findOne(data.getProductId()); LoanProduct loanProduct = this.loanProductRepository.findById(data.getProductId()).get();
Office office = this.officeRepositoryWrapper.findOneWithNotFoundDetection(data.getOfficeId()); Office office = this.officeRepositoryWrapper.findOneWithNotFoundDetection(data.getOfficeId());
ProvisioningCategory provisioningCategory = provisioningCategoryRepository.findOne(data.getCategoryId()); ProvisioningCategory provisioningCategory = provisioningCategoryRepository.findById(data.getCategoryId()).get();
GLAccount liabilityAccount = glAccountRepository.findOne(data.getLiablityAccount()); GLAccount liabilityAccount = glAccountRepository.findById(data.getLiablityAccount()).get();
GLAccount expenseAccount = glAccountRepository.findOne(data.getExpenseAccount()); GLAccount expenseAccount = glAccountRepository.findById(data.getExpenseAccount()).get();
MonetaryCurrency currency = loanProduct.getPrincipalAmount().getCurrency(); MonetaryCurrency currency = loanProduct.getPrincipalAmount().getCurrency();
Money money = Money.of(currency, data.getOutstandingBalance()); Money money = Money.of(currency, data.getOutstandingBalance());
Money amountToReserve = money.percentageOf(data.getPercentage(), MoneyHelper.getRoundingMode()); Money amountToReserve = money.percentageOf(data.getPercentage(), MoneyHelper.getRoundingMode());
@@ -38,9 +38,7 @@ public class AccountingRuleRepositoryWrapper {
} }
public AccountingRule findOneWithNotFoundDetection(final Long id) { public AccountingRule findOneWithNotFoundDetection(final Long id) {
final AccountingRule accountingRule = this.repository.findOne(id); return this.repository.findById(id).orElseThrow(() -> new AccountingRuleNotFoundException(id));
if (accountingRule == null) { throw new AccountingRuleNotFoundException(id); }
return accountingRule;
} }
} }
@@ -335,8 +335,8 @@ public class AccountingRuleWritePlatformServiceJpaRepositoryImpl implements Acco
for (final String creditOrDebitTag : creditOrDebitTagArray) { for (final String creditOrDebitTag : creditOrDebitTagArray) {
if (creditOrDebitTag != null && StringUtils.isNotBlank(creditOrDebitTag)) { if (creditOrDebitTag != null && StringUtils.isNotBlank(creditOrDebitTag)) {
final Long creditOrDebitTagIdLongValue = Long.valueOf(creditOrDebitTag); final Long creditOrDebitTagIdLongValue = Long.valueOf(creditOrDebitTag);
final CodeValue creditOrDebitAccount = this.codeValueRepository.findOne(creditOrDebitTagIdLongValue); final CodeValue creditOrDebitAccount = this.codeValueRepository.findById(creditOrDebitTagIdLongValue)
if (creditOrDebitAccount == null) { throw new CodeValueNotFoundException(creditOrDebitTagIdLongValue); } .orElseThrow(() -> new CodeValueNotFoundException(creditOrDebitTagIdLongValue));
final AccountingTagRule accountingTagRule = AccountingTagRule.create(creditOrDebitAccount, transactionType.getValue()); final AccountingTagRule accountingTagRule = AccountingTagRule.create(creditOrDebitAccount, transactionType.getValue());
accountingTagRules.add(accountingTagRule); accountingTagRules.add(accountingTagRule);
} }
@@ -105,8 +105,7 @@ public class AdHocWritePlatformServiceJpaRepositoryImpl implements AdHocWritePla
this.adHocCommandFromApiJsonDeserializer.validateForUpdate(command.json()); this.adHocCommandFromApiJsonDeserializer.validateForUpdate(command.json());
final AdHoc adHoc = this.adHocRepository.findOne(adHocId); final AdHoc adHoc = this.adHocRepository.findById(adHocId).orElseThrow(() -> new AdHocNotFoundException(adHocId));
if (adHoc == null) { throw new AdHocNotFoundException(adHocId); }
final Map<String, Object> changes = adHoc.update(command); final Map<String, Object> changes = adHoc.update(command);
if (!changes.isEmpty()) { if (!changes.isEmpty()) {
@@ -136,9 +135,8 @@ public class AdHocWritePlatformServiceJpaRepositoryImpl implements AdHocWritePla
/** /**
* Checking the adhocQuery present in DB or not using adHocId * Checking the adhocQuery present in DB or not using adHocId
*/ */
final AdHoc adHoc = this.adHocRepository.findOne(adHocId); final AdHoc adHoc = this.adHocRepository.findById(adHocId).orElseThrow(() -> new AdHocNotFoundException(adHocId));
if (adHoc == null) { throw new AdHocNotFoundException(adHocId); }
this.adHocRepository.delete(adHoc); this.adHocRepository.delete(adHoc);
return new CommandProcessingResultBuilder().withEntityId(adHocId).build(); return new CommandProcessingResultBuilder().withEntityId(adHocId).build();
} catch (final DataIntegrityViolationException e) { } catch (final DataIntegrityViolationException e) {
@@ -157,8 +155,7 @@ public class AdHocWritePlatformServiceJpaRepositoryImpl implements AdHocWritePla
/** /**
* Checking the adhocquery present in DB or not using adHocId * Checking the adhocquery present in DB or not using adHocId
*/ */
final AdHoc adHoc = this.adHocRepository.findOne(adHocId); final AdHoc adHoc = this.adHocRepository.findById(adHocId).orElseThrow(() -> new AdHocNotFoundException(adHocId));
if (adHoc == null) { throw new AdHocNotFoundException(adHocId); }
adHoc.disableActive(); adHoc.disableActive();
this.adHocRepository.save(adHoc); this.adHocRepository.save(adHoc);
return new CommandProcessingResultBuilder().withEntityId(adHocId).build(); return new CommandProcessingResultBuilder().withEntityId(adHocId).build();
@@ -179,8 +176,7 @@ public class AdHocWritePlatformServiceJpaRepositoryImpl implements AdHocWritePla
/** /**
* Checking the adHoc present in DB or not using id * Checking the adHoc present in DB or not using id
*/ */
final AdHoc adHoc = this.adHocRepository.findOne(adHocId); final AdHoc adHoc = this.adHocRepository.findById(adHocId).orElseThrow(() -> new AdHocNotFoundException(adHocId));
if (adHoc == null) { throw new AdHocNotFoundException(adHocId); }
adHoc.enableActive(); adHoc.enableActive();
this.adHocRepository.save(adHoc); this.adHocRepository.save(adHoc);
return new CommandProcessingResultBuilder().withEntityId(adHocId).build(); return new CommandProcessingResultBuilder().withEntityId(adHocId).build();
@@ -190,4 +186,4 @@ public class AdHocWritePlatformServiceJpaRepositoryImpl implements AdHocWritePla
"Unknown data integrity issue with resource: " + e.getMostSpecificCause()); "Unknown data integrity issue with resource: " + e.getMostSpecificCause());
} }
} }
} }
@@ -159,15 +159,15 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio
validateMakerCheckerTransaction(makerCheckerId); validateMakerCheckerTransaction(makerCheckerId);
validateIsUpdateAllowed(); validateIsUpdateAllowed();
this.commandSourceRepository.delete(makerCheckerId); this.commandSourceRepository.deleteById(makerCheckerId);
return makerCheckerId; return makerCheckerId;
} }
private CommandSource validateMakerCheckerTransaction(final Long makerCheckerId) { private CommandSource validateMakerCheckerTransaction(final Long makerCheckerId) {
final CommandSource commandSourceInput = this.commandSourceRepository.findOne(makerCheckerId); final CommandSource commandSourceInput = this.commandSourceRepository.findById(makerCheckerId)
if (commandSourceInput == null) { throw new CommandNotFoundException(makerCheckerId); } .orElseThrow(() -> new CommandNotFoundException(makerCheckerId));
if (!(commandSourceInput.isMarkedAsAwaitingApproval())) { throw new CommandNotAwaitingApprovalException(makerCheckerId); } if (!(commandSourceInput.isMarkedAsAwaitingApproval())) { throw new CommandNotAwaitingApprovalException(makerCheckerId); }
this.context.authenticatedUser().validateHasCheckerPermissionTo(commandSourceInput.getPermissionCode()); this.context.authenticatedUser().validateHasCheckerPermissionTo(commandSourceInput.getPermissionCode());
@@ -189,4 +189,4 @@ public class PortfolioCommandSourceWritePlatformServiceImpl implements Portfolio
this.commandSourceRepository.save(commandSourceInput); this.commandSourceRepository.save(commandSourceInput);
return makerCheckerId; return makerCheckerId;
} }
} }
@@ -76,7 +76,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
public CommandProcessingResult processAndLogCommand(final CommandWrapper wrapper, final JsonCommand command, public CommandProcessingResult processAndLogCommand(final CommandWrapper wrapper, final JsonCommand command,
final boolean isApprovedByChecker) { final boolean isApprovedByChecker) {
final boolean rollbackTransaction = this.configurationDomainService.isMakerCheckerEnabledForTask(wrapper.taskPermissionName()); final boolean rollbackTransaction = this.configurationDomainService.isMakerCheckerEnabledForTask(wrapper.taskPermissionName());
final NewCommandSourceHandler handler = findCommandHandler(wrapper); final NewCommandSourceHandler handler = findCommandHandler(wrapper);
@@ -86,7 +86,7 @@ public class SynchronousCommandProcessingService implements CommandProcessingSer
CommandSource commandSourceResult = null; CommandSource commandSourceResult = null;
if (command.commandId() != null) { if (command.commandId() != null) {
commandSourceResult = this.commandSourceRepository.findOne(command.commandId()); commandSourceResult = this.commandSourceRepository.findById(command.commandId()).orElse(null);
commandSourceResult.markAsChecked(maker, DateTime.now()); commandSourceResult.markAsChecked(maker, DateTime.now());
} else { } else {
commandSourceResult = CommandSource.fullEntryFrom(wrapper, command, maker); commandSourceResult = CommandSource.fullEntryFrom(wrapper, command, maker);
@@ -33,9 +33,8 @@ public class AccountNumberFormatRepositoryWrapper {
} }
public AccountNumberFormat findOneWithNotFoundDetection(final Long id) { public AccountNumberFormat findOneWithNotFoundDetection(final Long id) {
final AccountNumberFormat accountNumberFormat = this.repository.findOne(id); return this.repository.findById(id)
if (accountNumberFormat == null) { throw new AccountNumberFormatNotFoundException(id); } .orElseThrow(() -> new AccountNumberFormatNotFoundException(id));
return accountNumberFormat;
} }
public void save(final AccountNumberFormat accountNumberFormat) { public void save(final AccountNumberFormat accountNumberFormat) {
@@ -53,4 +52,4 @@ public class AccountNumberFormatRepositoryWrapper {
public AccountNumberFormat findByAccountType(final EntityAccountType entityAccountType) { public AccountNumberFormat findByAccountType(final EntityAccountType entityAccountType) {
return this.repository.findOneByAccountTypeEnum(entityAccountType.getValue()); return this.repository.findOneByAccountTypeEnum(entityAccountType.getValue());
} }
} }
@@ -74,7 +74,7 @@ public class BulkImportEventListener implements ApplicationListener<BulkImportEv
.loadTenantById(tenantIdentifier); .loadTenantById(tenantIdentifier);
ThreadLocalContextUtil.setTenant(tenant); ThreadLocalContextUtil.setTenant(tenant);
ImportHandler importHandler = null; ImportHandler importHandler = null;
final ImportDocument importDocument = this.importRepository.findOne(event.getImportId()); final ImportDocument importDocument = this.importRepository.findById(event.getImportId()).orElse(null);
final GlobalEntityType entityType = GlobalEntityType.fromInt(importDocument.getEntityType()); final GlobalEntityType entityType = GlobalEntityType.fromInt(importDocument.getEntityType());
switch(entityType) { switch(entityType) {
@@ -171,4 +171,4 @@ public class BulkImportEventListener implements ApplicationListener<BulkImportEv
this.documentService.updateDocument(documentCommand, bis); this.documentService.updateDocument(documentCommand, bis);
} }
} }
@@ -193,7 +193,7 @@ public class BulkImportWorkbookServiceImpl implements BulkImportWorkbookService
DocumentWritePlatformServiceJpaRepositoryImpl.DOCUMENT_MANAGEMENT_ENTITY.IMPORT.name(), DocumentWritePlatformServiceJpaRepositoryImpl.DOCUMENT_MANAGEMENT_ENTITY.IMPORT.name(),
this.securityContext.authenticatedUser().getId(), null, clonedInputStreamWorkbook, this.securityContext.authenticatedUser().getId(), null, clonedInputStreamWorkbook,
URLConnection.guessContentTypeFromName(fileName), fileName, null, fileName); URLConnection.guessContentTypeFromName(fileName), fileName, null, fileName);
final Document document = this.documentRepository.findOne(documentId); final Document document = this.documentRepository.findById(documentId).orElse(null);
final ImportDocument importDocument = ImportDocument.instance(document, final ImportDocument importDocument = ImportDocument.instance(document,
DateUtils.getLocalDateTimeOfTenant(), entityType.getValue(), DateUtils.getLocalDateTimeOfTenant(), entityType.getValue(),
@@ -25,7 +25,7 @@ import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler; import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver; import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.DefaultKeyGenerator; import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -52,7 +52,7 @@ public class PlatformCacheConfiguration implements CachingConfigurer {
@Override @Override
public KeyGenerator keyGenerator() { public KeyGenerator keyGenerator() {
return new DefaultKeyGenerator(); return new SimpleKeyGenerator();
} }
@Override @Override
@@ -60,4 +60,4 @@ public class PlatformCacheConfiguration implements CachingConfigurer {
//TODO https://issues.apache.org/jira/browse/FINERACT-705 //TODO https://issues.apache.org/jira/browse/FINERACT-705
return null; return null;
} }
} }
@@ -85,8 +85,7 @@ public class EmailMessageAssembler {
} }
public EmailMessage assembleFromResourceId(final Long resourceId) { public EmailMessage assembleFromResourceId(final Long resourceId) {
final EmailMessage email = this.emailMessageRepository.findOne(resourceId); return this.emailMessageRepository.findById(resourceId)
if (email == null) { throw new EmailNotFoundException(resourceId); } .orElseThrow(() -> new EmailNotFoundException(resourceId));
return email;
} }
} }
@@ -131,13 +131,14 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai
final Long businessRuleId = command.longValueOfParameterNamed(EmailCampaignValidator.businessRuleId); final Long businessRuleId = command.longValueOfParameterNamed(EmailCampaignValidator.businessRuleId);
final Report businessRule = this.reportRepository.findOne(businessRuleId); final Report businessRule = this.reportRepository.findById(businessRuleId)
if (businessRule == null) { throw new ReportNotFoundException(businessRuleId); } .orElseThrow(() -> new ReportNotFoundException(businessRuleId));
final Long reportId = command.longValueOfParameterNamed(EmailCampaignValidator.stretchyReportId); final Long reportId = command.longValueOfParameterNamed(EmailCampaignValidator.stretchyReportId);
final Report report = this.reportRepository.findOne(reportId); final Report report = this.reportRepository.findById(reportId)
if (report == null) { throw new ReportNotFoundException(reportId); } .orElseThrow(() -> new ReportNotFoundException(reportId));
// find all report parameters and store them as json string // find all report parameters and store them as json string
final Set<ReportParameterUsage> reportParameterUsages = report.getReportParameterUsages(); final Set<ReportParameterUsage> reportParameterUsages = report.getReportParameterUsages();
final Map<String, String> stretchyReportParams = new HashMap<>(); final Map<String, String> stretchyReportParams = new HashMap<>();
@@ -165,16 +166,16 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai
try { try {
this.context.authenticatedUser(); this.context.authenticatedUser();
this.emailCampaignValidator.validateForUpdate(command.json()); this.emailCampaignValidator.validateForUpdate(command.json());
final EmailCampaign emailCampaign = this.emailCampaignRepository.findOne(resourceId); final EmailCampaign emailCampaign = this.emailCampaignRepository.findById(resourceId)
.orElseThrow(() -> new EmailCampaignNotFound(resourceId));
if (emailCampaign == null) { throw new EmailCampaignNotFound(resourceId); }
if (emailCampaign.isActive()) { throw new EmailCampaignMustBeClosedToEditException(emailCampaign.getId()); } if (emailCampaign.isActive()) { throw new EmailCampaignMustBeClosedToEditException(emailCampaign.getId()); }
final Map<String, Object> changes = emailCampaign.update(command); final Map<String, Object> changes = emailCampaign.update(command);
if (changes.containsKey(EmailCampaignValidator.businessRuleId)) { if (changes.containsKey(EmailCampaignValidator.businessRuleId)) {
final Long newValue = command.longValueOfParameterNamed(EmailCampaignValidator.businessRuleId); final Long newValue = command.longValueOfParameterNamed(EmailCampaignValidator.businessRuleId);
final Report reportId = this.reportRepository.findOne(newValue); final Report reportId = this.reportRepository.findById(newValue)
if (reportId == null) { throw new ReportNotFoundException(newValue); } .orElseThrow(() -> new ReportNotFoundException(newValue));
emailCampaign.updateBusinessRuleId(reportId); emailCampaign.updateBusinessRuleId(reportId);
} }
@@ -198,9 +199,9 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai
@Override @Override
public CommandProcessingResult delete(final Long resourceId) { public CommandProcessingResult delete(final Long resourceId) {
this.context.authenticatedUser(); this.context.authenticatedUser();
final EmailCampaign emailCampaign = this.emailCampaignRepository.findOne(resourceId); final EmailCampaign emailCampaign = this.emailCampaignRepository.findById(resourceId)
.orElseThrow(() -> new EmailCampaignNotFound(resourceId));
if (emailCampaign == null) { throw new EmailCampaignNotFound(resourceId); }
if (emailCampaign.isActive()) { throw new EmailCampaignMustBeClosedToBeDeletedException(emailCampaign.getId()); } if (emailCampaign.isActive()) { throw new EmailCampaignMustBeClosedToBeDeletedException(emailCampaign.getId()); }
/* /*
@@ -231,7 +232,7 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai
for (HashMap<String, Object> entry : runReportObject) { for (HashMap<String, Object> entry : runReportObject) {
String message = this.compileEmailTemplate(messageTemplate, campaignName, entry); String message = this.compileEmailTemplate(messageTemplate, campaignName, entry);
Integer clientId = (Integer) entry.get("id"); Integer clientId = (Integer) entry.get("id");
EmailCampaign emailCampaign = this.emailCampaignRepository.findOne(campaignId); EmailCampaign emailCampaign = this.emailCampaignRepository.findById(campaignId).orElse(null);
Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId.longValue()); Client client = this.clientRepositoryWrapper.findOneWithNotFoundDetection(clientId.longValue());
String emailAddress = client.emailAddress(); String emailAddress = client.emailAddress();
@@ -285,8 +286,8 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai
} }
private void updateTriggerDates(Long campaignId) { private void updateTriggerDates(Long campaignId) {
final EmailCampaign emailCampaign = this.emailCampaignRepository.findOne(campaignId); final EmailCampaign emailCampaign = this.emailCampaignRepository.findById(campaignId)
if (emailCampaign == null) { throw new EmailCampaignNotFound(campaignId); } .orElseThrow(() -> new EmailCampaignNotFound(campaignId));
LocalDateTime nextTriggerDate = emailCampaign.getNextTriggerDate(); LocalDateTime nextTriggerDate = emailCampaign.getNextTriggerDate();
emailCampaign.setLastTriggerDate(nextTriggerDate.toDate()); emailCampaign.setLastTriggerDate(nextTriggerDate.toDate());
// calculate new trigger date and insert into next trigger date // calculate new trigger date and insert into next trigger date
@@ -327,9 +328,8 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai
this.emailCampaignValidator.validateActivation(command.json()); this.emailCampaignValidator.validateActivation(command.json());
final EmailCampaign emailCampaign = this.emailCampaignRepository.findOne(campaignId); final EmailCampaign emailCampaign = this.emailCampaignRepository.findById(campaignId)
.orElseThrow(() -> new EmailCampaignNotFound(campaignId));
if (emailCampaign == null) { throw new EmailCampaignNotFound(campaignId); }
final Locale locale = command.extractLocale(); final Locale locale = command.extractLocale();
final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
@@ -387,8 +387,8 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai
final AppUser currentUser = this.context.authenticatedUser(); final AppUser currentUser = this.context.authenticatedUser();
this.emailCampaignValidator.validateClosedDate(command.json()); this.emailCampaignValidator.validateClosedDate(command.json());
final EmailCampaign emailCampaign = this.emailCampaignRepository.findOne(campaignId); final EmailCampaign emailCampaign = this.emailCampaignRepository.findById(campaignId)
if (emailCampaign == null) { throw new EmailCampaignNotFound(campaignId); } .orElseThrow(() -> new EmailCampaignNotFound(campaignId));
final Locale locale = command.extractLocale(); final Locale locale = command.extractLocale();
final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
@@ -485,9 +485,8 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai
final AppUser currentUser = this.context.authenticatedUser(); final AppUser currentUser = this.context.authenticatedUser();
final EmailCampaign emailCampaign = this.emailCampaignRepository.findOne(campaignId); final EmailCampaign emailCampaign = this.emailCampaignRepository.findById(campaignId)
.orElseThrow(() -> new EmailCampaignNotFound(campaignId));
if (emailCampaign == null) { throw new EmailCampaignNotFound(campaignId); }
final Locale locale = command.extractLocale(); final Locale locale = command.extractLocale();
final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
@@ -562,7 +561,7 @@ public class EmailCampaignWritePlatformCommandHandlerImpl implements EmailCampai
if (isValidEmail(emailMessage.getEmailAddress())) { if (isValidEmail(emailMessage.getEmailAddress())) {
final EmailCampaign emailCampaign = this.emailCampaignRepository.findOne(emailMessage.getEmailCampaign().getId()); // final EmailCampaign emailCampaign = this.emailCampaignRepository.findById(emailMessage.getEmailCampaign().getId()).orElse(null); //
final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat = ScheduledEmailAttachmentFileFormat final ScheduledEmailAttachmentFileFormat emailAttachmentFileFormat = ScheduledEmailAttachmentFileFormat
.instance(emailCampaign.getEmailAttachmentFileFormat()); .instance(emailCampaign.getEmailAttachmentFileFormat());
@@ -185,7 +185,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService {
"Loan Type cannot be Invalid for the Triggered Sms Campaign"); "Loan Type cannot be Invalid for the Triggered Sms Campaign");
} }
if (loan.isGroupLoan()) { if (loan.isGroupLoan()) {
Group group = this.groupRepository.findOne(loan.getGroupId()); Group group = this.groupRepository.findById(loan.getGroupId()).orElse(null);
groupClients.addAll(group.getClientMembers()); groupClients.addAll(group.getClientMembers());
} else { } else {
groupClients.add(loan.client()); groupClients.add(loan.client());
@@ -206,7 +206,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService {
} }
if (spkeycheck && !(value.equals("-1") || spvalue.equals(value))) { if (spkeycheck && !(value.equals("-1") || spvalue.equals(value))) {
if (key.equals("officeId")) { if (key.equals("officeId")) {
Office campaignOffice = this.officeRepository.findOne(Long.valueOf(value)); Office campaignOffice = this.officeRepository.findById(Long.valueOf(value)).orElse(null);
if (campaignOffice if (campaignOffice
.doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) { .doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) {
throw new SmsRuntimeException("error.msg.no.office", throw new SmsRuntimeException("error.msg.no.office",
@@ -266,7 +266,7 @@ public class SmsCampaignDomainServiceImpl implements SmsCampaignDomainService {
} }
if (spkeycheck && !(value.equals("-1") || spvalue.equals(value))) { if (spkeycheck && !(value.equals("-1") || spvalue.equals(value))) {
if (key.equals("officeId")) { if (key.equals("officeId")) {
Office campaignOffice = this.officeRepository.findOne(Long.valueOf(value)); Office campaignOffice = this.officeRepository.findById(Long.valueOf(value)).orElse(null);
if (campaignOffice.doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) { if (campaignOffice.doesNotHaveAnOfficeInHierarchyWithId(client.getOffice().getId())) {
throw new SmsRuntimeException("error.msg.no.office", throw new SmsRuntimeException("error.msg.no.office",
"Office not found for the id"); "Office not found for the id");
@@ -142,8 +142,8 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
final AppUser currentUser = this.context.authenticatedUser(); final AppUser currentUser = this.context.authenticatedUser();
this.smsCampaignValidator.validateCreate(command.json()); this.smsCampaignValidator.validateCreate(command.json());
final Long runReportId = command.longValueOfParameterNamed(SmsCampaignValidator.runReportId); final Long runReportId = command.longValueOfParameterNamed(SmsCampaignValidator.runReportId);
Report report = this.reportRepository.findOne(runReportId); Report report = this.reportRepository.findById(runReportId)
if (report == null) { throw new ReportNotFoundException(runReportId); } .orElseThrow(() -> new ReportNotFoundException(runReportId));
SmsCampaign smsCampaign = SmsCampaign.instance(currentUser, report, command); SmsCampaign smsCampaign = SmsCampaign.instance(currentUser, report, command);
if (smsCampaign.getRecurrenceStartDate() != null && smsCampaign.getRecurrenceStartDate().isBefore(DateUtils.getLocalDateOfTenant())) { throw new GeneralPlatformDomainRuleException( if (smsCampaign.getRecurrenceStartDate() != null && smsCampaign.getRecurrenceStartDate().isBefore(DateUtils.getLocalDateOfTenant())) { throw new GeneralPlatformDomainRuleException(
"error.msg.campaign.recurrenceStartDate.in.the.past", "Recurrence start date cannot be the past date.", "error.msg.campaign.recurrenceStartDate.in.the.past", "Recurrence start date cannot be the past date.",
@@ -163,17 +163,16 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
this.context.authenticatedUser(); this.context.authenticatedUser();
this.smsCampaignValidator.validateForUpdate(command.json()); this.smsCampaignValidator.validateForUpdate(command.json());
final SmsCampaign smsCampaign = this.smsCampaignRepository.findOne(resourceId); final SmsCampaign smsCampaign = this.smsCampaignRepository.findById(resourceId)
.orElseThrow(() -> new SmsCampaignNotFound(resourceId));
if (smsCampaign == null) { throw new SmsCampaignNotFound(resourceId); }
if (smsCampaign.isActive()) { throw new SmsCampaignMustBeClosedToEditException(smsCampaign.getId()); } if (smsCampaign.isActive()) { throw new SmsCampaignMustBeClosedToEditException(smsCampaign.getId()); }
final Map<String, Object> changes = smsCampaign.update(command); final Map<String, Object> changes = smsCampaign.update(command);
if (changes.containsKey(SmsCampaignValidator.runReportId)) { if (changes.containsKey(SmsCampaignValidator.runReportId)) {
final Long newValue = command.longValueOfParameterNamed(SmsCampaignValidator.runReportId); final Long newValue = command.longValueOfParameterNamed(SmsCampaignValidator.runReportId);
final Report reportId = this.reportRepository.findOne(newValue); final Report reportId = this.reportRepository.findById(newValue)
if (reportId == null) { throw new ReportNotFoundException(newValue); } .orElseThrow(() -> new ReportNotFoundException(newValue));
;
smsCampaign.updateBusinessRuleId(reportId); smsCampaign.updateBusinessRuleId(reportId);
} }
@@ -196,9 +195,9 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
@Override @Override
public CommandProcessingResult delete(final Long resourceId) { public CommandProcessingResult delete(final Long resourceId) {
this.context.authenticatedUser(); this.context.authenticatedUser();
final SmsCampaign smsCampaign = this.smsCampaignRepository.findOne(resourceId); final SmsCampaign smsCampaign = this.smsCampaignRepository.findById(resourceId)
.orElseThrow(() -> new SmsCampaignNotFound(resourceId));
if (smsCampaign == null) { throw new SmsCampaignNotFound(resourceId); }
if (smsCampaign.isActive()) { throw new SmsCampaignMustBeClosedToBeDeletedException(smsCampaign.getId()); } if (smsCampaign.isActive()) { throw new SmsCampaignMustBeClosedToBeDeletedException(smsCampaign.getId()); }
/* /*
@@ -267,7 +266,7 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
queryParamForRunReport.put("loanId", loan.getId().toString()); queryParamForRunReport.put("loanId", loan.getId().toString());
if (loan.isGroupLoan()) { if (loan.isGroupLoan()) {
Group group = this.groupRepository.findOne(loan.getGroupId()); Group group = this.groupRepository.findById(loan.getGroupId()).orElse(null);
clientSet.addAll(group.getClientMembers()); clientSet.addAll(group.getClientMembers());
queryParamForRunReport.put("groupId", group.getId().toString()); queryParamForRunReport.put("groupId", group.getId().toString());
} else { } else {
@@ -402,8 +401,8 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
} }
private void updateTriggerDates(Long campaignId) { private void updateTriggerDates(Long campaignId) {
final SmsCampaign smsCampaign = this.smsCampaignRepository.findOne(campaignId); final SmsCampaign smsCampaign = this.smsCampaignRepository.findById(campaignId)
if (smsCampaign == null) { throw new SmsCampaignNotFound(campaignId); } .orElseThrow(() -> new SmsCampaignNotFound(campaignId));
LocalDateTime nextTriggerDate = smsCampaign.getNextTriggerDate(); LocalDateTime nextTriggerDate = smsCampaign.getNextTriggerDate();
smsCampaign.setLastTriggerDate(nextTriggerDate.toDate()); smsCampaign.setLastTriggerDate(nextTriggerDate.toDate());
// calculate new trigger date and insert into next trigger date // calculate new trigger date and insert into next trigger date
@@ -444,9 +443,8 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
this.smsCampaignValidator.validateActivation(command.json()); this.smsCampaignValidator.validateActivation(command.json());
final SmsCampaign smsCampaign = this.smsCampaignRepository.findOne(campaignId); final SmsCampaign smsCampaign = this.smsCampaignRepository.findById(campaignId)
.orElseThrow(() -> new SmsCampaignNotFound(campaignId));
if (smsCampaign == null) { throw new SmsCampaignNotFound(campaignId); }
final Locale locale = command.extractLocale(); final Locale locale = command.extractLocale();
final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
@@ -501,8 +499,8 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
final AppUser currentUser = this.context.authenticatedUser(); final AppUser currentUser = this.context.authenticatedUser();
this.smsCampaignValidator.validateClosedDate(command.json()); this.smsCampaignValidator.validateClosedDate(command.json());
final SmsCampaign smsCampaign = this.smsCampaignRepository.findOne(campaignId); final SmsCampaign smsCampaign = this.smsCampaignRepository.findById(campaignId)
if (smsCampaign == null) { throw new SmsCampaignNotFound(campaignId); } .orElseThrow(() -> new SmsCampaignNotFound(campaignId));
final Locale locale = command.extractLocale(); final Locale locale = command.extractLocale();
final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
@@ -610,9 +608,8 @@ public class SmsCampaignWritePlatformServiceJpaImpl implements SmsCampaignWriteP
final AppUser currentUser = this.context.authenticatedUser(); final AppUser currentUser = this.context.authenticatedUser();
final SmsCampaign smsCampaign = this.smsCampaignRepository.findOne(campaignId); final SmsCampaign smsCampaign = this.smsCampaignRepository.findById(campaignId)
.orElseThrow(() -> new SmsCampaignNotFound(campaignId));
if (smsCampaign == null) { throw new SmsCampaignNotFound(campaignId); }
final Locale locale = command.extractLocale(); final Locale locale = command.extractLocale();
final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale); final DateTimeFormatter fmt = DateTimeFormat.forPattern(command.dateFormat()).withLocale(locale);
@@ -46,9 +46,7 @@ public class CodeValueRepositoryWrapper {
} }
public CodeValue findOneWithNotFoundDetection(final Long id) { public CodeValue findOneWithNotFoundDetection(final Long id) {
final CodeValue codeValue = this.repository.findOne(id); return this.repository.findById(id).orElseThrow(() -> new CodeValueNotFoundException(id));
if (codeValue == null) { throw new CodeValueNotFoundException(id); }
return codeValue;
} }
public CodeValue findOneByCodeNameAndIdWithNotFoundDetection(final String codeName, final Long id) { public CodeValue findOneByCodeNameAndIdWithNotFoundDetection(final String codeName, final Long id) {
@@ -63,4 +61,4 @@ public class CodeValueRepositoryWrapper {
return codeValue; return codeValue;
} }
} }
@@ -96,7 +96,7 @@ public class CodeValueReadPlatformServiceImpl implements CodeValueReadPlatformSe
this.context.authenticatedUser(); this.context.authenticatedUser();
final CodeValueDataMapper rm = new CodeValueDataMapper(); final CodeValueDataMapper rm = new CodeValueDataMapper();
final String sql = "select " + rm.schema() + "where cv.id = ? order by position"; final String sql = "select " + rm.schema() + " where cv.id = ? order by position";
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { codeValueId }); return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { codeValueId });
} catch (final EmptyResultDataAccessException e) { } catch (final EmptyResultDataAccessException e) {
@@ -104,4 +104,4 @@ public class CodeValueReadPlatformServiceImpl implements CodeValueReadPlatformSe
} }
} }
} }
@@ -73,10 +73,8 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue
this.fromApiJsonDeserializer.validateForCreate(command.json()); this.fromApiJsonDeserializer.validateForCreate(command.json());
final Long codeId = command.entityId(); final Long codeId = command.entityId();
final Code code = this.codeRepository.findOne(codeId); final Code code = this.codeRepository.findById(codeId)
if (code == null) { .orElseThrow(() -> new CodeNotFoundException(codeId));
throw new CodeNotFoundException(codeId);
}
final CodeValue codeValue = CodeValue.fromJson(code, command); final CodeValue codeValue = CodeValue.fromJson(code, command);
this.codeValueRepository.save(codeValue); this.codeValueRepository.save(codeValue);
@@ -149,8 +147,8 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue
try { try {
this.context.authenticatedUser(); this.context.authenticatedUser();
final Code code = this.codeRepository.findOne(codeId); final Code code = this.codeRepository.findById(codeId)
if (code == null) { throw new CodeNotFoundException(codeId); } .orElseThrow(() -> new CodeNotFoundException(codeId));
final CodeValue codeValueToDelete = this.codeValueRepositoryWrapper.findOneWithNotFoundDetection(codeValueId); final CodeValue codeValueToDelete = this.codeValueRepositoryWrapper.findOneWithNotFoundDetection(codeValueId);
@@ -172,4 +170,4 @@ public class CodeValueWritePlatformServiceJpaRepositoryImpl implements CodeValue
"Unknown data integrity issue with resource: " + dve.getMostSpecificCause().getMessage()); "Unknown data integrity issue with resource: " + dve.getMostSpecificCause().getMessage());
} }
} }
} }
@@ -135,9 +135,8 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
} }
private Code retrieveCodeBy(final Long codeId) { private Code retrieveCodeBy(final Long codeId) {
final Code code = this.codeRepository.findOne(codeId); return this.codeRepository.findById(codeId)
if (code == null) { throw new CodeNotFoundException(codeId.toString()); } .orElseThrow(() -> new CodeNotFoundException(codeId.toString()));
return code;
} }
/* /*
@@ -155,4 +154,4 @@ public class CodeWritePlatformServiceJpaRepositoryImpl implements CodeWritePlatf
throw new PlatformDataIntegrityException("error.msg.cund.unknown.data.integrity.issue", throw new PlatformDataIntegrityException("error.msg.cund.unknown.data.integrity.issue",
"Unknown data integrity issue with resource: " + realCause.getMessage()); "Unknown data integrity issue with resource: " + realCause.getMessage());
} }
} }
@@ -112,13 +112,13 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService
@Override @Override
public boolean isEhcacheEnabled() { public boolean isEhcacheEnabled() {
return this.cacheTypeRepository.findOne(Long.valueOf(1)).isEhcacheEnabled(); return this.cacheTypeRepository.findById(1L).get().isEhcacheEnabled();
} }
@Transactional @Transactional
@Override @Override
public void updateCache(final CacheType cacheType) { public void updateCache(final CacheType cacheType) {
final PlatformCache cache = this.cacheTypeRepository.findOne(Long.valueOf(1)); final PlatformCache cache = this.cacheTypeRepository.findById(1L).get();
cache.update(cacheType); cache.update(cacheType);
this.cacheTypeRepository.save(cache); this.cacheTypeRepository.save(cache);
} }
@@ -333,4 +333,4 @@ public class ConfigurationDomainServiceJpa implements ConfigurationDomainService
} }
return configurations.get(key); return configurations.get(key);
} }
} }
@@ -45,9 +45,8 @@ public class GlobalConfigurationRepositoryWrapper {
} }
public GlobalConfigurationProperty findOneWithNotFoundDetection(final Long configId) { public GlobalConfigurationProperty findOneWithNotFoundDetection(final Long configId) {
final GlobalConfigurationProperty property = this.repository.findOne(configId); return this.repository.findById(configId)
if (property == null) { throw new GlobalConfigurationPropertyNotFoundException(configId); } .orElseThrow(() -> new GlobalConfigurationPropertyNotFoundException(configId));
return property;
} }
public void save(final GlobalConfigurationProperty globalConfigurationProperty) { public void save(final GlobalConfigurationProperty globalConfigurationProperty) {
@@ -62,4 +61,4 @@ public class GlobalConfigurationRepositoryWrapper {
this.repository.delete(globalConfigurationProperty); this.repository.delete(globalConfigurationProperty);
} }
} }
@@ -21,13 +21,17 @@ package org.apache.fineract.infrastructure.core.boot;
import org.apache.fineract.notification.config.MessagingConfiguration; import org.apache.fineract.notification.config.MessagingConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration; import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/** /**
* Base Spring Configuration with what's common to all Configuration subclasses. * Base Spring Configuration with what's common to all Configuration subclasses.
@@ -48,7 +52,11 @@ import org.springframework.context.annotation.PropertySource;
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class,
FlywayAutoConfiguration.class }) FlywayAutoConfiguration.class,
GsonAutoConfiguration.class,
JdbcTemplateAutoConfiguration.class})
@EnableWebSecurity
@EnableTransactionManagement
public abstract class AbstractApplicationConfiguration { public abstract class AbstractApplicationConfiguration {
} }
@@ -25,8 +25,7 @@ import java.net.URL;
import org.apache.catalina.connector.Connector; import org.apache.catalina.connector.Connector;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.coyote.http11.Http11NioProtocol; import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
@@ -38,8 +37,8 @@ public class EmbeddedTomcatWithSSLConfiguration {
// http://docs.spring.io/spring-boot/docs/1.1.5.RELEASE/reference/htmlsingle/#howto-enable-multiple-connectors-in-tomcat // http://docs.spring.io/spring-boot/docs/1.1.5.RELEASE/reference/htmlsingle/#howto-enable-multiple-connectors-in-tomcat
@Bean @Bean
public EmbeddedServletContainerFactory servletContainer() { public TomcatServletWebServerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.setContextPath(getContextPath()); tomcat.setContextPath(getContextPath());
tomcat.addAdditionalTomcatConnectors(createSslConnector()); tomcat.addAdditionalTomcatConnectors(createSslConnector());
return tomcat; return tomcat;
@@ -117,4 +116,4 @@ public class EmbeddedTomcatWithSSLConfiguration {
} }
} }
} }
@@ -19,7 +19,7 @@
package org.apache.fineract.infrastructure.core.boot; package org.apache.fineract.infrastructure.core.boot;
import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.ImportResource;
/** /**
@@ -50,4 +50,4 @@ public class WarWebApplicationInitializer extends SpringBootServletInitializer {
return application.sources(Configuration.class); return application.sources(Configuration.class);
} }
} }
@@ -19,7 +19,7 @@
package org.apache.fineract.infrastructure.core.boot; package org.apache.fineract.infrastructure.core.boot;
import org.apache.fineract.infrastructure.security.filter.TwoFactorAuthenticationFilter; import org.apache.fineract.infrastructure.security.filter.TwoFactorAuthenticationFilter;
import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -24,8 +24,9 @@ import javax.servlet.Servlet;
import org.apache.fineract.infrastructure.core.filters.ResponseCorsFilter; import org.apache.fineract.infrastructure.core.filters.ResponseCorsFilter;
import org.apache.fineract.infrastructure.security.filter.TenantAwareBasicAuthenticationFilter; import org.apache.fineract.infrastructure.security.filter.TenantAwareBasicAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Profile;
@@ -46,10 +47,12 @@ public class WebXmlConfiguration {
@Autowired @Autowired
private TenantAwareBasicAuthenticationFilter basicAuthenticationProcessingFilter; private TenantAwareBasicAuthenticationFilter basicAuthenticationProcessingFilter;
/*
@Bean @Bean
public Filter springSecurityFilterChain() { public Filter springSecurityFilterChain() {
return new DelegatingFilterProxy(); return new DelegatingFilterProxy();
} }
*/
@Bean @Bean
public ServletRegistrationBean jersey() { public ServletRegistrationBean jersey() {
@@ -77,4 +80,4 @@ public class WebXmlConfiguration {
return filterRegistrationBean; return filterRegistrationBean;
} }
} }
@@ -21,7 +21,7 @@ package org.apache.fineract.infrastructure.core.boot;
import javax.servlet.Filter; import javax.servlet.Filter;
import javax.servlet.Servlet; import javax.servlet.Servlet;
import org.springframework.boot.context.embedded.ServletRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Profile;
@@ -71,4 +71,4 @@ public class WebXmlOauthConfiguration {
return registrationBean; return registrationBean;
} }
} }
@@ -19,7 +19,9 @@
package org.apache.fineract.infrastructure.core.domain; package org.apache.fineract.infrastructure.core.domain;
import java.io.Serializable; import java.io.Serializable;
import java.time.Instant;
import java.util.Date; import java.util.Date;
import java.util.Optional;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.FetchType; import javax.persistence.FetchType;
@@ -47,7 +49,7 @@ import org.springframework.data.jpa.domain.AbstractAuditable;
* the type of the auditing type's identifier * the type of the auditing type's identifier
*/ */
@MappedSuperclass @MappedSuperclass
public abstract class AbstractAuditableCustom<U, PK extends Serializable> extends AbstractPersistableCustom<PK> implements Auditable<AppUser, Long> { public abstract class AbstractAuditableCustom<U, PK extends Serializable> extends AbstractPersistableCustom<PK> implements Auditable<AppUser, Long, Instant> {
private static final long serialVersionUID = 141481953116476081L; private static final long serialVersionUID = 141481953116476081L;
@@ -73,9 +75,8 @@ public abstract class AbstractAuditableCustom<U, PK extends Serializable> extend
* @see org.springframework.data.domain.Auditable#getCreatedBy() * @see org.springframework.data.domain.Auditable#getCreatedBy()
*/ */
@Override @Override
public AppUser getCreatedBy() { public Optional<AppUser> getCreatedBy() {
return Optional.ofNullable(this.createdBy);
return this.createdBy;
} }
/* /*
@@ -96,22 +97,19 @@ public abstract class AbstractAuditableCustom<U, PK extends Serializable> extend
* @see org.springframework.data.domain.Auditable#getCreatedDate() * @see org.springframework.data.domain.Auditable#getCreatedDate()
*/ */
@Override @Override
public DateTime getCreatedDate() { public Optional<Instant> getCreatedDate() {
return null == this.createdDate ? Optional.empty() : Optional.of(this.createdDate.toInstant());
return null == this.createdDate ? null : new DateTime(this.createdDate);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see * @see
* org.springframework.data.domain.Auditable#setCreatedDate(org.joda.time * org.springframework.data.domain.Auditable#setCreatedDate(T)
* .DateTime)
*/ */
@Override @Override
public void setCreatedDate(final DateTime createdDate) { public void setCreatedDate(final Instant createdDate) {
this.createdDate = null == createdDate ? null : Date.from(createdDate);
this.createdDate = null == createdDate ? null : createdDate.toDate();
} }
/* /*
@@ -120,9 +118,8 @@ public abstract class AbstractAuditableCustom<U, PK extends Serializable> extend
* @see org.springframework.data.domain.Auditable#getLastModifiedBy() * @see org.springframework.data.domain.Auditable#getLastModifiedBy()
*/ */
@Override @Override
public AppUser getLastModifiedBy() { public Optional<AppUser> getLastModifiedBy() {
return Optional.ofNullable(this.lastModifiedBy);
return this.lastModifiedBy;
} }
/* /*
@@ -144,21 +141,18 @@ public abstract class AbstractAuditableCustom<U, PK extends Serializable> extend
* @see org.springframework.data.domain.Auditable#getLastModifiedDate() * @see org.springframework.data.domain.Auditable#getLastModifiedDate()
*/ */
@Override @Override
public DateTime getLastModifiedDate() { public Optional<Instant> getLastModifiedDate() {
return null == this.lastModifiedDate ? Optional.empty() : Optional.of(this.lastModifiedDate.toInstant());
return null == this.lastModifiedDate ? null : new DateTime(this.lastModifiedDate);
} }
/* /*
* (non-Javadoc) * (non-Javadoc)
* *
* @see * @see
* org.springframework.data.domain.Auditable#setLastModifiedDate(org.joda * org.springframework.data.domain.Auditable#setLastModifiedDate(T)
* .time.DateTime)
*/ */
@Override @Override
public void setLastModifiedDate(final DateTime lastModifiedDate) { public void setLastModifiedDate(final Instant lastModifiedDate) {
this.lastModifiedDate = null == lastModifiedDate ? null : Date.from(lastModifiedDate);
this.lastModifiedDate = null == lastModifiedDate ? null : lastModifiedDate.toDate();
} }
} }
@@ -26,20 +26,21 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import java.util.Optional;
public class AuditorAwareImpl implements AuditorAware<AppUser> { public class AuditorAwareImpl implements AuditorAware<AppUser> {
@Autowired @Autowired
private AppUserRepository userRepository; private AppUserRepository userRepository;
@Override @Override
public AppUser getCurrentAuditor() { public Optional<AppUser> getCurrentAuditor() {
Optional<AppUser> currentUser;
AppUser currentUser = null;
final SecurityContext securityContext = SecurityContextHolder.getContext(); final SecurityContext securityContext = SecurityContextHolder.getContext();
if (securityContext != null) { if (securityContext != null) {
final Authentication authentication = securityContext.getAuthentication(); final Authentication authentication = securityContext.getAuthentication();
if (authentication != null) { if (authentication != null) {
currentUser = (AppUser) authentication.getPrincipal(); currentUser = Optional.ofNullable((AppUser) authentication.getPrincipal());
} else { } else {
currentUser = retrieveSuperUser(); currentUser = retrieveSuperUser();
} }
@@ -49,7 +50,7 @@ public class AuditorAwareImpl implements AuditorAware<AppUser> {
return currentUser; return currentUser;
} }
private AppUser retrieveSuperUser() { private Optional<AppUser> retrieveSuperUser() {
return this.userRepository.findOne(Long.valueOf("1")); return this.userRepository.findById(Long.valueOf("1"));
} }
} }
@@ -0,0 +1,54 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.infrastructure.core.domain;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.Md4PasswordEncoder;
import org.springframework.security.crypto.password.MessageDigestPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import java.util.HashMap;
import java.util.Map;
public class DefaultPasswordEncoderFactories {
@SuppressWarnings("deprecation")
public static PasswordEncoder createDelegatingPasswordEncoder() {
String encodingId = "bcrypt";
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(encodingId, new BCryptPasswordEncoder());
encoders.put("ldap", new org.springframework.security.crypto.password.LdapShaPasswordEncoder());
encoders.put("MD4", new Md4PasswordEncoder());
encoders.put("MD5", new MessageDigestPasswordEncoder("MD5"));
encoders.put("noop", NoOpPasswordEncoder.getInstance());
encoders.put("pbkdf2", new Pbkdf2PasswordEncoder());
encoders.put("scrypt", new SCryptPasswordEncoder());
encoders.put("SHA-1", new MessageDigestPasswordEncoder("SHA-1"));
encoders.put("SHA-256", new MessageDigestPasswordEncoder("SHA-256"));
DelegatingPasswordEncoder delegatingPasswordEncoder = new DelegatingPasswordEncoder(encodingId, encoders);
delegatingPasswordEncoder.setDefaultPasswordEncoderForMatches(new MessageDigestPasswordEncoder("SHA-256"));
return delegatingPasswordEncoder;
}
}
@@ -22,8 +22,8 @@ import org.apache.fineract.infrastructure.security.domain.PlatformUser;
import org.apache.fineract.infrastructure.security.service.PlatformPasswordEncoder; import org.apache.fineract.infrastructure.security.service.PlatformPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@@ -32,16 +32,14 @@ import org.springframework.stereotype.Service;
public class DefaultPlatformPasswordEncoder implements PlatformPasswordEncoder { public class DefaultPlatformPasswordEncoder implements PlatformPasswordEncoder {
private final PasswordEncoder passwordEncoder; private final PasswordEncoder passwordEncoder;
private final SaltSource saltSource;
@Autowired @Autowired
public DefaultPlatformPasswordEncoder(final PasswordEncoder passwordEncoder, final SaltSource saltSource) { public DefaultPlatformPasswordEncoder(final PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
this.saltSource = saltSource;
} }
@Override @Override
public String encode(final PlatformUser appUser) { public String encode(final PlatformUser appUser) {
return this.passwordEncoder.encodePassword(appUser.getPassword(), this.saltSource.getSalt(appUser)); return this.passwordEncoder.encode(appUser.getPassword());
} }
} }
@@ -0,0 +1,33 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.infrastructure.core.security;
import org.apache.fineract.infrastructure.core.domain.DefaultPasswordEncoderFactories;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return DefaultPasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
@@ -37,7 +37,7 @@ import org.joda.time.LocalDateTime;
import org.joda.time.MonthDay; import org.joda.time.MonthDay;
import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatter;
import org.springframework.format.number.NumberFormatter; import org.springframework.format.number.NumberStyleFormatter;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
@@ -622,7 +622,7 @@ public class JsonParserHelper {
source = source.replaceAll(" ", Character.toString('\u00a0')); source = source.replaceAll(" ", Character.toString('\u00a0'));
} }
final NumberFormatter numberFormatter = new NumberFormatter(); final NumberStyleFormatter numberFormatter = new NumberStyleFormatter();
final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale); final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale);
if (parsedNumber instanceof BigDecimal) { if (parsedNumber instanceof BigDecimal) {
number = (BigDecimal) parsedNumber; number = (BigDecimal) parsedNumber;
@@ -719,4 +719,4 @@ public class JsonParserHelper {
} }
return clientApplicationLocale; return clientApplicationLocale;
} }
} }
@@ -20,6 +20,7 @@ package org.apache.fineract.infrastructure.core.service;
import java.util.List; import java.util.List;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.RowMapper;
@@ -31,8 +32,8 @@ public class PaginationHelper<E> {
final List<E> items = jt.query(sqlFetchRows, args, rowMapper); final List<E> items = jt.query(sqlFetchRows, args, rowMapper);
// determine how many rows are available // determine how many rows are available
@SuppressWarnings("deprecation") // final int totalFilteredRecords = jt.queryForInt(sqlCountRows);
final int totalFilteredRecords = jt.queryForInt(sqlCountRows); final int totalFilteredRecords = jt.queryForObject(sqlCountRows, Integer.class);
return new Page<>(items, totalFilteredRecords); return new Page<>(items, totalFilteredRecords);
} }
@@ -41,9 +42,8 @@ public class PaginationHelper<E> {
final List<Long> items = jdbcTemplate.queryForList(sql, type); final List<Long> items = jdbcTemplate.queryForList(sql, type);
// determine how many rows are available // determine how many rows are available
@SuppressWarnings("deprecation") Integer totalFilteredRecords = jdbcTemplate.queryForObject(sqlCountRows, Integer.class);
final int totalFilteredRecords = jdbcTemplate.queryForInt(sqlCountRows);
return new Page<>(items, totalFilteredRecords); return new Page<>(items, ObjectUtils.defaultIfNull(totalFilteredRecords, 0));
} }
} }
@@ -43,12 +43,7 @@ public class ReportRepositoryWrapper {
* @return {@link Report} object * @return {@link Report} object
*/ */
public Report findOneThrowExceptionIfNotFound(final Long id) { public Report findOneThrowExceptionIfNotFound(final Long id) {
final Report report = this.reportRepository.findOne(id); return this.reportRepository.findById(id)
.orElseThrow(() -> new ReportNotFoundException(id));
if (report == null) {
throw new ReportNotFoundException(id);
}
return report;
} }
} }
@@ -258,8 +258,8 @@ public class EntityDatatableChecksWritePlatformServiceImpl implements EntityData
@Override @Override
public CommandProcessingResult deleteCheck(final Long entityDatatableCheckId) { public CommandProcessingResult deleteCheck(final Long entityDatatableCheckId) {
final EntityDatatableChecks check = this.entityDatatableChecksRepository.findOne(entityDatatableCheckId); final EntityDatatableChecks check = this.entityDatatableChecksRepository.findById(entityDatatableCheckId)
if (check == null) { throw new EntityDatatableChecksNotFoundException(entityDatatableCheckId); } .orElseThrow(() -> new EntityDatatableChecksNotFoundException(entityDatatableCheckId));
this.entityDatatableChecksRepository.delete(check); this.entityDatatableChecksRepository.delete(check);
@@ -293,4 +293,4 @@ public class EntityDatatableChecksWritePlatformServiceImpl implements EntityData
"Unknown data integrity issue with resource: " + realCause.getMessage()); "Unknown data integrity issue with resource: " + realCause.getMessage());
} }
} }
@@ -32,16 +32,16 @@ public interface ReadWriteNonCoreDataService {
DatatableData retrieveDatatable(String datatable); DatatableData retrieveDatatable(String datatable);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'REGISTER_DATATABLE')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'REGISTER_DATATABLE')")
void registerDatatable(JsonCommand command); void registerDatatable(JsonCommand command);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'REGISTER_DATATABLE')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'REGISTER_DATATABLE')")
void registerDatatable(String dataTableName, String applicationTableName); void registerDatatable(String dataTableName, String applicationTableName);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'REGISTER_DATATABLE')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'REGISTER_DATATABLE')")
void registerDatatable(JsonCommand command, String permissionTable); void registerDatatable(JsonCommand command, String permissionTable);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'DEREGISTER_DATATABLE')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'DEREGISTER_DATATABLE')")
void deregisterDatatable(String datatable); void deregisterDatatable(String datatable);
GenericResultsetData retrieveDataTableGenericResultSet(String datatable, Long appTableId, String order, Long id); GenericResultsetData retrieveDataTableGenericResultSet(String datatable, Long appTableId, String order, Long id);
@@ -71,4 +71,4 @@ public interface ReadWriteNonCoreDataService {
String getDataTableName(String Url); String getDataTableName(String Url);
Long countDatatableEntries(String datatableName,Long appTableId,String foreignKeyColumn); Long countDatatableEntries(String datatableName,Long appTableId,String foreignKeyColumn);
} }
@@ -34,6 +34,7 @@ import javax.sql.DataSource;
import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.fineract.infrastructure.codes.service.CodeReadPlatformService; import org.apache.fineract.infrastructure.codes.service.CodeReadPlatformService;
import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService; import org.apache.fineract.infrastructure.configuration.domain.ConfigurationDomainService;
import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.api.JsonCommand;
@@ -747,13 +748,13 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ
final StringBuilder checkColumnCodeMapping = new StringBuilder(); final StringBuilder checkColumnCodeMapping = new StringBuilder();
checkColumnCodeMapping.append("select ccm.code_id from x_table_column_code_mappings ccm where ccm.column_alias_name='") checkColumnCodeMapping.append("select ccm.code_id from x_table_column_code_mappings ccm where ccm.column_alias_name='")
.append(dataTableNameAlias).append("_").append(name).append("'"); .append(dataTableNameAlias).append("_").append(name).append("'");
int codeId = 0; Integer codeId = 0;
try { try {
codeId = this.jdbcTemplate.queryForInt(checkColumnCodeMapping.toString()); codeId = this.jdbcTemplate.queryForObject(checkColumnCodeMapping.toString(), Integer.class);
} catch (final EmptyResultDataAccessException e) { } catch (final EmptyResultDataAccessException e) {
logger.info(e.getMessage()); logger.info(e.getMessage());
} }
return codeId; return ObjectUtils.defaultIfNull(codeId, 0);
} }
private void parseDatatableColumnForAdd(final JsonObject column, StringBuilder sqlBuilder, final String dataTableNameAlias, private void parseDatatableColumnForAdd(final JsonObject column, StringBuilder sqlBuilder, final String dataTableNameAlias,
@@ -810,8 +811,7 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ
.append(" WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY'").append(" AND i.TABLE_SCHEMA = DATABASE()") .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(" AND i.TABLE_NAME = '").append(datatableName).append("' AND i.CONSTRAINT_NAME = 'fk_").append(datatableAlias)
.append("_").append(name).append("' "); .append("_").append(name).append("' ");
@SuppressWarnings("deprecation") final int count = this.jdbcTemplate.queryForObject(findFKSql.toString(), Integer.class);
final int count = this.jdbcTemplate.queryForInt(findFKSql.toString());
if (count > 0) { if (count > 0) {
codeMappings.add(datatableAlias + "_" + name); codeMappings.add(datatableAlias + "_" + name);
constrainBuilder.append(", DROP FOREIGN KEY `fk_").append(datatableAlias).append("_").append(name).append("` "); constrainBuilder.append(", DROP FOREIGN KEY `fk_").append(datatableAlias).append("_").append(name).append("` ");
@@ -1786,4 +1786,4 @@ public class ReadWriteNonCoreDataServiceImpl implements ReadWriteNonCoreDataServ
return (count > 0) ? true : false; return (count > 0) ? true : false;
} }
} }
@@ -121,8 +121,8 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic
this.fromApiJsonDeserializer.validate(command.json()); this.fromApiJsonDeserializer.validate(command.json());
final Report report = this.reportRepository.findOne(reportId); final Report report = this.reportRepository.findById(reportId)
if (report == null) { throw new ReportNotFoundException(reportId); } .orElseThrow(() -> new ReportNotFoundException(reportId));
final Map<String, Object> changes = report.update(command, this.readReportingService.getAllowedReportTypes()); final Map<String, Object> changes = report.update(command, this.readReportingService.getAllowedReportTypes());
@@ -157,8 +157,8 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic
@Override @Override
public CommandProcessingResult deleteReport(final Long reportId) { public CommandProcessingResult deleteReport(final Long reportId) {
final Report report = this.reportRepository.findOne(reportId); final Report report = this.reportRepository.findById(reportId)
if (report == null) { throw new ReportNotFoundException(reportId); } .orElseThrow(() -> new ReportNotFoundException(reportId));
if (report.isCoreReport()) { if (report.isCoreReport()) {
// //
@@ -221,14 +221,15 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic
if (id != null) { if (id != null) {
// existing report parameter usage // existing report parameter usage
reportParameterUsageItem = this.reportParameterUsageRepository.findOne(id); reportParameterUsageItem = this.reportParameterUsageRepository.findById(id).orElse(null);
if (reportParameterUsageItem == null) { throw new ReportParameterNotFoundException(id); } if (reportParameterUsageItem == null) { throw new ReportParameterNotFoundException(id); }
// check parameter // check parameter
if (jsonObject.has("parameterId")) { if (jsonObject.has("parameterId")) {
final Long parameterId = jsonObject.get("parameterId").getAsLong(); final Long parameterId = jsonObject.get("parameterId").getAsLong();
reportParameter = this.reportParameterRepository.findOne(parameterId); reportParameter = this.reportParameterRepository.findById(parameterId)
if (reportParameter == null || !reportParameterUsageItem.hasParameterIdOf(parameterId)) { .orElseThrow(() -> new ReportParameterNotFoundException(parameterId));
if (!reportParameterUsageItem.hasParameterIdOf(parameterId)) {
// //
throw new ReportParameterNotFoundException(parameterId); throw new ReportParameterNotFoundException(parameterId);
} }
@@ -242,8 +243,8 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic
// new report parameter usage // new report parameter usage
if (jsonObject.has("parameterId")) { if (jsonObject.has("parameterId")) {
final Long parameterId = jsonObject.get("parameterId").getAsLong(); final Long parameterId = jsonObject.get("parameterId").getAsLong();
reportParameter = this.reportParameterRepository.findOne(parameterId); reportParameter = this.reportParameterRepository.findById(parameterId)
if (reportParameter == null) { throw new ReportParameterNotFoundException(parameterId); } .orElseThrow(() -> new ReportParameterNotFoundException(parameterId));
} else { } else {
throw new PlatformDataIntegrityException("error.msg.parameter.id.mandatory.in.report.parameter", throw new PlatformDataIntegrityException("error.msg.parameter.id.mandatory.in.report.parameter",
"parameterId column is mandatory in Report Parameter Entry"); "parameterId column is mandatory in Report Parameter Entry");
@@ -263,4 +264,4 @@ public class ReportWritePlatformServiceImpl implements ReportWritePlatformServic
return reportParameterUsages; return reportParameterUsages;
} }
} }
@@ -26,18 +26,18 @@ import org.springframework.security.access.prepost.PreAuthorize;
public interface DocumentWritePlatformService { public interface DocumentWritePlatformService {
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'CREATE_DOCUMENT')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'CREATE_DOCUMENT')")
Long createDocument(DocumentCommand documentCommand, InputStream inputStream); Long createDocument(DocumentCommand documentCommand, InputStream inputStream);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'UPDATE_DOCUMENT')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'UPDATE_DOCUMENT')")
CommandProcessingResult updateDocument(DocumentCommand documentCommand, InputStream inputStream); CommandProcessingResult updateDocument(DocumentCommand documentCommand, InputStream inputStream);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'DELETE_DOCUMENT')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'DELETE_DOCUMENT')")
CommandProcessingResult deleteDocument(DocumentCommand documentCommand); CommandProcessingResult deleteDocument(DocumentCommand documentCommand);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'CREATE_DOCUMENT')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'CREATE_DOCUMENT')")
Long createInternalDocument(String entityType, Long entityId, Long createInternalDocument(String entityType, Long entityId,
Long fileSize, InputStream inputStream, String mimeType, Long fileSize, InputStream inputStream, String mimeType,
String name, String description, String fileName); String name, String description, String fileName);
} }
@@ -114,9 +114,9 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr
validator.validateForUpdate(); validator.validateForUpdate();
// TODO check if entity id is valid and within data scope for the // TODO check if entity id is valid and within data scope for the
// user // user
final Document documentForUpdate = this.documentRepository.findOne(documentCommand.getId()); final Document documentForUpdate = this.documentRepository.findById(documentCommand.getId())
if (documentForUpdate == null) { throw new DocumentNotFoundException(documentCommand.getParentEntityType(), .orElseThrow(() -> new DocumentNotFoundException(documentCommand.getParentEntityType(),
documentCommand.getParentEntityId(), documentCommand.getId()); } documentCommand.getParentEntityId(), documentCommand.getId()));
final StorageType documentStoreType = documentForUpdate.storageType(); final StorageType documentStoreType = documentForUpdate.storageType();
oldLocation = documentForUpdate.getLocation(); oldLocation = documentForUpdate.getLocation();
@@ -153,9 +153,9 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr
validateParentEntityType(documentCommand); validateParentEntityType(documentCommand);
// TODO: Check document is present under this entity Id // TODO: Check document is present under this entity Id
final Document document = this.documentRepository.findOne(documentCommand.getId()); final Document document = this.documentRepository.findById(documentCommand.getId())
if (document == null) { throw new DocumentNotFoundException(documentCommand.getParentEntityType(), .orElseThrow(() -> new DocumentNotFoundException(documentCommand.getParentEntityType(),
documentCommand.getParentEntityId(), documentCommand.getId()); } documentCommand.getParentEntityId(), documentCommand.getId()));
this.documentRepository.delete(document); this.documentRepository.delete(document);
final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(document.storageType()); final ContentRepository contentRepository = this.contentRepositoryFactory.getRepository(document.storageType());
@@ -184,4 +184,4 @@ public class DocumentWritePlatformServiceJpaRepositoryImpl implements DocumentWr
return name().toString().toLowerCase(); return name().toString().toLowerCase();
} }
} }
} }
@@ -26,12 +26,12 @@ import org.springframework.security.access.prepost.PreAuthorize;
public interface ImageWritePlatformService { public interface ImageWritePlatformService {
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'CREATE_CLIENTIMAGE','CREATE_STAFFIMAGE')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'CREATE_CLIENTIMAGE','CREATE_STAFFIMAGE')")
CommandProcessingResult saveOrUpdateImage(String entityName, Long entityId, String imageName, InputStream inputStream, Long fileSize); CommandProcessingResult saveOrUpdateImage(String entityName, Long entityId, String imageName, InputStream inputStream, Long fileSize);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'CREATE_CLIENTIMAGE','CREATE_STAFFIMAGE')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'CREATE_CLIENTIMAGE','CREATE_STAFFIMAGE')")
CommandProcessingResult saveOrUpdateImage(String entityName, Long entityId, Base64EncodedImage encodedImage); CommandProcessingResult saveOrUpdateImage(String entityName, Long entityId, Base64EncodedImage encodedImage);
@PreAuthorize(value = "hasAnyRole('ALL_FUNCTIONS', 'DELETE_CLIENTIMAGE','DELETE_STAFFIMAGE')") @PreAuthorize(value = "hasAnyAuthority('ALL_FUNCTIONS', 'DELETE_CLIENTIMAGE','DELETE_STAFFIMAGE')")
CommandProcessingResult deleteImage(String entityName, Long entityId); CommandProcessingResult deleteImage(String entityName, Long entityId);
} }
@@ -165,13 +165,13 @@ public class FineractEntityDataValidator {
} }
public void checkForLoanProducts(final Long id) { public void checkForLoanProducts(final Long id) {
final LoanProduct loanProduct = this.loanProductRepository.findOne(id); this.loanProductRepository.findById(id)
if (loanProduct == null) { throw new LoanProductNotFoundException(id); } .orElseThrow(() -> new LoanProductNotFoundException(id));
} }
public void checkForSavingsProducts(final Long id) { public void checkForSavingsProducts(final Long id) {
final SavingsProduct savingsProduct = this.savingsProductRepository.findOne(id); this.savingsProductRepository.findById(id)
if (savingsProduct == null) { throw new SavingsProductNotFoundException(id); } .orElseThrow(() -> new SavingsProductNotFoundException(id));
} }
public void checkForCharges(final Long id) { public void checkForCharges(final Long id) {
@@ -179,8 +179,8 @@ public class FineractEntityDataValidator {
} }
public void checkForRoles(final Long id) { public void checkForRoles(final Long id) {
final Role role = this.roleRepository.findOne(id); this.roleRepository.findById(id)
if (role == null) { throw new RoleNotFoundException(id); } .orElseThrow(() -> new RoleNotFoundException(id));
} }
public void validateForUpdate(final String json) { public void validateForUpdate(final String json) {
@@ -39,9 +39,8 @@ public class FineractEntityAccessRepositoryWrapper {
} }
public FineractEntityAccess findOneWithNotFoundDetection(final Long id) { public FineractEntityAccess findOneWithNotFoundDetection(final Long id) {
final FineractEntityAccess fineractEntityAccess = this.repository.findOne(id); return this.repository.findById(id)
if (fineractEntityAccess == null) { throw new FineractEntityAccessNotFoundException(id); } .orElseThrow(() -> new FineractEntityAccessNotFoundException(id));
return fineractEntityAccess;
} }
public void save(final FineractEntityAccess fineractEntityAccess) { public void save(final FineractEntityAccess fineractEntityAccess) {
@@ -55,4 +54,4 @@ public class FineractEntityAccessRepositoryWrapper {
public void delete(final FineractEntityAccess fineractEntityAccess) { public void delete(final FineractEntityAccess fineractEntityAccess) {
this.repository.delete(fineractEntityAccess); this.repository.delete(fineractEntityAccess);
} }
} }
@@ -34,9 +34,8 @@ public class FineractEntityRelationRepositoryWrapper {
} }
public FineractEntityRelation findOneWithNotFoundDetection(final Long id) { public FineractEntityRelation findOneWithNotFoundDetection(final Long id) {
final FineractEntityRelation fineractEntityRelation = this.fineractEntityRelationRepository.findOne(id); return this.fineractEntityRelationRepository.findById(id)
if (fineractEntityRelation == null) { throw new FineractEntityAccessNotFoundException(id); } .orElseThrow(() -> new FineractEntityAccessNotFoundException(id));
return fineractEntityRelation;
} }
public FineractEntityRelation findOneByCodeName(final String codeName) { public FineractEntityRelation findOneByCodeName(final String codeName) {
@@ -33,9 +33,8 @@ public class FineractEntityToEntityMappingRepositoryWrapper {
} }
public FineractEntityToEntityMapping findOneWithNotFoundDetection(final Long id) { public FineractEntityToEntityMapping findOneWithNotFoundDetection(final Long id) {
final FineractEntityToEntityMapping fineractEntityToEntityMapping = this.fineractEntityToEntityMappingRepository.findOne(id); return this.fineractEntityToEntityMappingRepository.findById(id)
if (fineractEntityToEntityMapping == null) { throw new FineractEntityAccessNotFoundException(id); } .orElseThrow(() -> new FineractEntityAccessNotFoundException(id));
return fineractEntityToEntityMapping;
} }
public void delete(final FineractEntityToEntityMapping mapId) { public void delete(final FineractEntityToEntityMapping mapId) {
@@ -35,12 +35,8 @@ public class DeviceRegistrationRepositoryWrapper {
public DeviceRegistration findOneWithNotFoundDetection( public DeviceRegistration findOneWithNotFoundDetection(
final Long deviceRegistrationId) { final Long deviceRegistrationId) {
final DeviceRegistration deviceRegistration = this.repository return this.repository.findById(deviceRegistrationId)
.findOne(deviceRegistrationId); .orElseThrow(() -> new DeviceRegistrationNotFoundException(deviceRegistrationId));
if (deviceRegistration == null) {
throw new DeviceRegistrationNotFoundException(deviceRegistrationId);
}
return deviceRegistration;
} }
public void save(final DeviceRegistration deviceRegistration) { public void save(final DeviceRegistration deviceRegistration) {
@@ -126,7 +126,7 @@ public class NotificationSenderService {
} }
} }
this.smsMessageRepository.save(smsList); this.smsMessageRepository.saveAll(smsList);
} }
@@ -123,10 +123,8 @@ public class HookWritePlatformServiceJpaRepositoryImpl
if (command.hasParameter(templateIdParamName)) { if (command.hasParameter(templateIdParamName)) {
final Long ugdTemplateId = command final Long ugdTemplateId = command
.longValueOfParameterNamed(templateIdParamName); .longValueOfParameterNamed(templateIdParamName);
ugdTemplate = this.ugdTemplateRepository.findOne(ugdTemplateId); ugdTemplate = this.ugdTemplateRepository.findById(ugdTemplateId)
if (ugdTemplate == null) { .orElseThrow(() -> new TemplateNotFoundException(ugdTemplateId));
throw new TemplateNotFoundException(ugdTemplateId);
}
} }
final Hook hook = Hook.fromJson(command, template, config, final Hook hook = Hook.fromJson(command, template, config,
allEvents, ugdTemplate); allEvents, ugdTemplate);
@@ -168,8 +166,7 @@ public class HookWritePlatformServiceJpaRepositoryImpl
if (changes.containsKey(templateIdParamName)) { if (changes.containsKey(templateIdParamName)) {
final Long ugdTemplateId = command final Long ugdTemplateId = command
.longValueOfParameterNamed(templateIdParamName); .longValueOfParameterNamed(templateIdParamName);
final Template ugdTemplate = this.ugdTemplateRepository final Template ugdTemplate = this.ugdTemplateRepository.findById(ugdTemplateId).orElse(null);
.findOne(ugdTemplateId);
if (ugdTemplate == null) { if (ugdTemplate == null) {
changes.remove(templateIdParamName); changes.remove(templateIdParamName);
throw new TemplateNotFoundException(ugdTemplateId); throw new TemplateNotFoundException(ugdTemplateId);
@@ -236,11 +233,8 @@ public class HookWritePlatformServiceJpaRepositoryImpl
} }
private Hook retrieveHookBy(final Long hookId) { private Hook retrieveHookBy(final Long hookId) {
final Hook hook = this.hookRepository.findOne(hookId); return this.hookRepository.findById(hookId)
if (hook == null) { .orElseThrow(() -> new HookNotFoundException(hookId));
throw new HookNotFoundException(hookId);
}
return hook;
} }
private HookTemplate retrieveHookTemplateBy(final String templateName) { private HookTemplate retrieveHookTemplateBy(final String templateName) {
@@ -0,0 +1,153 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.infrastructure.openjpa;
import java.sql.Connection;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import org.apache.commons.logging.LogFactory;
import org.apache.openjpa.persistence.FetchPlan;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;
import org.apache.openjpa.persistence.jdbc.IsolationLevel;
import org.apache.openjpa.persistence.jdbc.JDBCFetchPlan;
import org.springframework.jdbc.datasource.ConnectionHandle;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.orm.jpa.DefaultJpaDialect;
import org.springframework.transaction.SavepointManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
public class OpenJpaDialect extends DefaultJpaDialect {
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
throws PersistenceException, SQLException, TransactionException {
OpenJPAEntityManager openJpaEntityManager = getOpenJPAEntityManager(entityManager);
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
// Pass custom isolation level on to OpenJPA's JDBCFetchPlan configuration
FetchPlan fetchPlan = openJpaEntityManager.getFetchPlan();
if (fetchPlan instanceof JDBCFetchPlan) {
IsolationLevel isolation = IsolationLevel.fromConnectionConstant(definition.getIsolationLevel());
((JDBCFetchPlan) fetchPlan).setIsolation(isolation);
}
}
entityManager.getTransaction().begin();
if (!definition.isReadOnly()) {
// Like with EclipseLink, make sure to start the logic transaction early so that other
// participants using the connection (such as JdbcTemplate) run in a transaction.
openJpaEntityManager.beginStore();
}
// Custom implementation for OpenJPA savepoint handling
return new OpenJpaTransactionData(openJpaEntityManager);
}
@Override
public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly)
throws PersistenceException, SQLException {
return new OpenJpaConnectionHandle(getOpenJPAEntityManager(entityManager));
}
/**
* Return the OpenJPA-specific variant of {@code EntityManager}.
* @param em the generic {@code EntityManager} instance
* @return the OpenJPA-specific variant of {@code EntityManager}
*/
protected OpenJPAEntityManager getOpenJPAEntityManager(EntityManager em) {
return OpenJPAPersistence.cast(em);
}
/**
* Transaction data Object exposed from {@code beginTransaction},
* implementing the {@link SavepointManager} interface.
*/
private static class OpenJpaTransactionData implements SavepointManager {
private final OpenJPAEntityManager entityManager;
private int savepointCounter = 0;
public OpenJpaTransactionData(OpenJPAEntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public Object createSavepoint() throws TransactionException {
this.savepointCounter++;
String savepointName = ConnectionHolder.SAVEPOINT_NAME_PREFIX + this.savepointCounter;
this.entityManager.setSavepoint(savepointName);
return savepointName;
}
@Override
public void rollbackToSavepoint(Object savepoint) throws TransactionException {
this.entityManager.rollbackToSavepoint((String) savepoint);
}
@Override
public void releaseSavepoint(Object savepoint) throws TransactionException {
try {
this.entityManager.releaseSavepoint((String) savepoint);
}
catch (Throwable ex) {
LogFactory.getLog(OpenJpaTransactionData.class).debug(
"Could not explicitly release OpenJPA savepoint", ex);
}
}
}
/**
* {@link ConnectionHandle} implementation that fetches a new OpenJPA-provided
* Connection for every {@code getConnection} call and closes the Connection on
* {@code releaseConnection}. This is necessary because OpenJPA requires the
* fetched Connection to be closed before continuing EntityManager work.
* @see org.apache.openjpa.persistence.OpenJPAEntityManager#getConnection()
*/
private static class OpenJpaConnectionHandle implements ConnectionHandle {
private final OpenJPAEntityManager entityManager;
public OpenJpaConnectionHandle(OpenJPAEntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public Connection getConnection() {
return (Connection) this.entityManager.getConnection();
}
@Override
public void releaseConnection(Connection con) {
JdbcUtils.closeConnection(con);
}
}
}
@@ -0,0 +1,111 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.infrastructure.openjpa;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import org.apache.openjpa.persistence.OpenJPAEntityManagerFactorySPI;
import org.apache.openjpa.persistence.OpenJPAEntityManagerSPI;
import org.apache.openjpa.persistence.PersistenceProviderImpl;
import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter;
import org.springframework.orm.jpa.vendor.Database;
public class OpenJpaVendorAdapter extends AbstractJpaVendorAdapter {
private final PersistenceProvider persistenceProvider = new PersistenceProviderImpl();
private final OpenJpaDialect jpaDialect = new OpenJpaDialect();
@Override
public PersistenceProvider getPersistenceProvider() {
return this.persistenceProvider;
}
@Override
public String getPersistenceProviderRootPackage() {
return "org.apache.openjpa";
}
@Override
public Map<String, Object> getJpaPropertyMap() {
Map<String, Object> jpaProperties = new HashMap<String, Object>();
if (getDatabasePlatform() != null) {
jpaProperties.put("openjpa.jdbc.DBDictionary", getDatabasePlatform());
}
else if (getDatabase() != null) {
String databaseDictonary = determineDatabaseDictionary(getDatabase());
if (databaseDictonary != null) {
jpaProperties.put("openjpa.jdbc.DBDictionary", databaseDictonary);
}
}
if (isGenerateDdl()) {
jpaProperties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
}
if (isShowSql()) {
// Taken from the OpenJPA 0.9.6 docs ("Standard OpenJPA Log Configuration + All SQL Statements")
jpaProperties.put("openjpa.Log", "DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE");
}
return jpaProperties;
}
/**
* Determine the OpenJPA database dictionary name for the given database.
* @param database the specified database
* @return the OpenJPA database dictionary name, or {@code null} if none found
*/
protected String determineDatabaseDictionary(Database database) {
switch (database) {
case DB2: return "db2";
case DERBY: return "derby";
case HSQL: return "hsql(SimulateLocking=true)";
case INFORMIX: return "informix";
case MYSQL: return "mysql";
case ORACLE: return "oracle";
case POSTGRESQL: return "postgres";
case SQL_SERVER: return "sqlserver";
case SYBASE: return "sybase";
default: return null;
}
}
@Override
public OpenJpaDialect getJpaDialect() {
return this.jpaDialect;
}
@Override
public Class<? extends EntityManagerFactory> getEntityManagerFactoryInterface() {
return OpenJPAEntityManagerFactorySPI.class;
}
@Override
public Class<? extends EntityManager> getEntityManagerInterface() {
return OpenJPAEntityManagerSPI.class;
}
}
@@ -38,9 +38,10 @@ public class ReportMailingJobRepositoryWrapper {
* @return ReportMailingJob object * @return ReportMailingJob object
**/ **/
public ReportMailingJob findOneThrowExceptionIfNotFound(final Long id) { public ReportMailingJob findOneThrowExceptionIfNotFound(final Long id) {
final ReportMailingJob reportMailingJob = this.reportMailingJobRepository.findOne(id); final ReportMailingJob reportMailingJob = this.reportMailingJobRepository.findById(id)
.orElseThrow(() -> new ReportMailingJobNotFoundException(id));
if (reportMailingJob == null || reportMailingJob.isDeleted()) { if (reportMailingJob.isDeleted()) {
throw new ReportMailingJobNotFoundException(id); throw new ReportMailingJobNotFoundException(id);
} }
@@ -62,7 +62,7 @@ public class InsecureTwoFactorAuthenticationFilter extends TwoFactorAuthenticati
} }
// Add two-factor authenticated authority if user is authenticated // Add two-factor authenticated authority if user is authenticated
if(authentication != null && authentication.isAuthenticated()) { if(authentication != null && authentication.isAuthenticated() && authentication.getPrincipal() instanceof AppUser) {
AppUser user = (AppUser) authentication.getPrincipal(); AppUser user = (AppUser) authentication.getPrincipal();
if(user == null) { if(user == null) {
@@ -79,4 +79,4 @@ public class InsecureTwoFactorAuthenticationFilter extends TwoFactorAuthenticati
chain.doFilter(req, res); chain.doFilter(req, res);
} }
} }
@@ -97,10 +97,7 @@ public class TenantAwareBasicAuthenticationFilter extends BasicAuthenticationFil
} }
@Override @Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
final StopWatch task = new StopWatch(); final StopWatch task = new StopWatch();
task.start(); task.start();
@@ -150,7 +147,8 @@ public class TenantAwareBasicAuthenticationFilter extends BasicAuthenticationFil
} }
} }
super.doFilter(req, res, chain); // filterChain.doFilter(request, response);
super.doFilterInternal(request, response, filterChain);
} catch (final InvalidTenantIdentiferException e) { } catch (final InvalidTenantIdentiferException e) {
// deal with exception at low level // deal with exception at low level
SecurityContextHolder.getContext().setAuthentication(null); SecurityContextHolder.getContext().setAuthentication(null);
@@ -187,4 +185,4 @@ public class TenantAwareBasicAuthenticationFilter extends BasicAuthenticationFil
throw new BadCredentialsException("User not authorised to use the requested resource."); throw new BadCredentialsException("User not authorised to use the requested resource.");
} }
} }
} }
@@ -74,8 +74,8 @@ public class SmsMessageAssembler {
boolean isNotification = false; boolean isNotification = false;
if (this.fromApiJsonHelper.parameterExists(SmsApiConstants.campaignIdParamName, element)) { if (this.fromApiJsonHelper.parameterExists(SmsApiConstants.campaignIdParamName, element)) {
final Long campaignId = this.fromApiJsonHelper.extractLongNamed(SmsApiConstants.campaignIdParamName, element); final Long campaignId = this.fromApiJsonHelper.extractLongNamed(SmsApiConstants.campaignIdParamName, element);
smsCampaign = this.smsCampaignRepository.findOne(campaignId); smsCampaign = this.smsCampaignRepository.findById(campaignId)
if (smsCampaign == null) { throw new SmsCampaignNotFound(campaignId); } .orElseThrow(() -> new SmsCampaignNotFound(campaignId));
isNotification = smsCampaign.isNotification(); isNotification = smsCampaign.isNotification();
} }
@@ -99,8 +99,7 @@ public class SmsMessageAssembler {
} }
public SmsMessage assembleFromResourceId(final Long resourceId) { public SmsMessage assembleFromResourceId(final Long resourceId) {
final SmsMessage sms = this.smsMessageRepository.findOne(resourceId); return this.smsMessageRepository.findById(resourceId)
if (sms == null) { throw new SmsNotFoundException(resourceId); } .orElseThrow(() -> new SmsNotFoundException(resourceId));
return sms;
} }
} }
@@ -135,7 +135,7 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob
} }
} }
if(toSaveMessages.size()>0){ if(toSaveMessages.size()>0){
this.smsMessageRepository.save(toSaveMessages); this.smsMessageRepository.saveAll(toSaveMessages);
this.smsMessageRepository.flush(); this.smsMessageRepository.flush();
this.genericExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas)); this.genericExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas));
} }
@@ -214,7 +214,7 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob
} }
} }
if(toSaveMessages.size()>0){ if(toSaveMessages.size()>0){
this.smsMessageRepository.save(toSaveMessages); this.smsMessageRepository.saveAll(toSaveMessages);
this.smsMessageRepository.flush(); this.smsMessageRepository.flush();
this.triggeredExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas)); this.triggeredExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), apiQueueResourceDatas));
} }
@@ -243,7 +243,7 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob
apiQueueResourceDatas.add(apiQueueResourceData); apiQueueResourceDatas.add(apiQueueResourceData);
smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue()); smsMessage.setStatusType(SmsMessageStatusType.WAITING_FOR_DELIVERY_REPORT.getValue());
} }
this.smsMessageRepository.save(smsMessages); this.smsMessageRepository.saveAll(smsMessages);
request.append(SmsMessageApiQueueResourceData.toJsonString(apiQueueResourceDatas)); request.append(SmsMessageApiQueueResourceData.toJsonString(apiQueueResourceDatas));
logger.info("Sending triggered SMS to specific provider with request - " + request.toString()); logger.info("Sending triggered SMS to specific provider with request - " + request.toString());
this.triggeredExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(), this.triggeredExecutorService.execute(new SmsTask(ThreadLocalContextUtil.getTenant(),
@@ -285,9 +285,9 @@ public class SmsMessageScheduledJobServiceImpl implements SmsMessageScheduledJob
if (!smsMessageDeliveryReportData.getHasError() if (!smsMessageDeliveryReportData.getHasError()
&& (deliveryStatus != 100)) { && (deliveryStatus != 100)) {
SmsMessage smsMessage = this.smsMessageRepository.findOne(smsMessageDeliveryReportData.getId()); SmsMessage smsMessage = this.smsMessageRepository.findById(smsMessageDeliveryReportData.getId()).orElse(null);
Integer statusType = smsMessage.getStatusType(); Integer statusType;
boolean statusChanged = false; boolean statusChanged;
switch (deliveryStatus) { switch (deliveryStatus) {
case 0: case 0:
@@ -63,7 +63,7 @@ public class WriteLikelihoodServiceImpl implements WriteLikelihoodService {
this.likelihoodDataValidator.validateForUpdate(command); this.likelihoodDataValidator.validateForUpdate(command);
final Likelihood likelihood = this.repository.findOne(likelihoodId); final Likelihood likelihood = this.repository.findById(likelihoodId).orElse(null);
if (!likelihood.update(command).isEmpty()) { if (!likelihood.update(command).isEmpty()) {
this.repository.save(likelihood); this.repository.save(likelihood);
@@ -75,7 +75,7 @@ public class WriteLikelihoodServiceImpl implements WriteLikelihoodService {
for (Likelihood aLikelihood : likelihoods) { for (Likelihood aLikelihood : likelihoods) {
aLikelihood.disable(); aLikelihood.disable();
} }
this.repository.save(likelihoods); this.repository.saveAll(likelihoods);
} }
} }
@@ -400,7 +400,7 @@ public class InteropServiceImpl implements InteropService {
} }
public InteropIdentifier findIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType) { public InteropIdentifier findIdentifier(@NotNull InteropIdentifierType idType, @NotNull String idValue, String subIdOrType) {
return identifierRepository.findOne(Specifications.where(idTypeEqual(idType)).and(idValueEqual(idValue)).and(subIdOrTypeEqual(subIdOrType))); return identifierRepository.findOne(Specifications.where(idTypeEqual(idType)).and(idValueEqual(idValue)).and(subIdOrTypeEqual(subIdOrType))).get();
} }
public static Specification<InteropIdentifier> idTypeEqual(@NotNull InteropIdentifierType idType) { public static Specification<InteropIdentifier> idTypeEqual(@NotNull InteropIdentifierType idType) {
@@ -426,4 +426,4 @@ public class InteropServiceImpl implements InteropService {
String getRoutingCode() { String getRoutingCode() {
return DEFAULT_ROUTING_CODE; return DEFAULT_ROUTING_CODE;
} }
} }
@@ -42,7 +42,7 @@ public class MixTaxonomyMappingWritePlatformServiceImpl implements MixTaxonomyMa
@Override @Override
public CommandProcessingResult updateMapping(final Long mappingId, final JsonCommand command) { public CommandProcessingResult updateMapping(final Long mappingId, final JsonCommand command) {
try { try {
MixTaxonomyMapping mapping = this.mappingRepository.findOne(mappingId); MixTaxonomyMapping mapping = this.mappingRepository.findById(mappingId).orElse(null);
if (mapping == null) { if (mapping == null) {
mapping = MixTaxonomyMapping.fromJson(command); mapping = MixTaxonomyMapping.fromJson(command);
} else { } else {
@@ -57,4 +57,4 @@ public class MixTaxonomyMappingWritePlatformServiceImpl implements MixTaxonomyMa
return CommandProcessingResult.empty(); return CommandProcessingResult.empty();
} }
} }
} }
@@ -71,7 +71,7 @@ public class NotificationEventListener implements SessionAwareMessageListener {
if (notificationData.getOfficeId() != null) { if (notificationData.getOfficeId() != null) {
List<Long> tempUserIds = new ArrayList<>(userIds); List<Long> tempUserIds = new ArrayList<>(userIds);
for (Long userId : tempUserIds) { for (Long userId : tempUserIds) {
AppUser appUser = appUserRepository.findOne(userId); AppUser appUser = appUserRepository.findById(userId).get();
if (!Objects.equals(appUser.getOffice().getId(), notificationData.getOfficeId())) { if (!Objects.equals(appUser.getOffice().getId(), notificationData.getOfficeId())) {
userIds.remove(userId); userIds.remove(userId);
} }
@@ -66,7 +66,7 @@ public class SpringEventListener implements ApplicationListener<SpringEvent> {
if (notificationData.getOfficeId() != null) { if (notificationData.getOfficeId() != null) {
List<Long> tempUserIds = new ArrayList<>(userIds); List<Long> tempUserIds = new ArrayList<>(userIds);
for (Long userId : tempUserIds) { for (Long userId : tempUserIds) {
AppUser appUser = appUserRepository.findOne(userId); AppUser appUser = appUserRepository.findById(userId).get();
if (!Objects.equals(appUser.getOffice().getId(), notificationData.getOfficeId())) { if (!Objects.equals(appUser.getOffice().getId(), notificationData.getOfficeId())) {
userIds.remove(userId); userIds.remove(userId);
} }
@@ -589,7 +589,7 @@ public class NotificationDomainServiceImpl implements NotificationDomainService
List<Long> subscriberIds = new ArrayList<>(); List<Long> subscriberIds = new ArrayList<>();
Long entityId = officeId; Long entityId = officeId;
String entityType= ""; String entityType= "";
if (officeRepository.findOne(entityId).getParent() == null) { if (officeRepository.findById(entityId).get().getParent() == null) {
entityType = "OFFICE"; entityType = "OFFICE";
} else { } else {
entityType = "BRANCH"; entityType = "BRANCH";
@@ -37,7 +37,7 @@ public class NotificationGeneratorReadRepositoryWrapperImpl implements Notificat
@Override @Override
public Notification findById(Long id) { public Notification findById(Long id) {
return this.notificationRepository.findOne(id); return this.notificationRepository.findById(id).orElse(null);
} }
@Override @Override
@@ -47,7 +47,7 @@ public class NotificationGeneratorReadRepositoryWrapperImpl implements Notificat
@Override @Override
public void delete(Long id) { public void delete(Long id) {
this.notificationRepository.delete(id); this.notificationRepository.deleteById(id);
} }
} }
@@ -37,7 +37,7 @@ public class NotificationMapperReadRepositoryWrapperImpl implements Notification
@Override @Override
public NotificationMapper findById(Long id) { public NotificationMapper findById(Long id) {
return this.notificationMapperRepository.findOne(id); return this.notificationMapperRepository.findById(id).orElse(null);
} }
@Override @Override
@@ -47,7 +47,7 @@ public class NotificationMapperReadRepositoryWrapperImpl implements Notification
@Override @Override
public void delete(Long id) { public void delete(Long id) {
this.notificationMapperRepository.delete(id); this.notificationMapperRepository.deleteById(id);
} }
} }
@@ -65,7 +65,7 @@ public class NotificationWritePlatformServiceImpl implements NotificationWritePl
} }
private Long insertIntoNotificationMapper(Long userId, Long generatedNotificationId) { private Long insertIntoNotificationMapper(Long userId, Long generatedNotificationId) {
AppUser appUser = this.appUserRepository.findOne(userId); AppUser appUser = this.appUserRepository.findById(userId).orElse(null);
NotificationMapper notificationMapper = new NotificationMapper( NotificationMapper notificationMapper = new NotificationMapper(
this.notificationGeneratorReadRepositoryWrapper.findById(generatedNotificationId), this.notificationGeneratorReadRepositoryWrapper.findById(generatedNotificationId),
appUser, appUser,
@@ -108,7 +108,7 @@ public class NotificationWritePlatformServiceImpl implements NotificationWritePl
private List<Long> insertIntoNotificationMapper(List<Long> userIds, Long generatedNotificationId) { private List<Long> insertIntoNotificationMapper(List<Long> userIds, Long generatedNotificationId) {
List<Long> mappedIds = new ArrayList<>(); List<Long> mappedIds = new ArrayList<>();
for (Long userId : userIds) { for (Long userId : userIds) {
AppUser appUser = this.appUserRepository.findOne(userId); AppUser appUser = this.appUserRepository.findById(userId).get();
NotificationMapper notificationMapper = new NotificationMapper( NotificationMapper notificationMapper = new NotificationMapper(
this.notificationGeneratorReadRepositoryWrapper.findById(generatedNotificationId), this.notificationGeneratorReadRepositoryWrapper.findById(generatedNotificationId),
appUser, appUser,
@@ -114,7 +114,7 @@ public class TopicDomainServiceImpl implements TopicDomainService {
if (changes.containsKey("name")) { if (changes.containsKey("name")) {
List<Topic> entityTopics = topicRepository.findByMemberType(previousRolename); List<Topic> entityTopics = topicRepository.findByMemberType(previousRolename);
for (Topic topic : entityTopics) { for (Topic topic : entityTopics) {
Office office = officeRepository.findOne(topic.getEntityId()); Office office = officeRepository.findById(topic.getEntityId()).get();
String title = updatedRole.getName() + " of " + office.getName(); String title = updatedRole.getName() + " of " + office.getName();
topic.setTitle(title); topic.setTitle(title);
topic.setMemberType(updatedRole.getName().toUpperCase()); topic.setMemberType(updatedRole.getName().toUpperCase());
@@ -237,8 +237,8 @@ public class TopicDomainServiceImpl implements TopicDomainService {
if (!ObjectUtils.isEmpty(rolesArray)) { if (!ObjectUtils.isEmpty(rolesArray)) {
for (final String roleId : rolesArray) { for (final String roleId : rolesArray) {
final Long id = Long.valueOf(roleId); final Long id = Long.valueOf(roleId);
final Role role = this.roleRepository.findOne(id); final Role role = this.roleRepository.findById(id)
if (role == null) { throw new RoleNotFoundException(id); } .orElseThrow(() -> new RoleNotFoundException(id));
allRoles.add(role); allRoles.add(role);
} }
} }
@@ -44,9 +44,8 @@ public class HolidayRepositoryWrapper {
} }
public Holiday findOneWithNotFoundDetection(final Long id) { public Holiday findOneWithNotFoundDetection(final Long id) {
final Holiday holiday = this.repository.findOne(id); return this.repository.findById(id)
if (holiday == null) { throw new HolidayNotFoundException(id); } .orElseThrow(() -> new HolidayNotFoundException(id));
return holiday;
} }
public void save(final Holiday holiday) { public void save(final Holiday holiday) {
@@ -54,7 +53,7 @@ public class HolidayRepositoryWrapper {
} }
public void save(final Iterable<Holiday> holidays) { public void save(final Iterable<Holiday> holidays) {
this.repository.save(holidays); this.repository.saveAll(holidays);
} }
public void saveAndFlush(final Holiday holiday) { public void saveAndFlush(final Holiday holiday) {
@@ -77,4 +76,4 @@ public class HolidayRepositoryWrapper {
final List<Holiday> holidays = findByOfficeIdAndGreaterThanDate(officeId, transactionDate.toDate()); final List<Holiday> holidays = findByOfficeIdAndGreaterThanDate(officeId, transactionDate.toDate());
return HolidayUtil.isHoliday(transactionDate, holidays); return HolidayUtil.isHoliday(transactionDate, holidays);
} }
} }
@@ -104,11 +104,11 @@ public class CurrencyWritePlatformServiceJpaRepositoryImpl implements CurrencyWr
changes.put("currencies", allowedCurrencyCodes.toArray(new String[allowedCurrencyCodes.size()])); changes.put("currencies", allowedCurrencyCodes.toArray(new String[allowedCurrencyCodes.size()]));
this.organisationCurrencyRepository.deleteAll(); this.organisationCurrencyRepository.deleteAll();
this.organisationCurrencyRepository.save(allowedCurrencies); this.organisationCurrencyRepository.saveAll(allowedCurrencies);
return new CommandProcessingResultBuilder() // return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) // .withCommandId(command.commandId()) //
.with(changes) // .with(changes) //
.build(); .build();
} }
} }
@@ -40,16 +40,15 @@ public class OfficeRepositoryWrapper {
} }
public Office findOneWithNotFoundDetection(final Long id) { public Office findOneWithNotFoundDetection(final Long id) {
final Office office = this.repository.findOne(id); return this.repository.findById(id)
if (office == null) { throw new OfficeNotFoundException(id); } .orElseThrow(() -> new OfficeNotFoundException(id));
return office;
} }
@Transactional(readOnly=true) @Transactional(readOnly=true)
public Office findOfficeHierarchy(final Long id) { public Office findOfficeHierarchy(final Long id) {
final Office office = this.repository.findOne(id); final Office office = this.repository.findById(id)
if (office == null) { throw new OfficeNotFoundException(id); } .orElseThrow(() -> new OfficeNotFoundException(id));
office.loadLazyCollections(); office.loadLazyCollections();
return office ; return office ;
} }
@@ -64,4 +63,4 @@ public class OfficeRepositoryWrapper {
public void delete(final Office entity) { public void delete(final Office entity) {
this.repository.delete(entity); this.repository.delete(entity);
} }
} }
@@ -217,7 +217,7 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP
this.context.authenticatedUser(); this.context.authenticatedUser();
this.officeTransactionRepository.delete(transactionId); this.officeTransactionRepository.deleteById(transactionId);
return new CommandProcessingResultBuilder() // return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) // .withCommandId(command.commandId()) //
@@ -268,4 +268,4 @@ public class OfficeWritePlatformServiceJpaRepositoryImpl implements OfficeWriteP
public PlatformSecurityContext getContext() { public PlatformSecurityContext getContext() {
return this.context; return this.context;
} }
} }
@@ -18,6 +18,7 @@
*/ */
package org.apache.fineract.organisation.provisioning.domain; package org.apache.fineract.organisation.provisioning.domain;
import java.time.Instant;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
@@ -69,9 +70,9 @@ public class ProvisioningCriteria extends AbstractAuditableCustom<AppUser, Long>
public ProvisioningCriteria(String criteriaName, AppUser createdBy, DateTime createdDate, AppUser lastModifiedBy, DateTime lastModifiedDate) { public ProvisioningCriteria(String criteriaName, AppUser createdBy, DateTime createdDate, AppUser lastModifiedBy, DateTime lastModifiedDate) {
this.criteriaName = criteriaName; this.criteriaName = criteriaName;
setCreatedBy(createdBy) ; setCreatedBy(createdBy) ;
setCreatedDate(createdDate) ; setCreatedDate(Instant.ofEpochMilli(createdDate.getMillis()));
setLastModifiedBy(lastModifiedBy) ; setLastModifiedBy(lastModifiedBy) ;
setLastModifiedDate(lastModifiedDate) ; setLastModifiedDate(lastModifiedDate == null ? null : Instant.ofEpochMilli(lastModifiedDate.getMillis()));
} }
public void setProvisioningCriteriaDefinitions(Set<ProvisioningCriteriaDefinition> provisioningCriteriaDefinition) { public void setProvisioningCriteriaDefinitions(Set<ProvisioningCriteriaDefinition> provisioningCriteriaDefinition) {
@@ -95,8 +95,8 @@ public class ProvisioningCategoryWritePlatformServiceJpaRepositoryImpl implement
public CommandProcessingResult updateProvisioningCategory(final Long categoryId, JsonCommand command) { public CommandProcessingResult updateProvisioningCategory(final Long categoryId, JsonCommand command) {
try { try {
this.fromApiJsonDeserializer.validateForUpdate(command.json()); this.fromApiJsonDeserializer.validateForUpdate(command.json());
final ProvisioningCategory provisioningCategoryForUpdate = this.provisioningCategoryRepository.findOne(categoryId); final ProvisioningCategory provisioningCategoryForUpdate = this.provisioningCategoryRepository.findById(categoryId)
if (provisioningCategoryForUpdate == null) { throw new ProvisioningCategoryNotFoundException(categoryId); } .orElseThrow(() -> new ProvisioningCategoryNotFoundException(categoryId));
final Map<String, Object> changes = provisioningCategoryForUpdate.update(command); final Map<String, Object> changes = provisioningCategoryForUpdate.update(command);
if (!changes.isEmpty()) { if (!changes.isEmpty()) {
this.provisioningCategoryRepository.save(provisioningCategoryForUpdate); this.provisioningCategoryRepository.save(provisioningCategoryForUpdate);
@@ -74,7 +74,7 @@ public class ProvisioningCriteriaAssembler {
jsonElement); jsonElement);
for (JsonElement element : jsonloanProducts) { for (JsonElement element : jsonloanProducts) {
Long productId = this.fromApiJsonHelper.extractLongNamed("id", element.getAsJsonObject()); Long productId = this.fromApiJsonHelper.extractLongNamed("id", element.getAsJsonObject());
loanProducts.add(loanProductRepository.findOne(productId)); loanProducts.add(loanProductRepository.findById(productId).orElse(null));
} }
} else { } else {
loanProducts = loanProductRepository.findAll(); loanProducts = loanProductRepository.findAll();
@@ -138,9 +138,9 @@ public class ProvisioningCriteriaAssembler {
Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject); Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject);
Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject); Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject);
ProvisioningCategory provisioningCategory = provisioningCategoryRepository.findOne(categoryId); ProvisioningCategory provisioningCategory = provisioningCategoryRepository.findById(categoryId).orElse(null);
GLAccount liabilityAccount = glAccountRepository.findOne(liabilityAccountId); GLAccount liabilityAccount = glAccountRepository.findById(liabilityAccountId).orElse(null);
GLAccount expenseAccount = glAccountRepository.findOne(expenseAccountId); GLAccount expenseAccount = glAccountRepository.findById(expenseAccountId).orElse(null);
return ProvisioningCriteriaDefinition.newPrivisioningCriteria(criteria, provisioningCategory, minimumAge, maximumAge, return ProvisioningCriteriaDefinition.newPrivisioningCriteria(criteria, provisioningCategory, minimumAge, maximumAge,
provisioningpercentage, liabilityAccount, expenseAccount); provisioningpercentage, liabilityAccount, expenseAccount);
} }
@@ -98,14 +98,12 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement
@Override @Override
public CommandProcessingResult deleteProvisioningCriteria(Long criteriaId) { public CommandProcessingResult deleteProvisioningCriteria(Long criteriaId) {
ProvisioningCriteria criteria = this.provisioningCriteriaRepository.findOne(criteriaId) ; this.provisioningCriteriaRepository.findById(criteriaId)
if(criteria == null) { .orElseThrow(() -> new ProvisioningCriteriaNotFoundException(criteriaId));
throw new ProvisioningCriteriaNotFoundException(criteriaId) ;
}
if(this.provisioningEntriesReadPlatformService.retrieveProvisioningEntryDataByCriteriaId(criteriaId) != null) { if(this.provisioningEntriesReadPlatformService.retrieveProvisioningEntryDataByCriteriaId(criteriaId) != null) {
throw new ProvisioningCriteriaCannotBeDeletedException(criteriaId) ; throw new ProvisioningCriteriaCannotBeDeletedException(criteriaId) ;
} }
this.provisioningCriteriaRepository.delete(criteriaId) ; this.provisioningCriteriaRepository.deleteById(criteriaId); ;
return new CommandProcessingResultBuilder().withEntityId(criteriaId).build(); return new CommandProcessingResultBuilder().withEntityId(criteriaId).build();
} }
@@ -113,7 +111,7 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement
public CommandProcessingResult updateProvisioningCriteria(final Long criteriaId, JsonCommand command) { public CommandProcessingResult updateProvisioningCriteria(final Long criteriaId, JsonCommand command) {
try { try {
this.fromApiJsonDeserializer.validateForUpdate(command.json()); this.fromApiJsonDeserializer.validateForUpdate(command.json());
ProvisioningCriteria provisioningCriteria = provisioningCriteriaRepository.findOne(criteriaId) ; ProvisioningCriteria provisioningCriteria = provisioningCriteriaRepository.findById(criteriaId).orElse(null);
if(provisioningCriteria == null) { if(provisioningCriteria == null) {
throw new ProvisioningCategoryNotFoundException(criteriaId) ; throw new ProvisioningCategoryNotFoundException(criteriaId) ;
} }
@@ -148,8 +146,8 @@ public class ProvisioningCriteriaWritePlatformServiceJpaRepositoryImpl implement
jsonObject, locale); jsonObject, locale);
Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject); Long liabilityAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_LIABILITY_ACCOUNT_PARAM, jsonObject);
Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject); Long expenseAccountId = this.fromApiJsonHelper.extractLongNamed(ProvisioningCriteriaConstants.JSON_EXPENSE_ACCOUNT_PARAM, jsonObject);
GLAccount liabilityAccount = glAccountRepository.findOne(liabilityAccountId); GLAccount liabilityAccount = glAccountRepository.findById(liabilityAccountId).orElse(null);
GLAccount expenseAccount = glAccountRepository.findOne(expenseAccountId); GLAccount expenseAccount = glAccountRepository.findById(expenseAccountId).orElse(null);
String categoryName = null ; String categoryName = null ;
String liabilityAccountName = null ; String liabilityAccountName = null ;
String expenseAccountName = null ; String expenseAccountName = null ;
@@ -39,9 +39,8 @@ public class StaffRepositoryWrapper {
} }
public Staff findOneWithNotFoundDetection(final Long id) { public Staff findOneWithNotFoundDetection(final Long id) {
final Staff staff = this.repository.findOne(id); return this.repository.findById(id)
if (staff == null) { throw new StaffNotFoundException(id); } .orElseThrow(() -> new StaffNotFoundException(id));
return staff;
} }
public Staff findByOfficeWithNotFoundDetection(final Long staffId, final Long officeId) { public Staff findByOfficeWithNotFoundDetection(final Long staffId, final Long officeId) {
@@ -51,8 +50,8 @@ public class StaffRepositoryWrapper {
} }
public Staff findByOfficeHierarchyWithNotFoundDetection(final Long staffId, final String hierarchy) { public Staff findByOfficeHierarchyWithNotFoundDetection(final Long staffId, final String hierarchy) {
final Staff staff = this.repository.findOne(staffId); final Staff staff = this.repository.findById(staffId)
if (staff == null) { throw new StaffNotFoundException(staffId); } .orElseThrow(() -> new StaffNotFoundException(staffId));
final String staffhierarchy = staff.office().getHierarchy(); final String staffhierarchy = staff.office().getHierarchy();
if (!hierarchy.startsWith(staffhierarchy)) { throw new StaffNotFoundException(staffId); } if (!hierarchy.startsWith(staffhierarchy)) { throw new StaffNotFoundException(staffId); }
return staff; return staff;
@@ -60,4 +59,4 @@ public class StaffRepositoryWrapper {
public void save(final Staff staff){ public void save(final Staff staff){
this.repository.save(staff); this.repository.save(staff);
} }
} }
@@ -93,9 +93,8 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla
try { try {
this.fromApiJsonDeserializer.validateForUpdate(command.json(), staffId); this.fromApiJsonDeserializer.validateForUpdate(command.json(), staffId);
final Staff staffForUpdate = this.staffRepository.findOne(staffId); final Staff staffForUpdate = this.staffRepository.findById(staffId)
if (staffForUpdate == null) { throw new StaffNotFoundException(staffId); } .orElseThrow(() -> new StaffNotFoundException(staffId));
final Map<String, Object> changesOnly = staffForUpdate.update(command); final Map<String, Object> changesOnly = staffForUpdate.update(command);
if (changesOnly.containsKey("officeId")) { if (changesOnly.containsKey("officeId")) {
@@ -146,4 +145,4 @@ public class StaffWritePlatformServiceJpaRepositoryImpl implements StaffWritePla
throw new PlatformDataIntegrityException("error.msg.staff.unknown.data.integrity.issue", throw new PlatformDataIntegrityException("error.msg.staff.unknown.data.integrity.issue",
"Unknown data integrity issue with resource: " + realCause.getMessage()); "Unknown data integrity issue with resource: " + realCause.getMessage());
} }
} }
@@ -32,8 +32,7 @@ public class CashierRepositoryWrapper {
} }
public Cashier findOneWithNotFoundDetection(final Long id) { public Cashier findOneWithNotFoundDetection(final Long id) {
final Cashier cashier = this.repository.findOne(id); return this.repository.findById(id)
if (cashier == null) { throw new TellerNotFoundException(id); } .orElseThrow(() -> new TellerNotFoundException(id));
return cashier;
} }
} }
@@ -35,8 +35,8 @@ public class TellerRepositoryWrapper {
@Transactional(readOnly=true) @Transactional(readOnly=true)
public Teller findOneWithNotFoundDetection(final Long id) { public Teller findOneWithNotFoundDetection(final Long id) {
final Teller teller = this.repository.findOne(id); final Teller teller = this.repository.findById(id)
if (teller == null) { throw new TellerNotFoundException(id); } .orElseThrow(() -> new TellerNotFoundException(id));
teller.initializeLazyCollections(); teller.initializeLazyCollections();
return teller; return teller;
} }
@@ -237,8 +237,8 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer
this.fromApiJsonDeserializer.validateForAllocateCashier(command.json()); this.fromApiJsonDeserializer.validateForAllocateCashier(command.json());
final Staff staff = this.staffRepository.findOne(staffId); final Staff staff = this.staffRepository.findById(staffId)
if (staff == null) { throw new StaffNotFoundException(staffId); } .orElseThrow(() -> new StaffNotFoundException(staffId));
final Boolean isFullDay = command.booleanObjectValueOfParameterNamed("isFullDay"); final Boolean isFullDay = command.booleanObjectValueOfParameterNamed("isFullDay");
if (!isFullDay) { if (!isFullDay) {
hourStartTime = command.longValueOfParameterNamed("hourStartTime"); hourStartTime = command.longValueOfParameterNamed("hourStartTime");
@@ -286,8 +286,8 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer
this.fromApiJsonDeserializer.validateForAllocateCashier(command.json()); this.fromApiJsonDeserializer.validateForAllocateCashier(command.json());
final Long staffId = command.longValueOfParameterNamed("staffId"); final Long staffId = command.longValueOfParameterNamed("staffId");
final Staff staff = this.staffRepository.findOne(staffId); final Staff staff = this.staffRepository.findById(staffId)
if (staff == null) { throw new StaffNotFoundException(staffId); } .orElseThrow(() -> new StaffNotFoundException(staffId));
final Cashier cashier = validateUserPriviledgeOnCashierAndRetrieve(currentUser, tellerId, cashierId); final Cashier cashier = validateUserPriviledgeOnCashierAndRetrieve(currentUser, tellerId, cashierId);
@@ -321,9 +321,7 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer
validateUserPriviledgeOnTellerAndRetrieve(currentUser, tellerId); validateUserPriviledgeOnTellerAndRetrieve(currentUser, tellerId);
final Cashier cashierToReturn = this.cashierRepository.findOne(cashierId); return this.cashierRepository.findById(cashierId).orElse(null);
return cashierToReturn;
} }
@Override @Override
@@ -380,8 +378,8 @@ public class TellerWritePlatformServiceJpaImpl implements TellerWritePlatformSer
try { try {
final AppUser currentUser = this.context.authenticatedUser(); final AppUser currentUser = this.context.authenticatedUser();
final Cashier cashier = this.cashierRepository.findOne(cashierId); final Cashier cashier = this.cashierRepository.findById(cashierId)
if (cashier == null) { throw new CashierNotFoundException(cashierId); } .orElseThrow(() -> new CashierNotFoundException(cashierId));
this.fromApiJsonDeserializer.validateForCashTxnForCashier(command.json()); this.fromApiJsonDeserializer.validateForCashTxnForCashier(command.json());
@@ -499,8 +499,7 @@ public class AccountTransfersReadPlatformServiceImpl implements
.append(transactionId); .append(transactionId);
} }
@SuppressWarnings("deprecation") final int count = this.jdbcTemplate.queryForObject(sql.toString(), Integer.class);
final int count = this.jdbcTemplate.queryForInt(sql.toString());
return count > 0; return count > 0;
} }
@@ -700,4 +699,4 @@ public class AccountTransfersReadPlatformServiceImpl implements
accountType, accountId, accountId }, BigDecimal.class); accountType, accountId, accountId }, BigDecimal.class);
} }
} }
@@ -165,8 +165,8 @@ public class StandingInstructionWritePlatformServiceImpl implements StandingInst
@Override @Override
public CommandProcessingResult update(final Long id, final JsonCommand command) { public CommandProcessingResult update(final Long id, final JsonCommand command) {
this.standingInstructionDataValidator.validateForUpdate(command); this.standingInstructionDataValidator.validateForUpdate(command);
AccountTransferStandingInstruction standingInstructionsForUpdate = this.standingInstructionRepository.findOne(id); AccountTransferStandingInstruction standingInstructionsForUpdate = this.standingInstructionRepository.findById(id)
if (standingInstructionsForUpdate == null) { throw new StandingInstructionNotFoundException(id); } .orElseThrow(() -> new StandingInstructionNotFoundException(id));
final Map<String, Object> actualChanges = standingInstructionsForUpdate.update(command); final Map<String, Object> actualChanges = standingInstructionsForUpdate.update(command);
return new CommandProcessingResultBuilder() // return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) // .withCommandId(command.commandId()) //
@@ -177,7 +177,7 @@ public class StandingInstructionWritePlatformServiceImpl implements StandingInst
@Override @Override
public CommandProcessingResult delete(final Long id) { public CommandProcessingResult delete(final Long id) {
AccountTransferStandingInstruction standingInstructionsForUpdate = this.standingInstructionRepository.findOne(id); AccountTransferStandingInstruction standingInstructionsForUpdate = this.standingInstructionRepository.findById(id).get();
// update the "deleted" and "name" properties of the standing instruction // update the "deleted" and "name" properties of the standing instruction
standingInstructionsForUpdate.delete(); standingInstructionsForUpdate.delete();
@@ -300,4 +300,4 @@ public class StandingInstructionWritePlatformServiceImpl implements StandingInst
this.jdbcTemplate.update(updateQuery.toString()); this.jdbcTemplate.update(updateQuery.toString());
return transferCompleted; return transferCompleted;
} }
} }

Some files were not shown because too many files have changed in this diff Show More