From 93cb646dd706bbb05e7ecaff6342d1a3ce0341d8 Mon Sep 17 00:00:00 2001 From: Adrien Cheype Date: Wed, 4 Nov 2015 18:15:28 +1100 Subject: [PATCH] Migrate to the jhispter v2.23.0 --- .gitignore | 1 - .yo-rc.json | 6 +- Gruntfile.js | 35 +- bower.json | 2 +- docker-compose-prod.yml | 19 + package.json | 44 +- pom.xml | 58 ++- .../nc/ird/malariaplantdb/Application.java | 25 +- .../ird/malariaplantdb/ApplicationWebXml.java | 5 +- .../aop/logging/LoggingAspect.java | 12 +- .../ExceptionHandlingAsyncTaskExecutor.java | 2 +- .../config/AsyncConfiguration.java | 31 +- .../config/CacheConfiguration.java | 16 +- .../config/CloudDatabaseConfiguration.java | 4 +- .../config/DatabaseConfiguration.java | 68 +-- .../config/JHipsterProperties.java | 453 ++++++++++++++++++ .../config/JacksonConfiguration.java | 32 +- .../config/LocaleConfiguration.java | 5 +- .../config/LoggingAspectConfiguration.java | 5 +- .../config/MailConfiguration.java | 70 --- .../config/MetricsConfiguration.java | 85 ++-- .../config/SecurityConfiguration.java | 1 + .../config/ThymeleafConfiguration.java | 4 +- .../malariaplantdb/config/WebConfigurer.java | 42 +- .../config/XAuthConfiguration.java | 18 +- .../config/apidoc/SwaggerConfiguration.java | 48 +- .../config/audit/AuditEventConverter.java | 16 +- .../liquibase/AsyncSpringLiquibase.java | 67 +++ .../config/liquibase/package-info.java | 4 + .../locale/AngularCookieLocaleResolver.java | 12 +- .../metrics/DatabaseHealthIndicator.java | 2 +- .../JHipsterHealthIndicatorConfiguration.java | 9 - .../metrics/JavaMailHealthIndicator.java | 42 -- .../domain/AbstractAuditingEntity.java | 21 +- .../nc/ird/malariaplantdb/domain/Author.java | 15 +- .../ird/malariaplantdb/domain/Authority.java | 9 +- .../ird/malariaplantdb/domain/Compiler.java | 15 +- .../ird/malariaplantdb/domain/Ethnology.java | 19 +- .../domain/InVitroPharmaco.java | 27 +- .../malariaplantdb/domain/InVivoPharmaco.java | 27 +- .../domain/PersistentAuditEvent.java | 15 +- .../domain/PlantIngredient.java | 12 +- .../ird/malariaplantdb/domain/PubSpecies.java | 17 +- .../malariaplantdb/domain/Publication.java | 9 +- .../nc/ird/malariaplantdb/domain/Species.java | 12 +- .../nc/ird/malariaplantdb/domain/User.java | 40 +- .../util/CustomDateTimeDeserializer.java | 30 -- .../domain/util/CustomDateTimeSerializer.java | 28 -- .../util/CustomLocalDateSerializer.java | 24 - .../domain/util/FixedH2Dialect.java | 7 +- .../util/ISO8601LocalDateDeserializer.java | 31 -- .../domain/util/JSR310DateConverters.java | 73 +++ .../domain/util/JSR310DateTimeSerializer.java | 25 + .../util/JSR310LocalDateDeserializer.java | 63 +++ .../util/JSR310PersistenceConverters.java | 56 +++ .../repository/AuthorityRepository.java | 1 + .../CustomAuditEventRepository.java | 14 +- .../repository/EthnologyRepository.java | 17 +- .../repository/InVitroPharmacoRepository.java | 18 +- .../repository/InVivoPharmacoRepository.java | 19 +- .../PersistenceAuditEventRepository.java | 3 +- .../repository/UserRepository.java | 4 +- .../security/CustomUserDetails.java | 98 ++++ .../Http401UnauthorizedEntryPoint.java | 5 +- .../security/SecurityUtils.java | 37 +- .../security/SpringSecurityAuditorAware.java | 3 +- .../security/UserDetailsService.java | 20 +- .../security/xauth/TokenProvider.java | 19 +- .../service/AuditEventService.java | 14 +- .../malariaplantdb/service/MailService.java | 18 +- .../malariaplantdb/service/UserService.java | 52 +- .../service/util/RandomUtil.java | 6 +- .../web/filter/CachingHttpHeadersFilter.java | 10 +- .../propertyeditors/LocaleDateTimeEditor.java | 63 --- .../web/propertyeditors/package-info.java | 4 - .../web/rest/AccountResource.java | 39 +- .../web/rest/AuditResource.java | 24 +- .../web/rest/AuthorResource.java | 4 +- .../web/rest/CompilerResource.java | 4 +- .../web/rest/EthnologyResource.java | 4 +- .../web/rest/InVitroPharmacoResource.java | 4 +- .../web/rest/InVivoPharmacoResource.java | 4 +- .../malariaplantdb/web/rest/LogsResource.java | 10 +- .../web/rest/PlantIngredientResource.java | 4 +- .../web/rest/PubSpeciesResource.java | 4 +- .../web/rest/PublicationResource.java | 4 +- .../web/rest/SpeciesResource.java | 4 +- .../malariaplantdb/web/rest/UserResource.java | 12 +- .../web/rest/dto/KeyAndPasswordDTO.java | 3 +- .../web/rest/dto/LoggerDTO.java | 6 +- .../web/rest/dto/ManagedUserDTO.java | 14 +- .../malariaplantdb/web/rest/dto/UserDTO.java | 25 +- .../web/rest/errors/ErrorDTO.java | 1 + .../web/rest/errors/ExceptionTranslator.java | 5 +- .../web/rest/util/HeaderUtil.java | 7 +- src/main/resources/.h2.server.properties | 5 +- src/main/resources/banner.txt | 17 +- src/main/resources/config/application-dev.yml | 79 +-- .../resources/config/application-prod.yml | 93 ++-- src/main/resources/config/application.yml | 89 ++-- .../00000000000000_initial_schema.xml | 52 +- .../20151005000001_added_entity_Author.xml | 4 +- .../20151005000002_added_entity_Compiler.xml | 9 +- .../20151005000003_added_entity_Species.xml | 9 +- ...20151005000004_added_entity_PubSpecies.xml | 11 +- ...005000005_added_entity_PlantIngredient.xml | 13 +- .../20151005000006_added_entity_Ethnology.xml | 20 +- ...1005000007_added_entity_InVivoPharmaco.xml | 20 +- ...005000008_added_entity_InVitroPharmaco.xml | 20 +- ...0151005000009_added_entity_Publication.xml | 41 +- .../resources/config/liquibase/master.xml | 30 +- src/main/resources/ehcache.xml | 72 +++ .../{logback.xml => logback-spring.xml} | 0 src/main/scss/main.scss | 4 +- src/main/webapp/index.html | 13 +- .../app/account/activate/activate.html | 2 +- .../scripts/app/account/login/login.html | 10 +- .../webapp/scripts/app/account/login/login.js | 2 +- .../app/account/logout/logout.controller.js | 6 - .../scripts/app/account/logout/logout.js | 19 - .../account/password/password.directive.js | 2 +- .../app/account/register/register.html | 17 +- .../account/reset/finish/reset.finish.html | 2 +- .../app/admin/metrics/metrics.controller.js | 3 - .../user-management/user-management.html | 2 +- .../admin/user-management/user-management.js | 4 +- src/main/webapp/scripts/app/app.js | 22 +- .../author/author-dialog.controller.js | 2 +- src/main/webapp/scripts/app/main/main.html | 7 +- .../components/alert/alert.directive.js | 118 +++-- .../scripts/components/alert/alert.service.js | 8 +- .../scripts/components/auth/auth.service.js | 8 +- .../components/auth/principal.service.js | 14 +- .../interceptor/auth.interceptor.js | 2 +- .../interceptor/notification.interceptor.js | 4 +- .../scripts/components/navbar/navbar.html | 129 ++--- .../components/util/capitalize.filter.js | 10 + .../components/util/dateutil.service.js | 10 +- .../security/SecurityUtilsTest.java | 4 +- .../service/UserServiceTest.java | 29 +- .../web/rest/AccountResourceTest.java | 7 +- .../web/rest/AuditResourceTest.java | 4 +- .../web/rest/PublicationResourceTest.java | 9 +- .../ird/malariaplantdb/web/rest/TestUtil.java | 40 +- src/test/javascript/karma.conf.js | 9 +- .../activate/activate.controller.spec.js | 63 +++ .../password/password.controller.spec.js | 81 ++-- .../password/password.directive.spec.js | 2 - .../register/register.controller.spec.js | 111 +++++ .../finish/reset.finish.controller.spec.js | 62 +++ .../request/reset.request.controller.spec.js | 109 +++++ .../settings/settings.controller.spec.js | 92 ++-- .../admin/health/health.controller.spec.js | 305 ++++++++++++ .../components/auth/auth.services.spec.js | 2 - .../javascript/spec/helpers/httpBackend.js | 11 + src/test/javascript/spec/helpers/module.js | 14 + src/test/resources/config/application.yml | 96 ++-- 157 files changed, 2891 insertions(+), 1588 deletions(-) create mode 100644 docker-compose-prod.yml create mode 100644 src/main/java/nc/ird/malariaplantdb/config/JHipsterProperties.java delete mode 100644 src/main/java/nc/ird/malariaplantdb/config/MailConfiguration.java create mode 100644 src/main/java/nc/ird/malariaplantdb/config/liquibase/AsyncSpringLiquibase.java create mode 100644 src/main/java/nc/ird/malariaplantdb/config/liquibase/package-info.java delete mode 100644 src/main/java/nc/ird/malariaplantdb/config/metrics/JavaMailHealthIndicator.java delete mode 100644 src/main/java/nc/ird/malariaplantdb/domain/util/CustomDateTimeDeserializer.java delete mode 100644 src/main/java/nc/ird/malariaplantdb/domain/util/CustomDateTimeSerializer.java delete mode 100644 src/main/java/nc/ird/malariaplantdb/domain/util/CustomLocalDateSerializer.java delete mode 100644 src/main/java/nc/ird/malariaplantdb/domain/util/ISO8601LocalDateDeserializer.java create mode 100644 src/main/java/nc/ird/malariaplantdb/domain/util/JSR310DateConverters.java create mode 100644 src/main/java/nc/ird/malariaplantdb/domain/util/JSR310DateTimeSerializer.java create mode 100644 src/main/java/nc/ird/malariaplantdb/domain/util/JSR310LocalDateDeserializer.java create mode 100644 src/main/java/nc/ird/malariaplantdb/domain/util/JSR310PersistenceConverters.java create mode 100644 src/main/java/nc/ird/malariaplantdb/security/CustomUserDetails.java delete mode 100644 src/main/java/nc/ird/malariaplantdb/web/propertyeditors/LocaleDateTimeEditor.java delete mode 100644 src/main/java/nc/ird/malariaplantdb/web/propertyeditors/package-info.java rename src/main/resources/{logback.xml => logback-spring.xml} (100%) delete mode 100644 src/main/webapp/scripts/app/account/logout/logout.controller.js delete mode 100644 src/main/webapp/scripts/app/account/logout/logout.js create mode 100755 src/main/webapp/scripts/components/util/capitalize.filter.js create mode 100644 src/test/javascript/spec/app/account/activate/activate.controller.spec.js create mode 100644 src/test/javascript/spec/app/account/register/register.controller.spec.js create mode 100644 src/test/javascript/spec/app/account/reset/finish/reset.finish.controller.spec.js create mode 100644 src/test/javascript/spec/app/account/reset/request/reset.request.controller.spec.js create mode 100644 src/test/javascript/spec/app/admin/health/health.controller.spec.js create mode 100644 src/test/javascript/spec/helpers/httpBackend.js create mode 100644 src/test/javascript/spec/helpers/module.js diff --git a/.gitignore b/.gitignore index acd33e3..7e7fb1c 100644 --- a/.gitignore +++ b/.gitignore @@ -21,7 +21,6 @@ *.pydevproject .project .metadata -/bin/** /tmp/** /tmp/**/* *.tmp diff --git a/.yo-rc.json b/.yo-rc.json index d860748..d3500dc 100644 --- a/.yo-rc.json +++ b/.yo-rc.json @@ -16,6 +16,10 @@ "frontendBuilder": "grunt", "javaVersion": "8", "enableTranslation": false, - "rememberMeKey": "cb0f037ff3c3646f9796359f3916f7e654f33744" + "rememberMeKey": "cb0f037ff3c3646f9796359f3916f7e654f33744", + "enableSocialSignIn": false, + "testFrameworks": [ + "gatling" + ] } } \ No newline at end of file diff --git a/Gruntfile.js b/Gruntfile.js index 9b4b93b..36d4d35 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -1,4 +1,4 @@ -// Generated on 2015-09-18 using generator-jhipster 2.21.0 +// Generated on 2015-11-04 using generator-jhipster 2.23.0 'use strict'; var fs = require('fs'); @@ -20,7 +20,7 @@ var useminAutoprefixer = { if(block.src.length === 0) { return {}; } else { - return require('grunt-usemin/lib/config/cssmin').createConfig(context, block) // Reuse cssmins createConfig + return require('grunt-usemin/lib/config/cssmin').createConfig(context, block); // Reuse cssmins createConfig } } }; @@ -75,6 +75,7 @@ module.exports = function (grunt) { src: ['src/main/webapp/index.html', 'src/main/scss/main.scss'], exclude: [ /angular-i18n/, // localizations are loaded dynamically + 'bower_components/bootstrap/', // Exclude Bootstrap LESS as we use bootstrap-sass /bootstrap-sass\/assets\/stylesheets/ ], ignorePath: /\.\.\/webapp\/bower_components\// // remove ../webapp/bower_components/ from paths of injected sass files @@ -229,7 +230,7 @@ module.exports = function (grunt) { ngtemplates: { dist: { cwd: 'src/main/webapp', - src: ['scripts/app/**/*.html', 'scripts/components/**/*.html',], + src: ['scripts/app/**/*.html', 'scripts/components/**/*.html'], dest: '.tmp/templates/templates.js', options: { module: 'malariaplantdbApp', @@ -372,7 +373,7 @@ module.exports = function (grunt) { 'src/main/webapp/index.html': 'src/main/webapp/index.html' } } - }, + } }); grunt.registerTask('serve', [ @@ -420,27 +421,27 @@ module.exports = function (grunt) { 'htmlmin' ]); - grunt.registerTask('appendSkipBower', 'Force skip of bower for Gradle', function () { + grunt.registerTask('appendSkipBower', 'Force skip of bower for Gradle', function () { - if (!grunt.file.exists(filepath)) { - // Assume this is a maven project - return true; - } + if (!grunt.file.exists(filepath)) { + // Assume this is a maven project + return true; + } - var fileContent = grunt.file.read(filepath); - var skipBowerIndex = fileContent.indexOf("skipBower=true"); + var fileContent = grunt.file.read(filepath); + var skipBowerIndex = fileContent.indexOf("skipBower=true"); - if (skipBowerIndex != -1) { - return true; - } + if (skipBowerIndex != -1) { + return true; + } - grunt.file.write(filepath, fileContent + "\nskipBower=true\n"); - }); + grunt.file.write(filepath, fileContent + "\nskipBower=true\n"); + }); grunt.registerTask('buildOpenshift', [ 'test', 'build', - 'copy:generateOpenshiftDirectory', + 'copy:generateOpenshiftDirectory' ]); grunt.registerTask('deployOpenshift', [ diff --git a/bower.json b/bower.json index 7bf4613..ab873fb 100644 --- a/bower.json +++ b/bower.json @@ -14,7 +14,7 @@ "angular-sanitize": "1.4.5", "angular-ui-router": "0.2.15", "bootstrap-sass": "3.3.5", - "bootswatch" : "3.3.5", + "bootswatch": "3.3.5", "jquery": "2.1.4", "json3": "3.3.2", "modernizr": "2.8.3", diff --git a/docker-compose-prod.yml b/docker-compose-prod.yml new file mode 100644 index 0000000..4f0b13e --- /dev/null +++ b/docker-compose-prod.yml @@ -0,0 +1,19 @@ +jhipster-prod-elasticsearch: + container_name: malariaplantdb-prod-elasticsearch + image: elasticsearch + # volumes: + # - ~/volumes/jhipster/malariaplantdb/prod-elasticsearch/:/usr/share/elasticsearch/data/ + ports: + - "9200:9200" + - "9300:9300" +jhipster-prod-postgresql: + container_name: malariaplantdb-prod-postgresql + image: postgres + # volumes: + # - ~/volumes/jhipster/malariaplantdb/prod-postgresql/:/var/lib/postgresql/ + environment: + - POSTGRES_USER=malariaplantdb + - POSTGRES_PASSWORD= + ports: + - "5432:5432" + diff --git a/package.json b/package.json index a48ca1e..c7d8975 100644 --- a/package.json +++ b/package.json @@ -3,18 +3,18 @@ "version": "0.0.0", "description": "Description for malariaplantdb", "private": true, - "dependencies": {}, + "dependencies": { + }, "devDependencies": { - "event-stream": "3.3.1", - "generator-jhipster": "2.21.0", "grunt": "0.4.5", - "grunt-angular-templates": "0.5.7", "grunt-autoprefixer": "2.2.0", - "grunt-browser-sync": "2.1.3", "grunt-build-control": "0.3.0", + "grunt-wiredep": "2.0.0", + "grunt-browser-sync": "2.1.3", + "browser-sync": "2.9.6", + "grunt-contrib-copy": "0.8.0", "grunt-contrib-clean": "0.6.0", "grunt-contrib-concat": "0.5.1", - "grunt-contrib-copy": "0.8.0", "grunt-contrib-cssmin": "0.11.0", "grunt-contrib-htmlmin": "0.4.0", "grunt-contrib-imagemin": "0.9.3", @@ -22,36 +22,38 @@ "grunt-contrib-uglify": "0.8.0", "grunt-contrib-watch": "0.6.1", "grunt-include-source": "^0.7.0", - "grunt-karma": "0.11.0", "grunt-modernizr": "0.6.0", "grunt-ng-annotate": "0.10.0", "grunt-ng-constant": "1.1.0", "grunt-rev": "0.1.0", - "grunt-sass": "1.0.0", "grunt-svgmin": "2.0.1", "grunt-text-replace": "0.4.0", "grunt-usemin": "3.0.0", - "grunt-wiredep": "2.0.0", - "jasmine-core": "2.1.0", + "grunt-angular-templates":"0.5.7", + "load-grunt-tasks": "3.1.0", + "grunt-karma": "0.11.0", + "time-grunt": "1.1.0", + "grunt-sass": "1.0.0", + "event-stream": "3.3.1", "jshint-stylish": "1.0.1", - "karma": "0.12.35", + "karma-script-launcher": "0.1.0", "karma-chrome-launcher": "0.1.12", - "karma-coverage": "0.4.2", "karma-html2js-preprocessor": "0.1.0", "karma-jasmine": "0.3.5", - "karma-jenkins-reporter": "0.0.2", - "karma-phantomjs-launcher": "0.2.0", "karma-requirejs": "0.2.2", - "karma-script-launcher": "0.1.0", - "load-grunt-tasks": "3.1.0", - "lodash": "3.3.1", + "karma-phantomjs-launcher": "0.2.0", "phantomjs": "1.9.17", - "requirejs": "2.1", - "time-grunt": "1.1.0", - "wiredep": "2.2.2", + "karma": "0.12.35", + "karma-coverage": "0.4.2", + "karma-jenkins-reporter": "0.0.2", + "generator-jhipster": "2.23.0", + "lodash": "3.3.1", "xml2js": "0.4.5", "yo": ">=1.3.0", - "zeparser": "0.0.7" + "requirejs": "2.1", + "jasmine-core": "2.1.0", + "zeparser": "0.0.7", + "wiredep": "2.2.2" }, "engines": { "node": ">=0.12.0" diff --git a/pom.xml b/pom.xml index 38c53ae..38a0595 100755 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ spring-boot-starter-parent org.springframework.boot - 1.2.5.RELEASE + 1.3.0.RC1 @@ -13,27 +13,38 @@ malariaplantdb 0.0.1-SNAPSHOT war - malariaplantdb + + + spring-milestones + http://repo.spring.io/milestone + + + + + spring-milestones + http://repo.spring.io/milestone + + + 3.0.0 - 2.4.0 + 2.4.1 3.1.0 1.4.0 2.4 2.6 - 2.1.6 - 2.1.6 - 4.3.10.Final + 2.1.7 + 2.1.7 + 4.3.11.Final 1.8 ${java.version} ${java.version} 1 - 1.4 3.4.1 1.2.1 3.5 @@ -43,11 +54,10 @@ 2.3.0 1.2 3.1.2 - 9.4-1201-jdbc41 + 9.4-1203-jdbc42 false 4.0.2.RELEASE 2.0.3 - 4.0.0.GA ${project.build.directory}/test-results 2.6 @@ -63,7 +73,6 @@ ${project.basedir}/src/main/ ${project.testresult.directory}/surefire-reports ${project.basedir}/src/test/ - @@ -127,7 +136,7 @@ com.fasterxml.jackson.datatype - jackson-datatype-joda + jackson-datatype-jsr310 com.fasterxml.jackson.datatype @@ -223,15 +232,6 @@ javax.inject ${javax.inject.version} - - joda-time - joda-time - - - joda-time - joda-time-hibernate - ${joda-time-hibernate.version} - org.assertj assertj-core @@ -257,11 +257,6 @@ org.hibernate hibernate-validator - - org.jadira.usertype - usertype.core - ${usertype-core.version} - org.liquibase liquibase-core @@ -294,10 +289,20 @@ org.springframework.boot spring-boot-autoconfigure + + org.springframework.boot + spring-boot-configuration-processor + true + org.springframework.boot spring-boot-loader-tools + + org.springframework.boot + spring-boot-devtools + true + org.springframework.boot spring-boot-starter-aop @@ -577,6 +582,7 @@ org.springframework.boot spring-boot-maven-plugin + true -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 --spring.profiles.active=dev @@ -647,6 +653,7 @@ org.springframework.boot spring-boot-maven-plugin + true --spring.profiles.active=dev,fast @@ -707,6 +714,7 @@ org.springframework.boot spring-boot-maven-plugin + true --spring.profiles.active=prod diff --git a/src/main/java/nc/ird/malariaplantdb/Application.java b/src/main/java/nc/ird/malariaplantdb/Application.java index 86d13a9..42c7c0d 100644 --- a/src/main/java/nc/ird/malariaplantdb/Application.java +++ b/src/main/java/nc/ird/malariaplantdb/Application.java @@ -1,12 +1,16 @@ package nc.ird.malariaplantdb; import nc.ird.malariaplantdb.config.Constants; +import nc.ird.malariaplantdb.config.JHipsterProperties; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration; import org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.env.Environment; import org.springframework.core.env.SimpleCommandLinePropertySource; @@ -20,7 +24,8 @@ import java.util.Collection; @ComponentScan -@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class}) +@EnableAutoConfiguration(exclude = { MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class }) +@EnableConfigurationProperties({ JHipsterProperties.class, LiquibaseProperties.class }) public class Application { private static final Logger log = LoggerFactory.getLogger(Application.class); @@ -64,14 +69,12 @@ public void initApplication() throws IOException { */ public static void main(String[] args) throws UnknownHostException { SpringApplication app = new SpringApplication(Application.class); - app.setShowBanner(false); SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); addDefaultProfile(app, source); - addLiquibaseScanPackages(); Environment env = app.run(args).getEnvironment(); log.info("Access URLs:\n----------------------------------------------------------\n\t" + - "Local: \t\thttp://127.0.0.1:{}\n\t" + - "External: \thttp://{}:{}\n----------------------------------------------------------", + "Local: \t\thttp://127.0.0.1:{}\n\t" + + "External: \thttp://{}:{}\n----------------------------------------------------------", env.getProperty("server.port"), InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port")); @@ -88,16 +91,4 @@ private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePr app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT); } } - - /** - * Set the liquibases.scan.packages to avoid an exception from ServiceLocator. - */ - private static void addLiquibaseScanPackages() { - System.setProperty("liquibase.scan.packages", "liquibase.change,liquibase.database," + - "liquibase.parser,liquibase.precondition,liquibase.datatype," + - "liquibase.serializer,liquibase.sqlgenerator,liquibase.executor," + - "liquibase.snapshot,liquibase.logging,liquibase.diff," + - "liquibase.structure,liquibase.structurecompare,liquibase.lockservice," + - "liquibase.ext,liquibase.changelog"); - } } diff --git a/src/main/java/nc/ird/malariaplantdb/ApplicationWebXml.java b/src/main/java/nc/ird/malariaplantdb/ApplicationWebXml.java index 34f0668..c86e102 100644 --- a/src/main/java/nc/ird/malariaplantdb/ApplicationWebXml.java +++ b/src/main/java/nc/ird/malariaplantdb/ApplicationWebXml.java @@ -1,6 +1,7 @@ package nc.ird.malariaplantdb; import nc.ird.malariaplantdb.config.Constants; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.builder.SpringApplicationBuilder; @@ -16,13 +17,11 @@ public class ApplicationWebXml extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.profiles(addDefaultProfile()) - .showBanner(false) - .sources(Application.class); + .sources(Application.class); } /** * Set a default profile if it has not been set. - *

