+ * You can find more information on how profiles work with JHipster on http://jhipster.github.io/profiles/.
*/
@PostConstruct
- public void initApplication() throws IOException {
+ public void initApplication() {
if (env.getActiveProfiles().length == 0) {
log.warn("No Spring profile configured, running with default configuration");
} else {
@@ -53,10 +49,6 @@ public void initApplication() throws IOException {
log.error("You have misconfigured your application! " +
"It should not run with both the 'dev' and 'prod' profiles at the same time.");
}
- if (activeProfiles.contains(Constants.SPRING_PROFILE_PRODUCTION) && activeProfiles.contains(Constants.SPRING_PROFILE_FAST)) {
- log.error("You have misconfigured your application! " +
- "It should not run with both the 'prod' and 'fast' profiles at the same time.");
- }
if (activeProfiles.contains(Constants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(Constants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! " +
"It should not run with both the 'dev' and 'cloud' profiles at the same time.");
@@ -66,15 +58,20 @@ public void initApplication() throws IOException {
/**
* Main method, used to run the application.
+ *
+ * @param args the command line arguments
+ * @throws UnknownHostException if the local host name could not be resolved into an address
*/
public static void main(String[] args) throws UnknownHostException {
- SpringApplication app = new SpringApplication(Application.class);
+ SpringApplication app = new SpringApplication(SampleApplicationApp.class);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
addDefaultProfile(app, source);
Environment env = app.run(args).getEnvironment();
- log.info("Access URLs:\n----------------------------------------------------------\n\t" +
+ log.info("\n----------------------------------------------------------\n\t" +
+ "Application '{}' is running! Access URLs:\n\t" +
"Local: \t\thttp://127.0.0.1:{}\n\t" +
"External: \thttp://{}:{}\n----------------------------------------------------------",
+ env.getProperty("spring.application.name"),
env.getProperty("server.port"),
InetAddress.getLocalHost().getHostAddress(),
env.getProperty("server.port"));
diff --git a/src/main/java/com/mycompany/myapp/async/ExceptionHandlingAsyncTaskExecutor.java b/src/main/java/com/mycompany/myapp/async/ExceptionHandlingAsyncTaskExecutor.java
index 300de6220..7603869da 100644
--- a/src/main/java/com/mycompany/myapp/async/ExceptionHandlingAsyncTaskExecutor.java
+++ b/src/main/java/com/mycompany/myapp/async/ExceptionHandlingAsyncTaskExecutor.java
@@ -22,7 +22,7 @@ public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {
@Override
public void execute(Runnable task) {
- executor.execute(task);
+ executor.execute(createWrappedRunnable(task));
}
@Override
diff --git a/src/main/java/com/mycompany/myapp/config/AsyncConfiguration.java b/src/main/java/com/mycompany/myapp/config/AsyncConfiguration.java
index 1d92d7458..cc1968775 100644
--- a/src/main/java/com/mycompany/myapp/config/AsyncConfiguration.java
+++ b/src/main/java/com/mycompany/myapp/config/AsyncConfiguration.java
@@ -33,7 +33,7 @@ public Executor getAsyncExecutor() {
executor.setCorePoolSize(jHipsterProperties.getAsync().getCorePoolSize());
executor.setMaxPoolSize(jHipsterProperties.getAsync().getMaxPoolSize());
executor.setQueueCapacity(jHipsterProperties.getAsync().getQueueCapacity());
- executor.setThreadNamePrefix("sampleapplication-Executor-");
+ executor.setThreadNamePrefix("sample-application-Executor-");
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
diff --git a/src/main/java/com/mycompany/myapp/config/CacheConfiguration.java b/src/main/java/com/mycompany/myapp/config/CacheConfiguration.java
index 242a6931c..5f1ccb143 100644
--- a/src/main/java/com/mycompany/myapp/config/CacheConfiguration.java
+++ b/src/main/java/com/mycompany/myapp/config/CacheConfiguration.java
@@ -22,7 +22,6 @@
@Configuration
@EnableCaching
@AutoConfigureAfter(value = { MetricsConfiguration.class, DatabaseConfiguration.class })
-@Profile("!" + Constants.SPRING_PROFILE_FAST)
public class CacheConfiguration {
private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
diff --git a/src/main/java/com/mycompany/myapp/config/Constants.java b/src/main/java/com/mycompany/myapp/config/Constants.java
index b0addca91..07b981771 100644
--- a/src/main/java/com/mycompany/myapp/config/Constants.java
+++ b/src/main/java/com/mycompany/myapp/config/Constants.java
@@ -5,14 +5,17 @@
*/
public final class Constants {
- // Spring profile for development, production and "fast", see http://jhipster.github.io/profiles.html
+ // Spring profile for development and production, see http://jhipster.github.io/profiles/
public static final String SPRING_PROFILE_DEVELOPMENT = "dev";
public static final String SPRING_PROFILE_PRODUCTION = "prod";
- public static final String SPRING_PROFILE_FAST = "fast";
// Spring profile used when deploying with Spring Cloud (used when deploying to CloudFoundry)
public static final String SPRING_PROFILE_CLOUD = "cloud";
// Spring profile used when deploying to Heroku
public static final String SPRING_PROFILE_HEROKU = "heroku";
+ // Spring profile used to disable swagger
+ public static final String SPRING_PROFILE_NO_SWAGGER = "no-swagger";
+ // Spring profile used to disable running liquibase
+ public static final String SPRING_PROFILE_NO_LIQUIBASE = "no-liquibase";
public static final String SYSTEM_ACCOUNT = "system";
diff --git a/src/main/java/com/mycompany/myapp/config/DatabaseConfiguration.java b/src/main/java/com/mycompany/myapp/config/DatabaseConfiguration.java
index ff3a5fd40..3babacfef 100644
--- a/src/main/java/com/mycompany/myapp/config/DatabaseConfiguration.java
+++ b/src/main/java/com/mycompany/myapp/config/DatabaseConfiguration.java
@@ -4,7 +4,6 @@
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;
@@ -12,8 +11,10 @@
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
+import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
+import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -43,8 +44,9 @@ public class DatabaseConfiguration {
private MetricRegistry metricRegistry;
@Bean(destroyMethod = "close")
- @ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
- public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
+ @ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_CLOUD + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_HEROKU + "')}")
+ @ConfigurationProperties(prefix = "spring.datasource.hikari")
+ public DataSource dataSource(DataSourceProperties dataSourceProperties) {
log.debug("Configuring Datasource");
if (dataSourceProperties.getUrl() == null) {
log.error("Your database connection pool configuration is incorrect! The application" +
@@ -53,34 +55,26 @@ public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipster
throw new ApplicationContextException("Database connection pool is not configured correctly");
}
- HikariConfig config = new HikariConfig();
- config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
- config.addDataSourceProperty("url", dataSourceProperties.getUrl());
- if (dataSourceProperties.getUsername() != null) {
- config.addDataSourceProperty("user", dataSourceProperties.getUsername());
- } else {
- 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
- }
+ HikariDataSource hikariDataSource = (HikariDataSource) DataSourceBuilder
+ .create(dataSourceProperties.getClassLoader())
+ .type(HikariDataSource.class)
+ .driverClassName(dataSourceProperties.getDriverClassName())
+ .url(dataSourceProperties.getUrl())
+ .username(dataSourceProperties.getUsername())
+ .password(dataSourceProperties.getPassword())
+ .build();
- //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
- if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
- config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts());
- config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize());
- config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit());
- }
if (metricRegistry != null) {
- config.setMetricRegistry(metricRegistry);
+ hikariDataSource.setMetricRegistry(metricRegistry);
}
- return new HikariDataSource(config);
+ return hikariDataSource;
}
/**
* Open the TCP port for the H2 database, so it is available remotely.
+ *
+ * @return the H2 database TCP server
+ * @throws SQLException if the server failed to start
*/
@Bean(initMethod = "start", destroyMethod = "stop")
@Profile(Constants.SPRING_PROFILE_DEVELOPMENT)
@@ -99,18 +93,13 @@ public SpringLiquibase liquibase(DataSource dataSource, DataSourceProperties dat
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(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);
- } else {
- liquibase.setShouldRun(false);
- }
+ if (env.acceptsProfiles(Constants.SPRING_PROFILE_NO_LIQUIBASE)) {
+ liquibase.setShouldRun(false);
} else {
+ liquibase.setShouldRun(liquibaseProperties.isEnabled());
log.debug("Configuring Liquibase");
}
+
return liquibase;
}
diff --git a/src/main/java/com/mycompany/myapp/config/JHipsterProperties.java b/src/main/java/com/mycompany/myapp/config/JHipsterProperties.java
index 3ebc310ae..75fb35d4e 100644
--- a/src/main/java/com/mycompany/myapp/config/JHipsterProperties.java
+++ b/src/main/java/com/mycompany/myapp/config/JHipsterProperties.java
@@ -5,6 +5,7 @@
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.cors.CorsConfiguration;
+
/**
* Properties specific to JHipster.
*
@@ -19,8 +20,6 @@ public class JHipsterProperties {
private final Http http = new Http();
- private final Datasource datasource = new Datasource();
-
private final Cache cache = new Cache();
private final Mail mail = new Mail();
@@ -33,8 +32,6 @@ public class JHipsterProperties {
private final CorsConfiguration cors = new CorsConfiguration();
-
-
public Async getAsync() {
return async;
}
@@ -43,10 +40,6 @@ public Http getHttp() {
return http;
}
- public Datasource getDatasource() {
- return datasource;
- }
-
public Cache getCache() {
return cache;
}
@@ -71,7 +64,6 @@ public CorsConfiguration getCors() {
return cors;
}
-
public static class Async {
private int corePoolSize = 2;
@@ -115,7 +107,7 @@ public Cache getCache() {
public static class Cache {
- private int timeToLiveInDays = 31;
+ private int timeToLiveInDays = 1461;
public int getTimeToLiveInDays() {
return timeToLiveInDays;
@@ -127,49 +119,6 @@ public void setTimeToLiveInDays(int 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;
@@ -217,13 +166,13 @@ public void setFrom(String from) {
public static class Security {
- private final Rememberme rememberme = new Rememberme();
+ private final RememberMe rememberMe = new RememberMe();
- public Rememberme getRememberme() {
- return rememberme;
+ public RememberMe getRememberMe() {
+ return rememberMe;
}
- public static class Rememberme {
+ public static class RememberMe {
@NotNull
private String key;
@@ -248,7 +197,11 @@ public static class Swagger {
private String termsOfServiceUrl;
- private String contact;
+ private String contactName;
+
+ private String contactUrl;
+
+ private String contactEmail;
private String license;
@@ -286,12 +239,28 @@ public void setTermsOfServiceUrl(String termsOfServiceUrl) {
this.termsOfServiceUrl = termsOfServiceUrl;
}
- public String getContact() {
- return contact;
+ public String getContactName() {
+ return contactName;
}
- public void setContact(String contact) {
- this.contact = contact;
+ public void setContactName(String contactName) {
+ this.contactName = contactName;
+ }
+
+ public String getContactUrl() {
+ return contactUrl;
+ }
+
+ public void setContactUrl(String contactUrl) {
+ this.contactUrl = contactUrl;
+ }
+
+ public String getContactEmail() {
+ return contactEmail;
+ }
+
+ public void setContactEmail(String contactEmail) {
+ this.contactEmail = contactEmail;
}
public String getLicense() {
@@ -319,6 +288,8 @@ public static class Metrics {
private final Graphite graphite = new Graphite();
+ private final Logs logs = new Logs();
+
public Jmx getJmx() {
return jmx;
}
@@ -331,6 +302,11 @@ public Graphite getGraphite() {
return graphite;
}
+ public Logs getLogs() {
+ return logs;
+ }
+
+
public static class Jmx {
private boolean enabled = true;
@@ -419,5 +395,67 @@ public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
+
+ public static class Logs {
+
+ private boolean enabled = false;
+
+ private long reportFrequency = 60;
+
+ public long getReportFrequency() {
+ return reportFrequency;
+ }
+
+ public void setReportFrequency(int reportFrequency) {
+ this.reportFrequency = reportFrequency;
+ }
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
+ }
}
+
+ private final Logging logging = new Logging();
+
+ public Logging getLogging() { return logging; }
+
+ public static class Logging {
+
+ private final Logstash logstash = new Logstash();
+
+ public Logstash getLogstash() { return logstash; }
+
+ public static class Logstash {
+
+ private boolean enabled = false;
+
+ private String host = "localhost";
+
+ private int port = 5000;
+
+ private int queueSize = 512;
+
+ 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 int getQueueSize() { return queueSize; }
+
+ public void setQueueSize(int queueSize) { this.queueSize = queueSize; }
+ }
+ }
+
}
diff --git a/src/main/java/com/mycompany/myapp/config/LocaleConfiguration.java b/src/main/java/com/mycompany/myapp/config/LocaleConfiguration.java
index 1a51df6d7..0775b8bba 100644
--- a/src/main/java/com/mycompany/myapp/config/LocaleConfiguration.java
+++ b/src/main/java/com/mycompany/myapp/config/LocaleConfiguration.java
@@ -4,10 +4,8 @@
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
-import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
@@ -31,15 +29,6 @@ public LocaleResolver localeResolver() {
return cookieLocaleResolver;
}
- @Bean
- public MessageSource messageSource() {
- ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
- messageSource.setBasename("classpath:/i18n/messages");
- messageSource.setDefaultEncoding("UTF-8");
- messageSource.setCacheSeconds(propertyResolver.getProperty("cache-seconds", Integer.class, -1));
- return messageSource;
- }
-
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
diff --git a/src/main/java/com/mycompany/myapp/config/LoggingConfiguration.java b/src/main/java/com/mycompany/myapp/config/LoggingConfiguration.java
new file mode 100644
index 000000000..75921d4a5
--- /dev/null
+++ b/src/main/java/com/mycompany/myapp/config/LoggingConfiguration.java
@@ -0,0 +1,62 @@
+package com.mycompany.myapp.config;
+
+import ch.qos.logback.classic.AsyncAppender;
+import ch.qos.logback.classic.LoggerContext;
+import net.logstash.logback.appender.LogstashSocketAppender;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Configuration;
+
+import javax.annotation.PostConstruct;
+import javax.inject.Inject;
+
+@Configuration
+public class LoggingConfiguration {
+
+ private final Logger log = LoggerFactory.getLogger(LoggingConfiguration.class);
+
+ private LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
+
+ @Value("${spring.application.name}")
+ private String appName;
+
+ @Value("${server.port}")
+ private String serverPort;
+
+ @Inject
+ private JHipsterProperties jHipsterProperties;
+
+ @PostConstruct
+ private void init() {
+ if (jHipsterProperties.getLogging().getLogstash().isEnabled()) {
+ addLogstashAppender();
+ }
+ }
+
+ public void addLogstashAppender() {
+ log.info("Initializing Logstash logging");
+
+ LogstashSocketAppender logstashAppender = new LogstashSocketAppender();
+ logstashAppender.setName("LOGSTASH");
+ logstashAppender.setContext(context);
+
+ String customFields = "{\"app_name\":\"" + appName + "\",\"app_port\":\"" + serverPort + "\"}";
+
+ // Set the Logstash appender config from JHipster properties
+ logstashAppender.setSyslogHost(jHipsterProperties.getLogging().getLogstash().getHost());
+ logstashAppender.setPort(jHipsterProperties.getLogging().getLogstash().getPort());
+ logstashAppender.setCustomFields(customFields);
+ logstashAppender.start();
+
+ // Wrap the appender in an Async appender for performance
+ AsyncAppender asyncLogstashAppender = new AsyncAppender();
+ asyncLogstashAppender.setContext(context);
+ asyncLogstashAppender.setName("ASYNC_LOGSTASH");
+ asyncLogstashAppender.setQueueSize(jHipsterProperties.getLogging().getLogstash().getQueueSize());
+ asyncLogstashAppender.addAppender(logstashAppender);
+ asyncLogstashAppender.start();
+
+ context.getLogger("ROOT").addAppender(asyncLogstashAppender);
+ }
+}
diff --git a/src/main/java/com/mycompany/myapp/config/MetricsConfiguration.java b/src/main/java/com/mycompany/myapp/config/MetricsConfiguration.java
index d3a2f17d8..d5b4cf1c1 100644
--- a/src/main/java/com/mycompany/myapp/config/MetricsConfiguration.java
+++ b/src/main/java/com/mycompany/myapp/config/MetricsConfiguration.java
@@ -2,6 +2,7 @@
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.MetricRegistry;
+import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.graphite.Graphite;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.codahale.metrics.health.HealthCheckRegistry;
@@ -22,7 +23,6 @@
@Configuration
@EnableMetrics(proxyTargetClass = true)
-@Profile("!" + Constants.SPRING_PROFILE_FAST)
public class MetricsConfiguration extends MetricsConfigurerAdapter {
private static final String PROP_METRIC_REG_JVM_MEMORY = "jvm.memory";
@@ -65,11 +65,20 @@ public void init() {
JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
jmxReporter.start();
}
+
+ if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
+ log.info("Initializing Metrics Log reporting");
+ final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
+ .outputTo(LoggerFactory.getLogger("metrics"))
+ .convertRatesTo(TimeUnit.SECONDS)
+ .convertDurationsTo(TimeUnit.MILLISECONDS)
+ .build();
+ reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
+ }
}
@Configuration
@ConditionalOnClass(Graphite.class)
- @Profile("!" + Constants.SPRING_PROFILE_FAST)
public static class GraphiteRegistry {
private final Logger log = LoggerFactory.getLogger(GraphiteRegistry.class);
@@ -100,7 +109,6 @@ private void init() {
@Configuration
@ConditionalOnClass(SparkReporter.class)
- @Profile("!" + Constants.SPRING_PROFILE_FAST)
public static class SparkRegistry {
private final Logger log = LoggerFactory.getLogger(SparkRegistry.class);
diff --git a/src/main/java/com/mycompany/myapp/config/SecurityConfiguration.java b/src/main/java/com/mycompany/myapp/config/SecurityConfiguration.java
index c8a5586f7..02a1d7a6c 100644
--- a/src/main/java/com/mycompany/myapp/config/SecurityConfiguration.java
+++ b/src/main/java/com/mycompany/myapp/config/SecurityConfiguration.java
@@ -2,9 +2,11 @@
import com.mycompany.myapp.security.*;
import com.mycompany.myapp.web.filter.CsrfCookieGeneratorFilter;
+import com.mycompany.myapp.config.JHipsterProperties;
+
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import org.springframework.core.env.Environment;
+import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
@@ -27,7 +29,7 @@
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Inject
- private Environment env;
+ private JHipsterProperties jHipsterProperties;
@Inject
private AjaxAuthenticationSuccessHandler ajaxAuthenticationSuccessHandler;
@@ -62,10 +64,11 @@ public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
- .antMatchers("/scripts/**/*.{js,html}")
+ .antMatchers(HttpMethod.OPTIONS, "/**")
+ .antMatchers("/app/**/*.{js,html}")
.antMatchers("/bower_components/**")
.antMatchers("/i18n/**")
- .antMatchers("/assets/**")
+ .antMatchers("/content/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**")
.antMatchers("/h2-console/**");
@@ -84,7 +87,7 @@ protected void configure(HttpSecurity http) throws Exception {
.rememberMe()
.rememberMeServices(rememberMeServices)
.rememberMeParameter("remember-me")
- .key(env.getProperty("jhipster.security.rememberme.key"))
+ .key(jHipsterProperties.getSecurity().getRememberMe().getKey())
.and()
.formLogin()
.loginProcessingUrl("/api/authentication")
@@ -123,7 +126,6 @@ protected void configure(HttpSecurity http) throws Exception {
.antMatchers("/info/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/autoconfig/**").hasAuthority(AuthoritiesConstants.ADMIN)
.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()
diff --git a/src/main/java/com/mycompany/myapp/config/ThymeleafConfiguration.java b/src/main/java/com/mycompany/myapp/config/ThymeleafConfiguration.java
index d1dd3d673..1b7565851 100644
--- a/src/main/java/com/mycompany/myapp/config/ThymeleafConfiguration.java
+++ b/src/main/java/com/mycompany/myapp/config/ThymeleafConfiguration.java
@@ -3,9 +3,7 @@
import org.apache.commons.lang.CharEncoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.context.MessageSource;
import org.springframework.context.annotation.*;
-import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
@Configuration
@@ -24,14 +22,4 @@ public ClassLoaderTemplateResolver emailTemplateResolver() {
emailTemplateResolver.setOrder(1);
return emailTemplateResolver;
}
-
- @Bean
- @Description("Spring mail message resolver")
- public MessageSource emailMessageSource() {
- log.info("loading non-reloadable mail messages resources");
- ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
- messageSource.setBasename("classpath:/mails/messages/messages");
- messageSource.setDefaultEncoding(CharEncoding.UTF_8);
- return messageSource;
- }
}
diff --git a/src/main/java/com/mycompany/myapp/config/WebConfigurer.java b/src/main/java/com/mycompany/myapp/config/WebConfigurer.java
index 674b56ca9..edfdcadeb 100644
--- a/src/main/java/com/mycompany/myapp/config/WebConfigurer.java
+++ b/src/main/java/com/mycompany/myapp/config/WebConfigurer.java
@@ -4,7 +4,6 @@
import com.codahale.metrics.servlet.InstrumentedFilter;
import com.codahale.metrics.servlets.MetricsServlet;
import com.mycompany.myapp.web.filter.CachingHttpHeadersFilter;
-import com.mycompany.myapp.web.filter.StaticResourcesProductionFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -19,6 +18,7 @@
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
+import java.io.File;
import java.util.*;
import javax.inject.Inject;
import javax.servlet.*;
@@ -35,7 +35,7 @@ public class WebConfigurer implements ServletContextInitializer, EmbeddedServlet
private Environment env;
@Inject
- private JHipsterProperties props;
+ private JHipsterProperties jHipsterProperties;
@Autowired(required = false)
private MetricRegistry metricRegistry;
@@ -44,12 +44,9 @@ public class WebConfigurer implements ServletContextInitializer, EmbeddedServlet
public void onStartup(ServletContext servletContext) throws ServletException {
log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles()));
EnumSet disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
- if (!env.acceptsProfiles(Constants.SPRING_PROFILE_FAST)) {
- initMetrics(servletContext, disps);
- }
+ initMetrics(servletContext, disps);
if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) {
initCachingHttpHeadersFilter(servletContext, disps);
- initStaticResourcesProductionFilter(servletContext, disps);
}
if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) {
initH2Console(servletContext);
@@ -58,7 +55,7 @@ public void onStartup(ServletContext servletContext) throws ServletException {
}
/**
- * Set up Mime types.
+ * Set up Mime types and, if needed, set the document root.
*/
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
@@ -68,24 +65,17 @@ public void customize(ConfigurableEmbeddedServletContainer container) {
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", "text/html;charset=utf-8");
container.setMimeMappings(mappings);
- }
- /**
- * Initializes the static resources production Filter.
- */
- private void initStaticResourcesProductionFilter(ServletContext servletContext,
- EnumSet disps) {
-
- log.debug("Registering static resources production Filter");
- FilterRegistration.Dynamic staticResourcesProductionFilter =
- servletContext.addFilter("staticResourcesProductionFilter",
- new StaticResourcesProductionFilter());
-
- staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/");
- staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/index.html");
- staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/assets/*");
- staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
- staticResourcesProductionFilter.setAsyncSupported(true);
+ // When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets.
+ File root;
+ if (env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) {
+ root = new File("target/www/");
+ } else {
+ root = new File("src/main/webapp/");
+ }
+ if (root.exists() && root.isDirectory()) {
+ container.setDocumentRoot(root);
+ }
}
/**
@@ -96,10 +86,10 @@ private void initCachingHttpHeadersFilter(ServletContext servletContext,
log.debug("Registering Caching HTTP Headers Filter");
FilterRegistration.Dynamic cachingHttpHeadersFilter =
servletContext.addFilter("cachingHttpHeadersFilter",
- new CachingHttpHeadersFilter(env));
+ new CachingHttpHeadersFilter(jHipsterProperties));
- cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/dist/assets/*");
- cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/dist/scripts/*");
+ cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/content/*");
+ cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/app/*");
cachingHttpHeadersFilter.setAsyncSupported(true);
}
@@ -132,7 +122,7 @@ private void initMetrics(ServletContext servletContext, EnumSet
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
- CorsConfiguration config = props.getCors();
+ CorsConfiguration config = jHipsterProperties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
@@ -148,7 +138,7 @@ private void initH2Console(ServletContext servletContext) {
log.debug("Initialize H2 console");
ServletRegistration.Dynamic h2ConsoleServlet = servletContext.addServlet("H2Console", new org.h2.server.web.WebServlet());
h2ConsoleServlet.addMapping("/h2-console/*");
- h2ConsoleServlet.setInitParameter("-properties", "src/main/resources");
+ h2ConsoleServlet.setInitParameter("-properties", "src/main/resources/");
h2ConsoleServlet.setLoadOnStartup(1);
}
}
diff --git a/src/main/java/com/mycompany/myapp/config/apidoc/SwaggerConfiguration.java b/src/main/java/com/mycompany/myapp/config/apidoc/SwaggerConfiguration.java
index de4fe7edd..7c939658e 100644
--- a/src/main/java/com/mycompany/myapp/config/apidoc/SwaggerConfiguration.java
+++ b/src/main/java/com/mycompany/myapp/config/apidoc/SwaggerConfiguration.java
@@ -6,11 +6,13 @@
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.*;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StopWatch;
import springfox.documentation.service.ApiInfo;
+import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@@ -26,7 +28,7 @@
*/
@Configuration
@EnableSwagger2
-@Profile("!" + Constants.SPRING_PROFILE_PRODUCTION)
+@ConditionalOnExpression("#{!environment.acceptsProfiles('" + Constants.SPRING_PROFILE_NO_SWAGGER + "') && !environment.acceptsProfiles('" + Constants.SPRING_PROFILE_PRODUCTION + "')}")
public class SwaggerConfiguration {
private final Logger log = LoggerFactory.getLogger(SwaggerConfiguration.class);
@@ -35,29 +37,36 @@ public class SwaggerConfiguration {
/**
* Swagger Springfox configuration.
+ *
+ * @param jHipsterProperties the properties of the application
+ * @return the Swagger Springfox configuration
*/
@Bean
- @Profile("!" + Constants.SPRING_PROFILE_FAST)
public Docket swaggerSpringfoxDocket(JHipsterProperties jHipsterProperties) {
log.debug("Starting Swagger");
StopWatch watch = new StopWatch();
watch.start();
+ Contact contact = new Contact(
+ jHipsterProperties.getSwagger().getContactName(),
+ jHipsterProperties.getSwagger().getContactUrl(),
+ jHipsterProperties.getSwagger().getContactEmail());
+
ApiInfo apiInfo = new ApiInfo(
jHipsterProperties.getSwagger().getTitle(),
jHipsterProperties.getSwagger().getDescription(),
jHipsterProperties.getSwagger().getVersion(),
jHipsterProperties.getSwagger().getTermsOfServiceUrl(),
- jHipsterProperties.getSwagger().getContact(),
+ contact,
jHipsterProperties.getSwagger().getLicense(),
jHipsterProperties.getSwagger().getLicenseUrl());
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
- .genericModelSubstitutes(ResponseEntity.class)
.forCodeGeneration(true)
.genericModelSubstitutes(ResponseEntity.class)
.ignoredParameterTypes(Pageable.class)
- .directModelSubstitute(java.time.LocalDate.class, String.class)
+ .ignoredParameterTypes(java.sql.Date.class)
+ .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
.directModelSubstitute(java.time.LocalDateTime.class, Date.class)
.select()
diff --git a/src/main/java/com/mycompany/myapp/config/liquibase/AsyncSpringLiquibase.java b/src/main/java/com/mycompany/myapp/config/liquibase/AsyncSpringLiquibase.java
index c932d22e3..41fed7c84 100644
--- a/src/main/java/com/mycompany/myapp/config/liquibase/AsyncSpringLiquibase.java
+++ b/src/main/java/com/mycompany/myapp/config/liquibase/AsyncSpringLiquibase.java
@@ -16,7 +16,7 @@
/**
* Specific liquibase.integration.spring.SpringLiquibase that will update the database asynchronously.
*
- * By default, this asynchronous version only works when using the "dev" profile.
+ * 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
@@ -27,7 +27,6 @@
*
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 {
@@ -42,18 +41,22 @@ public class AsyncSpringLiquibase extends SpringLiquibase {
@Override
public void afterPropertiesSet() throws LiquibaseException {
- if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT, Constants.SPRING_PROFILE_HEROKU)) {
- 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);
- }
- });
+ if (!env.acceptsProfiles(Constants.SPRING_PROFILE_NO_LIQUIBASE)) {
+ if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT, Constants.SPRING_PROFILE_HEROKU)) {
+ 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();
+ }
} else {
- log.debug("Starting Liquibase synchronously");
- initDb();
+ log.debug("Liquibase is disabled");
}
}
diff --git a/src/main/java/com/mycompany/myapp/domain/AbstractAuditingEntity.java b/src/main/java/com/mycompany/myapp/domain/AbstractAuditingEntity.java
index 65e75f7fd..28d6857b3 100644
--- a/src/main/java/com/mycompany/myapp/domain/AbstractAuditingEntity.java
+++ b/src/main/java/com/mycompany/myapp/domain/AbstractAuditingEntity.java
@@ -28,13 +28,11 @@ public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
- @NotNull
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
@JsonIgnore
private String createdBy;
@CreatedDate
- @NotNull
@Column(name = "created_date", nullable = false)
@JsonIgnore
private ZonedDateTime createdDate = ZonedDateTime.now();
diff --git a/src/main/java/com/mycompany/myapp/domain/Authority.java b/src/main/java/com/mycompany/myapp/domain/Authority.java
index 796ca480d..251fa2703 100644
--- a/src/main/java/com/mycompany/myapp/domain/Authority.java
+++ b/src/main/java/com/mycompany/myapp/domain/Authority.java
@@ -18,6 +18,8 @@
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Authority implements Serializable {
+ private static final long serialVersionUID = 1L;
+
@NotNull
@Size(min = 0, max = 50)
@Id
diff --git a/src/main/java/com/mycompany/myapp/domain/BankAccount.java b/src/main/java/com/mycompany/myapp/domain/BankAccount.java
index 31670bf80..16a181f4c 100644
--- a/src/main/java/com/mycompany/myapp/domain/BankAccount.java
+++ b/src/main/java/com/mycompany/myapp/domain/BankAccount.java
@@ -20,6 +20,8 @@
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class BankAccount implements Serializable {
+ private static final long serialVersionUID = 1L;
+
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@@ -27,13 +29,12 @@ public class BankAccount implements Serializable {
@NotNull
@Column(name = "name", nullable = false)
private String name;
-
+
@NotNull
@Column(name = "balance", precision=10, scale=2, nullable = false)
private BigDecimal balance;
-
+
@ManyToOne
- @JoinColumn(name = "user_id")
private User user;
@OneToMany(mappedBy = "bankAccount")
@@ -52,7 +53,7 @@ public void setId(Long id) {
public String getName() {
return name;
}
-
+
public void setName(String name) {
this.name = name;
}
@@ -60,7 +61,7 @@ public void setName(String name) {
public BigDecimal getBalance() {
return balance;
}
-
+
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
diff --git a/src/main/java/com/mycompany/myapp/domain/Label.java b/src/main/java/com/mycompany/myapp/domain/Label.java
index 69ae9f154..fad09d17e 100644
--- a/src/main/java/com/mycompany/myapp/domain/Label.java
+++ b/src/main/java/com/mycompany/myapp/domain/Label.java
@@ -19,6 +19,8 @@
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Label implements Serializable {
+ private static final long serialVersionUID = 1L;
+
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@@ -27,7 +29,7 @@ public class Label implements Serializable {
@Size(min = 3)
@Column(name = "label", nullable = false)
private String label;
-
+
@ManyToMany(mappedBy = "labels")
@JsonIgnore
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@@ -44,7 +46,7 @@ public void setId(Long id) {
public String getLabel() {
return label;
}
-
+
public void setLabel(String label) {
this.label = label;
}
diff --git a/src/main/java/com/mycompany/myapp/domain/Operation.java b/src/main/java/com/mycompany/myapp/domain/Operation.java
index efe7cef51..c5e7570b0 100644
--- a/src/main/java/com/mycompany/myapp/domain/Operation.java
+++ b/src/main/java/com/mycompany/myapp/domain/Operation.java
@@ -2,12 +2,12 @@
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
-import java.time.ZonedDateTime;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.math.BigDecimal;
+import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
@@ -20,6 +20,8 @@
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Operation implements Serializable {
+ private static final long serialVersionUID = 1L;
+
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@@ -27,16 +29,15 @@ public class Operation implements Serializable {
@NotNull
@Column(name = "date", nullable = false)
private ZonedDateTime date;
-
+
@Column(name = "description")
private String description;
-
+
@NotNull
@Column(name = "amount", precision=10, scale=2, nullable = false)
private BigDecimal amount;
-
+
@ManyToOne
- @JoinColumn(name = "bank_account_id")
private BankAccount bankAccount;
@ManyToMany
@@ -57,7 +58,7 @@ public void setId(Long id) {
public ZonedDateTime getDate() {
return date;
}
-
+
public void setDate(ZonedDateTime date) {
this.date = date;
}
@@ -65,7 +66,7 @@ public void setDate(ZonedDateTime date) {
public String getDescription() {
return description;
}
-
+
public void setDescription(String description) {
this.description = description;
}
@@ -73,7 +74,7 @@ public void setDescription(String description) {
public BigDecimal getAmount() {
return amount;
}
-
+
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
diff --git a/src/main/java/com/mycompany/myapp/domain/PersistentToken.java b/src/main/java/com/mycompany/myapp/domain/PersistentToken.java
index 86dd023ae..6ebc196d2 100644
--- a/src/main/java/com/mycompany/myapp/domain/PersistentToken.java
+++ b/src/main/java/com/mycompany/myapp/domain/PersistentToken.java
@@ -22,10 +22,9 @@
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class PersistentToken implements Serializable {
-
+ private static final long serialVersionUID = 1L;
+
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("d MMMM yyyy");
-
-
private static final int MAX_USER_AGENT_LEN = 255;
diff --git a/src/main/java/com/mycompany/myapp/domain/User.java b/src/main/java/com/mycompany/myapp/domain/User.java
index f86173989..a86e77379 100644
--- a/src/main/java/com/mycompany/myapp/domain/User.java
+++ b/src/main/java/com/mycompany/myapp/domain/User.java
@@ -22,6 +22,8 @@
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
+ private static final long serialVersionUID = 1L;
+
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@@ -46,11 +48,13 @@ public class User extends AbstractAuditingEntity implements Serializable {
@Column(name = "last_name", length = 50)
private String lastName;
+ @NotNull
@Email
@Size(max = 100)
@Column(length = 100, unique = true)
private String email;
+ @NotNull
@Column(nullable = false)
private boolean activated = false;
diff --git a/src/main/java/com/mycompany/myapp/domain/util/JSR310DateTimeSerializer.java b/src/main/java/com/mycompany/myapp/domain/util/JSR310DateTimeSerializer.java
index 4becb6338..ddcbe0215 100644
--- a/src/main/java/com/mycompany/myapp/domain/util/JSR310DateTimeSerializer.java
+++ b/src/main/java/com/mycompany/myapp/domain/util/JSR310DateTimeSerializer.java
@@ -12,7 +12,7 @@
public final class JSR310DateTimeSerializer extends JsonSerializer {
private static final DateTimeFormatter ISOFormatter =
- DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Z"));
+ DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneId.of("Z"));
public static final JSR310DateTimeSerializer INSTANCE = new JSR310DateTimeSerializer();
diff --git a/src/main/java/com/mycompany/myapp/repository/CustomAuditEventRepository.java b/src/main/java/com/mycompany/myapp/repository/CustomAuditEventRepository.java
index 7da8cd308..f34eb4b48 100644
--- a/src/main/java/com/mycompany/myapp/repository/CustomAuditEventRepository.java
+++ b/src/main/java/com/mycompany/myapp/repository/CustomAuditEventRepository.java
@@ -5,7 +5,6 @@
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository;
-import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@@ -18,54 +17,48 @@
import java.util.List;
/**
- * Wraps an implementation of Spring Boot's AuditEventRepository.
+ * An implementation of Spring Boot's AuditEventRepository.
*/
@Repository
-public class CustomAuditEventRepository {
+public class CustomAuditEventRepository implements AuditEventRepository {
- @Inject
- private PersistenceAuditEventRepository persistenceAuditEventRepository;
+ private static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE";
- @Bean
- public AuditEventRepository auditEventRepository() {
- return new AuditEventRepository() {
+ private static final String ANONYMOUS_USER = "anonymousUser";
- private static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE";
-
- private static final String ANONYMOUS_USER = "anonymousUser";
+ @Inject
+ private PersistenceAuditEventRepository persistenceAuditEventRepository;
- @Inject
- private AuditEventConverter auditEventConverter;
+ @Inject
+ private AuditEventConverter auditEventConverter;
- @Override
- public List find(String principal, Date after) {
- Iterable persistentAuditEvents;
- if (principal == null && after == null) {
- persistentAuditEvents = persistenceAuditEventRepository.findAll();
- } else if (after == null) {
- persistentAuditEvents = persistenceAuditEventRepository.findByPrincipal(principal);
- } else {
- persistentAuditEvents =
- persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfter(principal, LocalDateTime.from(after.toInstant()));
- }
- return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
- }
+ @Override
+ public List find(String principal, Date after) {
+ Iterable persistentAuditEvents;
+ if (principal == null && after == null) {
+ persistentAuditEvents = persistenceAuditEventRepository.findAll();
+ } else if (after == null) {
+ persistentAuditEvents = persistenceAuditEventRepository.findByPrincipal(principal);
+ } else {
+ persistentAuditEvents =
+ persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfter(principal, LocalDateTime.from(after.toInstant()));
+ }
+ return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
+ }
- @Override
- @Transactional(propagation = Propagation.REQUIRES_NEW)
- public void add(AuditEvent event) {
- if (!AUTHORIZATION_FAILURE.equals(event.getType()) &&
- !ANONYMOUS_USER.equals(event.getPrincipal().toString())) {
+ @Override
+ @Transactional(propagation = Propagation.REQUIRES_NEW)
+ public void add(AuditEvent event) {
+ if (!AUTHORIZATION_FAILURE.equals(event.getType()) &&
+ !ANONYMOUS_USER.equals(event.getPrincipal().toString())) {
- PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
- persistentAuditEvent.setPrincipal(event.getPrincipal());
- persistentAuditEvent.setAuditEventType(event.getType());
- Instant instant = Instant.ofEpochMilli(event.getTimestamp().getTime());
- persistentAuditEvent.setAuditEventDate(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
- persistentAuditEvent.setData(auditEventConverter.convertDataToStrings(event.getData()));
- persistenceAuditEventRepository.save(persistentAuditEvent);
- }
- }
- };
+ PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
+ persistentAuditEvent.setPrincipal(event.getPrincipal());
+ persistentAuditEvent.setAuditEventType(event.getType());
+ 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/com/mycompany/myapp/repository/PersistenceAuditEventRepository.java b/src/main/java/com/mycompany/myapp/repository/PersistenceAuditEventRepository.java
index c87393046..05582531c 100644
--- a/src/main/java/com/mycompany/myapp/repository/PersistenceAuditEventRepository.java
+++ b/src/main/java/com/mycompany/myapp/repository/PersistenceAuditEventRepository.java
@@ -4,6 +4,8 @@
import java.time.LocalDateTime;
import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
import java.util.List;
@@ -16,5 +18,5 @@ public interface PersistenceAuditEventRepository extends JpaRepository findByPrincipalAndAuditEventDateAfter(String principal, LocalDateTime after);
- List findAllByAuditEventDateBetween(LocalDateTime fromDate, LocalDateTime toDate);
+ Page findAllByAuditEventDateBetween(LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable);
}
diff --git a/src/main/java/com/mycompany/myapp/security/CustomPersistentRememberMeServices.java b/src/main/java/com/mycompany/myapp/security/CustomPersistentRememberMeServices.java
index 7e971c5ea..dbceb3da2 100644
--- a/src/main/java/com/mycompany/myapp/security/CustomPersistentRememberMeServices.java
+++ b/src/main/java/com/mycompany/myapp/security/CustomPersistentRememberMeServices.java
@@ -4,6 +4,7 @@
import com.mycompany.myapp.domain.User;
import com.mycompany.myapp.repository.PersistentTokenRepository;
import com.mycompany.myapp.repository.UserRepository;
+import com.mycompany.myapp.config.JHipsterProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
@@ -25,9 +26,9 @@
/**
* Custom implementation of Spring Security's RememberMeServices.
- *
+ *
* Persistent tokens are used by Spring Security to automatically log in users.
- *
+ *
* This is a specific implementation of Spring Security's remember-me authentication, but it is much
* more powerful than the standard implementations:
*
@@ -35,17 +36,16 @@
*
It stores more information, such as the IP address and the user agent, for audit purposes
*
When a user logs out, only his current session is invalidated, and not all of his sessions
* The main algorithm comes from Spring Security's PersistentTokenBasedRememberMeServices, but this class
* couldn't be cleanly extended.
- *
*/
@Service
public class CustomPersistentRememberMeServices extends
@@ -71,15 +71,14 @@ public class CustomPersistentRememberMeServices extends
private UserRepository userRepository;
@Inject
- public CustomPersistentRememberMeServices(Environment env, org.springframework.security.core.userdetails
+ public CustomPersistentRememberMeServices(JHipsterProperties jHipsterProperties, org.springframework.security.core.userdetails
.UserDetailsService userDetailsService) {
- super(env.getProperty("jhipster.security.rememberme.key"), userDetailsService);
+ super(jHipsterProperties.getSecurity().getRememberMe().getKey(), userDetailsService);
random = new SecureRandom();
}
@Override
- @Transactional
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request,
HttpServletResponse response) {
@@ -129,7 +128,7 @@ protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse re
/**
* When logout occurs, only invalidate the current token, and not all user sessions.
- *
+ *
* The standard Spring Security implementations are too basic: they invalidate all tokens for the
* current user, so when he logs out from one browser, all his other sessions are destroyed.
*/
diff --git a/src/main/java/com/mycompany/myapp/security/SecurityUtils.java b/src/main/java/com/mycompany/myapp/security/SecurityUtils.java
index 752a3a0de..a93352f06 100644
--- a/src/main/java/com/mycompany/myapp/security/SecurityUtils.java
+++ b/src/main/java/com/mycompany/myapp/security/SecurityUtils.java
@@ -5,7 +5,6 @@
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
@@ -20,6 +19,8 @@ private SecurityUtils() {
/**
* Get the login of the current user.
+ *
+ * @return the login of the current user
*/
public static String getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
@@ -54,27 +55,13 @@ public static boolean isAuthenticated() {
return true;
}
- /**
- * Return the current user, or throws an exception, if the user is not
- * authenticated yet.
- *
- * @return the current user
- */
- public static User getCurrentUser() {
- SecurityContext securityContext = SecurityContextHolder.getContext();
- Authentication authentication = securityContext.getAuthentication();
- if (authentication != null) {
- if (authentication.getPrincipal() instanceof User) {
- return (User) 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
+ *
+ * @param authority the authorithy to check
+ * @return true if the current user has the authority, false otherwise
*/
public static boolean isCurrentUserInRole(String authority) {
SecurityContext securityContext = SecurityContextHolder.getContext();
diff --git a/src/main/java/com/mycompany/myapp/service/AuditEventService.java b/src/main/java/com/mycompany/myapp/service/AuditEventService.java
index 948d9afad..6419a54fc 100644
--- a/src/main/java/com/mycompany/myapp/service/AuditEventService.java
+++ b/src/main/java/com/mycompany/myapp/service/AuditEventService.java
@@ -1,10 +1,11 @@
package com.mycompany.myapp.service;
import com.mycompany.myapp.config.audit.AuditEventConverter;
-import com.mycompany.myapp.domain.PersistentAuditEvent;
import com.mycompany.myapp.repository.PersistenceAuditEventRepository;
import java.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -14,7 +15,6 @@
/**
* Service for managing audit events.
- *
*
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
*
@@ -36,15 +36,14 @@ public AuditEventService(
this.auditEventConverter = auditEventConverter;
}
- public List findAll() {
- return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
+ public Page findAll(Pageable pageable) {
+ return persistenceAuditEventRepository.findAll(pageable)
+ .map(persistentAuditEvents -> auditEventConverter.convertToAuditEvent(persistentAuditEvents));
}
- public List findByDates(LocalDateTime fromDate, LocalDateTime toDate) {
- List persistentAuditEvents =
- persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate);
-
- return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
+ public Page findByDates(LocalDateTime fromDate, LocalDateTime toDate, Pageable pageable) {
+ return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable)
+ .map(persistentAuditEvents -> auditEventConverter.convertToAuditEvent(persistentAuditEvents));
}
public Optional find(Long id) {
diff --git a/src/main/java/com/mycompany/myapp/service/MailService.java b/src/main/java/com/mycompany/myapp/service/MailService.java
index a51cf48a3..4ce2b3f3d 100644
--- a/src/main/java/com/mycompany/myapp/service/MailService.java
+++ b/src/main/java/com/mycompany/myapp/service/MailService.java
@@ -22,7 +22,6 @@
/**
* Service for sending e-mails.
- *
*
* We use the @Async annotation to send e-mails asynchronously.
*
diff --git a/src/main/java/com/mycompany/myapp/service/UserService.java b/src/main/java/com/mycompany/myapp/service/UserService.java
index 2e560e023..f4c393e52 100644
--- a/src/main/java/com/mycompany/myapp/service/UserService.java
+++ b/src/main/java/com/mycompany/myapp/service/UserService.java
@@ -31,12 +31,14 @@ public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
+
@Inject
private PasswordEncoder passwordEncoder;
@Inject
private UserRepository userRepository;
+
@Inject
private PersistentTokenRepository persistentTokenRepository;
@@ -45,7 +47,7 @@ public class UserService {
public Optional activateRegistration(String key) {
log.debug("Activating user for activation key {}", key);
- userRepository.findOneByActivationKey(key)
+ return userRepository.findOneByActivationKey(key)
.map(user -> {
// activate given user for the registration key.
user.setActivated(true);
@@ -54,7 +56,6 @@ public Optional activateRegistration(String key) {
log.debug("Activated user: {}", user);
return user;
});
- return Optional.empty();
}
public Optional completePasswordReset(String newPassword, String key) {
@@ -117,7 +118,7 @@ public User createUser(ManagedUserDTO managedUserDTO) {
user.setLastName(managedUserDTO.getLastName());
user.setEmail(managedUserDTO.getEmail());
if (managedUserDTO.getLangKey() == null) {
- user.setLangKey("en"); // default language is English
+ user.setLangKey("en"); // default language
} else {
user.setLangKey(managedUserDTO.getLangKey());
}
@@ -139,7 +140,7 @@ public User createUser(ManagedUserDTO managedUserDTO) {
}
public void updateUserInformation(String firstName, String lastName, String email, String langKey) {
- userRepository.findOneByLogin(SecurityUtils.getCurrentUser().getUsername()).ifPresent(u -> {
+ userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(u -> {
u.setFirstName(firstName);
u.setLastName(lastName);
u.setEmail(email);
@@ -157,7 +158,7 @@ public void deleteUserInformation(String login) {
}
public void changePassword(String password) {
- userRepository.findOneByLogin(SecurityUtils.getCurrentUser().getUsername()).ifPresent(u -> {
+ userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(u -> {
String encryptedPassword = passwordEncoder.encode(password);
u.setPassword(encryptedPassword);
userRepository.save(u);
@@ -182,7 +183,7 @@ public User getUserWithAuthorities(Long id) {
@Transactional(readOnly = true)
public User getUserWithAuthorities() {
- User user = userRepository.findOneByLogin(SecurityUtils.getCurrentUser().getUsername()).get();
+ User user = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).get();
user.getAuthorities().size(); // eagerly load the association
return user;
}
@@ -190,7 +191,6 @@ public User getUserWithAuthorities() {
/**
* Persistent Token are used for providing automatic authentication, they should be automatically deleted after
* 30 days.
- *
*
* This is scheduled to get fired everyday, at midnight.
*
@@ -208,7 +208,6 @@ public void removeOldPersistentTokens() {
/**
* Not activated users should be automatically deleted after 3 days.
- *
*
* This is scheduled to get fired everyday, at 01:00 (am).
*
diff --git a/src/main/java/com/mycompany/myapp/web/filter/CachingHttpHeadersFilter.java b/src/main/java/com/mycompany/myapp/web/filter/CachingHttpHeadersFilter.java
index 85022cb66..79c76e587 100644
--- a/src/main/java/com/mycompany/myapp/web/filter/CachingHttpHeadersFilter.java
+++ b/src/main/java/com/mycompany/myapp/web/filter/CachingHttpHeadersFilter.java
@@ -1,6 +1,6 @@
package com.mycompany.myapp.web.filter;
-import org.springframework.core.env.Environment;
+import com.mycompany.myapp.config.JHipsterProperties;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
@@ -15,18 +15,17 @@ public class CachingHttpHeadersFilter implements Filter {
// We consider the last modified date is the start up time of the server
private final static long LAST_MODIFIED = System.currentTimeMillis();
- private long CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(31L);
+ private long CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(1461L);
- private Environment env;
+ private JHipsterProperties jHipsterProperties;;
- public CachingHttpHeadersFilter(Environment env) {
- this.env = env;
+ public CachingHttpHeadersFilter(JHipsterProperties jHipsterProperties) {
+ this.jHipsterProperties = jHipsterProperties;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
- CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(env.getProperty("jhipster.http.cache.timeToLiveInDays",
- Long.class, 31L));
+ CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(jHipsterProperties.getHttp().getCache().getTimeToLiveInDays());
}
@Override
diff --git a/src/main/java/com/mycompany/myapp/web/filter/StaticResourcesProductionFilter.java b/src/main/java/com/mycompany/myapp/web/filter/StaticResourcesProductionFilter.java
deleted file mode 100644
index ee5f9a994..000000000
--- a/src/main/java/com/mycompany/myapp/web/filter/StaticResourcesProductionFilter.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.mycompany.myapp.web.filter;
-
-
-import org.apache.commons.lang.StringUtils;
-
-import javax.servlet.*;
-import javax.servlet.http.HttpServletRequest;
-import java.io.IOException;
-
-/**
- * This filter is used in production, to serve static resources generated by "grunt build".
- *
- *
- * It is configured to serve resources from the "dist" directory, which is the Grunt
- * destination directory.
- *
- */
-public class StaticResourcesProductionFilter implements Filter {
-
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- // Nothing to initialize
- }
-
- @Override
- public void destroy() {
- // Nothing to destroy
- }
-
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- HttpServletRequest httpRequest = (HttpServletRequest) request;
- String contextPath = ((HttpServletRequest) request).getContextPath();
- String requestURI = httpRequest.getRequestURI();
- requestURI = StringUtils.substringAfter(requestURI, contextPath);
- if (StringUtils.equals("/", requestURI)) {
- requestURI = "/index.html";
- }
- String newURI = "/dist" + requestURI;
- request.getRequestDispatcher(newURI).forward(request, response);
- }
-}
diff --git a/src/main/java/com/mycompany/myapp/web/rest/AccountResource.java b/src/main/java/com/mycompany/myapp/web/rest/AccountResource.java
index 8c1b77c53..e8b6ad2a2 100644
--- a/src/main/java/com/mycompany/myapp/web/rest/AccountResource.java
+++ b/src/main/java/com/mycompany/myapp/web/rest/AccountResource.java
@@ -16,6 +16,7 @@
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -50,17 +51,25 @@ public class AccountResource {
private MailService mailService;
/**
- * POST /register -> register the user.
+ * POST /register : register the user.
+ *
+ * @param userDTO the user DTO
+ * @param request the HTTP request
+ * @return the ResponseEntity with status 201 (Created) if the user is registred or 400 (Bad Request) if the login or e-mail is already in use
*/
@RequestMapping(value = "/register",
- method = RequestMethod.POST,
- produces = MediaType.TEXT_PLAIN_VALUE)
+ method = RequestMethod.POST,
+ produces={MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE})
@Timed
public ResponseEntity> registerAccount(@Valid @RequestBody UserDTO userDTO, HttpServletRequest request) {
+
+ HttpHeaders textPlainHeaders = new HttpHeaders();
+ textPlainHeaders.setContentType(MediaType.TEXT_PLAIN);
+
return userRepository.findOneByLogin(userDTO.getLogin())
- .map(user -> new ResponseEntity<>("login already in use", HttpStatus.BAD_REQUEST))
+ .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
.orElseGet(() -> userRepository.findOneByEmail(userDTO.getEmail())
- .map(user -> new ResponseEntity<>("e-mail address already in use", HttpStatus.BAD_REQUEST))
+ .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
.orElseGet(() -> {
User user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(),
userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(),
@@ -79,20 +88,26 @@ public ResponseEntity> registerAccount(@Valid @RequestBody UserDTO userDTO, Ht
}
/**
- * GET /activate -> activate the registered user.
+ * GET /activate : activate the registered user.
+ *
+ * @param key the activation key
+ * @return the ResponseEntity with status 200 (OK) and the activated user in body, or status 500 (Internal Server Error) if the user couldn't be activated
*/
@RequestMapping(value = "/activate",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity activateAccount(@RequestParam(value = "key") String key) {
- return Optional.ofNullable(userService.activateRegistration(key))
+ return userService.activateRegistration(key)
.map(user -> new ResponseEntity(HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
}
/**
- * GET /authenticate -> check if the user is authenticated, and return its login.
+ * GET /authenticate : check if the user is authenticated, and return its login.
+ *
+ * @param request the HTTP request
+ * @return the login if the user is authenticated
*/
@RequestMapping(value = "/authenticate",
method = RequestMethod.GET,
@@ -104,7 +119,9 @@ public String isAuthenticated(HttpServletRequest request) {
}
/**
- * GET /account -> get the current user.
+ * GET /account : get the current user.
+ *
+ * @return the ResponseEntity with status 200 (OK) and the current user in body, or status 500 (Internal Server Error) if the user couldn't be returned
*/
@RequestMapping(value = "/account",
method = RequestMethod.GET,
@@ -117,7 +134,10 @@ public ResponseEntity getAccount() {
}
/**
- * POST /account -> update the current user information.
+ * POST /account : update the current user information.
+ *
+ * @param userDTO the current user information
+ * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) or 500 (Internal Server Error) if the user couldn't be updated
*/
@RequestMapping(value = "/account",
method = RequestMethod.POST,
@@ -129,7 +149,7 @@ public ResponseEntity saveAccount(@RequestBody UserDTO userDTO) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("user-management", "emailexists", "Email already in use")).body(null);
}
return userRepository
- .findOneByLogin(SecurityUtils.getCurrentUser().getUsername())
+ .findOneByLogin(SecurityUtils.getCurrentUserLogin())
.map(u -> {
userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(),
userDTO.getLangKey());
@@ -139,11 +159,14 @@ public ResponseEntity saveAccount(@RequestBody UserDTO userDTO) {
}
/**
- * POST /change_password -> changes the current user's password
+ * POST /account/change_password : changes the current user's password
+ *
+ * @param password the new password
+ * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) if the new password is not strong enough
*/
@RequestMapping(value = "/account/change_password",
method = RequestMethod.POST,
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity> changePassword(@RequestBody String password) {
if (!checkPasswordLength(password)) {
@@ -154,14 +177,17 @@ public ResponseEntity> changePassword(@RequestBody String password) {
}
/**
- * GET /account/sessions -> get the current open sessions.
+ * GET /account/sessions : get the current open sessions.
+ *
+ * @return the ResponseEntity with status 200 (OK) and the current open sessions in body,
+ * or status 500 (Internal Server Error) if the current open sessions couldn't be retrieved
*/
@RequestMapping(value = "/account/sessions",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity> getCurrentSessions() {
- return userRepository.findOneByLogin(SecurityUtils.getCurrentUser().getUsername())
+ return userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin())
.map(user -> new ResponseEntity<>(
persistentTokenRepository.findByUser(user),
HttpStatus.OK))
@@ -169,7 +195,7 @@ public ResponseEntity> getCurrentSessions() {
}
/**
- * DELETE /account/sessions?series={series} -> invalidate an existing session.
+ * DELETE /account/sessions?series={series} : invalidate an existing session.
*
* - You can only delete your own sessions, not any other user's session
* - If you delete one of your existing sessions, and that you are currently logged in on that session, you will
@@ -180,19 +206,29 @@ public ResponseEntity> getCurrentSessions() {
* anymore.
* There is an API to invalidate the current session, but there is no API to check which session uses which
* cookie.
+ *
+ * @param series the series of an existing session
+ * @throws UnsupportedEncodingException if the series couldnt be URL decoded
*/
@RequestMapping(value = "/account/sessions/{series}",
method = RequestMethod.DELETE)
@Timed
public void invalidateSession(@PathVariable String series) throws UnsupportedEncodingException {
String decodedSeries = URLDecoder.decode(series, "UTF-8");
- userRepository.findOneByLogin(SecurityUtils.getCurrentUser().getUsername()).ifPresent(u -> {
+ userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(u -> {
persistentTokenRepository.findByUser(u).stream()
.filter(persistentToken -> StringUtils.equals(persistentToken.getSeries(), decodedSeries))
.findAny().ifPresent(t -> persistentTokenRepository.delete(decodedSeries));
});
}
+ /**
+ * POST /account/reset_password/init : Send an e-mail to reset the password of the user
+ *
+ * @param mail the mail of the user
+ * @param request the HTTP request
+ * @return the ResponseEntity with status 200 (OK) if the e-mail was sent, or status 400 (Bad Request) if the e-mail address is not registred
+ */
@RequestMapping(value = "/account/reset_password/init",
method = RequestMethod.POST,
produces = MediaType.TEXT_PLAIN_VALUE)
@@ -211,16 +247,24 @@ public ResponseEntity> requestPasswordReset(@RequestBody String mail, HttpServ
}).orElse(new ResponseEntity<>("e-mail address not registered", HttpStatus.BAD_REQUEST));
}
+ /**
+ * POST /account/reset_password/finish : Finish to reset the password of the user
+ *
+ * @param keyAndPassword the generated key and the new password
+ * @return the ResponseEntity with status 200 (OK) if the password has been reset,
+ * or status 400 (Bad Request) or 500 (Internal Server Error) if the password could not be reset
+ */
@RequestMapping(value = "/account/reset_password/finish",
method = RequestMethod.POST,
- produces = MediaType.APPLICATION_JSON_VALUE)
+ produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity finishPasswordReset(@RequestBody KeyAndPasswordDTO keyAndPassword) {
if (!checkPasswordLength(keyAndPassword.getNewPassword())) {
return new ResponseEntity<>("Incorrect password", HttpStatus.BAD_REQUEST);
}
return userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey())
- .map(user -> new ResponseEntity(HttpStatus.OK)).orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
+ .map(user -> new ResponseEntity(HttpStatus.OK))
+ .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
}
private boolean checkPasswordLength(String password) {
diff --git a/src/main/java/com/mycompany/myapp/web/rest/AuditResource.java b/src/main/java/com/mycompany/myapp/web/rest/AuditResource.java
index 1dbccb5fc..dd45cc94d 100644
--- a/src/main/java/com/mycompany/myapp/web/rest/AuditResource.java
+++ b/src/main/java/com/mycompany/myapp/web/rest/AuditResource.java
@@ -3,13 +3,18 @@
import com.mycompany.myapp.service.AuditEventService;
import java.time.LocalDate;
+import com.mycompany.myapp.web.rest.util.PaginationUtil;
import org.springframework.boot.actuate.audit.AuditEvent;
+import org.springframework.data.domain.Page;
+import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
+import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
+import java.net.URISyntaxException;
import javax.inject.Inject;
import java.util.List;
@@ -27,20 +32,48 @@ public AuditResource(AuditEventService auditEventService) {
this.auditEventService = auditEventService;
}
+ /**
+ * GET /audits : get a page of AuditEvents.
+ *
+ * @param pageable the pagination information
+ * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
+ * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
+ */
@RequestMapping(method = RequestMethod.GET)
- public List getAll() {
- return auditEventService.findAll();
+ public ResponseEntity> getAll(Pageable pageable) throws URISyntaxException {
+ Page page = auditEventService.findAll(pageable);
+ HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/audits");
+ return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
+ /**
+ * GET /audits : get a page of AuditEvents between the fromDate and toDate.
+ *
+ * @param fromDate the start of the time period of AuditEvents to get
+ * @param toDate the end of the time period of AuditEvents to get
+ * @param pageable the pagination information
+ * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
+ * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
+ */
+
@RequestMapping(method = RequestMethod.GET,
params = {"fromDate", "toDate"})
- public List getByDates(
+ public ResponseEntity> getByDates(
@RequestParam(value = "fromDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate fromDate,
- @RequestParam(value = "toDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate) {
+ @RequestParam(value = "toDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate toDate,
+ Pageable pageable) throws URISyntaxException {
- return auditEventService.findByDates(fromDate.atTime(0, 0), toDate.atTime(23, 59));
+ Page page = auditEventService.findByDates(fromDate.atTime(0, 0), toDate.atTime(23, 59), pageable);
+ HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/audits");
+ return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
+ /**
+ * GET /audits/:id : get an AuditEvent by id.
+ *
+ * @param id the id of the entity to get
+ * @return the ResponseEntity with status 200 (OK) and the AuditEvent in body, or status 404 (Not Found)
+ */
@RequestMapping(value = "/{id:.+}",
method = RequestMethod.GET)
public ResponseEntity get(@PathVariable Long id) {
diff --git a/src/main/java/com/mycompany/myapp/web/rest/BankAccountResource.java b/src/main/java/com/mycompany/myapp/web/rest/BankAccountResource.java
index 611ff4ea9..409256ba5 100644
--- a/src/main/java/com/mycompany/myapp/web/rest/BankAccountResource.java
+++ b/src/main/java/com/mycompany/myapp/web/rest/BankAccountResource.java
@@ -32,9 +32,13 @@ public class BankAccountResource {
private BankAccountRepository bankAccountRepository;
/**
- * POST /bankAccounts -> Create a new bankAccount.
+ * POST /bank-accounts : Create a new bankAccount.
+ *
+ * @param bankAccount the bankAccount to create
+ * @return the ResponseEntity with status 201 (Created) and with body the new bankAccount, or with status 400 (Bad Request) if the bankAccount has already an ID
+ * @throws URISyntaxException if the Location URI syntax is incorrect
*/
- @RequestMapping(value = "/bankAccounts",
+ @RequestMapping(value = "/bank-accounts",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@@ -44,15 +48,21 @@ public ResponseEntity createBankAccount(@Valid @RequestBody BankAcc
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("bankAccount", "idexists", "A new bankAccount cannot already have an ID")).body(null);
}
BankAccount result = bankAccountRepository.save(bankAccount);
- return ResponseEntity.created(new URI("/api/bankAccounts/" + result.getId()))
+ return ResponseEntity.created(new URI("/api/bank-accounts/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert("bankAccount", result.getId().toString()))
.body(result);
}
/**
- * PUT /bankAccounts -> Updates an existing bankAccount.
+ * PUT /bank-accounts : Updates an existing bankAccount.
+ *
+ * @param bankAccount the bankAccount to update
+ * @return the ResponseEntity with status 200 (OK) and with body the updated bankAccount,
+ * or with status 400 (Bad Request) if the bankAccount is not valid,
+ * or with status 500 (Internal Server Error) if the bankAccount couldnt be updated
+ * @throws URISyntaxException if the Location URI syntax is incorrect
*/
- @RequestMapping(value = "/bankAccounts",
+ @RequestMapping(value = "/bank-accounts",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@@ -68,21 +78,27 @@ public ResponseEntity updateBankAccount(@Valid @RequestBody BankAcc
}
/**
- * GET /bankAccounts -> get all the bankAccounts.
+ * GET /bank-accounts : get all the bankAccounts.
+ *
+ * @return the ResponseEntity with status 200 (OK) and the list of bankAccounts in body
*/
- @RequestMapping(value = "/bankAccounts",
+ @RequestMapping(value = "/bank-accounts",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List getAllBankAccounts() {
log.debug("REST request to get all BankAccounts");
- return bankAccountRepository.findAll();
- }
+ List bankAccounts = bankAccountRepository.findAll();
+ return bankAccounts;
+ }
/**
- * GET /bankAccounts/:id -> get the "id" bankAccount.
+ * GET /bank-accounts/:id : get the "id" bankAccount.
+ *
+ * @param id the id of the bankAccount to retrieve
+ * @return the ResponseEntity with status 200 (OK) and with body the bankAccount, or with status 404 (Not Found)
*/
- @RequestMapping(value = "/bankAccounts/{id}",
+ @RequestMapping(value = "/bank-accounts/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@@ -97,9 +113,12 @@ public ResponseEntity getBankAccount(@PathVariable Long id) {
}
/**
- * DELETE /bankAccounts/:id -> delete the "id" bankAccount.
+ * DELETE /bank-accounts/:id : delete the "id" bankAccount.
+ *
+ * @param id the id of the bankAccount to delete
+ * @return the ResponseEntity with status 200 (OK)
*/
- @RequestMapping(value = "/bankAccounts/{id}",
+ @RequestMapping(value = "/bank-accounts/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@@ -108,4 +127,5 @@ public ResponseEntity deleteBankAccount(@PathVariable Long id) {
bankAccountRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("bankAccount", id.toString())).build();
}
+
}
diff --git a/src/main/java/com/mycompany/myapp/web/rest/LabelResource.java b/src/main/java/com/mycompany/myapp/web/rest/LabelResource.java
index 76ac0e944..71301b88e 100644
--- a/src/main/java/com/mycompany/myapp/web/rest/LabelResource.java
+++ b/src/main/java/com/mycompany/myapp/web/rest/LabelResource.java
@@ -32,7 +32,11 @@ public class LabelResource {
private LabelRepository labelRepository;
/**
- * POST /labels -> Create a new label.
+ * POST /labels : Create a new label.
+ *
+ * @param label the label to create
+ * @return the ResponseEntity with status 201 (Created) and with body the new label, or with status 400 (Bad Request) if the label has already an ID
+ * @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/labels",
method = RequestMethod.POST,
@@ -50,7 +54,13 @@ public ResponseEntity