Skip to content

Commit 1d61601

Browse files
njc12345maibin
authored andcommitted
BAEL-1267 spring rest project through tomcat created in java (eugenp#2969)
* BAEL-1267 spring rest project through tomcat created in java * BAEL-1267 including empty file for webapp
1 parent bc3d331 commit 1d61601

11 files changed

Lines changed: 383 additions & 0 deletions

File tree

‎pom.xml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,8 @@
231231
<module>spring-zuul</module>
232232
<module>spring-reactor</module>
233233
<module>spring-vertx</module>
234+
235+
<module>spring-rest-embedded-tomcat</module>
234236

235237

236238
<module>testing</module>
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>org.baeldung.embedded</groupId>
5+
<artifactId>SpringRestTomcat</artifactId>
6+
<version>0.0.1-SNAPSHOT</version>
7+
8+
<name>spring-rest-embedded-tomcat</name>
9+
<packaging>war</packaging>
10+
11+
<dependencies>
12+
<dependency>
13+
<groupId>junit</groupId>
14+
<artifactId>junit</artifactId>
15+
<version>${junit.version}</version>
16+
<scope>test</scope>
17+
</dependency>
18+
19+
<dependency>
20+
<groupId>org.springframework</groupId>
21+
<artifactId>spring-core</artifactId>
22+
<version>${spring.version}</version>
23+
</dependency>
24+
<dependency>
25+
<groupId>org.springframework</groupId>
26+
<artifactId>spring-webmvc</artifactId>
27+
<version>${spring.version}</version>
28+
</dependency>
29+
30+
<dependency>
31+
<groupId>javax.servlet</groupId>
32+
<artifactId>javax.servlet-api</artifactId>
33+
<version>4.0.0</version>
34+
</dependency>
35+
36+
<dependency>
37+
<groupId>com.fasterxml.jackson.core</groupId>
38+
<artifactId>jackson-databind</artifactId>
39+
<version>${jackson.library}</version>
40+
</dependency>
41+
42+
<dependency>
43+
<groupId>org.apache.tomcat.embed</groupId>
44+
<artifactId>tomcat-embed-core</artifactId>
45+
<version>9.0.1</version>
46+
<scope>test</scope>
47+
</dependency>
48+
49+
<dependency>
50+
<groupId>org.apache.tomcat</groupId>
51+
<artifactId>tomcat-jasper</artifactId>
52+
<version>9.0.1</version>
53+
<scope>test</scope>
54+
</dependency>
55+
56+
<dependency>
57+
<groupId>org.apache.httpcomponents</groupId>
58+
<artifactId>httpclient</artifactId>
59+
<version>4.5.3</version>
60+
</dependency>
61+
62+
<dependency>
63+
<groupId>org.apache.httpcomponents</groupId>
64+
<artifactId>httpcore</artifactId>
65+
<version>4.4.8</version>
66+
</dependency>
67+
68+
</dependencies>
69+
70+
<build>
71+
<finalName>spring-rest-embedded-tomcat</finalName>
72+
</build>
73+
74+
<properties>
75+
<spring.version>5.0.1.RELEASE</spring.version>
76+
<junit.version>4.12</junit.version>
77+
<jackson.library>2.9.2</jackson.library>
78+
<maven.compiler.source>1.8</maven.compiler.source>
79+
<maven.compiler.target>1.8</maven.compiler.target>
80+
<failOnMissingWebXml>false</failOnMissingWebXml>
81+
</properties>
82+
83+
</project>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.baeldung.embedded.configuration;
2+
3+
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
4+
5+
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
6+
7+
@Override
8+
protected Class<?>[] getRootConfigClasses() {
9+
return new Class[] { UserConfiguration.class };
10+
}
11+
12+
@Override
13+
protected Class<?>[] getServletConfigClasses() {
14+
return null;
15+
}
16+
17+
@Override
18+
protected String[] getServletMappings() {
19+
return new String[] { "/" };
20+
}
21+
22+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package org.baeldung.embedded.configuration;
2+
3+
import org.springframework.context.annotation.ComponentScan;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
6+
7+
@Configuration
8+
@EnableWebMvc
9+
@ComponentScan(basePackages = "org.baeldung.embedded")
10+
public class UserConfiguration {
11+
12+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package org.baeldung.embedded.controller;
2+
3+
import org.baeldung.embedded.domain.User;
4+
import org.baeldung.embedded.service.UserService;
5+
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.web.bind.annotation.PathVariable;
7+
import org.springframework.web.bind.annotation.RequestMapping;
8+
import org.springframework.web.bind.annotation.RequestMethod;
9+
import org.springframework.web.bind.annotation.ResponseBody;
10+
import org.springframework.web.bind.annotation.RestController;
11+
12+
@RestController
13+
public class UserController {
14+
15+
@Autowired
16+
UserService userService;
17+
18+
@RequestMapping("/")
19+
public String welcome() {
20+
return "Hello World!";
21+
}
22+
23+
@RequestMapping(method = RequestMethod.GET, value = "/user/{userName}")
24+
@ResponseBody
25+
public User user(@PathVariable String userName) {
26+
return this.userService.getUser(userName);
27+
}
28+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package org.baeldung.embedded.domain;
2+
3+
public class User {
4+
5+
private String name;
6+
private String hobby;
7+
8+
public String getName() {
9+
return name;
10+
}
11+
12+
public void setName(String name) {
13+
this.name = name;
14+
}
15+
16+
public String getHobby() {
17+
return hobby;
18+
}
19+
20+
public void setHobby(String hobby) {
21+
this.hobby = hobby;
22+
}
23+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package org.baeldung.embedded.service;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
import org.baeldung.embedded.domain.User;
7+
import org.springframework.stereotype.Service;
8+
9+
@Service
10+
public class UserService {
11+
private List<User> users = new ArrayList<>();
12+
13+
public void addUser(String name) {
14+
User user = new User();
15+
user.setName(name);
16+
if (name == "HarryPotter") {
17+
user.setHobby("Quidditch");
18+
} else {
19+
user.setHobby("MuggleActivity");
20+
}
21+
users.add(user);
22+
}
23+
24+
public User getUser(String name) {
25+
for (User user : users) {
26+
if (user.getName()
27+
.equalsIgnoreCase(name)) {
28+
return user;
29+
}
30+
}
31+
32+
User user = new User();
33+
user.setName(name);
34+
user.setHobby("None");
35+
36+
return user;
37+
}
38+
}

‎spring-rest-embedded-tomcat/src/main/webapp/emptyFile‎

Whitespace-only changes.
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package org.baeldung.embedded;
2+
3+
import java.io.File;
4+
import java.util.concurrent.CountDownLatch;
5+
import org.apache.catalina.Context;
6+
import org.apache.catalina.startup.Tomcat;
7+
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
8+
import org.springframework.web.context.WebApplicationContext;
9+
import org.springframework.web.context.support.WebApplicationContextUtils;
10+
11+
public class EmbeddedTomcatApp {
12+
13+
private Tomcat tomcatInstance;
14+
private WebApplicationContext webApplicationContext;
15+
private CountDownLatch started = new CountDownLatch(1);
16+
17+
public void start() throws Exception {
18+
tomcatInstance = new Tomcat();
19+
tomcatInstance.setBaseDir(new File(getClass().getResource(".")
20+
.toURI()).getAbsolutePath()); // Tomcat's temporary directory
21+
tomcatInstance.setPort(0);
22+
23+
Context webapp = tomcatInstance.addWebapp("", new File("src/main/webapp/").getAbsolutePath());
24+
25+
webapp.addLifecycleListener(event -> {
26+
if (event.getType()
27+
.equals("after_stop")) {
28+
started.countDown();
29+
} else if (event.getType()
30+
.equals("after_start")) {
31+
webApplicationContext = WebApplicationContextUtils
32+
.findWebApplicationContext(webapp.getServletContext());
33+
34+
((ConfigurableListableBeanFactory) webApplicationContext
35+
.getAutowireCapableBeanFactory()).registerSingleton("baseUrl", getBaseUrl());
36+
37+
started.countDown();
38+
}
39+
});
40+
41+
tomcatInstance.start();
42+
started.await();
43+
}
44+
45+
public Tomcat getTomcatInstance() {
46+
return this.tomcatInstance;
47+
}
48+
49+
public String getBaseUrl() {
50+
return String.format("http://localhost:%d%s", getLocalPort(), getWebApplicationContext().getServletContext()
51+
.getContextPath());
52+
}
53+
54+
public int getLocalPort() {
55+
return tomcatInstance.getConnector()
56+
.getLocalPort();
57+
}
58+
59+
public WebApplicationContext getWebApplicationContext() {
60+
return webApplicationContext;
61+
}
62+
63+
public boolean isStarted() {
64+
return started.getCount() == 0;
65+
}
66+
67+
public boolean isStartedSucessfully() {
68+
return webApplicationContext != null;
69+
}
70+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package org.baeldung.embedded;
2+
3+
import org.junit.runner.notification.RunNotifier;
4+
import org.junit.runners.BlockJUnit4ClassRunner;
5+
import org.junit.runners.model.InitializationError;
6+
import org.junit.runners.model.Statement;
7+
8+
public class EmbeddedTomcatRunner extends BlockJUnit4ClassRunner {
9+
10+
public EmbeddedTomcatRunner(Class<?> klass) throws InitializationError {
11+
super(klass);
12+
}
13+
14+
// use one static Tomcat instance shared across all tests
15+
private static EmbeddedTomcatApp embeddedTomcatApp = new EmbeddedTomcatApp();
16+
17+
@Override
18+
protected Statement classBlock(RunNotifier notifier) {
19+
ensureSharedTomcatStarted();
20+
Statement result = super.classBlock(notifier);
21+
return result;
22+
}
23+
24+
private void ensureSharedTomcatStarted() {
25+
if (!embeddedTomcatApp.isStarted()) {
26+
try {
27+
embeddedTomcatApp.start();
28+
} catch (Exception e) {
29+
throw new RuntimeException("Error while starting embedded Tomcat server", e);
30+
}
31+
}
32+
}
33+
34+
@Override
35+
protected Object createTest() throws Exception {
36+
if (!embeddedTomcatApp.isStartedSucessfully()) {
37+
throw new RuntimeException("Tomcat server not started successfully. Skipping test");
38+
}
39+
Object testInstance = super.createTest();
40+
embeddedTomcatApp.getWebApplicationContext()
41+
.getAutowireCapableBeanFactory()
42+
.autowireBean(testInstance);
43+
return testInstance;
44+
}
45+
}

0 commit comments

Comments
 (0)