*

* Please use -Dspring.profiles.active=dev *

diff --git a/src/main/java/nc/ird/malariaplantdb/aop/logging/LoggingAspect.java b/src/main/java/nc/ird/malariaplantdb/aop/logging/LoggingAspect.java index bb0858f..784465d 100644 --- a/src/main/java/nc/ird/malariaplantdb/aop/logging/LoggingAspect.java +++ b/src/main/java/nc/ird/malariaplantdb/aop/logging/LoggingAspect.java @@ -1,6 +1,7 @@ package nc.ird.malariaplantdb.aop.logging; import nc.ird.malariaplantdb.config.Constants; + import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterThrowing; @@ -26,16 +27,17 @@ public class LoggingAspect { private Environment env; @Pointcut("within(nc.ird.malariaplantdb.repository..*) || within(nc.ird.malariaplantdb.service..*) || within(nc.ird.malariaplantdb.web.rest..*)") - public void loggingPointcut() {} + public void loggingPointcut() { + } @AfterThrowing(pointcut = "loggingPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), - joinPoint.getSignature().getName(), e.getCause(), e); + joinPoint.getSignature().getName(), e.getCause(), e); } else { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), - joinPoint.getSignature().getName(), e.getCause()); + joinPoint.getSignature().getName(), e.getCause()); } } @@ -43,13 +45,13 @@ public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { if (log.isDebugEnabled()) { log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(), - joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); + joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs())); } try { Object result = joinPoint.proceed(); if (log.isDebugEnabled()) { log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(), - joinPoint.getSignature().getName(), result); + joinPoint.getSignature().getName(), result); } return result; } catch (IllegalArgumentException e) { diff --git a/src/main/java/nc/ird/malariaplantdb/async/ExceptionHandlingAsyncTaskExecutor.java b/src/main/java/nc/ird/malariaplantdb/async/ExceptionHandlingAsyncTaskExecutor.java index e15920f..4a5a6ff 100644 --- a/src/main/java/nc/ird/malariaplantdb/async/ExceptionHandlingAsyncTaskExecutor.java +++ b/src/main/java/nc/ird/malariaplantdb/async/ExceptionHandlingAsyncTaskExecutor.java @@ -10,7 +10,7 @@ import org.springframework.core.task.AsyncTaskExecutor; public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor, - InitializingBean, DisposableBean { + InitializingBean, DisposableBean { private final Logger log = LoggerFactory.getLogger(ExceptionHandlingAsyncTaskExecutor.class); diff --git a/src/main/java/nc/ird/malariaplantdb/config/AsyncConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/AsyncConfiguration.java index e325c3d..673e8df 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/AsyncConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/AsyncConfiguration.java @@ -1,47 +1,38 @@ package nc.ird.malariaplantdb.config; +import nc.ird.malariaplantdb.async.ExceptionHandlingAsyncTaskExecutor; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; -import org.springframework.boot.bind.RelaxedPropertyResolver; -import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; -import org.springframework.scheduling.annotation.AsyncConfigurer; -import org.springframework.scheduling.annotation.EnableAsync; -import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.*; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; -import nc.ird.malariaplantdb.async.ExceptionHandlingAsyncTaskExecutor; +import javax.inject.Inject; @Configuration @EnableAsync @EnableScheduling -@Profile("!" + Constants.SPRING_PROFILE_FAST) -public class AsyncConfiguration implements AsyncConfigurer, EnvironmentAware { +public class AsyncConfiguration implements AsyncConfigurer { private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class); - private RelaxedPropertyResolver propertyResolver; - - @Override - public void setEnvironment(Environment environment) { - this.propertyResolver = new RelaxedPropertyResolver(environment, "async."); - } + @Inject + private JHipsterProperties jHipsterProperties; @Override - @Bean + @Bean(name = "taskExecutor") public Executor getAsyncExecutor() { log.debug("Creating Async Task Executor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); - executor.setCorePoolSize(propertyResolver.getProperty("corePoolSize", Integer.class, 2)); - executor.setMaxPoolSize(propertyResolver.getProperty("maxPoolSize", Integer.class, 50)); - executor.setQueueCapacity(propertyResolver.getProperty("queueCapacity", Integer.class, 10000)); + executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize()); + executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize()); + executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity()); executor.setThreadNamePrefix("malariaplantdb-Executor-"); return new ExceptionHandlingAsyncTaskExecutor(executor); } diff --git a/src/main/java/nc/ird/malariaplantdb/config/CacheConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/CacheConfiguration.java index 3e0e68e..137f811 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/CacheConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/CacheConfiguration.java @@ -7,11 +7,8 @@ import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; +import org.springframework.context.annotation.*; import org.springframework.cache.ehcache.EhCacheCacheManager; -import org.springframework.core.env.Environment; import org.springframework.util.Assert; import javax.annotation.PreDestroy; @@ -24,7 +21,7 @@ @Configuration @EnableCaching -@AutoConfigureAfter(value = {MetricsConfiguration.class, DatabaseConfiguration.class}) +@AutoConfigureAfter(value = { MetricsConfiguration.class, DatabaseConfiguration.class }) @Profile("!" + Constants.SPRING_PROFILE_FAST) public class CacheConfiguration { @@ -33,9 +30,6 @@ public class CacheConfiguration { @PersistenceContext private EntityManager entityManager; - @Inject - private Environment env; - @Inject private MetricRegistry metricRegistry; @@ -51,10 +45,10 @@ public void destroy() { } @Bean - public CacheManager cacheManager() { + public CacheManager cacheManager(JHipsterProperties jHipsterProperties) { log.debug("Starting Ehcache"); cacheManager = net.sf.ehcache.CacheManager.create(); - cacheManager.getConfiguration().setMaxBytesLocalHeap(env.getProperty("cache.ehcache.maxBytesLocalHeap", String.class, "16M")); + cacheManager.getConfiguration().setMaxBytesLocalHeap(jHipsterProperties.getCache().getEhcache().getMaxBytesLocalHeap()); log.debug("Registering Ehcache Metrics gauges"); Set> entities = entityManager.getMetamodel().getEntities(); for (EntityType entity : entities) { @@ -67,7 +61,7 @@ public CacheManager cacheManager() { net.sf.ehcache.Cache cache = cacheManager.getCache(name); if (cache != null) { - cache.getCacheConfiguration().setTimeToLiveSeconds(env.getProperty("cache.timeToLiveSeconds", Long.class, 3600L)); + cache.getCacheConfiguration().setTimeToLiveSeconds(jHipsterProperties.getCache().getTimeToLiveSeconds()); net.sf.ehcache.Ehcache decoratedCache = InstrumentedEhcache.instrument(metricRegistry, cache); cacheManager.replaceCacheWithDecoratedCache(cache, decoratedCache); } diff --git a/src/main/java/nc/ird/malariaplantdb/config/CloudDatabaseConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/CloudDatabaseConfiguration.java index df739ae..421b174 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/CloudDatabaseConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/CloudDatabaseConfiguration.java @@ -3,9 +3,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.config.java.AbstractCloudConfig; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; +import org.springframework.context.annotation.*; import javax.sql.DataSource; diff --git a/src/main/java/nc/ird/malariaplantdb/config/DatabaseConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/DatabaseConfiguration.java index 2c9e80a..ce168d9 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/DatabaseConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/DatabaseConfiguration.java @@ -1,17 +1,20 @@ package nc.ird.malariaplantdb.config; +import nc.ird.malariaplantdb.config.liquibase.AsyncSpringLiquibase; + import com.codahale.metrics.MetricRegistry; import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import liquibase.integration.spring.SpringLiquibase; +import org.h2.tools.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; -import org.springframework.boot.bind.RelaxedPropertyResolver; +import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; +import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties; import org.springframework.context.ApplicationContextException; -import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @@ -20,9 +23,10 @@ import org.springframework.data.jpa.repository.config.EnableJpaAuditing; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.util.StringUtils; +import javax.inject.Inject; import javax.sql.DataSource; +import java.sql.SQLException; import java.util.Arrays; @Configuration @@ -30,62 +34,68 @@ @EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") @EnableTransactionManagement @EnableElasticsearchRepositories("nc.ird.malariaplantdb.repository.search") -public class DatabaseConfiguration implements EnvironmentAware { +public class DatabaseConfiguration { private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class); - private RelaxedPropertyResolver dataSourcePropertyResolver; - - private RelaxedPropertyResolver liquiBasePropertyResolver; - + @Inject private Environment env; @Autowired(required = false) private MetricRegistry metricRegistry; - @Override - public void setEnvironment(Environment env) { - this.env = env; - this.dataSourcePropertyResolver = new RelaxedPropertyResolver(env, "spring.datasource."); - this.liquiBasePropertyResolver = new RelaxedPropertyResolver(env, "liquiBase."); - } - @Bean(destroyMethod = "close") @ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}") - public DataSource dataSource() { + public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) { log.debug("Configuring Datasource"); - if (dataSourcePropertyResolver.getProperty("url") == null && dataSourcePropertyResolver.getProperty("databaseName") == null) { + if (dataSourceProperties.getUrl() == null) { log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", - Arrays.toString(env.getActiveProfiles())); + Arrays.toString(env.getActiveProfiles())); throw new ApplicationContextException("Database connection pool is not configured correctly"); } HikariConfig config = new HikariConfig(); - config.setDataSourceClassName(dataSourcePropertyResolver.getProperty("dataSourceClassName")); - if(StringUtils.isEmpty(dataSourcePropertyResolver.getProperty("url"))) { - config.addDataSourceProperty("databaseName", dataSourcePropertyResolver.getProperty("databaseName")); - config.addDataSourceProperty("serverName", dataSourcePropertyResolver.getProperty("serverName")); + config.setDataSourceClassName(dataSourceProperties.getDriverClassName()); + config.addDataSourceProperty("url", dataSourceProperties.getUrl()); + if (dataSourceProperties.getUsername() != null) { + config.addDataSourceProperty("user", dataSourceProperties.getUsername()); } else { - config.addDataSourceProperty("url", dataSourcePropertyResolver.getProperty("url")); + config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user + } + if (dataSourceProperties.getPassword() != null) { + config.addDataSourceProperty("password", dataSourceProperties.getPassword()); + } else { + config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password } - config.addDataSourceProperty("user", dataSourcePropertyResolver.getProperty("username")); - config.addDataSourceProperty("password", dataSourcePropertyResolver.getProperty("password")); if (metricRegistry != null) { config.setMetricRegistry(metricRegistry); } return new HikariDataSource(config); } + /** + * Open the TCP port for the H2 database, so it is available remotely. + */ + @Bean(initMethod = "start", destroyMethod = "stop") + public Server h2TCPServer() throws SQLException { + return Server.createTcpServer("-tcp","-tcpAllowOthers"); + } @Bean - public SpringLiquibase liquibase(DataSource dataSource) { - SpringLiquibase liquibase = new SpringLiquibase(); + public SpringLiquibase liquibase(DataSource dataSource, DataSourceProperties dataSourceProperties, + LiquibaseProperties liquibaseProperties) { + + // Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously + SpringLiquibase liquibase = new AsyncSpringLiquibase(); liquibase.setDataSource(dataSource); liquibase.setChangeLog("classpath:config/liquibase/master.xml"); - liquibase.setContexts(liquiBasePropertyResolver.getProperty("context")); + liquibase.setContexts(liquibaseProperties.getContexts()); + liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); + liquibase.setDropFirst(liquibaseProperties.isDropFirst()); + liquibase.setShouldRun(liquibaseProperties.isEnabled()); if (env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) { - if ("org.h2.jdbcx.JdbcDataSource".equals(dataSourcePropertyResolver.getProperty("dataSourceClassName"))) { + if ("org.h2.jdbcx.JdbcDataSource".equals(dataSourceProperties.getDriverClassName())) { liquibase.setShouldRun(true); log.warn("Using '{}' profile with H2 database in memory is not optimal, you should consider switching to" + " MySQL or Postgresql to avoid rebuilding your database upon each start.", Constants.SPRING_PROFILE_FAST); diff --git a/src/main/java/nc/ird/malariaplantdb/config/JHipsterProperties.java b/src/main/java/nc/ird/malariaplantdb/config/JHipsterProperties.java new file mode 100644 index 0000000..6af430f --- /dev/null +++ b/src/main/java/nc/ird/malariaplantdb/config/JHipsterProperties.java @@ -0,0 +1,453 @@ +package nc.ird.malariaplantdb.config; + +import javax.validation.constraints.NotNull; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Properties specific to JHipster. + * + *

+ * Properties are configured in the application.yml file. + *

+ */ +@ConfigurationProperties(prefix = "jhipster", ignoreUnknownFields = false) +public class JHipsterProperties { + + private final Async async = new Async(); + + private final Http http = new Http(); + + private final Datasource datasource = new Datasource(); + + private final Cache cache = new Cache(); + + private final Mail mail = new Mail(); + + private final Security security = new Security(); + + private final Swagger swagger = new Swagger(); + + private final Metrics metrics = new Metrics(); + + + + public Async getAsync() { + return async; + } + + public Http getHttp() { + return http; + } + + public Datasource getDatasource() { + return datasource; + } + + public Cache getCache() { + return cache; + } + + public Mail getMail() { + return mail; + } + + public Security getSecurity() { + return security; + } + + public Swagger getSwagger() { + return swagger; + } + + public Metrics getMetrics() { + return metrics; + } + + + public static class Async { + + private int corePoolSize = 2; + + private int maxPoolSize = 50; + + private int queueCapacity = 10000; + + public int getCorePoolSize() { + return corePoolSize; + } + + public void setCorePoolSize(int corePoolSize) { + this.corePoolSize = corePoolSize; + } + + public int getMaxPoolSize() { + return maxPoolSize; + } + + public void setMaxPoolSize(int maxPoolSize) { + this.maxPoolSize = maxPoolSize; + } + + public int getQueueCapacity() { + return queueCapacity; + } + + public void setQueueCapacity(int queueCapacity) { + this.queueCapacity = queueCapacity; + } + } + + public static class Http { + + private final Cache cache = new Cache(); + + public Cache getCache() { + return cache; + } + + public static class Cache { + + private int timeToLiveInDays = 31; + + public int getTimeToLiveInDays() { + return timeToLiveInDays; + } + + public void setTimeToLiveInDays(int timeToLiveInDays) { + this.timeToLiveInDays = timeToLiveInDays; + } + } + } + + public static class Datasource { + + private boolean cachePrepStmts = true; + + private int prepStmtCacheSize = 250; + + private int prepStmtCacheSqlLimit = 2048; + + private boolean useServerPrepStmts = true; + + public boolean isCachePrepStmts() { + return cachePrepStmts; + } + + public void setCachePrepStmts(boolean cachePrepStmts) { + this.cachePrepStmts = cachePrepStmts; + } + + public int getPrepStmtCacheSize() { + return prepStmtCacheSize; + } + + public void setPrepStmtCacheSize(int prepStmtCacheSize) { + this.prepStmtCacheSize = prepStmtCacheSize; + } + + public int getPrepStmtCacheSqlLimit() { + return prepStmtCacheSqlLimit; + } + + public void setPrepStmtCacheSqlLimit(int prepStmtCacheSqlLimit) { + this.prepStmtCacheSqlLimit = prepStmtCacheSqlLimit; + } + + public boolean isUseServerPrepStmts() { + return useServerPrepStmts; + } + + public void setUseServerPrepStmts(boolean useServerPrepStmts) { + this.useServerPrepStmts = useServerPrepStmts; + } + } + + public static class Cache { + + private int timeToLiveSeconds = 3600; + + private final Ehcache ehcache = new Ehcache(); + + public int getTimeToLiveSeconds() { + return timeToLiveSeconds; + } + + public void setTimeToLiveSeconds(int timeToLiveSeconds) { + this.timeToLiveSeconds = timeToLiveSeconds; + } + + public Ehcache getEhcache() { + return ehcache; + } + + public static class Ehcache { + + private String maxBytesLocalHeap = "16M"; + + public String getMaxBytesLocalHeap() { + return maxBytesLocalHeap; + } + + public void setMaxBytesLocalHeap(String maxBytesLocalHeap) { + this.maxBytesLocalHeap = maxBytesLocalHeap; + } + } + } + + public static class Mail { + + private String from = "malariaplantdb@localhost"; + + public String getFrom() { + return from; + } + + public void setFrom(String from) { + this.from = from; + } + } + + public static class Security { + + private final Rememberme rememberme = new Rememberme(); + + private final Authentication authentication = new Authentication(); + + public Rememberme getRememberme() { + return rememberme; + } + + public Authentication getAuthentication() { + return authentication; + } + + public static class Authentication { + + private final Xauth xauth = new Xauth(); + + public Xauth getXauth() { + return xauth; + } + + public static class Xauth { + + private String secret; + + private int tokenValidityInSeconds = 1800; + + public String getSecret() { + return secret; + } + + public void setSecret(String secret) { + this.secret = secret; + } + + public int getTokenValidityInSeconds() { + return tokenValidityInSeconds; + } + + public void setTokenValidityInSeconds(int tokenValidityInSeconds) { + this.tokenValidityInSeconds = tokenValidityInSeconds; + } + } + } + public static class Rememberme { + + @NotNull + private String key; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + } + } + + public static class Swagger { + + private String title = "malariaplantdb API"; + + private String description = "malariaplantdb API documentation"; + + private String version = "0.0.1"; + + private String termsOfServiceUrl; + + private String contact; + + private String license; + + private String licenseUrl; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getTermsOfServiceUrl() { + return termsOfServiceUrl; + } + + public void setTermsOfServiceUrl(String termsOfServiceUrl) { + this.termsOfServiceUrl = termsOfServiceUrl; + } + + public String getContact() { + return contact; + } + + public void setContact(String contact) { + this.contact = contact; + } + + public String getLicense() { + return license; + } + + public void setLicense(String license) { + this.license = license; + } + + public String getLicenseUrl() { + return licenseUrl; + } + + public void setLicenseUrl(String licenseUrl) { + this.licenseUrl = licenseUrl; + } + } + + public static class Metrics { + + private final Jmx jmx = new Jmx(); + + private final Spark spark = new Spark(); + + private final Graphite graphite = new Graphite(); + + public Jmx getJmx() { + return jmx; + } + + public Spark getSpark() { + return spark; + } + + public Graphite getGraphite() { + return graphite; + } + + public static class Jmx { + + private boolean enabled = true; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + } + + public static class Spark { + + private boolean enabled = false; + + private String host = "localhost"; + + private int port = 9999; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + } + + public static class Graphite { + + private boolean enabled = false; + + private String host = "localhost"; + + private int port = 2003; + + private String prefix = "malariaplantdb"; + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public String getPrefix() { + return prefix; + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + } + } + } +} diff --git a/src/main/java/nc/ird/malariaplantdb/config/JacksonConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/JacksonConfiguration.java index 3d8b4fd..eeea564 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/JacksonConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/JacksonConfiguration.java @@ -1,26 +1,28 @@ package nc.ird.malariaplantdb.config; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; +import nc.ird.malariaplantdb.domain.util.*; + +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import java.time.*; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import nc.ird.malariaplantdb.domain.util.CustomDateTimeDeserializer; -import nc.ird.malariaplantdb.domain.util.CustomDateTimeSerializer; -import nc.ird.malariaplantdb.domain.util.CustomLocalDateSerializer; -import nc.ird.malariaplantdb.domain.util.ISO8601LocalDateDeserializer; -import com.fasterxml.jackson.datatype.joda.JodaModule; - @Configuration public class JacksonConfiguration { @Bean - public JodaModule jacksonJodaModule() { - JodaModule module = new JodaModule(); - module.addSerializer(DateTime.class, new CustomDateTimeSerializer()); - module.addDeserializer(DateTime.class, new CustomDateTimeDeserializer()); - module.addSerializer(LocalDate.class, new CustomLocalDateSerializer()); - module.addDeserializer(LocalDate.class, new ISO8601LocalDateDeserializer()); - return module; + Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() { + JavaTimeModule module = new JavaTimeModule(); + module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE); + module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE); + module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE); + module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE); + module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE); + return new Jackson2ObjectMapperBuilder() + .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .findModulesViaServiceLoader(true) + .modulesToInstall(module); } } diff --git a/src/main/java/nc/ird/malariaplantdb/config/LocaleConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/LocaleConfiguration.java index 07f8567..917c035 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/LocaleConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/LocaleConfiguration.java @@ -1,6 +1,7 @@ package nc.ird.malariaplantdb.config; import nc.ird.malariaplantdb.config.locale.AngularCookieLocaleResolver; + import org.springframework.boot.bind.RelaxedPropertyResolver; import org.springframework.context.EnvironmentAware; import org.springframework.context.MessageSource; @@ -20,7 +21,7 @@ public class LocaleConfiguration extends WebMvcConfigurerAdapter implements Envi @Override public void setEnvironment(Environment environment) { - this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.messageSource."); + this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.messages."); } @Bean(name = "localeResolver") @@ -35,7 +36,7 @@ public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("classpath:/i18n/messages"); messageSource.setDefaultEncoding("UTF-8"); - messageSource.setCacheSeconds(propertyResolver.getProperty("cacheSeconds", Integer.class, 1)); + messageSource.setCacheSeconds(propertyResolver.getProperty("cache-seconds", Integer.class, -1)); return messageSource; } diff --git a/src/main/java/nc/ird/malariaplantdb/config/LoggingAspectConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/LoggingAspectConfiguration.java index 4ce73ca..5dd3b02 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/LoggingAspectConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/LoggingAspectConfiguration.java @@ -1,10 +1,7 @@ package nc.ird.malariaplantdb.config; import nc.ird.malariaplantdb.aop.logging.LoggingAspect; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.context.annotation.Profile; +import org.springframework.context.annotation.*; @Configuration @EnableAspectJAutoProxy diff --git a/src/main/java/nc/ird/malariaplantdb/config/MailConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/MailConfiguration.java deleted file mode 100644 index d489f71..0000000 --- a/src/main/java/nc/ird/malariaplantdb/config/MailConfiguration.java +++ /dev/null @@ -1,70 +0,0 @@ -package nc.ird.malariaplantdb.config; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.bind.RelaxedPropertyResolver; -import org.springframework.context.EnvironmentAware; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.mail.javamail.JavaMailSenderImpl; - -import java.util.Properties; - -@Configuration -public class MailConfiguration implements EnvironmentAware { - - private static final String ENV_SPRING_MAIL = "mail."; - private static final String DEFAULT_HOST = "127.0.0.1"; - private static final String PROP_HOST = "host"; - private static final String DEFAULT_PROP_HOST = "localhost"; - private static final String PROP_PORT = "port"; - private static final String PROP_USER = "username"; - private static final String PROP_PASSWORD = "password"; - private static final String PROP_PROTO = "protocol"; - private static final String PROP_TLS = "tls"; - private static final String PROP_AUTH = "auth"; - private static final String PROP_SMTP_AUTH = "mail.smtp.auth"; - private static final String PROP_STARTTLS = "mail.smtp.starttls.enable"; - private static final String PROP_TRANSPORT_PROTO = "mail.transport.protocol"; - - private final Logger log = LoggerFactory.getLogger(MailConfiguration.class); - - private RelaxedPropertyResolver propertyResolver; - - @Override - public void setEnvironment(Environment environment) { - this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_SPRING_MAIL); - } - - @Bean - public JavaMailSenderImpl javaMailSender() { - log.debug("Configuring mail server"); - String host = propertyResolver.getProperty(PROP_HOST, DEFAULT_PROP_HOST); - int port = propertyResolver.getProperty(PROP_PORT, Integer.class, 0); - String user = propertyResolver.getProperty(PROP_USER); - String password = propertyResolver.getProperty(PROP_PASSWORD); - String protocol = propertyResolver.getProperty(PROP_PROTO); - Boolean tls = propertyResolver.getProperty(PROP_TLS, Boolean.class, false); - Boolean auth = propertyResolver.getProperty(PROP_AUTH, Boolean.class, false); - - JavaMailSenderImpl sender = new JavaMailSenderImpl(); - if (host != null && !host.isEmpty()) { - sender.setHost(host); - } else { - log.warn("Warning! Your SMTP server is not configured. We will try to use one on localhost."); - log.debug("Did you configure your SMTP settings in your application.yml?"); - sender.setHost(DEFAULT_HOST); - } - sender.setPort(port); - sender.setUsername(user); - sender.setPassword(password); - - Properties sendProperties = new Properties(); - sendProperties.setProperty(PROP_SMTP_AUTH, auth.toString()); - sendProperties.setProperty(PROP_STARTTLS, tls.toString()); - sendProperties.setProperty(PROP_TRANSPORT_PROTO, protocol); - sender.setJavaMailProperties(sendProperties); - return sender; - } -} diff --git a/src/main/java/nc/ird/malariaplantdb/config/MetricsConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/MetricsConfiguration.java index 74856e6..2fa0bc2 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/MetricsConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/MetricsConfiguration.java @@ -12,12 +12,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.bind.RelaxedPropertyResolver; -import org.springframework.context.EnvironmentAware; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; +import org.springframework.context.annotation.*; import javax.annotation.PostConstruct; import javax.inject.Inject; @@ -28,18 +23,8 @@ @Configuration @EnableMetrics(proxyTargetClass = true) @Profile("!" + Constants.SPRING_PROFILE_FAST) -public class MetricsConfiguration extends MetricsConfigurerAdapter implements EnvironmentAware { - - private static final String ENV_METRICS = "metrics."; - private static final String ENV_METRICS_GRAPHITE = "metrics.graphite."; - private static final String ENV_METRICS_SPARK = "metrics.spark."; - private static final String PROP_JMX_ENABLED = "jmx.enabled"; - private static final String PROP_GRAPHITE_ENABLED = "enabled"; - private static final String PROP_SPARK_ENABLED = "enabled"; - private static final String PROP_GRAPHITE_PREFIX = ""; - - private static final String PROP_PORT = "port"; - private static final String PROP_HOST = "host"; +public class MetricsConfiguration extends MetricsConfigurerAdapter { + private static final String PROP_METRIC_REG_JVM_MEMORY = "jvm.memory"; private static final String PROP_METRIC_REG_JVM_GARBAGE = "jvm.garbage"; private static final String PROP_METRIC_REG_JVM_THREADS = "jvm.threads"; @@ -52,12 +37,8 @@ public class MetricsConfiguration extends MetricsConfigurerAdapter implements En private HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry(); - private RelaxedPropertyResolver propertyResolver; - - @Override - public void setEnvironment(Environment environment) { - this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_METRICS); - } + @Inject + private JHipsterProperties jHipsterProperties; @Override @Bean @@ -79,8 +60,8 @@ public void init() { metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet()); metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge()); metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer())); - if (propertyResolver.getProperty(PROP_JMX_ENABLED, Boolean.class, false)) { - log.info("Initializing Metrics JMX reporting"); + if (jHipsterProperties.getMetrics().getJmx().isEnabled()) { + log.debug("Initializing Metrics JMX reporting"); JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build(); jmxReporter.start(); } @@ -89,35 +70,29 @@ public void init() { @Configuration @ConditionalOnClass(Graphite.class) @Profile("!" + Constants.SPRING_PROFILE_FAST) - public static class GraphiteRegistry implements EnvironmentAware { + public static class GraphiteRegistry { private final Logger log = LoggerFactory.getLogger(GraphiteRegistry.class); @Inject private MetricRegistry metricRegistry; - private RelaxedPropertyResolver propertyResolver; - - @Override - public void setEnvironment(Environment environment) { - this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_METRICS_GRAPHITE); - } + @Inject + private JHipsterProperties jHipsterProperties; @PostConstruct private void init() { - Boolean graphiteEnabled = propertyResolver.getProperty(PROP_GRAPHITE_ENABLED, Boolean.class, false); - if (graphiteEnabled) { + if (jHipsterProperties.getMetrics().getGraphite().isEnabled()) { log.info("Initializing Metrics Graphite reporting"); - String graphiteHost = propertyResolver.getRequiredProperty(PROP_HOST); - Integer graphitePort = propertyResolver.getRequiredProperty(PROP_PORT, Integer.class); - String graphitePrefix = propertyResolver.getProperty(PROP_GRAPHITE_PREFIX, String.class, ""); - + String graphiteHost = jHipsterProperties.getMetrics().getGraphite().getHost(); + Integer graphitePort = jHipsterProperties.getMetrics().getGraphite().getPort(); + String graphitePrefix = jHipsterProperties.getMetrics().getGraphite().getPrefix(); Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, graphitePort)); GraphiteReporter graphiteReporter = GraphiteReporter.forRegistry(metricRegistry) - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .prefixedWith(graphitePrefix) - .build(graphite); + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .prefixedWith(graphitePrefix) + .build(graphite); graphiteReporter.start(1, TimeUnit.MINUTES); } } @@ -126,32 +101,26 @@ private void init() { @Configuration @ConditionalOnClass(SparkReporter.class) @Profile("!" + Constants.SPRING_PROFILE_FAST) - public static class SparkRegistry implements EnvironmentAware { + public static class SparkRegistry { private final Logger log = LoggerFactory.getLogger(SparkRegistry.class); @Inject private MetricRegistry metricRegistry; - private RelaxedPropertyResolver propertyResolver; - - @Override - public void setEnvironment(Environment environment) { - this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_METRICS_SPARK); - } + @Inject + private JHipsterProperties jHipsterProperties; @PostConstruct private void init() { - Boolean sparkEnabled = propertyResolver.getProperty(PROP_SPARK_ENABLED, Boolean.class, false); - if (sparkEnabled) { + if (jHipsterProperties.getMetrics().getSpark().isEnabled()) { log.info("Initializing Metrics Spark reporting"); - String sparkHost = propertyResolver.getRequiredProperty(PROP_HOST); - Integer sparkPort = propertyResolver.getRequiredProperty(PROP_PORT, Integer.class); - + String sparkHost = jHipsterProperties.getMetrics().getSpark().getHost(); + Integer sparkPort = jHipsterProperties.getMetrics().getSpark().getPort(); SparkReporter sparkReporter = SparkReporter.forRegistry(metricRegistry) - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS) - .build(sparkHost, sparkPort); + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build(sparkHost, sparkPort); sparkReporter.start(1, TimeUnit.MINUTES); } } diff --git a/src/main/java/nc/ird/malariaplantdb/config/SecurityConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/SecurityConfiguration.java index a616d53..63da0bb 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/SecurityConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/SecurityConfiguration.java @@ -100,6 +100,7 @@ protected void configure(HttpSecurity http) throws Exception { .antMatchers("/env/**").hasAuthority(AuthoritiesConstants.ADMIN) .antMatchers("/trace/**").hasAuthority(AuthoritiesConstants.ADMIN) .antMatchers("/mappings/**").hasAuthority(AuthoritiesConstants.ADMIN) + .antMatchers("/liquibase/**").hasAuthority(AuthoritiesConstants.ADMIN) .antMatchers("/v2/api-docs/**").permitAll() .antMatchers("/configuration/security").permitAll() .antMatchers("/configuration/ui").permitAll() diff --git a/src/main/java/nc/ird/malariaplantdb/config/ThymeleafConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/ThymeleafConfiguration.java index bffac79..5f63bb7 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/ThymeleafConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/ThymeleafConfiguration.java @@ -4,9 +4,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Description; +import org.springframework.context.annotation.*; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; diff --git a/src/main/java/nc/ird/malariaplantdb/config/WebConfigurer.java b/src/main/java/nc/ird/malariaplantdb/config/WebConfigurer.java index 4b3a6e2..8a7f368 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/WebConfigurer.java +++ b/src/main/java/nc/ird/malariaplantdb/config/WebConfigurer.java @@ -5,7 +5,6 @@ import com.codahale.metrics.servlets.MetricsServlet; import nc.ird.malariaplantdb.web.filter.CachingHttpHeadersFilter; import nc.ird.malariaplantdb.web.filter.StaticResourcesProductionFilter; -import nc.ird.malariaplantdb.web.filter.gzip.GZipServletFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -17,12 +16,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; +import java.util.*; import javax.inject.Inject; import javax.servlet.*; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; /** * Configuration of web application with Servlet 3.0 APIs. @@ -49,7 +45,6 @@ public void onStartup(ServletContext servletContext) throws ServletException { if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) { initCachingHttpHeadersFilter(servletContext, disps); initStaticResourcesProductionFilter(servletContext, disps); - initGzipFilter(servletContext, disps); } if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) { initH2Console(servletContext); @@ -70,25 +65,6 @@ public void customize(ConfigurableEmbeddedServletContainer container) { container.setMimeMappings(mappings); } - /** - * Initializes the GZip filter. - */ - private void initGzipFilter(ServletContext servletContext, EnumSet disps) { - log.debug("Registering GZip Filter"); - FilterRegistration.Dynamic compressingFilter = servletContext.addFilter("gzipFilter", new GZipServletFilter()); - Map parameters = new HashMap<>(); - compressingFilter.setInitParameters(parameters); - compressingFilter.addMappingForUrlPatterns(disps, true, "*.css"); - compressingFilter.addMappingForUrlPatterns(disps, true, "*.json"); - compressingFilter.addMappingForUrlPatterns(disps, true, "*.html"); - compressingFilter.addMappingForUrlPatterns(disps, true, "*.js"); - compressingFilter.addMappingForUrlPatterns(disps, true, "*.svg"); - compressingFilter.addMappingForUrlPatterns(disps, true, "*.ttf"); - compressingFilter.addMappingForUrlPatterns(disps, true, "/api/*"); - compressingFilter.addMappingForUrlPatterns(disps, true, "/metrics/*"); - compressingFilter.setAsyncSupported(true); - } - /** * Initializes the static resources production Filter. */ @@ -97,8 +73,8 @@ private void initStaticResourcesProductionFilter(ServletContext servletContext, log.debug("Registering static resources production Filter"); FilterRegistration.Dynamic staticResourcesProductionFilter = - servletContext.addFilter("staticResourcesProductionFilter", - new StaticResourcesProductionFilter()); + servletContext.addFilter("staticResourcesProductionFilter", + new StaticResourcesProductionFilter()); staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/"); staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/index.html"); @@ -114,8 +90,8 @@ private void initCachingHttpHeadersFilter(ServletContext servletContext, EnumSet disps) { log.debug("Registering Caching HTTP Headers Filter"); FilterRegistration.Dynamic cachingHttpHeadersFilter = - servletContext.addFilter("cachingHttpHeadersFilter", - new CachingHttpHeadersFilter(env)); + servletContext.addFilter("cachingHttpHeadersFilter", + new CachingHttpHeadersFilter(env)); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/assets/*"); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/scripts/*"); @@ -128,20 +104,20 @@ private void initCachingHttpHeadersFilter(ServletContext servletContext, private void initMetrics(ServletContext servletContext, EnumSet disps) { log.debug("Initializing Metrics registries"); servletContext.setAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE, - metricRegistry); + metricRegistry); servletContext.setAttribute(MetricsServlet.METRICS_REGISTRY, - metricRegistry); + metricRegistry); log.debug("Registering Metrics Filter"); FilterRegistration.Dynamic metricsFilter = servletContext.addFilter("webappMetricsFilter", - new InstrumentedFilter()); + new InstrumentedFilter()); metricsFilter.addMappingForUrlPatterns(disps, true, "/*"); metricsFilter.setAsyncSupported(true); log.debug("Registering Metrics Servlet"); ServletRegistration.Dynamic metricsAdminServlet = - servletContext.addServlet("metricsServlet", new MetricsServlet()); + servletContext.addServlet("metricsServlet", new MetricsServlet()); metricsAdminServlet.addMapping("/metrics/metrics/*"); metricsAdminServlet.setAsyncSupported(true); diff --git a/src/main/java/nc/ird/malariaplantdb/config/XAuthConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/XAuthConfiguration.java index 0192a7a..fa3fb28 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/XAuthConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/XAuthConfiguration.java @@ -1,29 +1,19 @@ package nc.ird.malariaplantdb.config; import nc.ird.malariaplantdb.security.xauth.TokenProvider; -import org.springframework.boot.bind.RelaxedPropertyResolver; -import org.springframework.context.EnvironmentAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; /** * Configures x-auth-token security. */ @Configuration -public class XAuthConfiguration implements EnvironmentAware { - - private RelaxedPropertyResolver propertyResolver; - - @Override - public void setEnvironment(Environment environment) { - this.propertyResolver = new RelaxedPropertyResolver(environment, "authentication.xauth."); - } +public class XAuthConfiguration { @Bean - public TokenProvider tokenProvider(){ - String secret = propertyResolver.getProperty("secret", String.class, "mySecretXAuthSecret"); - int validityInSeconds = propertyResolver.getProperty("tokenValidityInSeconds", Integer.class, 3600); + public TokenProvider tokenProvider(JHipsterProperties jHipsterProperties) { + String secret = jHipsterProperties.getSecurity().getAuthentication().getXauth().getSecret(); + int validityInSeconds = jHipsterProperties.getSecurity().getAuthentication().getXauth().getTokenValidityInSeconds(); return new TokenProvider(secret, validityInSeconds); } } diff --git a/src/main/java/nc/ird/malariaplantdb/config/apidoc/SwaggerConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/apidoc/SwaggerConfiguration.java index a5df909..7653517 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/apidoc/SwaggerConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/apidoc/SwaggerConfiguration.java @@ -1,15 +1,12 @@ package nc.ird.malariaplantdb.config.apidoc; import nc.ird.malariaplantdb.config.Constants; +import nc.ird.malariaplantdb.config.JHipsterProperties; + import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.boot.bind.RelaxedPropertyResolver; -import org.springframework.context.EnvironmentAware; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; +import org.springframework.context.annotation.*; import org.springframework.http.ResponseEntity; import org.springframework.util.StopWatch; import springfox.documentation.service.ApiInfo; @@ -29,35 +26,34 @@ @Configuration @EnableSwagger2 @Profile("!"+Constants.SPRING_PROFILE_PRODUCTION) -public class SwaggerConfiguration implements EnvironmentAware { +public class SwaggerConfiguration { private final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class); public static final String DEFAULT_INCLUDE_PATTERN = "/api/.*"; - private RelaxedPropertyResolver propertyResolver; - - @Override - public void setEnvironment(Environment environment) { - this.propertyResolver = new RelaxedPropertyResolver(environment, "swagger."); - } - /** * Swagger Springfox configuration. */ @Bean - public Docket swaggerSpringfoxDocket() { + public Docket swaggerSpringfoxDocket(JHipsterProperties jHipsterProperties) { log.debug("Starting Swagger"); StopWatch watch = new StopWatch(); watch.start(); + ApiInfo apiInfo = new ApiInfo( + jHipsterProperties.getSwagger().getTitle(), + jHipsterProperties.getSwagger().getDescription(), + jHipsterProperties.getSwagger().getVersion(), + jHipsterProperties.getSwagger().getTermsOfServiceUrl(), + jHipsterProperties.getSwagger().getContact(), + jHipsterProperties.getSwagger().getLicense(), + jHipsterProperties.getSwagger().getLicenseUrl()); + Docket docket = new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) + .apiInfo(apiInfo) .genericModelSubstitutes(ResponseEntity.class) .forCodeGeneration(true) .genericModelSubstitutes(ResponseEntity.class) - .directModelSubstitute(org.joda.time.LocalDate.class, String.class) - .directModelSubstitute(org.joda.time.LocalDateTime.class, Date.class) - .directModelSubstitute(org.joda.time.DateTime.class, Date.class) .directModelSubstitute(java.time.LocalDate.class, String.class) .directModelSubstitute(java.time.ZonedDateTime.class, Date.class) .directModelSubstitute(java.time.LocalDateTime.class, Date.class) @@ -68,18 +64,4 @@ public Docket swaggerSpringfoxDocket() { log.debug("Started Swagger in {} ms", watch.getTotalTimeMillis()); return docket; } - - /** - * API Info as it appears on the swagger-ui page. - */ - private ApiInfo apiInfo() { - return new ApiInfo( - propertyResolver.getProperty("title"), - propertyResolver.getProperty("description"), - propertyResolver.getProperty("version"), - propertyResolver.getProperty("termsOfServiceUrl"), - propertyResolver.getProperty("contact"), - propertyResolver.getProperty("license"), - propertyResolver.getProperty("licenseUrl")); - } } diff --git a/src/main/java/nc/ird/malariaplantdb/config/audit/AuditEventConverter.java b/src/main/java/nc/ird/malariaplantdb/config/audit/AuditEventConverter.java index 07d0cb5..b4aa75a 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/audit/AuditEventConverter.java +++ b/src/main/java/nc/ird/malariaplantdb/config/audit/AuditEventConverter.java @@ -1,13 +1,16 @@ package nc.ird.malariaplantdb.config.audit; import nc.ird.malariaplantdb.domain.PersistentAuditEvent; + import org.springframework.boot.actuate.audit.AuditEvent; -import org.springframework.context.annotation.Configuration; import org.springframework.security.web.authentication.WebAuthenticationDetails; +import org.springframework.stereotype.Component; +import java.time.Instant; +import java.time.ZoneId; import java.util.*; -@Configuration +@Component public class AuditEventConverter { /** @@ -20,13 +23,10 @@ public List convertToAuditEvent(Iterable persi if (persistentAuditEvents == null) { return Collections.emptyList(); } - List auditEvents = new ArrayList<>(); - for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) { auditEvents.add(convertToAuditEvent(persistentAuditEvent)); } - return auditEvents; } @@ -37,8 +37,9 @@ public List convertToAuditEvent(Iterable persi * @return the converted list. */ public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) { - return new AuditEvent(persistentAuditEvent.getAuditEventDate().toDate(), persistentAuditEvent.getPrincipal(), - persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData())); + Instant instant = persistentAuditEvent.getAuditEventDate().atZone(ZoneId.systemDefault()).toInstant(); + return new AuditEvent(Date.from(instant), persistentAuditEvent.getPrincipal(), + persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData())); } /** @@ -55,7 +56,6 @@ public Map convertDataToObjects(Map data) { results.put(key, data.get(key)); } } - return results; } diff --git a/src/main/java/nc/ird/malariaplantdb/config/liquibase/AsyncSpringLiquibase.java b/src/main/java/nc/ird/malariaplantdb/config/liquibase/AsyncSpringLiquibase.java new file mode 100644 index 0000000..27cad80 --- /dev/null +++ b/src/main/java/nc/ird/malariaplantdb/config/liquibase/AsyncSpringLiquibase.java @@ -0,0 +1,67 @@ +package nc.ird.malariaplantdb.config.liquibase; + +import javax.inject.Inject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.env.Environment; +import org.springframework.core.task.TaskExecutor; +import org.springframework.util.StopWatch; + +import nc.ird.malariaplantdb.config.Constants; +import liquibase.exception.LiquibaseException; +import liquibase.integration.spring.SpringLiquibase; + +/** + * Specific liquibase.integration.spring.SpringLiquibase that will update the database asynchronously. + *

+ * By default, this asynchronous version only works when using the "dev" profile.
+ * The standard liquibase.integration.spring.SpringLiquibase starts Liquibase in the current thread: + *

    + *
  • This is needed if you want to do some database requests at startup
  • + *
  • This ensure that the database is ready when the application starts
  • + *
+ * But as this is a rather slow process, we use this asynchronous version to speed up our start-up time: + *
    + *
  • On a recent MacBook Pro, start-up time is down from 14 seconds to 8 seconds
  • + *
  • In production, this can help your application run on platforms like Heroku, where it must start/restart very quickly
  • + *
+ *

+ */ +public class AsyncSpringLiquibase extends SpringLiquibase { + + private final Logger log = LoggerFactory.getLogger(AsyncSpringLiquibase.class); + + @Inject + @Qualifier("taskExecutor") + private TaskExecutor taskExecutor; + + @Inject + private Environment env; + + @Override + public void afterPropertiesSet() throws LiquibaseException { + if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) { + taskExecutor.execute(() -> { + try { + log.warn("Starting Liquibase asynchronously, your database might not be ready at startup!"); + initDb(); + } catch (LiquibaseException e) { + log.error("Liquibase could not start correctly, your database is NOT ready: {}", e.getMessage(), e); + } + }); + } else { + log.debug("Starting Liquibase synchronously"); + initDb(); + } + } + + protected void initDb() throws LiquibaseException { + StopWatch watch = new StopWatch(); + watch.start(); + super.afterPropertiesSet(); + watch.stop(); + log.debug("Started Liquibase in {} ms", watch.getTotalTimeMillis()); + } +} diff --git a/src/main/java/nc/ird/malariaplantdb/config/liquibase/package-info.java b/src/main/java/nc/ird/malariaplantdb/config/liquibase/package-info.java new file mode 100644 index 0000000..f6c63fc --- /dev/null +++ b/src/main/java/nc/ird/malariaplantdb/config/liquibase/package-info.java @@ -0,0 +1,4 @@ +/** + * Liquibase specific code. + */ +package nc.ird.malariaplantdb.config.liquibase; diff --git a/src/main/java/nc/ird/malariaplantdb/config/locale/AngularCookieLocaleResolver.java b/src/main/java/nc/ird/malariaplantdb/config/locale/AngularCookieLocaleResolver.java index 161584e..3a01681 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/locale/AngularCookieLocaleResolver.java +++ b/src/main/java/nc/ird/malariaplantdb/config/locale/AngularCookieLocaleResolver.java @@ -6,12 +6,11 @@ import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.util.WebUtils; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import java.util.Locale; import java.util.TimeZone; +import javax.servlet.http.*; + /** * Angular cookie saved the locale with a double quote (%22en%22). * So the default CookieLocaleResolver#StringUtils.parseLocaleString(localePart) @@ -35,6 +34,7 @@ public LocaleContext resolveLocaleContext(final HttpServletRequest request) { public Locale getLocale() { return (Locale) request.getAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME); } + @Override public TimeZone getTimeZone() { return (TimeZone) request.getAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME); @@ -74,14 +74,14 @@ private void parseLocaleCookieIfNecessary(HttpServletRequest request) { } if (logger.isTraceEnabled()) { logger.trace("Parsed cookie value [" + cookie.getValue() + "] into locale '" + locale + - "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : "")); + "'" + (timeZone != null ? " and time zone '" + timeZone.getID() + "'" : "")); } } request.setAttribute(LOCALE_REQUEST_ATTRIBUTE_NAME, - (locale != null ? locale: determineDefaultLocale(request))); + (locale != null ? locale: determineDefaultLocale(request))); request.setAttribute(TIME_ZONE_REQUEST_ATTRIBUTE_NAME, - (timeZone != null ? timeZone : determineDefaultTimeZone(request))); + (timeZone != null ? timeZone : determineDefaultTimeZone(request))); } } } diff --git a/src/main/java/nc/ird/malariaplantdb/config/metrics/DatabaseHealthIndicator.java b/src/main/java/nc/ird/malariaplantdb/config/metrics/DatabaseHealthIndicator.java index 5657c56..46ede4b 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/metrics/DatabaseHealthIndicator.java +++ b/src/main/java/nc/ird/malariaplantdb/config/metrics/DatabaseHealthIndicator.java @@ -14,7 +14,7 @@ * SpringBoot Actuator HealthIndicator check for the Database. */ public class DatabaseHealthIndicator extends AbstractHealthIndicator { - + private JdbcTemplate jdbcTemplate; private static Map queries = new HashMap<>(); diff --git a/src/main/java/nc/ird/malariaplantdb/config/metrics/JHipsterHealthIndicatorConfiguration.java b/src/main/java/nc/ird/malariaplantdb/config/metrics/JHipsterHealthIndicatorConfiguration.java index ce96514..8e375bf 100644 --- a/src/main/java/nc/ird/malariaplantdb/config/metrics/JHipsterHealthIndicatorConfiguration.java +++ b/src/main/java/nc/ird/malariaplantdb/config/metrics/JHipsterHealthIndicatorConfiguration.java @@ -3,7 +3,6 @@ import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.mail.javamail.JavaMailSenderImpl; import javax.inject.Inject; import javax.sql.DataSource; @@ -11,9 +10,6 @@ @Configuration public class JHipsterHealthIndicatorConfiguration { - @Inject - private JavaMailSenderImpl javaMailSender; - @Inject private DataSource dataSource; @@ -21,9 +17,4 @@ public class JHipsterHealthIndicatorConfiguration { public HealthIndicator dbHealthIndicator() { return new DatabaseHealthIndicator(dataSource); } - - @Bean - public HealthIndicator mailHealthIndicator() { - return new JavaMailHealthIndicator(javaMailSender); - } } diff --git a/src/main/java/nc/ird/malariaplantdb/config/metrics/JavaMailHealthIndicator.java b/src/main/java/nc/ird/malariaplantdb/config/metrics/JavaMailHealthIndicator.java deleted file mode 100644 index b227c31..0000000 --- a/src/main/java/nc/ird/malariaplantdb/config/metrics/JavaMailHealthIndicator.java +++ /dev/null @@ -1,42 +0,0 @@ -package nc.ird.malariaplantdb.config.metrics; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.actuate.health.AbstractHealthIndicator; -import org.springframework.boot.actuate.health.Health; -import org.springframework.mail.javamail.JavaMailSenderImpl; -import org.springframework.util.Assert; - -import javax.mail.MessagingException; - -/** - * SpringBoot Actuator HealthIndicator check for JavaMail. - */ -public class JavaMailHealthIndicator extends AbstractHealthIndicator { - - private final Logger log = LoggerFactory.getLogger(JavaMailHealthIndicator.class); - - private JavaMailSenderImpl javaMailSender; - - public JavaMailHealthIndicator(JavaMailSenderImpl javaMailSender) { - Assert.notNull(javaMailSender, "javaMailSender must not be null"); - this.javaMailSender = javaMailSender; - } - - @Override - protected void doHealthCheck(Health.Builder builder) throws Exception { - log.debug("Initializing JavaMail health indicator"); - try { - javaMailSender.getSession().getTransport().connect(javaMailSender.getHost(), - javaMailSender.getPort(), - javaMailSender.getUsername(), - javaMailSender.getPassword()); - - builder.up(); - - } catch (MessagingException e) { - log.debug("Cannot connect to e-mail server. Error: {}", e.getMessage()); - builder.down(e); - } - } -} diff --git a/src/main/java/nc/ird/malariaplantdb/domain/AbstractAuditingEntity.java b/src/main/java/nc/ird/malariaplantdb/domain/AbstractAuditingEntity.java index a5f4346..9426065 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/AbstractAuditingEntity.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/AbstractAuditingEntity.java @@ -1,15 +1,14 @@ package nc.ird.malariaplantdb.domain; -import org.hibernate.annotations.Type; -import org.hibernate.envers.Audited; import com.fasterxml.jackson.annotation.JsonIgnore; -import org.joda.time.DateTime; +import org.hibernate.envers.Audited; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; -import org.springframework.data.jpa.domain.support.AuditingEntityListener; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; +import java.time.ZonedDateTime; import javax.persistence.Column; import javax.persistence.EntityListeners; import javax.persistence.MappedSuperclass; @@ -32,10 +31,9 @@ public abstract class AbstractAuditingEntity { @CreatedDate @NotNull - @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") @Column(name = "created_date", nullable = false) @JsonIgnore - private DateTime createdDate = DateTime.now(); + private ZonedDateTime createdDate = ZonedDateTime.now(); @LastModifiedBy @Column(name = "last_modified_by", length = 50) @@ -43,10 +41,9 @@ public abstract class AbstractAuditingEntity { private String lastModifiedBy; @LastModifiedDate - @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") @Column(name = "last_modified_date") @JsonIgnore - private DateTime lastModifiedDate = DateTime.now(); + private ZonedDateTime lastModifiedDate = ZonedDateTime.now(); public String getCreatedBy() { return createdBy; @@ -56,11 +53,11 @@ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } - public DateTime getCreatedDate() { + public ZonedDateTime getCreatedDate() { return createdDate; } - public void setCreatedDate(DateTime createdDate) { + public void setCreatedDate(ZonedDateTime createdDate) { this.createdDate = createdDate; } @@ -72,11 +69,11 @@ public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } - public DateTime getLastModifiedDate() { + public ZonedDateTime getLastModifiedDate() { return lastModifiedDate; } - public void setLastModifiedDate(DateTime lastModifiedDate) { + public void setLastModifiedDate(ZonedDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/Author.java b/src/main/java/nc/ird/malariaplantdb/domain/Author.java index af83584..f1afaaa 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/Author.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/Author.java @@ -1,6 +1,6 @@ package nc.ird.malariaplantdb.domain; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; import nc.ird.malariaplantdb.domain.util.comparator.AuthorComparator; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @@ -23,24 +23,22 @@ @Entity //@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") @JsonPropertyOrder({"id", "publication", "family", "given"}) -@Table(name = "AUTHOR") +@Table(name = "author") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName="author") public class Author implements Serializable, Comparable { + private final static Comparator COMPARATOR = new AuthorComparator(); @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @NotNull @ManyToOne private Publication publication; - @NotNull @Size(max = 255) @Column(name = "family", length = 255, nullable = false) private String family; - @Size(max = 255) @Column(name = "given", length = 255) private String given; @@ -88,9 +86,8 @@ public boolean equals(Object o) { Author author = (Author) o; - if ( ! Objects.equals(id, author.id)) return false; + return Objects.equals(id, author.id); - return true; } @Override @@ -107,10 +104,8 @@ public String toString() { '}'; } - private final static Comparator COMPARATOR = new AuthorComparator(); - @Override - public int compareTo(Author o) { + public int compareTo(@NotNull Author o) { return COMPARATOR.compare(this, o); } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/Authority.java b/src/main/java/nc/ird/malariaplantdb/domain/Authority.java index 4b4b914..1881a9e 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/Authority.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/Authority.java @@ -2,11 +2,10 @@ import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; +import javax.persistence.Column; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; @@ -15,7 +14,7 @@ * An authority (a security role) used by Spring Security. */ @Entity -@Table(name = "JHI_AUTHORITY") +@Table(name = "jhi_authority") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Authority implements Serializable { @@ -59,7 +58,7 @@ public int hashCode() { @Override public String toString() { return "Authority{" + - "name='" + name + '\'' + - "}"; + "name='" + name + '\'' + + "}"; } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/Compiler.java b/src/main/java/nc/ird/malariaplantdb/domain/Compiler.java index 4f8f3c0..d2c118a 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/Compiler.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/Compiler.java @@ -26,35 +26,31 @@ */ @Entity @JsonPropertyOrder({"id", "family", "given", "institution", "institutionAddress", "email"}) -@Table(name = "COMPILER", uniqueConstraints = @UniqueConstraint(columnNames = {"email"}, name = "uk_compiler_email")) +@Table(name = "compiler", uniqueConstraints = @UniqueConstraint(columnNames = {"email"}, name = "uk_compiler_email")) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName="compiler") public class Compiler implements Serializable, Comparable { + private final static Comparator COMPARATOR = new CompilerComparator(); @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @NotNull @Size(max = 255) @Column(name = "family", length = 255, nullable = false) private String family; - @NotNull @Size(max = 255) @Column(name = "given", length = 255, nullable = false) private String given; - @Size(max = 255) @Column(name = "institution", length = 255) private String institution; - @Size(max = 255) @Lob @Type(type="org.hibernate.type.StringClobType") @Column(name = "institution_address", length = 255) private String institutionAddress; - @NotNull @Size(max = 255) @Email @@ -120,9 +116,8 @@ public boolean equals(Object o) { Compiler compiler = (Compiler) o; - if ( ! Objects.equals(id, compiler.id)) return false; + return Objects.equals(id, compiler.id); - return true; } @Override @@ -142,10 +137,8 @@ public String toString() { '}'; } - private final static Comparator COMPARATOR = new CompilerComparator(); - @Override - public int compareTo(Compiler o) { + public int compareTo(@NotNull Compiler o) { return COMPARATOR.compare(this, o); } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/Ethnology.java b/src/main/java/nc/ird/malariaplantdb/domain/Ethnology.java index c1dc955..53b35e2 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/Ethnology.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/Ethnology.java @@ -1,9 +1,7 @@ package nc.ird.malariaplantdb.domain; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import nc.ird.malariaplantdb.domain.util.comparator.EthnologyComparator; -import nc.ird.malariaplantdb.domain.util.comparator.PlantIngredientComparator; import org.hibernate.annotations.*; import org.hibernate.annotations.Cache; import org.springframework.data.elasticsearch.annotations.Document; @@ -26,19 +24,18 @@ @Entity @JsonPropertyOrder({"id", "publication", "plantIngredients", "ethnoRelevancy", "treatmentType", "traditionalRecipeDetails", "preparationMode", "administrationRoute"}) -@Table(name = "ETHNOLOGY") +@Table(name = "ethnology") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName="ethnology") public class Ethnology implements Serializable, Comparable { + private final static Comparator COMPARATOR = new EthnologyComparator(); @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @NotNull @ManyToOne private Publication publication; - @NotNull @ManyToMany(fetch = FetchType.EAGER) @BatchSize(size = 10) @@ -48,27 +45,22 @@ public class Ethnology implements Serializable, Comparable { inverseJoinColumns = @JoinColumn(name="plant_ingredients_id", referencedColumnName="ID")) @SortNatural private SortedSet plantIngredients = new TreeSet<>(); - @NotNull @Lob @Type(type="org.hibernate.type.StringClobType") @Column(name = "ethno_relevancy", nullable = false) private String ethnoRelevancy; - @NotNull @Size(max = 255) @Column(name = "treatment_type", length = 255, nullable = false) private String treatmentType; - @Lob @Type(type="org.hibernate.type.StringClobType") @Column(name = "traditional_recipe_details") private String traditionalRecipeDetails; - @Size(max = 255) @Column(name = "preparation_mode", length = 255) private String preparationMode; - @Size(max = 255) @Column(name = "administration_route", length = 255) private String administrationRoute; @@ -148,9 +140,8 @@ public boolean equals(Object o) { Ethnology ethnology = (Ethnology) o; - if ( ! Objects.equals(id, ethnology.id)) return false; + return Objects.equals(id, ethnology.id); - return true; } @Override @@ -170,10 +161,8 @@ public String toString() { '}'; } - private final static Comparator COMPARATOR = new EthnologyComparator(); - @Override - public int compareTo(Ethnology o) { + public int compareTo(@NotNull Ethnology o) { return COMPARATOR.compare(this, o); } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/InVitroPharmaco.java b/src/main/java/nc/ird/malariaplantdb/domain/InVitroPharmaco.java index 4edebfd..30044c1 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/InVitroPharmaco.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/InVitroPharmaco.java @@ -1,9 +1,7 @@ package nc.ird.malariaplantdb.domain; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import nc.ird.malariaplantdb.domain.util.comparator.InVitroPharmacoComparator; -import nc.ird.malariaplantdb.domain.util.comparator.PlantIngredientComparator; import org.hibernate.annotations.*; import org.hibernate.annotations.Cache; import org.springframework.data.elasticsearch.annotations.Document; @@ -27,19 +25,18 @@ @JsonPropertyOrder({"id", "publication", "plantIngredients", "testedEntity", "extractionSolvent", "additiveProduct", "compoundName", "screeningTest", "measureMethod", "concentration", "molConcentration", "inhibition", "ic50", "molIc50", "selectivityIndex", "compilersObservations"}) -@Table(name = "IN_VITRO_PHARMACO") +@Table(name = "in_vitro_pharmaco") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName="invitropharmaco") public class InVitroPharmaco implements Serializable, Comparable { + private final static Comparator COMPARATOR = new InVitroPharmacoComparator(); @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @NotNull @ManyToOne private Publication publication; - @ManyToMany(fetch = FetchType.EAGER) @BatchSize(size = 100) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @@ -48,69 +45,56 @@ public class InVitroPharmaco implements Serializable, Comparable plantIngredients = new TreeSet<>(); - @NotNull @Size(max = 255) @Column(name = "tested_entity", length = 255, nullable = false) private String testedEntity; - @Size(max = 255) @Column(name = "extraction_solvent", length = 255) private String extractionSolvent; - @Size(max = 255) @Column(name = "additive_product", length = 255) private String additiveProduct; - @Size(max = 255) @Column(name = "compound_name", length = 255) private String compoundName; - @NotNull @Size(max = 255) @Column(name = "screening_test", length = 255, nullable = false) private String screeningTest; - @Size(max = 255) @Column(name = "measure_method", length = 255) private String measureMethod; - @Min(value = 0) @Max(value = 1000000) @Digits(integer=7, fraction=4) @Column(name = "concentration", precision=11, scale=4) private BigDecimal concentration; - @Min(value = 0) @Max(value = 1000000) @Digits(integer=7, fraction=4) @Column(name = "mol_concentration", precision=11, scale=4) private BigDecimal molConcentration; - @Min(value = 0) @Max(value = 100) @Digits(integer=3, fraction=2) @Column(name = "inhibition", precision=5, scale=2) private BigDecimal inhibition; - @Min(value = 0) @Max(value = 1000000) @Digits(integer=7, fraction=4) @Column(name = "ic50", precision=11, scale=4) private BigDecimal ic50; - @Min(value = 0) @Max(value = 1000000) @Digits(integer=7, fraction=4) @Column(name = "mol_ic50", precision=11, scale=4) private BigDecimal molIc50; - @Min(value = 0) @Max(value = 100) @Digits(integer=3, fraction=2) @Column(name = "selectivity_index", precision=5, scale=2) private BigDecimal selectivityIndex; - @Lob @Type(type = "org.hibernate.type.StringClobType") @Column(name = "compilers_observations") @@ -255,9 +239,8 @@ public boolean equals(Object o) { InVitroPharmaco inVitroPharmaco = (InVitroPharmaco) o; - if ( ! Objects.equals(id, inVitroPharmaco.id)) return false; + return Objects.equals(id, inVitroPharmaco.id); - return true; } @Override @@ -285,10 +268,8 @@ public String toString() { '}'; } - private final static Comparator COMPARATOR = new InVitroPharmacoComparator(); - @Override - public int compareTo(InVitroPharmaco o) { + public int compareTo(@NotNull InVitroPharmaco o) { return COMPARATOR.compare(this, o); } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/InVivoPharmaco.java b/src/main/java/nc/ird/malariaplantdb/domain/InVivoPharmaco.java index e0dbae2..d1bb617 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/InVivoPharmaco.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/InVivoPharmaco.java @@ -1,9 +1,7 @@ package nc.ird.malariaplantdb.domain; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import nc.ird.malariaplantdb.domain.util.comparator.InVivoPharmacoComparator; -import nc.ird.malariaplantdb.domain.util.comparator.PlantIngredientComparator; import org.hibernate.annotations.*; import org.hibernate.annotations.Cache; import org.springframework.data.elasticsearch.annotations.Document; @@ -27,19 +25,18 @@ @JsonPropertyOrder({"id", "publication", "plantIngredients", "testedEntity", "extractionSolvent", "additiveProduct", "compoundName", "screeningTest","treatmentRoute", "dose", "inhibition", "survivalPercent", "survivalTime", "ed50", "ld50", "compilersObservations"}) -@Table(name = "IN_VIVO_PHARMACO") +@Table(name = "in_vivo_pharmaco") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName="invivopharmaco") public class InVivoPharmaco implements Serializable, Comparable { + private final static Comparator COMPARATOR = new InVivoPharmacoComparator(); @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @NotNull @ManyToOne private Publication publication; - @ManyToMany(fetch = FetchType.EAGER) @BatchSize(size = 100) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @@ -48,69 +45,56 @@ public class InVivoPharmaco implements Serializable, Comparable inverseJoinColumns = @JoinColumn(name="plant_ingredients_id", referencedColumnName="ID")) @SortNatural private SortedSet plantIngredients = new TreeSet<>(); - @NotNull @Size(max = 255) @Column(name = "tested_entity", length = 255, nullable = false) private String testedEntity; - @Size(max = 255) @Column(name = "extraction_solvent", length = 255) private String extractionSolvent; - @Size(max = 255) @Column(name = "additive_product", length = 255) private String additiveProduct; - @Size(max = 255) @Column(name = "compound_name", length = 255) private String compoundName; - @NotNull @Size(max = 255) @Column(name = "screening_test", length = 255, nullable = false) private String screeningTest; - @Size(max = 255) @Column(name = "treatment_route", length = 255) private String treatmentRoute; - @Min(value = 0) @Max(value = 1000000) @Digits(integer=7, fraction=4) @Column(name = "dose", precision=11, scale=4) private BigDecimal dose; - @Min(value = 0) @Max(value = 100) @Digits(integer=3, fraction=2) @Column(name = "inhibition", precision=5, scale=2) private BigDecimal inhibition; - @Min(value = 0) @Max(value = 100) @Digits(integer=3, fraction=2) @Column(name = "survival_percent", precision=5, scale=2) private BigDecimal survivalPercent; - @Min(value = 0) @Max(value = 1000000) @Digits(integer=3, fraction=2) @Column(name = "survival_time", precision=5, scale=2) private BigDecimal survivalTime; - @Min(value = 0) @Max(value = 1000000) @Digits(integer=7, fraction=4) @Column(name = "ed50", precision=11, scale=4) private BigDecimal ed50; - @Min(value = 0) @Max(value = 1000000) @Digits(integer=7, fraction=4) @Column(name = "ld50", precision=11, scale=4) private BigDecimal ld50; - @Lob @Type(type = "org.hibernate.type.StringClobType") @Column(name = "compilers_observations") @@ -255,9 +239,8 @@ public boolean equals(Object o) { InVivoPharmaco inVivoPharmaco = (InVivoPharmaco) o; - if ( ! Objects.equals(id, inVivoPharmaco.id)) return false; + return Objects.equals(id, inVivoPharmaco.id); - return true; } @Override @@ -285,10 +268,8 @@ public String toString() { '}'; } - private final static Comparator COMPARATOR = new InVivoPharmacoComparator(); - @Override - public int compareTo(InVivoPharmaco o) { + public int compareTo(@NotNull InVivoPharmaco o) { return COMPARATOR.compare(this, o); } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/PersistentAuditEvent.java b/src/main/java/nc/ird/malariaplantdb/domain/PersistentAuditEvent.java index 98a5090..0a736e3 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/PersistentAuditEvent.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/PersistentAuditEvent.java @@ -1,8 +1,6 @@ package nc.ird.malariaplantdb.domain; -import org.hibernate.annotations.Type; -import org.joda.time.LocalDateTime; - +import java.time.LocalDateTime; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.HashMap; @@ -13,8 +11,8 @@ * @see org.springframework.boot.actuate.audit.AuditEvent */ @Entity -@Table(name = "JHI_PERSISTENT_AUDIT_EVENT") -public class PersistentAuditEvent { +@Table(name = "jhi_persistent_audit_event") +public class PersistentAuditEvent { @Id @GeneratedValue(strategy = GenerationType.AUTO) @@ -26,15 +24,14 @@ public class PersistentAuditEvent { private String principal; @Column(name = "event_date") - @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime") private LocalDateTime auditEventDate; @Column(name = "event_type") private String auditEventType; @ElementCollection - @MapKeyColumn(name="name") - @Column(name="value") - @CollectionTable(name="JHI_PERSISTENT_AUDIT_EVT_DATA", joinColumns=@JoinColumn(name="event_id")) + @MapKeyColumn(name = "name") + @Column(name = "value") + @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id")) private Map data = new HashMap<>(); public Long getId() { diff --git a/src/main/java/nc/ird/malariaplantdb/domain/PlantIngredient.java b/src/main/java/nc/ird/malariaplantdb/domain/PlantIngredient.java index ff2a4f4..c5e8e6f 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/PlantIngredient.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/PlantIngredient.java @@ -22,20 +22,19 @@ */ @Entity @JsonPropertyOrder({"id", "species", "partUsed"}) -@Table(name = "PLANT_INGREDIENT", uniqueConstraints = @UniqueConstraint(columnNames = {"species_id", "part_used"}, +@Table(name = "plant_ingredient", uniqueConstraints = @UniqueConstraint(columnNames = {"species_id", "part_used"}, name = "uk_plantingredient_speciesid_partused")) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName="plantingredient") public class PlantIngredient implements Serializable, Comparable { + private final static Comparator COMPARATOR = new PlantIngredientComparator(); @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @NotNull @ManyToOne private Species species; - @NotNull @Size(max = 255) @Column(name = "part_used", length = 255, nullable = false) @@ -76,9 +75,8 @@ public boolean equals(Object o) { PlantIngredient plantIngredient = (PlantIngredient) o; - if ( ! Objects.equals(id, plantIngredient.id)) return false; + return Objects.equals(id, plantIngredient.id); - return true; } @Override @@ -94,10 +92,8 @@ public String toString() { '}'; } - private final static Comparator COMPARATOR = new PlantIngredientComparator(); - @Override - public int compareTo(PlantIngredient o) { + public int compareTo(@NotNull PlantIngredient o) { return COMPARATOR.compare(this, o); } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/PubSpecies.java b/src/main/java/nc/ird/malariaplantdb/domain/PubSpecies.java index 5101867..b34ced1 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/PubSpecies.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/PubSpecies.java @@ -23,40 +23,34 @@ @Entity @JsonPropertyOrder({"id", "publication", "species", "speciesNameInPub", "isHerbariumVoucher", "herbarium", "country", "continent"}) -@Table(name = "PUB_SPECIES") +@Table(name = "pub_species") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName="pubspecies") public class PubSpecies implements Serializable, Comparable { + private final static Comparator COMPARATOR = new PubSpeciesComparator(); @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @NotNull @ManyToOne private Publication publication; - @NotNull @ManyToOne private Species species; - @NotNull @Size(max = 255) @Column(name = "species_name_in_pub", length = 255, nullable = false) private String speciesNameInPub; - @NotNull @Column(name = "is_herbarium_voucher") private Boolean isHerbariumVoucher; - @Column(name = "herbarium") private String herbarium; - @NotNull @Size(max = 255) @Column(name = "country", length = 255, nullable = false) private String country; - @Size(max = 255) @Column(name = "continent", length = 255) private String continent; @@ -136,9 +130,8 @@ public boolean equals(Object o) { PubSpecies pubSpecies = (PubSpecies) o; - if ( ! Objects.equals(id, pubSpecies.id)) return false; + return Objects.equals(id, pubSpecies.id); - return true; } @Override @@ -158,10 +151,8 @@ public String toString() { '}'; } - private final static Comparator COMPARATOR = new PubSpeciesComparator(); - @Override - public int compareTo(PubSpecies o) { + public int compareTo(@NotNull PubSpecies o) { return COMPARATOR.compare(this, o); } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/Publication.java b/src/main/java/nc/ird/malariaplantdb/domain/Publication.java index 62b8af1..cdc869f 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/Publication.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/Publication.java @@ -1,6 +1,8 @@ package nc.ird.malariaplantdb.domain; -import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.hibernate.annotations.*; import org.hibernate.annotations.Cache; import org.springframework.data.elasticsearch.annotations.Document; @@ -30,7 +32,7 @@ "number", "bookTitle", "publisher", "edition", "conferenceName", "conferencePlace", "university", "institution", "doi", "pmid", "isbn", "url", "isReviewed", "compilers", "compilersNotes", "pubSpecies", "ethnologies", "inVivoPharmacos", "inVitroPharmacos", "citation"}) -@Table(name = "PUBLICATION", uniqueConstraints = @UniqueConstraint(columnNames = {"title"}, +@Table(name = "publication", uniqueConstraints = @UniqueConstraint(columnNames = {"title"}, name = "uk_publication_title")) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName = "publication") @@ -392,9 +394,8 @@ public boolean equals(Object o) { Publication publication = (Publication) o; - if (!Objects.equals(id, publication.id)) return false; + return Objects.equals(id, publication.id); - return true; } @Override diff --git a/src/main/java/nc/ird/malariaplantdb/domain/Species.java b/src/main/java/nc/ird/malariaplantdb/domain/Species.java index 20da30d..ad242d3 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/Species.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/Species.java @@ -20,21 +20,20 @@ */ @Entity @JsonPropertyOrder({"id", "family", "species"}) -@Table(name = "SPECIES", uniqueConstraints = @UniqueConstraint(columnNames = {"family", "species"}, name = +@Table(name = "species", uniqueConstraints = @UniqueConstraint(columnNames = {"family", "species"}, name = "uk_species_family_species")) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @Document(indexName="species") public class Species implements Serializable, Comparable { + private final static Comparator COMPARATOR = new SpeciesComparator(); @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; - @NotNull @Size(max = 255) @Column(name = "family", length = 255, nullable = false) private String family; - @NotNull @Size(max = 255) @Column(name = "species", length = 255, nullable = false) @@ -75,9 +74,8 @@ public boolean equals(Object o) { Species species = (Species) o; - if ( ! Objects.equals(id, species.id)) return false; + return Objects.equals(id, species.id); - return true; } @Override @@ -94,10 +92,8 @@ public String toString() { '}'; } - private final static Comparator COMPARATOR = new SpeciesComparator(); - @Override - public int compareTo(Species o) { + public int compareTo(@NotNull Species o) { return COMPARATOR.compare(this, o); } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/User.java b/src/main/java/nc/ird/malariaplantdb/domain/User.java index e9a08df..3c60b9c 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/User.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/User.java @@ -3,11 +3,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; -import org.hibernate.annotations.Type; import org.hibernate.validator.constraints.Email; -import org.joda.time.DateTime; -import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Document; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; @@ -15,14 +13,15 @@ import java.io.Serializable; import java.util.HashSet; import java.util.Set; +import java.time.ZonedDateTime; /** * A user. */ @Entity -@Table(name = "JHI_USER") +@Table(name = "jhi_user") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) -@Document(indexName="user") +@Document(indexName = "user") public class User extends AbstractAuditingEntity implements Serializable { @Id @@ -37,7 +36,7 @@ public class User extends AbstractAuditingEntity implements Serializable { @JsonIgnore @NotNull - @Size(min = 60, max = 60) + @Size(min = 60, max = 60) @Column(length = 60) private String password; @@ -70,16 +69,15 @@ public class User extends AbstractAuditingEntity implements Serializable { @Column(name = "reset_key", length = 20) private String resetKey; - @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") @Column(name = "reset_date", nullable = true) - private DateTime resetDate = null; + private ZonedDateTime resetDate = null; @JsonIgnore @ManyToMany @JoinTable( - name = "JHI_USER_AUTHORITY", - joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, - inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}) + name = "jhi_user_authority", + joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, + inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) private Set authorities = new HashSet<>(); @@ -155,11 +153,11 @@ public void setResetKey(String resetKey) { this.resetKey = resetKey; } - public DateTime getResetDate() { + public ZonedDateTime getResetDate() { return resetDate; } - public void setResetDate(DateTime resetDate) { + public void setResetDate(ZonedDateTime resetDate) { this.resetDate = resetDate; } @@ -205,13 +203,13 @@ public int hashCode() { @Override public String toString() { return "User{" + - "login='" + login + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", email='" + email + '\'' + - ", activated='" + activated + '\'' + - ", langKey='" + langKey + '\'' + - ", activationKey='" + activationKey + '\'' + - "}"; + "login='" + login + '\'' + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", email='" + email + '\'' + + ", activated='" + activated + '\'' + + ", langKey='" + langKey + '\'' + + ", activationKey='" + activationKey + '\'' + + "}"; } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/util/CustomDateTimeDeserializer.java b/src/main/java/nc/ird/malariaplantdb/domain/util/CustomDateTimeDeserializer.java deleted file mode 100644 index 3f4eb82..0000000 --- a/src/main/java/nc/ird/malariaplantdb/domain/util/CustomDateTimeDeserializer.java +++ /dev/null @@ -1,30 +0,0 @@ -package nc.ird.malariaplantdb.domain.util; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import org.joda.time.DateTime; -import org.joda.time.format.ISODateTimeFormat; - -import java.io.IOException; - -/** - * Custom Jackson deserializer for transforming a JSON object to a Joda DateTime object. - */ -public class CustomDateTimeDeserializer extends JsonDeserializer { - - @Override - public DateTime deserialize(JsonParser jp, DeserializationContext ctxt) - throws IOException { - JsonToken t = jp.getCurrentToken(); - if (t == JsonToken.VALUE_STRING) { - String str = jp.getText().trim(); - return ISODateTimeFormat.dateTimeParser().parseDateTime(str); - } - if (t == JsonToken.VALUE_NUMBER_INT) { - return new DateTime(jp.getLongValue()); - } - throw ctxt.mappingException(handledType()); - } -} diff --git a/src/main/java/nc/ird/malariaplantdb/domain/util/CustomDateTimeSerializer.java b/src/main/java/nc/ird/malariaplantdb/domain/util/CustomDateTimeSerializer.java deleted file mode 100644 index b0d86c3..0000000 --- a/src/main/java/nc/ird/malariaplantdb/domain/util/CustomDateTimeSerializer.java +++ /dev/null @@ -1,28 +0,0 @@ -package nc.ird.malariaplantdb.domain.util; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import org.joda.time.DateTime; -import org.joda.time.DateTimeZone; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import java.io.IOException; - -/** - * Custom Jackson serializer for transforming a Joda DateTime object to JSON. - */ -public class CustomDateTimeSerializer extends JsonSerializer { - - private static DateTimeFormatter formatter = DateTimeFormat - .forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); - - @Override - public void serialize(DateTime value, JsonGenerator generator, - SerializerProvider serializerProvider) - throws IOException { - generator.writeString(formatter.print(value.toDateTime(DateTimeZone.UTC))); - } - -} diff --git a/src/main/java/nc/ird/malariaplantdb/domain/util/CustomLocalDateSerializer.java b/src/main/java/nc/ird/malariaplantdb/domain/util/CustomLocalDateSerializer.java deleted file mode 100644 index 42d18f0..0000000 --- a/src/main/java/nc/ird/malariaplantdb/domain/util/CustomLocalDateSerializer.java +++ /dev/null @@ -1,24 +0,0 @@ -package nc.ird.malariaplantdb.domain.util; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; - -import java.io.IOException; - -/** - * Custom Jackson serializer for transforming a Joda LocalDate object to JSON. - */ -public class CustomLocalDateSerializer extends JsonSerializer { - - private static DateTimeFormatter formatter = DateTimeFormat - .forPattern("yyyy-MM-dd"); - - @Override - public void serialize(LocalDate value, JsonGenerator jgen, SerializerProvider provider) throws IOException { - jgen.writeString(formatter.print(value)); - } -} diff --git a/src/main/java/nc/ird/malariaplantdb/domain/util/FixedH2Dialect.java b/src/main/java/nc/ird/malariaplantdb/domain/util/FixedH2Dialect.java index 86173ab..9ba5f07 100644 --- a/src/main/java/nc/ird/malariaplantdb/domain/util/FixedH2Dialect.java +++ b/src/main/java/nc/ird/malariaplantdb/domain/util/FixedH2Dialect.java @@ -1,12 +1,13 @@ package nc.ird.malariaplantdb.domain.util; -import org.hibernate.dialect.H2Dialect; - import java.sql.Types; +import org.hibernate.dialect.H2Dialect; + public class FixedH2Dialect extends H2Dialect { + public FixedH2Dialect() { super(); - registerColumnType( Types.FLOAT, "real" ); + registerColumnType(Types.FLOAT, "real"); } } diff --git a/src/main/java/nc/ird/malariaplantdb/domain/util/ISO8601LocalDateDeserializer.java b/src/main/java/nc/ird/malariaplantdb/domain/util/ISO8601LocalDateDeserializer.java deleted file mode 100644 index 2635908..0000000 --- a/src/main/java/nc/ird/malariaplantdb/domain/util/ISO8601LocalDateDeserializer.java +++ /dev/null @@ -1,31 +0,0 @@ -package nc.ird.malariaplantdb.domain.util; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import org.joda.time.LocalDate; -import org.joda.time.format.ISODateTimeFormat; - -import java.io.IOException; - - /** - * Custom Jackson deserializer for transforming a JSON object (using the ISO 8601 date format) - * to a Joda LocalDate object. - */ -public class ISO8601LocalDateDeserializer extends JsonDeserializer { - - @Override - public LocalDate deserialize(JsonParser jp, DeserializationContext ctxt) - throws IOException { - JsonToken t = jp.getCurrentToken(); - if (t == JsonToken.VALUE_STRING) { - String str = jp.getText().trim(); - return ISODateTimeFormat.dateTimeParser().parseDateTime(str).toLocalDate(); - } - if (t == JsonToken.VALUE_NUMBER_INT) { - return new LocalDate(jp.getLongValue()); - } - throw ctxt.mappingException(handledType()); - } -} diff --git a/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310DateConverters.java b/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310DateConverters.java new file mode 100644 index 0000000..58829d2 --- /dev/null +++ b/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310DateConverters.java @@ -0,0 +1,73 @@ +package nc.ird.malariaplantdb.domain.util; + +import java.time.*; +import java.util.Date; + +import org.springframework.core.convert.converter.Converter; + +public final class JSR310DateConverters { + + private JSR310DateConverters() {} + + public static class LocalDateToDateConverter implements Converter { + + public static final LocalDateToDateConverter INSTANCE = new LocalDateToDateConverter(); + + private LocalDateToDateConverter() {} + + @Override + public Date convert(LocalDate source) { + return source == null ? null : Date.from(source.atStartOfDay(ZoneId.systemDefault()).toInstant()); + } + } + + public static class DateToLocalDateConverter implements Converter { + public static final DateToLocalDateConverter INSTANCE = new DateToLocalDateConverter(); + private DateToLocalDateConverter() {} + + @Override + public LocalDate convert(Date source) { + return source == null ? null : ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()).toLocalDate(); + } + } + + public static class ZonedDateTimeToDateConverter implements Converter { + public static final ZonedDateTimeToDateConverter INSTANCE = new ZonedDateTimeToDateConverter(); + private ZonedDateTimeToDateConverter() {} + + @Override + public Date convert(ZonedDateTime source) { + return source == null ? null : Date.from(source.toInstant()); + } + } + + public static class DateToZonedDateTimeConverter implements Converter { + public static final DateToZonedDateTimeConverter INSTANCE = new DateToZonedDateTimeConverter(); + private DateToZonedDateTimeConverter() {} + + @Override + public ZonedDateTime convert(Date source) { + return source == null ? null : ZonedDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()); + } + } + + public static class LocalDateTimeToDateConverter implements Converter { + public static final LocalDateTimeToDateConverter INSTANCE = new LocalDateTimeToDateConverter(); + private LocalDateTimeToDateConverter() {} + + @Override + public Date convert(LocalDateTime source) { + return source == null ? null : Date.from(source.atZone(ZoneId.systemDefault()).toInstant()); + } + } + + public static class DateToLocalDateTimeConverter implements Converter { + public static final DateToLocalDateTimeConverter INSTANCE = new DateToLocalDateTimeConverter(); + private DateToLocalDateTimeConverter() {} + + @Override + public LocalDateTime convert(Date source) { + return source == null ? null : LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()); + } + } +} diff --git a/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310DateTimeSerializer.java b/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310DateTimeSerializer.java new file mode 100644 index 0000000..1822fcb --- /dev/null +++ b/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310DateTimeSerializer.java @@ -0,0 +1,25 @@ +package nc.ird.malariaplantdb.domain.util; + +import java.io.IOException; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAccessor; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +public final class JSR310DateTimeSerializer extends JsonSerializer { + + private static final DateTimeFormatter ISOFormatter = + DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Z")); + + public static final JSR310DateTimeSerializer INSTANCE = new JSR310DateTimeSerializer(); + + private JSR310DateTimeSerializer() {} + + @Override + public void serialize(TemporalAccessor value, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException { + generator.writeString(ISOFormatter.format(value)); + } +} diff --git a/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310LocalDateDeserializer.java b/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310LocalDateDeserializer.java new file mode 100644 index 0000000..393602a --- /dev/null +++ b/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310LocalDateDeserializer.java @@ -0,0 +1,63 @@ +package nc.ird.malariaplantdb.domain.util; + +import java.io.IOException; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +/** + * Custom Jackson deserializer for transforming a JSON object (using the ISO 8601 date formatwith optional time) + * to a JSR310 LocalDate object. + */ +public class JSR310LocalDateDeserializer extends JsonDeserializer { + + public static final JSR310LocalDateDeserializer INSTANCE = new JSR310LocalDateDeserializer(); + + private JSR310LocalDateDeserializer() {} + + private static final DateTimeFormatter ISO_DATE_OPTIONAL_TIME; + + static { + ISO_DATE_OPTIONAL_TIME = new DateTimeFormatterBuilder() + .append(DateTimeFormatter.ISO_LOCAL_DATE) + .optionalStart() + .appendLiteral('T') + .append(DateTimeFormatter.ISO_OFFSET_TIME) + .toFormatter(); + } + + @Override + public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException { + switch(parser.getCurrentToken()) { + case START_ARRAY: + if(parser.nextToken() == JsonToken.END_ARRAY) { + return null; + } + int year = parser.getIntValue(); + + parser.nextToken(); + int month = parser.getIntValue(); + + parser.nextToken(); + int day = parser.getIntValue(); + + if(parser.nextToken() != JsonToken.END_ARRAY) { + throw context.wrongTokenException(parser, JsonToken.END_ARRAY, "Expected array to end."); + } + return LocalDate.of(year, month, day); + + case VALUE_STRING: + String string = parser.getText().trim(); + if(string.length() == 0) { + return null; + } + return LocalDate.parse(string, ISO_DATE_OPTIONAL_TIME); + } + throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string."); + } +} diff --git a/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310PersistenceConverters.java b/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310PersistenceConverters.java new file mode 100644 index 0000000..3f56267 --- /dev/null +++ b/src/main/java/nc/ird/malariaplantdb/domain/util/JSR310PersistenceConverters.java @@ -0,0 +1,56 @@ +package nc.ird.malariaplantdb.domain.util; + +import nc.ird.malariaplantdb.domain.util.JSR310DateConverters.*; + +import java.time.*; +import java.util.Date; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; + +public final class JSR310PersistenceConverters { + + private JSR310PersistenceConverters() {} + + @Converter(autoApply = true) + public static class LocalDateConverter implements AttributeConverter { + + @Override + public java.sql.Date convertToDatabaseColumn(LocalDate date) { + return date == null ? null : java.sql.Date.valueOf(date); + } + + @Override + public LocalDate convertToEntityAttribute(java.sql.Date date) { + return date == null ? null : date.toLocalDate(); + } + } + + @Converter(autoApply = true) + public static class ZonedDateTimeConverter implements AttributeConverter { + + @Override + public Date convertToDatabaseColumn(ZonedDateTime zonedDateTime) { + return ZonedDateTimeToDateConverter.INSTANCE.convert(zonedDateTime); + } + + @Override + public ZonedDateTime convertToEntityAttribute(Date date) { + return DateToZonedDateTimeConverter.INSTANCE.convert(date); + } + } + + @Converter(autoApply = true) + public static class LocalDateTimeConverter implements AttributeConverter { + + @Override + public Date convertToDatabaseColumn(LocalDateTime localDateTime) { + return LocalDateTimeToDateConverter.INSTANCE.convert(localDateTime); + } + + @Override + public LocalDateTime convertToEntityAttribute(Date date) { + return DateToLocalDateTimeConverter.INSTANCE.convert(date); + } + } +} diff --git a/src/main/java/nc/ird/malariaplantdb/repository/AuthorityRepository.java b/src/main/java/nc/ird/malariaplantdb/repository/AuthorityRepository.java index 15ba7af..bd3e495 100644 --- a/src/main/java/nc/ird/malariaplantdb/repository/AuthorityRepository.java +++ b/src/main/java/nc/ird/malariaplantdb/repository/AuthorityRepository.java @@ -1,6 +1,7 @@ package nc.ird.malariaplantdb.repository; import nc.ird.malariaplantdb.domain.Authority; + import org.springframework.data.jpa.repository.JpaRepository; /** diff --git a/src/main/java/nc/ird/malariaplantdb/repository/CustomAuditEventRepository.java b/src/main/java/nc/ird/malariaplantdb/repository/CustomAuditEventRepository.java index cfa2063..c909a78 100644 --- a/src/main/java/nc/ird/malariaplantdb/repository/CustomAuditEventRepository.java +++ b/src/main/java/nc/ird/malariaplantdb/repository/CustomAuditEventRepository.java @@ -2,7 +2,7 @@ import nc.ird.malariaplantdb.config.audit.AuditEventConverter; import nc.ird.malariaplantdb.domain.PersistentAuditEvent; -import org.joda.time.LocalDateTime; + import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.boot.actuate.audit.AuditEventRepository; import org.springframework.context.annotation.Bean; @@ -11,6 +11,9 @@ import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; import java.util.Date; import java.util.List; @@ -43,7 +46,7 @@ public List find(String principal, Date after) { persistentAuditEvents = persistenceAuditEventRepository.findByPrincipal(principal); } else { persistentAuditEvents = - persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfter(principal, new LocalDateTime(after)); + persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfter(principal, LocalDateTime.from(after.toInstant())); } return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } @@ -51,13 +54,14 @@ public List find(String principal, Date after) { @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void add(AuditEvent event) { - if(!AUTHORIZATION_FAILURE.equals(event.getType()) && - !ANONYMOUS_USER.equals(event.getPrincipal().toString())){ + if (!AUTHORIZATION_FAILURE.equals(event.getType()) && + !ANONYMOUS_USER.equals(event.getPrincipal().toString())) { PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent(); persistentAuditEvent.setPrincipal(event.getPrincipal()); persistentAuditEvent.setAuditEventType(event.getType()); - persistentAuditEvent.setAuditEventDate(new LocalDateTime(event.getTimestamp())); + Instant instant = Instant.ofEpochMilli(event.getTimestamp().getTime()); + persistentAuditEvent.setAuditEventDate(LocalDateTime.ofInstant(instant, ZoneId.systemDefault())); persistentAuditEvent.setData(auditEventConverter.convertDataToStrings(event.getData())); persistenceAuditEventRepository.save(persistentAuditEvent); } diff --git a/src/main/java/nc/ird/malariaplantdb/repository/EthnologyRepository.java b/src/main/java/nc/ird/malariaplantdb/repository/EthnologyRepository.java index f60105b..a5bfaf4 100644 --- a/src/main/java/nc/ird/malariaplantdb/repository/EthnologyRepository.java +++ b/src/main/java/nc/ird/malariaplantdb/repository/EthnologyRepository.java @@ -1,20 +1,19 @@ package nc.ird.malariaplantdb.repository; import nc.ird.malariaplantdb.domain.Ethnology; -import org.springframework.data.jpa.repository.*; -import org.springframework.data.repository.query.Param; - -import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; /** * Spring Data JPA repository for the Ethnology entity. */ public interface EthnologyRepository extends JpaRepository { - @Query("select distinct ethnology from Ethnology ethnology left join fetch ethnology.plantIngredients") - List findAllWithEagerRelationships(); - - @Query("select ethnology from Ethnology ethnology left join fetch ethnology.plantIngredients where ethnology.id =:id") - Ethnology findOneWithEagerRelationships(@Param("id") Long id); + // Other method to fetch the authors and compilers relationships, but as it's by a join, the firsResult and + // maxResults are applied in memory + //@Query("select distinct ethnology from Ethnology ethnology left join fetch ethnology.plantIngredients") + //List findAllWithEagerRelationships(); + //@Query("select ethnology from Ethnology ethnology left join fetch ethnology.plantIngredients where ethnology + // .id =:id") + //Ethnology findOneWithEagerRelationships(@Param("id") Long id); } diff --git a/src/main/java/nc/ird/malariaplantdb/repository/InVitroPharmacoRepository.java b/src/main/java/nc/ird/malariaplantdb/repository/InVitroPharmacoRepository.java index 13fd89f..f6411cd 100644 --- a/src/main/java/nc/ird/malariaplantdb/repository/InVitroPharmacoRepository.java +++ b/src/main/java/nc/ird/malariaplantdb/repository/InVitroPharmacoRepository.java @@ -1,20 +1,20 @@ package nc.ird.malariaplantdb.repository; import nc.ird.malariaplantdb.domain.InVitroPharmaco; -import org.springframework.data.jpa.repository.*; -import org.springframework.data.repository.query.Param; - -import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; /** * Spring Data JPA repository for the InVitroPharmaco entity. */ public interface InVitroPharmacoRepository extends JpaRepository { - @Query("select distinct inVitroPharmaco from InVitroPharmaco inVitroPharmaco left join fetch inVitroPharmaco.plantIngredients") - List findAllWithEagerRelationships(); - - @Query("select inVitroPharmaco from InVitroPharmaco inVitroPharmaco left join fetch inVitroPharmaco.plantIngredients where inVitroPharmaco.id =:id") - InVitroPharmaco findOneWithEagerRelationships(@Param("id") Long id); + // Other method to fetch the authors and compilers relationships, but as it's by a join, the firsResult and + // maxResults are applied in memory + //@Query("select distinct inVitroPharmaco from InVitroPharmaco inVitroPharmaco left join fetch inVitroPharmaco" + + // ".plantIngredients") + //List findAllWithEagerRelationships(); + //@Query("select inVitroPharmaco from InVitroPharmaco inVitroPharmaco left join fetch inVitroPharmaco" + + // ".plantIngredients where inVitroPharmaco.id =:id") + //InVitroPharmaco findOneWithEagerRelationships(@Param("id") Long id); } diff --git a/src/main/java/nc/ird/malariaplantdb/repository/InVivoPharmacoRepository.java b/src/main/java/nc/ird/malariaplantdb/repository/InVivoPharmacoRepository.java index a22d48f..7315337 100644 --- a/src/main/java/nc/ird/malariaplantdb/repository/InVivoPharmacoRepository.java +++ b/src/main/java/nc/ird/malariaplantdb/repository/InVivoPharmacoRepository.java @@ -1,20 +1,21 @@ package nc.ird.malariaplantdb.repository; import nc.ird.malariaplantdb.domain.InVivoPharmaco; -import org.springframework.data.jpa.repository.*; -import org.springframework.data.repository.query.Param; - -import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; /** * Spring Data JPA repository for the InVivoPharmaco entity. */ public interface InVivoPharmacoRepository extends JpaRepository { - @Query("select distinct inVivoPharmaco from InVivoPharmaco inVivoPharmaco left join fetch inVivoPharmaco.plantIngredients") - List findAllWithEagerRelationships(); - - @Query("select inVivoPharmaco from InVivoPharmaco inVivoPharmaco left join fetch inVivoPharmaco.plantIngredients where inVivoPharmaco.id =:id") - InVivoPharmaco findOneWithEagerRelationships(@Param("id") Long id); + // Other method to fetch the authors and compilers relationships, but as it's by a join, the firsResult and + // maxResults are applied in memory + //@Query("select distinct inVivoPharmaco from InVivoPharmaco inVivoPharmaco left join fetch inVivoPharmaco" + + // ".plantIngredients") + //List findAllWithEagerRelationships(); + // + //@Query("select inVivoPharmaco from InVivoPharmaco inVivoPharmaco left join fetch inVivoPharmaco" + + // ".plantIngredients where inVivoPharmaco.id =:id") + //InVivoPharmaco findOneWithEagerRelationships(@Param("id") Long id); } diff --git a/src/main/java/nc/ird/malariaplantdb/repository/PersistenceAuditEventRepository.java b/src/main/java/nc/ird/malariaplantdb/repository/PersistenceAuditEventRepository.java index 008c57b..9676134 100644 --- a/src/main/java/nc/ird/malariaplantdb/repository/PersistenceAuditEventRepository.java +++ b/src/main/java/nc/ird/malariaplantdb/repository/PersistenceAuditEventRepository.java @@ -1,7 +1,8 @@ package nc.ird.malariaplantdb.repository; import nc.ird.malariaplantdb.domain.PersistentAuditEvent; -import org.joda.time.LocalDateTime; + +import java.time.LocalDateTime; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; diff --git a/src/main/java/nc/ird/malariaplantdb/repository/UserRepository.java b/src/main/java/nc/ird/malariaplantdb/repository/UserRepository.java index 2bcf6c9..c9132c9 100644 --- a/src/main/java/nc/ird/malariaplantdb/repository/UserRepository.java +++ b/src/main/java/nc/ird/malariaplantdb/repository/UserRepository.java @@ -2,7 +2,7 @@ import nc.ird.malariaplantdb.domain.User; -import org.joda.time.DateTime; +import java.time.ZonedDateTime; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -16,7 +16,7 @@ public interface UserRepository extends JpaRepository { Optional findOneByActivationKey(String activationKey); - List findAllByActivatedIsFalseAndCreatedDateBefore(DateTime dateTime); + List findAllByActivatedIsFalseAndCreatedDateBefore(ZonedDateTime dateTime); Optional findOneByResetKey(String resetKey); diff --git a/src/main/java/nc/ird/malariaplantdb/security/CustomUserDetails.java b/src/main/java/nc/ird/malariaplantdb/security/CustomUserDetails.java new file mode 100644 index 0000000..2a09f77 --- /dev/null +++ b/src/main/java/nc/ird/malariaplantdb/security/CustomUserDetails.java @@ -0,0 +1,98 @@ +package nc.ird.malariaplantdb.security; + +import java.util.Collection; +import java.util.Set; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +/** + * Class representing the Spring Security authenticated user. + * + * @see UserDetails + * + */ +public class CustomUserDetails implements UserDetails { + + private static final long serialVersionUID = 1L; + + private final Long id; + private final String password; + private final String username; + private final Set authorities; + private final boolean accountNonExpired; + private final boolean accountNonLocked; + private final boolean credentialsNonExpired; + private final boolean enabled; + + /** + * @param id + * @param username + * @param password + * @param authorities + * @param accountNonExpired + * @param accountNonLocked + * @param credentialsNonExpired + * @param enabled + */ + public CustomUserDetails(Long id, String username, String password, Set authorities, boolean accountNonExpired, boolean accountNonLocked, + boolean credentialsNonExpired, boolean enabled) { + this.id = id; + this.username = username; + this.password = password; + this.authorities = authorities; + this.accountNonExpired = accountNonExpired; + this.accountNonLocked = accountNonLocked; + this.credentialsNonExpired = credentialsNonExpired; + this.enabled = enabled; + } + + public Long getId() { + return id; + } + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public String getUsername() { + return username; + } + + @Override + public boolean isAccountNonExpired() { + return accountNonExpired; + } + + @Override + public boolean isAccountNonLocked() { + return accountNonLocked; + } + + @Override + public boolean isCredentialsNonExpired() { + return credentialsNonExpired; + } + + @Override + public boolean isEnabled() { + return enabled; + } + + public boolean isUserInRole(String authority) { + return authorities.contains(new SimpleGrantedAuthority(authority)); + } + + @Override + public String toString() { + return "CustomUserDetails{" + id + ',' + username + ',' + authorities + '}'; + } +} diff --git a/src/main/java/nc/ird/malariaplantdb/security/Http401UnauthorizedEntryPoint.java b/src/main/java/nc/ird/malariaplantdb/security/Http401UnauthorizedEntryPoint.java index 06b8dd3..4648e11 100644 --- a/src/main/java/nc/ird/malariaplantdb/security/Http401UnauthorizedEntryPoint.java +++ b/src/main/java/nc/ird/malariaplantdb/security/Http401UnauthorizedEntryPoint.java @@ -23,8 +23,9 @@ public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint { * Always returns a 401 error code to the client. */ @Override - public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException, - ServletException { + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) + throws IOException, + ServletException { log.debug("Pre-authenticated entry point called. Rejecting access"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied"); diff --git a/src/main/java/nc/ird/malariaplantdb/security/SecurityUtils.java b/src/main/java/nc/ird/malariaplantdb/security/SecurityUtils.java index 8a11077..59041ff 100644 --- a/src/main/java/nc/ird/malariaplantdb/security/SecurityUtils.java +++ b/src/main/java/nc/ird/malariaplantdb/security/SecurityUtils.java @@ -20,14 +20,13 @@ private SecurityUtils() { /** * Get the login of the current user. */ - public static String getCurrentLogin() { + public static String getCurrentUserLogin() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); - UserDetails springSecurityUser = null; String userName = null; - if(authentication != null) { + if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { - springSecurityUser = (UserDetails) authentication.getPrincipal(); + UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); userName = springSecurityUser.getUsername(); } else if (authentication.getPrincipal() instanceof String) { userName = (String) authentication.getPrincipal(); @@ -54,15 +53,41 @@ public static boolean isAuthenticated() { return true; } + /** + * Return the current user id, or throws an exception, if the user is not authenticated yet. + * + * @return the current user id + */ + public static Long getCurrentUserId() { + return getCurrentUser().getId(); + } + + /** + * Return the current user, or throws an exception, if the user is not + * authenticated yet. + * + * @return the current user + */ + public static CustomUserDetails getCurrentUser() { + SecurityContext securityContext = SecurityContextHolder.getContext(); + Authentication authentication = securityContext.getAuthentication(); + if (authentication != null) { + if (authentication.getPrincipal() instanceof CustomUserDetails) { + return (CustomUserDetails) authentication.getPrincipal(); + } + } + throw new IllegalStateException("User not found!"); + } + /** * If the current user has a specific authority (security role). * - *

The name of this method comes from the isUserInRole() method in the Servlet API

+ *

The name of this method comes from the isUserInRole() method in the Servlet API

*/ public static boolean isUserInRole(String authority) { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication authentication = securityContext.getAuthentication(); - if(authentication != null) { + if (authentication != null) { if (authentication.getPrincipal() instanceof UserDetails) { UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal(); return springSecurityUser.getAuthorities().contains(new SimpleGrantedAuthority(authority)); diff --git a/src/main/java/nc/ird/malariaplantdb/security/SpringSecurityAuditorAware.java b/src/main/java/nc/ird/malariaplantdb/security/SpringSecurityAuditorAware.java index 94c0f71..113baed 100644 --- a/src/main/java/nc/ird/malariaplantdb/security/SpringSecurityAuditorAware.java +++ b/src/main/java/nc/ird/malariaplantdb/security/SpringSecurityAuditorAware.java @@ -1,6 +1,7 @@ package nc.ird.malariaplantdb.security; import nc.ird.malariaplantdb.config.Constants; + import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; @@ -12,7 +13,7 @@ public class SpringSecurityAuditorAware implements AuditorAware { @Override public String getCurrentAuditor() { - String userName = SecurityUtils.getCurrentLogin(); + String userName = SecurityUtils.getCurrentUserLogin(); return (userName != null ? userName : Constants.SYSTEM_ACCOUNT); } } diff --git a/src/main/java/nc/ird/malariaplantdb/security/UserDetailsService.java b/src/main/java/nc/ird/malariaplantdb/security/UserDetailsService.java index f42d61d..a4c055b 100644 --- a/src/main/java/nc/ird/malariaplantdb/security/UserDetailsService.java +++ b/src/main/java/nc/ird/malariaplantdb/security/UserDetailsService.java @@ -13,12 +13,9 @@ import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; -import java.util.ArrayList; -import java.util.Collection; import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; -import java.util.Collections; -import java.util.List; /** * Authenticate a user from the database. @@ -36,17 +33,18 @@ public class UserDetailsService implements org.springframework.security.core.use public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); String lowercaseLogin = login.toLowerCase(); - Optional userFromDatabase = userRepository.findOneByLogin(lowercaseLogin); + Optional userFromDatabase = userRepository.findOneByLogin(lowercaseLogin); return userFromDatabase.map(user -> { if (!user.getActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } - List grantedAuthorities = user.getAuthorities().stream() + Set grantedAuthorities = user.getAuthorities().stream() .map(authority -> new SimpleGrantedAuthority(authority.getName())) - .collect(Collectors.toList()); - return new org.springframework.security.core.userdetails.User(lowercaseLogin, - user.getPassword(), - grantedAuthorities); - }).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); + .collect(Collectors.toSet()); + return new CustomUserDetails(user.getId(), lowercaseLogin, + user.getPassword(), + grantedAuthorities, true, true, true, true); + }).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + + "database")); } } diff --git a/src/main/java/nc/ird/malariaplantdb/security/xauth/TokenProvider.java b/src/main/java/nc/ird/malariaplantdb/security/xauth/TokenProvider.java index fce5489..50b27a6 100644 --- a/src/main/java/nc/ird/malariaplantdb/security/xauth/TokenProvider.java +++ b/src/main/java/nc/ird/malariaplantdb/security/xauth/TokenProvider.java @@ -51,6 +51,23 @@ public boolean validateToken(String authToken, UserDetails userDetails) { long expires = Long.parseLong(parts[1]); String signature = parts[2]; String signatureToMatch = computeSignature(userDetails, expires); - return expires >= System.currentTimeMillis() && signature.equals(signatureToMatch); + return expires >= System.currentTimeMillis() && constantTimeEquals(signature, signatureToMatch); } + + /** + * String comparison that doesn't stop at the first character that is different but instead always + * iterates the whole string length to prevent timing attacks. + */ + private boolean constantTimeEquals(String a, String b) { + if (a.length() != b.length()) { + return false; + } else { + int equal = 0; + for (int i = 0; i < a.length(); i++) { + equal |= a.charAt(i) ^ b.charAt(i); + } + return equal == 0; + } + } + } diff --git a/src/main/java/nc/ird/malariaplantdb/service/AuditEventService.java b/src/main/java/nc/ird/malariaplantdb/service/AuditEventService.java index 31a4b92..205cb2f 100644 --- a/src/main/java/nc/ird/malariaplantdb/service/AuditEventService.java +++ b/src/main/java/nc/ird/malariaplantdb/service/AuditEventService.java @@ -3,7 +3,7 @@ import nc.ird.malariaplantdb.config.audit.AuditEventConverter; import nc.ird.malariaplantdb.domain.PersistentAuditEvent; import nc.ird.malariaplantdb.repository.PersistenceAuditEventRepository; -import org.joda.time.LocalDateTime; +import java.time.LocalDateTime; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -24,12 +24,14 @@ public class AuditEventService { private PersistenceAuditEventRepository persistenceAuditEventRepository; + private AuditEventConverter auditEventConverter; @Inject public AuditEventService( - PersistenceAuditEventRepository persistenceAuditEventRepository, - AuditEventConverter auditEventConverter) { + PersistenceAuditEventRepository persistenceAuditEventRepository, + AuditEventConverter auditEventConverter) { + this.persistenceAuditEventRepository = persistenceAuditEventRepository; this.auditEventConverter = auditEventConverter; } @@ -40,13 +42,13 @@ public List findAll() { public List findByDates(LocalDateTime fromDate, LocalDateTime toDate) { List persistentAuditEvents = - persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate); + persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate); return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } public Optional find(Long id) { - return Optional.ofNullable(persistenceAuditEventRepository.findOne(id)).map(auditEventConverter::convertToAuditEvent); + return Optional.ofNullable(persistenceAuditEventRepository.findOne(id)).map + (auditEventConverter::convertToAuditEvent); } - } diff --git a/src/main/java/nc/ird/malariaplantdb/service/MailService.java b/src/main/java/nc/ird/malariaplantdb/service/MailService.java index db5a59f..d2031f0 100644 --- a/src/main/java/nc/ird/malariaplantdb/service/MailService.java +++ b/src/main/java/nc/ird/malariaplantdb/service/MailService.java @@ -1,11 +1,12 @@ package nc.ird.malariaplantdb.service; +import nc.ird.malariaplantdb.config.JHipsterProperties; import nc.ird.malariaplantdb.domain.User; + import org.apache.commons.lang.CharEncoding; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; -import org.springframework.core.env.Environment; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.scheduling.annotation.Async; @@ -13,7 +14,8 @@ import org.thymeleaf.context.Context; import org.thymeleaf.spring4.SpringTemplateEngine; -import javax.annotation.PostConstruct; + + import javax.inject.Inject; import javax.mail.internet.MimeMessage; import java.util.Locale; @@ -31,7 +33,7 @@ public class MailService { private final Logger log = LoggerFactory.getLogger(MailService.class); @Inject - private Environment env; + private JHipsterProperties jHipsterProperties; @Inject private JavaMailSenderImpl javaMailSender; @@ -47,22 +49,17 @@ public class MailService { */ private String from; - @PostConstruct - public void init() { - this.from = env.getProperty("mail.from"); - } - @Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { log.debug("Send e-mail[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", - isMultipart, isHtml, to, subject, content); + isMultipart, isHtml, to, subject, content); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8); message.setTo(to); - message.setFrom(from); + message.setFrom(jHipsterProperties.getMail().getFrom()); message.setSubject(subject); message.setText(content, isHtml); javaMailSender.send(mimeMessage); @@ -95,4 +92,5 @@ public void sendPasswordResetMail(User user, String baseUrl) { String subject = messageSource.getMessage("email.reset.title", null, locale); sendEmail(user.getEmail(), subject, content, false, true); } + } diff --git a/src/main/java/nc/ird/malariaplantdb/service/UserService.java b/src/main/java/nc/ird/malariaplantdb/service/UserService.java index 9ef0d6b..faeb584 100644 --- a/src/main/java/nc/ird/malariaplantdb/service/UserService.java +++ b/src/main/java/nc/ird/malariaplantdb/service/UserService.java @@ -7,8 +7,8 @@ import nc.ird.malariaplantdb.repository.search.UserSearchRepository; import nc.ird.malariaplantdb.security.SecurityUtils; import nc.ird.malariaplantdb.service.util.RandomUtil; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; +import java.time.ZonedDateTime; +import java.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; @@ -17,10 +17,7 @@ import org.springframework.transaction.annotation.Transactional; import javax.inject.Inject; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; +import java.util.*; /** * Service class for managing users. @@ -62,32 +59,32 @@ public Optional completePasswordReset(String newPassword, String key) { log.debug("Reset user password for reset key {}", key); return userRepository.findOneByResetKey(key) - .filter(user -> { - DateTime oneDayAgo = DateTime.now().minusHours(24); - return user.getResetDate().isAfter(oneDayAgo.toInstant().getMillis()); + .filter(user -> { + ZonedDateTime oneDayAgo = ZonedDateTime.now().minusHours(24); + return user.getResetDate().isAfter(oneDayAgo); }) .map(user -> { - user.setPassword(passwordEncoder.encode(newPassword)); - user.setResetKey(null); - user.setResetDate(null); - userRepository.save(user); - return user; + user.setPassword(passwordEncoder.encode(newPassword)); + user.setResetKey(null); + user.setResetDate(null); + userRepository.save(user); + return user; }); } public Optional requestPasswordReset(String mail) { - return userRepository.findOneByEmail(mail) - .filter(user -> user.getActivated() == true) - .map(user -> { - user.setResetKey(RandomUtil.generateResetKey()); - user.setResetDate(DateTime.now()); - userRepository.save(user); - return user; - }); + return userRepository.findOneByEmail(mail) + .filter(user -> user.getActivated()) + .map(user -> { + user.setResetKey(RandomUtil.generateResetKey()); + user.setResetDate(ZonedDateTime.now()); + userRepository.save(user); + return user; + }); } public User createUserInformation(String login, String password, String firstName, String lastName, String email, - String langKey) { + String langKey) { User newUser = new User(); Authority authority = authorityRepository.findOne("ROLE_USER"); @@ -113,7 +110,7 @@ public User createUserInformation(String login, String password, String firstNam } public void updateUserInformation(String firstName, String lastName, String email, String langKey) { - userRepository.findOneByLogin(SecurityUtils.getCurrentLogin()).ifPresent(u -> { + userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(u -> { u.setFirstName(firstName); u.setLastName(lastName); u.setEmail(email); @@ -125,7 +122,7 @@ public void updateUserInformation(String firstName, String lastName, String emai } public void changePassword(String password) { - userRepository.findOneByLogin(SecurityUtils.getCurrentLogin()).ifPresent(u-> { + userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(u-> { String encryptedPassword = passwordEncoder.encode(password); u.setPassword(encryptedPassword); userRepository.save(u); @@ -141,7 +138,6 @@ public Optional getUserWithAuthoritiesByLogin(String login) { }); } - @Transactional(readOnly = true) public User getUserWithAuthorities(Long id) { User user = userRepository.findOne(id); @@ -151,7 +147,7 @@ public User getUserWithAuthorities(Long id) { @Transactional(readOnly = true) public User getUserWithAuthorities() { - User user = userRepository.findOneByLogin(SecurityUtils.getCurrentLogin()).get(); + User user = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).get(); user.getAuthorities().size(); // eagerly load the association return user; } @@ -165,7 +161,7 @@ public User getUserWithAuthorities() { */ @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { - DateTime now = new DateTime(); + ZonedDateTime now = ZonedDateTime.now(); List users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3)); for (User user : users) { log.debug("Deleting not activated user {}", user.getLogin()); diff --git a/src/main/java/nc/ird/malariaplantdb/service/util/RandomUtil.java b/src/main/java/nc/ird/malariaplantdb/service/util/RandomUtil.java index de58e07..4f45bf3 100644 --- a/src/main/java/nc/ird/malariaplantdb/service/util/RandomUtil.java +++ b/src/main/java/nc/ird/malariaplantdb/service/util/RandomUtil.java @@ -35,7 +35,7 @@ public static String generateActivationKey() { * * @return the generated reset key */ - public static String generateResetKey() { - return RandomStringUtils.randomNumeric(DEF_COUNT); - } + public static String generateResetKey() { + return RandomStringUtils.randomNumeric(DEF_COUNT); + } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/filter/CachingHttpHeadersFilter.java b/src/main/java/nc/ird/malariaplantdb/web/filter/CachingHttpHeadersFilter.java index 0568996..e007ac2 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/filter/CachingHttpHeadersFilter.java +++ b/src/main/java/nc/ird/malariaplantdb/web/filter/CachingHttpHeadersFilter.java @@ -9,7 +9,6 @@ /** * This filter is used in production, to put HTTP cache headers with a long (1 month) expiration time. - *

*/ public class CachingHttpHeadersFilter implements Filter { @@ -21,12 +20,13 @@ public class CachingHttpHeadersFilter implements Filter { private Environment env; public CachingHttpHeadersFilter(Environment env) { - this.env = env; + this.env = env; } @Override public void init(FilterConfig filterConfig) throws ServletException { - CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(env.getProperty("http.cache.timeToLiveInDays", Long.class, 31L)); + CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(env.getProperty("jhipster.http.cache.timeToLiveInDays", + Long.class, 31L)); } @Override @@ -35,7 +35,9 @@ public void destroy() { } @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Cache-Control", "max-age=" + CACHE_TIME_TO_LIVE + ", public"); diff --git a/src/main/java/nc/ird/malariaplantdb/web/propertyeditors/LocaleDateTimeEditor.java b/src/main/java/nc/ird/malariaplantdb/web/propertyeditors/LocaleDateTimeEditor.java deleted file mode 100644 index 44979ab..0000000 --- a/src/main/java/nc/ird/malariaplantdb/web/propertyeditors/LocaleDateTimeEditor.java +++ /dev/null @@ -1,63 +0,0 @@ -package nc.ird.malariaplantdb.web.propertyeditors; - -import org.joda.time.LocalDateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import org.springframework.util.StringUtils; - -import java.beans.PropertyEditorSupport; -import java.util.Date; - -/** - * Custom PropertyEditorSupport to convert from String to - * Date using JodaTime (http://www.joda.org/joda-time/). - */ -public class LocaleDateTimeEditor extends PropertyEditorSupport { - - private final DateTimeFormatter formatter; - - private final boolean allowEmpty; - - /** - * Create a new LocaleDateTimeEditor instance, using the given format for - * parsing and rendering. - *

- * The "allowEmpty" parameter states if an empty String should be allowed - * for parsing, i.e. get interpreted as null value. Otherwise, an - * IllegalArgumentException gets thrown. - * - * @param dateFormat DateFormat to use for parsing and rendering - * @param allowEmpty if empty strings should be allowed - */ - public LocaleDateTimeEditor(String dateFormat, boolean allowEmpty) { - this.formatter = DateTimeFormat.forPattern(dateFormat); - this.allowEmpty = allowEmpty; - } - - /** - * Format the YearMonthDay as String, using the specified format. - * - * @return DateTime formatted string - */ - @Override - public String getAsText() { - Date value = (Date) getValue(); - return value != null ? new LocalDateTime(value).toString(formatter) : ""; - } - - /** - * Parse the value from the given text, using the specified format. - * - * @param text the text to format - * @throws IllegalArgumentException - */ - @Override - public void setAsText( String text ) throws IllegalArgumentException { - if ( allowEmpty && !StringUtils.hasText(text) ) { - // Treat empty String as null value. - setValue(null); - } else { - setValue(new LocalDateTime(formatter.parseDateTime(text))); - } - } -} diff --git a/src/main/java/nc/ird/malariaplantdb/web/propertyeditors/package-info.java b/src/main/java/nc/ird/malariaplantdb/web/propertyeditors/package-info.java deleted file mode 100644 index 7aec228..0000000 --- a/src/main/java/nc/ird/malariaplantdb/web/propertyeditors/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Property Editors. - */ -package nc.ird.malariaplantdb.web.propertyeditors; diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/AccountResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/AccountResource.java index bda4497..fb89e2e 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/AccountResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/AccountResource.java @@ -9,6 +9,7 @@ import nc.ird.malariaplantdb.service.UserService; import nc.ird.malariaplantdb.web.rest.dto.KeyAndPasswordDTO; import nc.ird.malariaplantdb.web.rest.dto.UserDTO; + import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,7 +24,6 @@ import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.*; -import java.util.stream.Collectors; /** * REST controller for managing the current user's account. @@ -47,8 +47,8 @@ public class AccountResource { * POST /register -> register the user. */ @RequestMapping(value = "/register", - method = RequestMethod.POST, - produces = MediaType.TEXT_PLAIN_VALUE) + method = RequestMethod.POST, + produces = MediaType.TEXT_PLAIN_VALUE) @Timed public ResponseEntity registerAccount(@Valid @RequestBody UserDTO userDTO, HttpServletRequest request) { return userRepository.findOneByLogin(userDTO.getLogin()) @@ -75,8 +75,8 @@ public ResponseEntity registerAccount(@Valid @RequestBody UserDTO userDTO, Ht * GET /activate -> activate the registered user. */ @RequestMapping(value = "/activate", - method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity activateAccount(@RequestParam(value = "key") String key) { return Optional.ofNullable(userService.activateRegistration(key)) @@ -88,8 +88,8 @@ public ResponseEntity activateAccount(@RequestParam(value = "key") Strin * GET /authenticate -> check if the user is authenticated, and return its login. */ @RequestMapping(value = "/authenticate", - method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) @Timed public String isAuthenticated(HttpServletRequest request) { log.debug("REST request to check if the current user is authenticated"); @@ -100,8 +100,8 @@ public String isAuthenticated(HttpServletRequest request) { * GET /account -> get the current user. */ @RequestMapping(value = "/account", - method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity getAccount() { return Optional.ofNullable(userService.getUserWithAuthorities()) @@ -113,13 +113,13 @@ public ResponseEntity getAccount() { * POST /account -> update the current user information. */ @RequestMapping(value = "/account", - method = RequestMethod.POST, - produces = MediaType.APPLICATION_JSON_VALUE) + method = RequestMethod.POST, + produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity saveAccount(@RequestBody UserDTO userDTO) { return userRepository .findOneByLogin(userDTO.getLogin()) - .filter(u -> u.getLogin().equals(SecurityUtils.getCurrentLogin())) + .filter(u -> u.getLogin().equals(SecurityUtils.getCurrentUserLogin())) .map(u -> { userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey()); @@ -132,8 +132,8 @@ public ResponseEntity saveAccount(@RequestBody UserDTO userDTO) { * POST /change_password -> changes the current user's password */ @RequestMapping(value = "/account/change_password", - method = RequestMethod.POST, - produces = MediaType.APPLICATION_JSON_VALUE) + method = RequestMethod.POST, + produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity changePassword(@RequestBody String password) { if (!checkPasswordLength(password)) { @@ -148,7 +148,6 @@ public ResponseEntity changePassword(@RequestBody String password) { produces = MediaType.TEXT_PLAIN_VALUE) @Timed public ResponseEntity requestPasswordReset(@RequestBody String mail, HttpServletRequest request) { - return userService.requestPasswordReset(mail) .map(user -> { String baseUrl = request.getScheme() + @@ -156,10 +155,9 @@ public ResponseEntity requestPasswordReset(@RequestBody String mail, HttpServ request.getServerName() + ":" + request.getServerPort(); - mailService.sendPasswordResetMail(user, baseUrl); - return new ResponseEntity<>("e-mail was sent", HttpStatus.OK); + mailService.sendPasswordResetMail(user, baseUrl); + return new ResponseEntity<>("e-mail was sent", HttpStatus.OK); }).orElse(new ResponseEntity<>("e-mail address not registered", HttpStatus.BAD_REQUEST)); - } @RequestMapping(value = "/account/reset_password/finish", @@ -175,7 +173,8 @@ public ResponseEntity finishPasswordReset(@RequestBody KeyAndPasswordDTO } private boolean checkPasswordLength(String password) { - return (!StringUtils.isEmpty(password) && password.length() >= UserDTO.PASSWORD_MIN_LENGTH && password.length() <= UserDTO.PASSWORD_MAX_LENGTH); + return (!StringUtils.isEmpty(password) && + password.length() >= UserDTO.PASSWORD_MIN_LENGTH && + password.length() <= UserDTO.PASSWORD_MAX_LENGTH); } - } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/AuditResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/AuditResource.java index cf7f381..7901c99 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/AuditResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/AuditResource.java @@ -1,11 +1,11 @@ package nc.ird.malariaplantdb.web.rest; import nc.ird.malariaplantdb.service.AuditEventService; -import nc.ird.malariaplantdb.web.propertyeditors.LocaleDateTimeEditor; -import org.joda.time.LocalDateTime; + +import java.time.LocalDate; import org.springframework.boot.actuate.audit.AuditEvent; +import org.springframework.format.annotation.DateTimeFormat; import org.springframework.http.MediaType; -import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -27,27 +27,23 @@ public AuditResource(AuditEventService auditEventService) { this.auditEventService = auditEventService; } - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("yyyy-MM-dd", false)); - } - @RequestMapping(method = RequestMethod.GET) public List getAll() { return auditEventService.findAll(); } @RequestMapping(method = RequestMethod.GET, - params = {"fromDate", "toDate"}) - public List getByDates(@RequestParam(value = "fromDate") LocalDateTime fromDate, - @RequestParam(value = "toDate") LocalDateTime toDate) { - return auditEventService.findByDates(fromDate, toDate); + params = {"fromDate", "toDate"}) + public List getByDates( + @RequestParam(value = "fromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate, + @RequestParam(value = "toDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate) { + + return auditEventService.findByDates(fromDate.atTime(0, 0), toDate.atTime(23, 59)); } @RequestMapping(value = "/{id:.+}", - method = RequestMethod.GET) + method = RequestMethod.GET) public ResponseEntity get(@PathVariable Long id) { - return auditEventService.find(id) .map((entity) -> new ResponseEntity<>(entity, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/AuthorResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/AuthorResource.java index 08bc657..c2b6acd 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/AuthorResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/AuthorResource.java @@ -25,7 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; /** * REST controller for managing Author. @@ -134,7 +134,7 @@ public ResponseEntity deleteAuthor(@PathVariable Long id) { @Timed public List searchAuthors(@PathVariable String query) { return StreamSupport - .stream(authorSearchRepository.search(queryString(query)).spliterator(), false) + .stream(authorSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/CompilerResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/CompilerResource.java index b264558..63a0e83 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/CompilerResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/CompilerResource.java @@ -25,7 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; /** * REST controller for managing Compiler. @@ -134,7 +134,7 @@ public ResponseEntity deleteCompiler(@PathVariable Long id) { @Timed public List searchCompilers(@PathVariable String query) { return StreamSupport - .stream(compilerSearchRepository.search(queryString(query)).spliterator(), false) + .stream(compilerSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/EthnologyResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/EthnologyResource.java index 2be3876..1fe32ac 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/EthnologyResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/EthnologyResource.java @@ -25,7 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; /** * REST controller for managing Ethnology. @@ -134,7 +134,7 @@ public ResponseEntity deleteEthnology(@PathVariable Long id) { @Timed public List searchEthnologies(@PathVariable String query) { return StreamSupport - .stream(ethnologySearchRepository.search(queryString(query)).spliterator(), false) + .stream(ethnologySearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/InVitroPharmacoResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/InVitroPharmacoResource.java index 818694b..38d0846 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/InVitroPharmacoResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/InVitroPharmacoResource.java @@ -25,7 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; /** * REST controller for managing InVitroPharmaco. @@ -134,7 +134,7 @@ public ResponseEntity deleteInVitroPharmaco(@PathVariable Long id) { @Timed public List searchInVitroPharmacos(@PathVariable String query) { return StreamSupport - .stream(inVitroPharmacoSearchRepository.search(queryString(query)).spliterator(), false) + .stream(inVitroPharmacoSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/InVivoPharmacoResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/InVivoPharmacoResource.java index e678c90..f9392c1 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/InVivoPharmacoResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/InVivoPharmacoResource.java @@ -25,7 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; /** * REST controller for managing InVivoPharmaco. @@ -134,7 +134,7 @@ public ResponseEntity deleteInVivoPharmaco(@PathVariable Long id) { @Timed public List searchInVivoPharmacos(@PathVariable String query) { return StreamSupport - .stream(inVivoPharmacoSearchRepository.search(queryString(query)).spliterator(), false) + .stream(inVivoPharmacoSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/LogsResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/LogsResource.java index f00dc37..4e92252 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/LogsResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/LogsResource.java @@ -1,9 +1,10 @@ package nc.ird.malariaplantdb.web.rest; +import nc.ird.malariaplantdb.web.rest.dto.LoggerDTO; + import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.codahale.metrics.annotation.Timed; -import nc.ird.malariaplantdb.web.rest.dto.LoggerDTO; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -20,8 +21,8 @@ public class LogsResource { @RequestMapping(value = "/logs", - method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) @Timed public List getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); @@ -29,11 +30,10 @@ public List getList() { .stream() .map(LoggerDTO::new) .collect(Collectors.toList()); - } @RequestMapping(value = "/logs", - method = RequestMethod.PUT) + method = RequestMethod.PUT) @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerDTO jsonLogger) { diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/PlantIngredientResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/PlantIngredientResource.java index e14660e..f34ef69 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/PlantIngredientResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/PlantIngredientResource.java @@ -25,7 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; /** * REST controller for managing PlantIngredient. @@ -134,7 +134,7 @@ public ResponseEntity deletePlantIngredient(@PathVariable Long id) { @Timed public List searchPlantIngredients(@PathVariable String query) { return StreamSupport - .stream(plantIngredientSearchRepository.search(queryString(query)).spliterator(), false) + .stream(plantIngredientSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/PubSpeciesResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/PubSpeciesResource.java index 9b147e5..172f9b1 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/PubSpeciesResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/PubSpeciesResource.java @@ -25,7 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; /** * REST controller for managing PubSpecies. @@ -134,7 +134,7 @@ public ResponseEntity deletePubSpecies(@PathVariable Long id) { @Timed public List searchPubSpecies(@PathVariable String query) { return StreamSupport - .stream(pubSpeciesSearchRepository.search(queryString(query)).spliterator(), false) + .stream(pubSpeciesSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/PublicationResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/PublicationResource.java index 0229142..fec20b3 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/PublicationResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/PublicationResource.java @@ -25,7 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; /** * REST controller for managing Publication. @@ -134,7 +134,7 @@ public ResponseEntity deletePublication(@PathVariable Long id) { @Timed public List searchPublications(@PathVariable String query) { return StreamSupport - .stream(publicationSearchRepository.search(queryString(query)).spliterator(), false) + .stream(publicationSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/SpeciesResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/SpeciesResource.java index 5e11875..16412cc 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/SpeciesResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/SpeciesResource.java @@ -25,7 +25,7 @@ import java.util.stream.Collectors; import java.util.stream.StreamSupport; -import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; /** * REST controller for managing Species. @@ -134,7 +134,7 @@ public ResponseEntity deleteSpecies(@PathVariable Long id) { @Timed public List searchSpecies(@PathVariable String query) { return StreamSupport - .stream(speciesSearchRepository.search(queryString(query)).spliterator(), false) + .stream(speciesSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/UserResource.java b/src/main/java/nc/ird/malariaplantdb/web/rest/UserResource.java index b6a3a9e..be16aa2 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/UserResource.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/UserResource.java @@ -79,8 +79,8 @@ public class UserResource { * POST /users -> Create a new user. */ @RequestMapping(value = "/users", - method = RequestMethod.POST, - produces = MediaType.APPLICATION_JSON_VALUE) + method = RequestMethod.POST, + produces = MediaType.APPLICATION_JSON_VALUE) @Timed @Secured(AuthoritiesConstants.ADMIN) public ResponseEntity createUser(@RequestBody User user) throws URISyntaxException { @@ -149,14 +149,14 @@ public ResponseEntity> getAllUsers(Pageable pageable) * GET /users/:login -> get the "login" user. */ @RequestMapping(value = "/users/{login}", - method = RequestMethod.GET, - produces = MediaType.APPLICATION_JSON_VALUE) + method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity getUser(@PathVariable String login) { log.debug("REST request to get User : {}", login); return userService.getUserWithAuthoritiesByLogin(login) .map(user -> new ManagedUserDTO(user)) - .map(userDTO -> new ResponseEntity<>(userDTO, HttpStatus.OK)) + .map(managedUserDTO -> new ResponseEntity<>(managedUserDTO, HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND)); } @@ -170,7 +170,7 @@ public ResponseEntity getUser(@PathVariable String login) { @Timed public List search(@PathVariable String query) { return StreamSupport - .stream(userSearchRepository.search(queryString(query)).spliterator(), false) + .stream(userSearchRepository.search(queryStringQuery(query)).spliterator(), false) .collect(Collectors.toList()); } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/dto/KeyAndPasswordDTO.java b/src/main/java/nc/ird/malariaplantdb/web/rest/dto/KeyAndPasswordDTO.java index 9e9bc9a..6ecd3aa 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/dto/KeyAndPasswordDTO.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/dto/KeyAndPasswordDTO.java @@ -5,7 +5,8 @@ public class KeyAndPasswordDTO { private String key; private String newPassword; - public KeyAndPasswordDTO() {} + public KeyAndPasswordDTO() { + } public String getKey() { return key; diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/dto/LoggerDTO.java b/src/main/java/nc/ird/malariaplantdb/web/rest/dto/LoggerDTO.java index c1201b9..8eebef1 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/dto/LoggerDTO.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/dto/LoggerDTO.java @@ -37,8 +37,8 @@ public void setLevel(String level) { @Override public String toString() { return "LoggerDTO{" + - "name='" + name + '\'' + - ", level='" + level + '\'' + - '}'; + "name='" + name + '\'' + + ", level='" + level + '\'' + + '}'; } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/dto/ManagedUserDTO.java b/src/main/java/nc/ird/malariaplantdb/web/rest/dto/ManagedUserDTO.java index dd9f262..760e814 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/dto/ManagedUserDTO.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/dto/ManagedUserDTO.java @@ -1,6 +1,6 @@ package nc.ird.malariaplantdb.web.rest.dto; -import org.joda.time.DateTime; +import java.time.ZonedDateTime; import nc.ird.malariaplantdb.domain.User; @@ -11,11 +11,11 @@ public class ManagedUserDTO extends UserDTO { private Long id; - private DateTime createdDate; + private ZonedDateTime createdDate; private String lastModifiedBy; - private DateTime lastModifiedDate; + private ZonedDateTime lastModifiedDate; public ManagedUserDTO() { } @@ -36,11 +36,11 @@ public void setId(Long id) { this.id = id; } - public DateTime getCreatedDate() { + public ZonedDateTime getCreatedDate() { return createdDate; } - public void setCreatedDate(DateTime createdDate) { + public void setCreatedDate(ZonedDateTime createdDate) { this.createdDate = createdDate; } @@ -52,11 +52,11 @@ public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } - public DateTime getLastModifiedDate() { + public ZonedDateTime getLastModifiedDate() { return lastModifiedDate; } - public void setLastModifiedDate(DateTime lastModifiedDate) { + public void setLastModifiedDate(ZonedDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/dto/UserDTO.java b/src/main/java/nc/ird/malariaplantdb/web/rest/dto/UserDTO.java index 93a0dde..bed79a1 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/dto/UserDTO.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/dto/UserDTO.java @@ -5,12 +5,9 @@ import org.hibernate.validator.constraints.Email; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; +import javax.validation.constraints.*; import java.util.Set; import java.util.stream.Collectors; - /** * A DTO representing a user, with his authorities. */ @@ -56,7 +53,7 @@ public UserDTO(User user) { } public UserDTO(String login, String password, String firstName, String lastName, - String email, boolean activated, String langKey, Set authorities) { + String email, boolean activated, String langKey, Set authorities) { this.login = login; this.password = password; @@ -103,14 +100,14 @@ public Set getAuthorities() { @Override public String toString() { return "UserDTO{" + - "login='" + login + '\'' + - ", password='" + password + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", email='" + email + '\'' + - ", activated=" + activated + - ", langKey='" + langKey + '\'' + - ", authorities=" + authorities + - '}'; + "login='" + login + '\'' + + ", password='" + password + '\'' + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", email='" + email + '\'' + + ", activated=" + activated + + ", langKey='" + langKey + '\'' + + ", authorities=" + authorities + + "}"; } } diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/errors/ErrorDTO.java b/src/main/java/nc/ird/malariaplantdb/web/rest/errors/ErrorDTO.java index 2f26941..8d2ca39 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/errors/ErrorDTO.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/errors/ErrorDTO.java @@ -8,6 +8,7 @@ * DTO for transfering error message with a list of field errors. */ public class ErrorDTO implements Serializable { + private static final long serialVersionUID = 1L; private final String message; diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/errors/ExceptionTranslator.java b/src/main/java/nc/ird/malariaplantdb/web/rest/errors/ExceptionTranslator.java index 4ee75c7..df55e7e 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/errors/ExceptionTranslator.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/errors/ExceptionTranslator.java @@ -9,10 +9,7 @@ import org.springframework.validation.FieldError; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.*; /** * Controller advice to translate the server side exceptions to client-friendly json structures. diff --git a/src/main/java/nc/ird/malariaplantdb/web/rest/util/HeaderUtil.java b/src/main/java/nc/ird/malariaplantdb/web/rest/util/HeaderUtil.java index c503fb9..4a52626 100644 --- a/src/main/java/nc/ird/malariaplantdb/web/rest/util/HeaderUtil.java +++ b/src/main/java/nc/ird/malariaplantdb/web/rest/util/HeaderUtil.java @@ -7,14 +7,14 @@ * */ public class HeaderUtil { - + public static HttpHeaders createAlert(String message, String param) { HttpHeaders headers = new HttpHeaders(); headers.add("X-malariaplantdbApp-alert", message); headers.add("X-malariaplantdbApp-params", param); return headers; } - + public static HttpHeaders createEntityCreationAlert(String entityName, String param) { return createAlert("A new " + entityName + " is created with identifier " + param, param); } @@ -26,5 +26,4 @@ public static HttpHeaders createEntityUpdateAlert(String entityName, String para public static HttpHeaders createEntityDeletionAlert(String entityName, String param) { return createAlert("A " + entityName + " is deleted with identifier " + param, param); } - -} \ No newline at end of file +} diff --git a/src/main/resources/.h2.server.properties b/src/main/resources/.h2.server.properties index d4be8ed..14b9b1d 100644 --- a/src/main/resources/.h2.server.properties +++ b/src/main/resources/.h2.server.properties @@ -1,6 +1,5 @@ #H2 Server Properties -#Mon Oct 26 16:26:56 NCT 2015 -0=JHipster H2 (Embedded)|org.h2.Driver|jdbc\:h2\:mem\:jhipster| -webAllowOthers=false +0=JHipster H2 (Memory)|org.h2.Driver|jdbc\:h2\:mem\:jhipster| +webAllowOthers=true webPort=8082 webSSL=false diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt index 04e048a..d614594 100644 --- a/src/main/resources/banner.txt +++ b/src/main/resources/banner.txt @@ -1,9 +1,8 @@ - _ _ ___ __ _____ ____ ___ __ _____ __ __ _ -| |_| | | | |_) ( (` | | | |_ | |_) ( (` | | / /\ / /` | |_/ -|_| | |_| |_| _)_) |_| |_|__ |_| \ _)_) |_| /_/--\ \_\_, |_| \ - ____ ___ ___ - | |_ / / \ | |_) - |_| \_\_/ |_| \ - _ __ _ __ ___ ____ _ __ - | | / /\ \ \ / / /\ | | \ | |_ \ \ / ( (` - \_|_| /_/--\ \_\/ /_/--\ |_|_/ |_|__ \_\/ _)_) + __ __ __ __ .______ _______.___________. _______ .______ + | | | | | | | | | _ \ / | || ____|| _ \ + | | | |__| | | | | |_) | | (----`---| |----`| |__ | |_) | +.--. | | | __ | | | | ___/ \ \ | | | __| | / +| `--' | | | | | | | | | .----) | | | | |____ | |\ \----. + \______/ |__| |__| |__| | _| |_______/ |__| |_______|| _| `._____| + + http://jhipster.github.io diff --git a/src/main/resources/config/application-dev.yml b/src/main/resources/config/application-dev.yml index 55a8cfb..d98519d 100644 --- a/src/main/resources/config/application-dev.yml +++ b/src/main/resources/config/application-dev.yml @@ -1,31 +1,35 @@ -server: - port: 8080 +# =================================================================== +# Spring Boot configuration for the "dev" profile. +# +# This configuration overrides the application.yml file. +# =================================================================== -liquibase: - context: dev +# =================================================================== +# Standard Spring Boot properties. +# Full reference is available at: +# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html +# =================================================================== spring: profiles: active: dev + devtools: + restart: + enabled: true + livereload: + enabled: false # we use Grunt + BrowserSync for livereload datasource: - dataSourceClassName: org.h2.jdbcx.JdbcDataSource + driver-class-name: org.h2.jdbcx.JdbcDataSource url: jdbc:h2:mem:jhipster;DB_CLOSE_DELAY=-1 - databaseName: - serverName: - username: + name: + username: password: - jpa: database-platform: nc.ird.malariaplantdb.domain.util.FixedH2Dialect database: H2 - openInView: false show_sql: true - generate-ddl: false - hibernate: - ddl-auto: none - naming-strategy: org.springframework.boot.orm.jpa.hibernate.SpringNamingStrategy properties: - hibernate.cache.use_second_level_cache: false + hibernate.cache.use_second_level_cache: true hibernate.cache.use_query_cache: false hibernate.generate_statistics: true hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory @@ -37,25 +41,38 @@ spring: path: logs: target/elasticsearch/log data: target/elasticsearch/data + mail: + host: localhost messages: cache-seconds: 1 thymeleaf: - mode: XHTML cache: false -metrics: - jmx.enabled: true - spark: - enabled: false - host: localhost - port: 9999 - graphite: - enabled: false - host: localhost - port: 2003 - prefix: malariaplantdb +liquibase: + contexts: dev + +server: + port: 8080 + +# =================================================================== +# JHipster specific properties +# =================================================================== -cache: - timeToLiveSeconds: 3600 - ehcache: - maxBytesLocalHeap: 16M +jhipster: + cache: # Hibernate 2nd level cache, used by CacheConfiguration + timeToLiveSeconds: 3600 + ehcache: + maxBytesLocalHeap: 16M + mail: # specific JHipster mail property, for standard properties see MailProperties + from: malariaplantdb@localhost + metrics: # DropWizard Metrics configuration, used by MetricsConfiguration + jmx.enabled: true + spark: + enabled: false + host: localhost + port: 9999 + graphite: + enabled: false + host: localhost + port: 2003 + prefix: malariaplantdb diff --git a/src/main/resources/config/application-prod.yml b/src/main/resources/config/application-prod.yml index 703cb55..db6def2 100644 --- a/src/main/resources/config/application-prod.yml +++ b/src/main/resources/config/application-prod.yml @@ -1,60 +1,81 @@ -server: - port: 8080 +# =================================================================== +# Spring Boot configuration for the "prod" profile. +# +# This configuration overrides the application.yml file. +# =================================================================== -liquibase: - context: prod +# =================================================================== +# Standard Spring Boot properties. +# Full reference is available at: +# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html +# =================================================================== spring: profiles: active: prod + devtools: + restart: + enabled: false + livereload: + enabled: false datasource: - dataSourceClassName: org.postgresql.ds.PGSimpleDataSource - url: - databaseName: malariaplantdb - serverName: localhost + driver-class-name: org.postgresql.ds.PGSimpleDataSource + url: jdbc:postgresql://localhost:5432/malariaplantdb + name: username: malariaplantdb - password: - + password: jpa: database-platform: nc.ird.malariaplantdb.domain.util.FixedPostgreSQL82Dialect database: POSTGRESQL - openInView: false show_sql: false - generate-ddl: false - hibernate: - ddl-auto: none - naming-strategy: org.springframework.boot.orm.jpa.hibernate.SpringNamingStrategy properties: hibernate.cache.use_second_level_cache: true hibernate.cache.use_query_cache: false hibernate.generate_statistics: false hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory - data: elasticsearch: cluster-name: - cluster-nodes: localhost:9200 + cluster-nodes: localhost:9300 + mail: + host: localhost + port: 25 + username: + password: thymeleaf: - mode: XHTML cache: true -metrics: - jmx.enabled: true - spark: - enabled: false - host: localhost - port: 9999 - graphite: - enabled: false - host: localhost - port: 2003 - prefix: malariaplantdb +liquibase: + contexts: prod + +server: + port: 8080 + compression: + enabled: true + mime-types: text/html,text/xml,text/plain,text/css, application/javascript, application/json -http: - cache: - timeToLiveInDays: 31 +# =================================================================== +# JHipster specific properties +# =================================================================== -cache: - timeToLiveSeconds: 3600 - ehcache: - maxBytesLocalHeap: 256M +jhipster: + http: + cache: # Used by the CachingHttpHeadersFilter + timeToLiveInDays: 31 + cache: # Hibernate 2nd level cache, used by CacheConfiguration + timeToLiveSeconds: 3600 + ehcache: + maxBytesLocalHeap: 256M + mail: # specific JHipster mail property, for standard properties see MailProperties + from: malariaplantdb@localhost + metrics: # DropWizard Metrics configuration, used by MetricsConfiguration + jmx.enabled: true + spark: + enabled: false + host: localhost + port: 9999 + graphite: + enabled: false + host: localhost + port: 2003 + prefix: malariaplantdb diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml index bc0d613..f8eeb6f 100644 --- a/src/main/resources/config/application.yml +++ b/src/main/resources/config/application.yml @@ -1,44 +1,59 @@ -# Disable the spring security default configuration from spring-boot-actuator -management.security.enabled: true -security.basic.enabled: false +# =================================================================== +# Spring Boot configuration. +# +# This configuration will be overriden by the Spring profile you use, +# for example application-dev.yml if you use the "dev" profile. +# =================================================================== -# Disable Jolokia - An http/json bridge for remote JMX access -endpoints.jolokia.enabled: false - -# security configuration (this key should be unique for your application, and kept secret) -jhipster.security.rememberme.key: cb0f037ff3c3646f9796359f3916f7e654f33744 - -async: - corePoolSize: 2 - maxPoolSize: 50 - queueCapacity: 10000 - -mail: - host: localhost - port: 25 - username: - password: - protocol: smtp - tls: false - auth: false - from: malariaplantdb@localhost - -authentication: - xauth: - secret: myXAuthSecret - # Token is valid 30 minutes - tokenValidityInSeconds: 1800 +# =================================================================== +# Standard Spring Boot properties. +# Full reference is available at: +# http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html +# =================================================================== spring: + jpa: + open-in-view: false + hibernate: + ddl-auto: none + naming-strategy: org.springframework.boot.orm.jpa.hibernate.SpringNamingStrategy + messages: + basename: classpath:/i18n/messages mvc: favicon: enabled: false + thymeleaf: + mode: XHTML + +security: + basic: + enabled: false + +# =================================================================== +# JHipster specific properties +# =================================================================== -swagger: - title: malariaplantdb API - description: malariaplantdb applications and beyond! - version: 0.0.1 - termsOfServiceUrl: http://jhipster.github.io/ - contact: - license: Apache 2.0 - licenseUrl: http://www.apache.org/licenses/LICENSE-2.0.html +jhipster: + async: + corePoolSize: 2 + maxPoolSize: 50 + queueCapacity: 10000 + mail: + from: malariaplantdb@localhost + security: + authentication: + xauth: + secret: myXAuthSecret + # Token is valid 30 minutes + tokenValidityInSeconds: 1800 + rememberme: + # security key (this key should be unique for your application, and kept secret) + key: cb0f037ff3c3646f9796359f3916f7e654f33744 + swagger: + title: malariaplantdb API + description: malariaplantdb API documentation + version: 0.0.1 + termsOfServiceUrl: + contact: + license: + licenseUrl: diff --git a/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml b/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml index 6243ab1..27b0643 100644 --- a/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml +++ b/src/main/resources/config/liquibase/changelog/00000000000000_initial_schema.xml @@ -8,8 +8,7 @@ - - + @@ -20,8 +19,8 @@ The initial schema has the '00000000000001' id, so that it is over-written if we re-generate it. --> - - + + @@ -53,24 +52,24 @@ - + - + @@ -79,41 +78,41 @@ - + + referencedTableName="jhi_authority"/> + referencedTableName="jhi_user"/> + tableName="jhi_user"> - + + tableName="jhi_authority"/> - - - + tableName="jhi_user_authority"/> + + + @@ -123,7 +122,7 @@ - + @@ -132,26 +131,27 @@ - + + referencedTableName="jhi_persistent_audit_event"/> + diff --git a/src/main/resources/config/liquibase/changelog/20151005000001_added_entity_Author.xml b/src/main/resources/config/liquibase/changelog/20151005000001_added_entity_Author.xml index 80ba0a1..74cfc7f 100644 --- a/src/main/resources/config/liquibase/changelog/20151005000001_added_entity_Author.xml +++ b/src/main/resources/config/liquibase/changelog/20151005000001_added_entity_Author.xml @@ -1,7 +1,7 @@ @@ -18,7 +18,7 @@ Added the entity Author. --> - + diff --git a/src/main/resources/config/liquibase/changelog/20151005000002_added_entity_Compiler.xml b/src/main/resources/config/liquibase/changelog/20151005000002_added_entity_Compiler.xml index d9f3b40..082becf 100644 --- a/src/main/resources/config/liquibase/changelog/20151005000002_added_entity_Compiler.xml +++ b/src/main/resources/config/liquibase/changelog/20151005000002_added_entity_Compiler.xml @@ -1,15 +1,14 @@ - - + @@ -21,7 +20,7 @@ Added the entity Compiler. --> - + @@ -38,7 +37,7 @@ - + diff --git a/src/main/resources/config/liquibase/changelog/20151005000003_added_entity_Species.xml b/src/main/resources/config/liquibase/changelog/20151005000003_added_entity_Species.xml index 403c6e5..6c05c13 100644 --- a/src/main/resources/config/liquibase/changelog/20151005000003_added_entity_Species.xml +++ b/src/main/resources/config/liquibase/changelog/20151005000003_added_entity_Species.xml @@ -1,15 +1,14 @@ - - + @@ -21,7 +20,7 @@ Added the entity Species. --> - + @@ -33,7 +32,7 @@ - diff --git a/src/main/resources/config/liquibase/changelog/20151005000004_added_entity_PubSpecies.xml b/src/main/resources/config/liquibase/changelog/20151005000004_added_entity_PubSpecies.xml index 984bde0..3aa4352 100644 --- a/src/main/resources/config/liquibase/changelog/20151005000004_added_entity_PubSpecies.xml +++ b/src/main/resources/config/liquibase/changelog/20151005000004_added_entity_PubSpecies.xml @@ -1,15 +1,14 @@ - - + @@ -18,7 +17,7 @@ Added the entity PubSpecies. --> - + @@ -40,10 +39,10 @@ + referencedTableName="species"/> diff --git a/src/main/resources/config/liquibase/changelog/20151005000005_added_entity_PlantIngredient.xml b/src/main/resources/config/liquibase/changelog/20151005000005_added_entity_PlantIngredient.xml index d232447..d9a7a31 100644 --- a/src/main/resources/config/liquibase/changelog/20151005000005_added_entity_PlantIngredient.xml +++ b/src/main/resources/config/liquibase/changelog/20151005000005_added_entity_PlantIngredient.xml @@ -1,15 +1,14 @@ - - + @@ -18,7 +17,7 @@ Added the entity PlantIngredient. --> - + @@ -31,12 +30,12 @@ + referencedTableName="species"/> - diff --git a/src/main/resources/config/liquibase/changelog/20151005000006_added_entity_Ethnology.xml b/src/main/resources/config/liquibase/changelog/20151005000006_added_entity_Ethnology.xml index d20ec7f..7e9e517 100644 --- a/src/main/resources/config/liquibase/changelog/20151005000006_added_entity_Ethnology.xml +++ b/src/main/resources/config/liquibase/changelog/20151005000006_added_entity_Ethnology.xml @@ -1,15 +1,14 @@ - - + @@ -21,7 +20,7 @@ Added the entity Ethnology. --> - + @@ -40,7 +39,7 @@ - + @@ -49,19 +48,20 @@ - + + referencedTableName="ethnology"/> + referencedTableName="plant_ingredient"/> diff --git a/src/main/resources/config/liquibase/changelog/20151005000007_added_entity_InVivoPharmaco.xml b/src/main/resources/config/liquibase/changelog/20151005000007_added_entity_InVivoPharmaco.xml index 6bd7aa0..d433276 100644 --- a/src/main/resources/config/liquibase/changelog/20151005000007_added_entity_InVivoPharmaco.xml +++ b/src/main/resources/config/liquibase/changelog/20151005000007_added_entity_InVivoPharmaco.xml @@ -1,15 +1,14 @@ - - + @@ -21,7 +20,7 @@ Added the entity InVivoPharmaco. --> - + @@ -45,7 +44,7 @@ - + @@ -54,19 +53,20 @@ - + + referencedTableName="in_vivo_pharmaco"/> + referencedTableName="plant_ingredient"/> diff --git a/src/main/resources/config/liquibase/changelog/20151005000008_added_entity_InVitroPharmaco.xml b/src/main/resources/config/liquibase/changelog/20151005000008_added_entity_InVitroPharmaco.xml index df94805..c1e2f3e 100644 --- a/src/main/resources/config/liquibase/changelog/20151005000008_added_entity_InVitroPharmaco.xml +++ b/src/main/resources/config/liquibase/changelog/20151005000008_added_entity_InVitroPharmaco.xml @@ -1,15 +1,14 @@ - - + @@ -21,7 +20,7 @@ Added the entity InVitroPharmaco. --> - + @@ -45,7 +44,7 @@ - + @@ -54,19 +53,20 @@ - + + referencedTableName="in_vitro_pharmaco"/> + referencedTableName="plant_ingredient"/> diff --git a/src/main/resources/config/liquibase/changelog/20151005000009_added_entity_Publication.xml b/src/main/resources/config/liquibase/changelog/20151005000009_added_entity_Publication.xml index 831c716..4977ba1 100644 --- a/src/main/resources/config/liquibase/changelog/20151005000009_added_entity_Publication.xml +++ b/src/main/resources/config/liquibase/changelog/20151005000009_added_entity_Publication.xml @@ -1,15 +1,14 @@ - - + @@ -21,7 +20,7 @@ Added the entity Publication. --> - + @@ -53,42 +52,42 @@ - + + referencedTableName="publication"/> + referencedTableName="publication"/> + referencedTableName="publication"/> + referencedTableName="publication"/> + referencedTableName="publication"/> - + @@ -97,19 +96,19 @@ - + + referencedTableName="publication"/> + referencedTableName="compiler"/> diff --git a/src/main/resources/config/liquibase/master.xml b/src/main/resources/config/liquibase/master.xml index f7ff920..26857d2 100644 --- a/src/main/resources/config/liquibase/master.xml +++ b/src/main/resources/config/liquibase/master.xml @@ -1,19 +1,27 @@ - - - - - - - - - + + + + + + + + + - diff --git a/src/main/resources/ehcache.xml b/src/main/resources/ehcache.xml index 09eb670..03017cd 100644 --- a/src/main/resources/ehcache.xml +++ b/src/main/resources/ehcache.xml @@ -36,4 +36,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/logback.xml b/src/main/resources/logback-spring.xml similarity index 100% rename from src/main/resources/logback.xml rename to src/main/resources/logback-spring.xml diff --git a/src/main/scss/main.scss b/src/main/scss/main.scss index dbd6049..cdca51b 100644 --- a/src/main/scss/main.scss +++ b/src/main/scss/main.scss @@ -32,8 +32,8 @@ body { color: #ccc } -.navbar-brand>img { - max-width:100px; +.navbar-brand > img { + max-width: 100px; margin-top: -15px; } diff --git a/src/main/webapp/index.html b/src/main/webapp/index.html index 7ce42bf..ca98403 100644 --- a/src/main/webapp/index.html +++ b/src/main/webapp/index.html @@ -25,7 +25,7 @@

@@ -62,7 +62,6 @@ - @@ -83,6 +82,8 @@ + + @@ -109,6 +110,7 @@ + @@ -117,8 +119,6 @@ - - @@ -156,6 +156,10 @@ + + + + @@ -187,7 +191,6 @@ - diff --git a/src/main/webapp/scripts/app/account/activate/activate.html b/src/main/webapp/scripts/app/account/activate/activate.html index 0a88057..714a596 100644 --- a/src/main/webapp/scripts/app/account/activate/activate.html +++ b/src/main/webapp/scripts/app/account/activate/activate.html @@ -4,7 +4,7 @@

Activation

- Your user has been activated. Please authenticate. + Your user has been activated. Please sign in.
diff --git a/src/main/webapp/scripts/app/account/login/login.html b/src/main/webapp/scripts/app/account/login/login.html index 764e5eb..d7bcd03 100644 --- a/src/main/webapp/scripts/app/account/login/login.html +++ b/src/main/webapp/scripts/app/account/login/login.html @@ -1,22 +1,24 @@
-

Authentication

+

Sign in

- Authentication failed! Please check your credentials and try again. + Failed to sign in! Please check your credentials and try again.
+
+
- +
- +

diff --git a/src/main/webapp/scripts/app/account/login/login.js b/src/main/webapp/scripts/app/account/login/login.js index 9aa7034..7cf70c3 100644 --- a/src/main/webapp/scripts/app/account/login/login.js +++ b/src/main/webapp/scripts/app/account/login/login.js @@ -8,7 +8,7 @@ angular.module('malariaplantdbApp') url: '/login', data: { authorities: [], - pageTitle: 'Authentication' + pageTitle: 'Sign in' }, views: { 'content@': { diff --git a/src/main/webapp/scripts/app/account/logout/logout.controller.js b/src/main/webapp/scripts/app/account/logout/logout.controller.js deleted file mode 100644 index 79298a6..0000000 --- a/src/main/webapp/scripts/app/account/logout/logout.controller.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -angular.module('malariaplantdbApp') - .controller('LogoutController', function (Auth) { - Auth.logout(); - }); diff --git a/src/main/webapp/scripts/app/account/logout/logout.js b/src/main/webapp/scripts/app/account/logout/logout.js deleted file mode 100644 index 937db2e..0000000 --- a/src/main/webapp/scripts/app/account/logout/logout.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -angular.module('malariaplantdbApp') - .config(function ($stateProvider) { - $stateProvider - .state('logout', { - parent: 'account', - url: '/logout', - data: { - authorities: [] - }, - views: { - 'content@': { - templateUrl: 'scripts/app/main/main.html', - controller: 'LogoutController' - } - } - }); - }); diff --git a/src/main/webapp/scripts/app/account/password/password.directive.js b/src/main/webapp/scripts/app/account/password/password.directive.js index d565c7f..6eecf3a 100644 --- a/src/main/webapp/scripts/app/account/password/password.directive.js +++ b/src/main/webapp/scripts/app/account/password/password.directive.js @@ -7,7 +7,7 @@ angular.module('malariaplantdbApp') replace: true, restrict: 'E', template: '
' + - 'Password strength:' + + 'Password strength:' + '
    ' + '
  • ' + '
' + diff --git a/src/main/webapp/scripts/app/account/register/register.html b/src/main/webapp/scripts/app/account/register/register.html index fe92e5e..9182fe2 100644 --- a/src/main/webapp/scripts/app/account/register/register.html +++ b/src/main/webapp/scripts/app/account/register/register.html @@ -22,29 +22,30 @@

Registration

The password and its confirmation do not match!
- +
+
- - Username +

- Your login is required. + Your username is required.

- Your login is required to be at least 1 character. + Your username is required to be at least 1 character.

- Your login cannot be longer than 50 characters. + Your username cannot be longer than 50 characters.

- Your login can only contain lower-case letters and digits. + Your username can only contain lower-case letters and digits.

@@ -115,7 +116,7 @@

Registration

- If you want to authenticate, you can try the default accounts:
- Administrator (login="admin" and password="admin")
- User (login="user" and password="user"). + If you want to sign in, you can try the default accounts:
- Administrator (login="admin" and password="admin")
- User (login="user" and password="user").
diff --git a/src/main/webapp/scripts/app/account/reset/finish/reset.finish.html b/src/main/webapp/scripts/app/account/reset/finish/reset.finish.html index 5c3a261..ac582d2 100644 --- a/src/main/webapp/scripts/app/account/reset/finish/reset.finish.html +++ b/src/main/webapp/scripts/app/account/reset/finish/reset.finish.html @@ -16,7 +16,7 @@

Reset password

-

Your password has been reset. Please authenticate.

+

Your password has been reset. Please sign in.

diff --git a/src/main/webapp/scripts/app/admin/metrics/metrics.controller.js b/src/main/webapp/scripts/app/admin/metrics/metrics.controller.js index f7ea3e5..520d3e0 100644 --- a/src/main/webapp/scripts/app/admin/metrics/metrics.controller.js +++ b/src/main/webapp/scripts/app/admin/metrics/metrics.controller.js @@ -23,7 +23,6 @@ angular.module('malariaplantdbApp') if (key.indexOf('web.rest') !== -1 || key.indexOf('service') !== -1) { $scope.servicesStats[key] = value; } - if (key.indexOf('net.sf.ehcache.Cache') !== -1) { // remove gets or puts var index = key.lastIndexOf('.'); @@ -57,6 +56,4 @@ angular.module('malariaplantdbApp') }); }); }; - - }); diff --git a/src/main/webapp/scripts/app/admin/user-management/user-management.html b/src/main/webapp/scripts/app/admin/user-management/user-management.html index 2a631d9..f071c89 100644 --- a/src/main/webapp/scripts/app/admin/user-management/user-management.html +++ b/src/main/webapp/scripts/app/admin/user-management/user-management.html @@ -153,7 +153,7 @@ - + {{user.id}} {{user.login}} {{user.email}} diff --git a/src/main/webapp/scripts/app/admin/user-management/user-management.js b/src/main/webapp/scripts/app/admin/user-management/user-management.js index 58c1c0b..b8feac3 100644 --- a/src/main/webapp/scripts/app/admin/user-management/user-management.js +++ b/src/main/webapp/scripts/app/admin/user-management/user-management.js @@ -33,8 +33,6 @@ angular.module('malariaplantdbApp') controller: 'UserManagementDetailController' } }, - resolve: { - - } + resolve: {} }); }); diff --git a/src/main/webapp/scripts/app/app.js b/src/main/webapp/scripts/app/app.js index 7c6397b..d8615c8 100644 --- a/src/main/webapp/scripts/app/app.js +++ b/src/main/webapp/scripts/app/app.js @@ -20,8 +20,14 @@ angular.module('malariaplantdbApp', ['LocalStorageModule', $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { var titleKey = 'malariaplantdb' ; - $rootScope.previousStateName = fromState.name; - $rootScope.previousStateParams = fromParams; + // Remember previous state unless we've been redirected to login or we've just + // reset the state memory after logout. If we're redirected to login, our + // previousState is already set in the authExpiredInterceptor. If we're going + // to login directly, we don't want to be sent to some previous state anyway + if (toState.name != 'login' && $rootScope.previousStateName) { + $rootScope.previousStateName = fromState.name; + $rootScope.previousStateParams = fromParams; + } // Set the page title key to the one configured in state or use default one if (toState.data.pageTitle) { @@ -67,4 +73,14 @@ angular.module('malariaplantdbApp', ['LocalStorageModule', $httpProvider.interceptors.push('authInterceptor'); $httpProvider.interceptors.push('notificationInterceptor'); - }); + }) + .config(['$urlMatcherFactoryProvider', function($urlMatcherFactory) { + $urlMatcherFactory.type('boolean', { + name : 'boolean', + decode: function(val) { return val == true ? true : val == "true" ? true : false }, + encode: function(val) { return val ? 1 : 0; }, + equals: function(a, b) { return this.is(a) && a === b; }, + is: function(val) { return [true,false,0,1].indexOf(val) >= 0 }, + pattern: /bool|true|0|1/ + }); + }]);; diff --git a/src/main/webapp/scripts/app/entities/author/author-dialog.controller.js b/src/main/webapp/scripts/app/entities/author/author-dialog.controller.js index 77e3f3f..15b1723 100644 --- a/src/main/webapp/scripts/app/entities/author/author-dialog.controller.js +++ b/src/main/webapp/scripts/app/entities/author/author-dialog.controller.js @@ -2,7 +2,7 @@ angular.module('malariaplantdbApp').controller('AuthorDialogController', ['$scope', '$stateParams', '$modalInstance', 'entity', 'Author', 'Publication', - function($scope, $controller, $stateParams, $modalInstance, entity, Author, Publication) { + function ($scope, $stateParams, $modalInstance, entity, Author, Publication) { $scope.author = entity; $scope.publications = Publication.sortedQuery(); diff --git a/src/main/webapp/scripts/app/main/main.html b/src/main/webapp/scripts/app/main/main.html index f78e7e8..5e3fa99 100644 --- a/src/main/webapp/scripts/app/main/main.html +++ b/src/main/webapp/scripts/app/main/main.html @@ -5,7 +5,9 @@

Malaria Plant DB Community

-

The database of medicinal plants against + +

The database of medicinal plants + against malaria

@@ -14,7 +16,7 @@

Malaria Plant DB Community

- If you want to authenticate, you can try the default accounts:
- Administrator (login="admin" and password="admin")
- User (login="user" and password="user"). + If you want to sign in, you can try the default accounts:
- Administrator (login="admin" and password="admin")
- User (login="user" and password="user").
@@ -24,6 +26,7 @@

Objectives

published (or to be published) information and grey literature (literature outside of commercial or academic publishing) on antimalarial medicinal plants: Their traditional use and/or their in vitro/in vivo biological activity, and/or toxicity.

+

The database is not a substitute for published material, as only relevant data from the publication (considered to be fundamental for result interpretation) has been retained.

diff --git a/src/main/webapp/scripts/components/alert/alert.directive.js b/src/main/webapp/scripts/components/alert/alert.directive.js index 667d40e..a13a92a 100644 --- a/src/main/webapp/scripts/components/alert/alert.directive.js +++ b/src/main/webapp/scripts/components/alert/alert.directive.js @@ -2,78 +2,76 @@ angular.module('malariaplantdbApp') .directive('jhAlert', function(AlertService) { - return { + return { restrict: 'E', template: '
' + - '' + - '
{{ alert.msg }}
', - controller: ['$scope', - function($scope) { - $scope.alerts = AlertService.get(); - $scope.$on('$destroy', function () { - $scope.alerts = []; - }); - } - ] + '
{{ alert.msg }}
' + + '
', + controller: ['$scope', + function($scope) { + $scope.alerts = AlertService.get(); + $scope.$on('$destroy', function () { + $scope.alerts = []; + }); + } + ] } }) - .directive('jhAlertError', function(AlertService, $rootScope) { - return { + return { restrict: 'E', template: '
' + - '
{{ alert.msg }}
' + - '
', - controller: ['$scope', - function($scope) { - $scope.alerts = AlertService.get(); - - var cleanHttpErrorListener = $rootScope.$on('malariaplantdbApp.httpError', function (event, httpResponse) { - var i; - event.stopPropagation(); - switch (httpResponse.status) { - // connection refused, server not reachable - case 0: - addErrorAlert("Server not reachable",'error.serverNotReachable'); - break; + '
{{ alert.msg }}
' + + '
', + controller: ['$scope', + function($scope) { + $scope.alerts = AlertService.get(); - case 400: - if (httpResponse.data && httpResponse.data.fieldErrors) { - for (i = 0; i < httpResponse.data.fieldErrors.length; i++) { - var fieldError = httpResponse.data.fieldErrors[i]; - // convert 'something[14].other[4].id' to 'something[].other[].id' so translations can be written to it - var convertedField = fieldError.field.replace(/\[\d*\]/g, "[]"); - var fieldName = convertedField.charAt(0).toUpperCase() + convertedField.slice(1); - addErrorAlert('Field ' + fieldName + ' cannot be empty', 'error.' + fieldError.message, {fieldName: fieldName}); - } - } else if (httpResponse.data && httpResponse.data.message) { - addErrorAlert(httpResponse.data.message, httpResponse.data.message, httpResponse.data); - } else { - addErrorAlert(httpResponse.data); - } - break; + var cleanHttpErrorListener = $rootScope.$on('malariaplantdbApp.httpError', function (event, httpResponse) { + var i; + event.stopPropagation(); + switch (httpResponse.status) { + // connection refused, server not reachable + case 0: + addErrorAlert("Server not reachable",'error.serverNotReachable'); + break; - default: - if (httpResponse.data && httpResponse.data.message) { - addErrorAlert(httpResponse.data.message); - } else { - addErrorAlert(JSON.stringify(httpResponse)); - } - } - }); + case 400: + if (httpResponse.data && httpResponse.data.fieldErrors) { + for (i = 0; i < httpResponse.data.fieldErrors.length; i++) { + var fieldError = httpResponse.data.fieldErrors[i]; + // convert 'something[14].other[4].id' to 'something[].other[].id' so translations can be written to it + var convertedField = fieldError.field.replace(/\[\d*\]/g, "[]"); + var fieldName = convertedField.charAt(0).toUpperCase() + convertedField.slice(1); + addErrorAlert('Field ' + fieldName + ' cannot be empty', 'error.' + fieldError.message, {fieldName: fieldName}); + } + } else if (httpResponse.data && httpResponse.data.message) { + addErrorAlert(httpResponse.data.message, httpResponse.data.message, httpResponse.data); + } else { + addErrorAlert(httpResponse.data); + } + break; - $scope.$on('$destroy', function () { - if(cleanHttpErrorListener !== undefined && cleanHttpErrorListener !== null){ - cleanHttpErrorListener(); - } - }); + default: + if (httpResponse.data && httpResponse.data.message) { + addErrorAlert(httpResponse.data.message); + } else { + addErrorAlert(JSON.stringify(httpResponse)); + } + } + }); - var addErrorAlert = function (message, key, data) { - AlertService.error(message); + $scope.$on('$destroy', function () { + if(cleanHttpErrorListener !== undefined && cleanHttpErrorListener !== null){ + cleanHttpErrorListener(); + } + }); - } + var addErrorAlert = function (message, key, data) { + AlertService.error(message); - } - ] + } + } + ] } }); diff --git a/src/main/webapp/scripts/components/alert/alert.service.js b/src/main/webapp/scripts/components/alert/alert.service.js index 252ad48..bc5962c 100644 --- a/src/main/webapp/scripts/components/alert/alert.service.js +++ b/src/main/webapp/scripts/components/alert/alert.service.js @@ -16,7 +16,8 @@ angular.module('malariaplantdbApp') }, alertId = 0, // unique id for each alert. Starts from 0. alerts = [], - timeout = 5000; // default timeout + timeout = 5000, + errorTimeout = 10000; // default timeout function clear() { alerts = []; @@ -39,9 +40,8 @@ angular.module('malariaplantdbApp') this.add({ type: "danger", msg: msg, - params: params - // no time out for errors - //timeout: timeout + params: params, + timeout: errorTimeout }); } diff --git a/src/main/webapp/scripts/components/auth/auth.service.js b/src/main/webapp/scripts/components/auth/auth.service.js index c07f70c..4ef9188 100644 --- a/src/main/webapp/scripts/components/auth/auth.service.js +++ b/src/main/webapp/scripts/components/auth/auth.service.js @@ -10,7 +10,6 @@ angular.module('malariaplantdbApp') AuthServerProvider.login(credentials).then(function (data) { // retrieve the logged account information Principal.identity(true).then(function(account) { - deferred.resolve(data); }); return cb(); @@ -26,6 +25,9 @@ angular.module('malariaplantdbApp') logout: function () { AuthServerProvider.logout(); Principal.authenticate(null); + // Reset state memory + $rootScope.previousStateName = undefined; + $rootScope.previousStateNameParams = undefined; }, authorize: function(force) { @@ -46,8 +48,8 @@ angular.module('malariaplantdbApp') else { // user is not authenticated. stow the state they wanted before you // send them to the signin state, so you can return them when you're done - $rootScope.returnToState = $rootScope.toState; - $rootScope.returnToStateParams = $rootScope.toStateParams; + $rootScope.previousStateName = $rootScope.toState; + $rootScope.previousStateNameParams = $rootScope.toStateParams; // now, send them to the signin state so they can log in $state.go('login'); diff --git a/src/main/webapp/scripts/components/auth/principal.service.js b/src/main/webapp/scripts/components/auth/principal.service.js index fab2f6e..00e648e 100644 --- a/src/main/webapp/scripts/components/auth/principal.service.js +++ b/src/main/webapp/scripts/components/auth/principal.service.js @@ -14,14 +14,14 @@ angular.module('malariaplantdbApp') }, hasAuthority: function (authority) { if (!_authenticated) { - return false; - } + return $q.when(false); + } - return this.identity().then(function(_id) { - return _id.authorities && _id.authorities.indexOf(authority) !== -1; - }, function(err){ - return false; - }); + return this.identity().then(function(_id) { + return _id.authorities && _id.authorities.indexOf(authority) !== -1; + }, function(err){ + return false; + }); }, hasAnyAuthority: function (authorities) { if (!_authenticated || !_identity || !_identity.authorities) { diff --git a/src/main/webapp/scripts/components/interceptor/auth.interceptor.js b/src/main/webapp/scripts/components/interceptor/auth.interceptor.js index 4e328ef..81b3645 100644 --- a/src/main/webapp/scripts/components/interceptor/auth.interceptor.js +++ b/src/main/webapp/scripts/components/interceptor/auth.interceptor.js @@ -31,4 +31,4 @@ angular.module('malariaplantdbApp') return $q.reject(response); } }; - }); \ No newline at end of file + }); diff --git a/src/main/webapp/scripts/components/interceptor/notification.interceptor.js b/src/main/webapp/scripts/components/interceptor/notification.interceptor.js index 463646b..c883b59 100644 --- a/src/main/webapp/scripts/components/interceptor/notification.interceptor.js +++ b/src/main/webapp/scripts/components/interceptor/notification.interceptor.js @@ -9,6 +9,6 @@ angular.module('malariaplantdbApp') AlertService.success(alertKey, { param : response.headers('X-malariaplantdbApp-params')}); } return response; - }, + } }; - }); \ No newline at end of file + }); diff --git a/src/main/webapp/scripts/components/navbar/navbar.html b/src/main/webapp/scripts/components/navbar/navbar.html index 9bc07e3..aa2a303 100644 --- a/src/main/webapp/scripts/components/navbar/navbar.html +++ b/src/main/webapp/scripts/components/navbar/navbar.html @@ -15,91 +15,108 @@