Skip to content

Commit bab6772

Browse files
committed
Main java spring boot application
1 parent 056662f commit bab6772

File tree

94 files changed

+5526
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

94 files changed

+5526
-0
lines changed

pom.xml

Lines changed: 720 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
package com.bookstore;
2+
3+
import com.bookstore.config.Constants;
4+
import org.slf4j.Logger;
5+
import org.slf4j.LoggerFactory;
6+
import org.springframework.boot.SpringApplication;
7+
import org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration;
8+
import org.springframework.boot.actuate.autoconfigure.MetricRepositoryAutoConfiguration;
9+
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
10+
import org.springframework.context.annotation.ComponentScan;
11+
import org.springframework.core.env.Environment;
12+
import org.springframework.core.env.SimpleCommandLinePropertySource;
13+
import com.google.common.base.Joiner;
14+
15+
import javax.annotation.PostConstruct;
16+
import javax.inject.Inject;
17+
import java.io.IOException;
18+
import java.net.InetAddress;
19+
import java.net.UnknownHostException;
20+
import java.util.Arrays;
21+
import java.util.Collection;
22+
23+
@ComponentScan
24+
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
25+
public class Application {
26+
27+
private static final Logger log = LoggerFactory.getLogger(Application.class);
28+
29+
@Inject
30+
private Environment env;
31+
32+
/**
33+
* Initializes bookstore.
34+
* <p/>
35+
* Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile
36+
* <p/>
37+
* <p>
38+
* You can find more information on how profiles work with JHipster on <a href="http://jhipster.github.io/profiles.html">http://jhipster.github.io/profiles.html</a>.
39+
* </p>
40+
*/
41+
@PostConstruct
42+
public void initApplication() throws IOException {
43+
if (env.getActiveProfiles().length == 0) {
44+
log.warn("No Spring profile configured, running with default configuration");
45+
} else {
46+
log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles()));
47+
Collection activeProfiles = Arrays.asList(env.getActiveProfiles());
48+
if (activeProfiles.contains("dev") && activeProfiles.contains("prod")) {
49+
log.error("You have misconfigured your application! " +
50+
"It should not run with both the 'dev' and 'prod' profiles at the same time.");
51+
}
52+
if (activeProfiles.contains("prod") && activeProfiles.contains("fast")) {
53+
log.error("You have misconfigured your application! " +
54+
"It should not run with both the 'prod' and 'fast' profiles at the same time.");
55+
}
56+
if (activeProfiles.contains("dev") && activeProfiles.contains("cloud")) {
57+
log.error("You have misconfigured your application! " +
58+
"It should not run with both the 'dev' and 'cloud' profiles at the same time.");
59+
}
60+
}
61+
}
62+
63+
/**
64+
* Main method, used to run the application.
65+
*/
66+
public static void main(String[] args) throws UnknownHostException {
67+
SpringApplication app = new SpringApplication(Application.class);
68+
app.setShowBanner(false);
69+
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
70+
addDefaultProfile(app, source);
71+
addLiquibaseScanPackages();
72+
Environment env = app.run(args).getEnvironment();
73+
log.info("Access URLs:\n----------------------------------------------------------\n\t" +
74+
"Local: \t\thttp://127.0.0.1:{}\n\t" +
75+
"External: \thttp://{}:{}\n----------------------------------------------------------",
76+
env.getProperty("server.port"),
77+
InetAddress.getLocalHost().getHostAddress(),
78+
env.getProperty("server.port"));
79+
80+
}
81+
82+
/**
83+
* If no profile has been configured, set by default the "dev" profile.
84+
*/
85+
private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) {
86+
if (!source.containsProperty("spring.profiles.active") &&
87+
!System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
88+
89+
app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT);
90+
}
91+
}
92+
93+
/**
94+
* Set the liquibases.scan.packages to avoid an exception from ServiceLocator.
95+
*/
96+
private static void addLiquibaseScanPackages() {
97+
System.setProperty("liquibase.scan.packages", Joiner.on(",").join(
98+
"liquibase.change", "liquibase.database", "liquibase.parser",
99+
"liquibase.precondition", "liquibase.datatype",
100+
"liquibase.serializer", "liquibase.sqlgenerator", "liquibase.executor",
101+
"liquibase.snapshot", "liquibase.logging", "liquibase.diff",
102+
"liquibase.structure", "liquibase.structurecompare", "liquibase.lockservice",
103+
"liquibase.ext", "liquibase.changelog"));
104+
}
105+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package com.bookstore;
2+
3+
import com.bookstore.config.Constants;
4+
import org.slf4j.Logger;
5+
import org.slf4j.LoggerFactory;
6+
import org.springframework.boot.builder.SpringApplicationBuilder;
7+
import org.springframework.boot.context.web.SpringBootServletInitializer;
8+
9+
/**
10+
* This is a helper Java class that provides an alternative to creating a web.xml.
11+
*/
12+
public class ApplicationWebXml extends SpringBootServletInitializer {
13+
14+
private final Logger log = LoggerFactory.getLogger(ApplicationWebXml.class);
15+
16+
@Override
17+
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
18+
return application.profiles(addDefaultProfile())
19+
.showBanner(false)
20+
.sources(Application.class);
21+
}
22+
23+
/**
24+
* Set a default profile if it has not been set.
25+
* <p/>
26+
* <p>
27+
* Please use -Dspring.profiles.active=dev
28+
* </p>
29+
*/
30+
private String addDefaultProfile() {
31+
String profile = System.getProperty("spring.profiles.active");
32+
if (profile != null) {
33+
log.info("Running with Spring profile(s) : {}", profile);
34+
return profile;
35+
}
36+
37+
log.warn("No Spring profile configured, running with default configuration");
38+
return Constants.SPRING_PROFILE_DEVELOPMENT;
39+
}
40+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.bookstore.aop.logging;
2+
3+
import com.bookstore.config.Constants;
4+
import org.aspectj.lang.JoinPoint;
5+
import org.aspectj.lang.ProceedingJoinPoint;
6+
import org.aspectj.lang.annotation.AfterThrowing;
7+
import org.aspectj.lang.annotation.Around;
8+
import org.aspectj.lang.annotation.Aspect;
9+
import org.aspectj.lang.annotation.Pointcut;
10+
import org.slf4j.Logger;
11+
import org.slf4j.LoggerFactory;
12+
import org.springframework.core.env.Environment;
13+
14+
import javax.inject.Inject;
15+
import java.util.Arrays;
16+
17+
/**
18+
* Aspect for logging execution of service and repository Spring components.
19+
*/
20+
@Aspect
21+
public class LoggingAspect {
22+
23+
private final Logger log = LoggerFactory.getLogger(this.getClass());
24+
25+
@Inject
26+
private Environment env;
27+
28+
@Pointcut("within(com.bookstore.repository..*) || within(com.bookstore.service..*) || within(com.bookstore.web.rest..*)")
29+
public void loggingPointcut() {}
30+
31+
@AfterThrowing(pointcut = "loggingPointcut()", throwing = "e")
32+
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
33+
if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) {
34+
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
35+
joinPoint.getSignature().getName(), e.getCause(), e);
36+
} else {
37+
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
38+
joinPoint.getSignature().getName(), e.getCause());
39+
}
40+
}
41+
42+
@Around("loggingPointcut()")
43+
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
44+
if (log.isDebugEnabled()) {
45+
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
46+
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
47+
}
48+
try {
49+
Object result = joinPoint.proceed();
50+
if (log.isDebugEnabled()) {
51+
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
52+
joinPoint.getSignature().getName(), result);
53+
}
54+
return result;
55+
} catch (IllegalArgumentException e) {
56+
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
57+
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
58+
59+
throw e;
60+
}
61+
}
62+
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package com.bookstore.async;
2+
3+
import java.util.concurrent.Callable;
4+
import java.util.concurrent.Future;
5+
6+
import org.slf4j.Logger;
7+
import org.slf4j.LoggerFactory;
8+
import org.springframework.beans.factory.DisposableBean;
9+
import org.springframework.beans.factory.InitializingBean;
10+
import org.springframework.core.task.AsyncTaskExecutor;
11+
12+
public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor,
13+
InitializingBean, DisposableBean {
14+
15+
private final Logger log = LoggerFactory.getLogger(ExceptionHandlingAsyncTaskExecutor.class);
16+
17+
private final AsyncTaskExecutor executor;
18+
19+
public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {
20+
this.executor = executor;
21+
}
22+
23+
@Override
24+
public void execute(Runnable task) {
25+
executor.execute(task);
26+
}
27+
28+
@Override
29+
public void execute(Runnable task, long startTimeout) {
30+
executor.execute(createWrappedRunnable(task), startTimeout);
31+
}
32+
33+
private <T> Callable<T> createCallable(final Callable<T> task) {
34+
return new Callable<T>() {
35+
36+
@Override
37+
public T call() throws Exception {
38+
try {
39+
return task.call();
40+
} catch (Exception e) {
41+
handle(e);
42+
throw e;
43+
}
44+
}
45+
};
46+
}
47+
48+
private Runnable createWrappedRunnable(final Runnable task) {
49+
return new Runnable() {
50+
51+
@Override
52+
public void run() {
53+
try {
54+
task.run();
55+
} catch (Exception e) {
56+
handle(e);
57+
}
58+
}
59+
};
60+
}
61+
62+
protected void handle(Exception e) {
63+
log.error("Caught async exception", e);
64+
}
65+
66+
@Override
67+
public Future<?> submit(Runnable task) {
68+
return executor.submit(createWrappedRunnable(task));
69+
}
70+
71+
@Override
72+
public <T> Future<T> submit(Callable<T> task) {
73+
return executor.submit(createCallable(task));
74+
}
75+
76+
@Override
77+
public void destroy() throws Exception {
78+
if (executor instanceof DisposableBean) {
79+
DisposableBean bean = (DisposableBean) executor;
80+
bean.destroy();
81+
}
82+
}
83+
84+
@Override
85+
public void afterPropertiesSet() throws Exception {
86+
if (executor instanceof InitializingBean) {
87+
InitializingBean bean = (InitializingBean) executor;
88+
bean.afterPropertiesSet();
89+
}
90+
}
91+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
/**
2+
* Async helpers.
3+
*/
4+
package com.bookstore.async;
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.bookstore.config;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
6+
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
7+
import org.springframework.boot.bind.RelaxedPropertyResolver;
8+
import org.springframework.context.EnvironmentAware;
9+
import org.springframework.context.annotation.Bean;
10+
import org.springframework.context.annotation.Configuration;
11+
import org.springframework.context.annotation.Profile;
12+
import org.springframework.core.env.Environment;
13+
import org.springframework.scheduling.annotation.AsyncConfigurer;
14+
import org.springframework.scheduling.annotation.EnableAsync;
15+
import org.springframework.scheduling.annotation.EnableScheduling;
16+
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
17+
18+
import java.util.concurrent.Executor;
19+
20+
import com.bookstore.async.ExceptionHandlingAsyncTaskExecutor;
21+
22+
@Configuration
23+
@EnableAsync
24+
@EnableScheduling
25+
@Profile("!" + Constants.SPRING_PROFILE_FAST)
26+
public class AsyncConfiguration implements AsyncConfigurer, EnvironmentAware {
27+
28+
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
29+
30+
private RelaxedPropertyResolver propertyResolver;
31+
32+
@Override
33+
public void setEnvironment(Environment environment) {
34+
this.propertyResolver = new RelaxedPropertyResolver(environment, "async.");
35+
}
36+
37+
@Override
38+
@Bean
39+
public Executor getAsyncExecutor() {
40+
log.debug("Creating Async Task Executor");
41+
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
42+
executor.setCorePoolSize(propertyResolver.getProperty("corePoolSize", Integer.class, 2));
43+
executor.setMaxPoolSize(propertyResolver.getProperty("maxPoolSize", Integer.class, 50));
44+
executor.setQueueCapacity(propertyResolver.getProperty("queueCapacity", Integer.class, 10000));
45+
executor.setThreadNamePrefix("bookstore-Executor-");
46+
return new ExceptionHandlingAsyncTaskExecutor(executor);
47+
}
48+
49+
@Override
50+
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
51+
return new SimpleAsyncUncaughtExceptionHandler();
52+
}
53+
}

0 commit comments

Comments
 (0)