BAEL-1267 spring rest project through tomcat created in java (#2969)

* BAEL-1267 spring rest project through tomcat created in java

* BAEL-1267 including empty file for webapp
This commit is contained in:
Nik 2017-11-07 13:47:10 +08:00 committed by maibin
parent bc3d33151c
commit 1d61601aa7
11 changed files with 383 additions and 0 deletions

View File

@ -231,6 +231,8 @@
<module>spring-zuul</module>
<module>spring-reactor</module>
<module>spring-vertx</module>
<module>spring-rest-embedded-tomcat</module>
<module>testing</module>

View File

@ -0,0 +1,83 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung.embedded</groupId>
<artifactId>SpringRestTomcat</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-rest-embedded-tomcat</name>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.8</version>
</dependency>
</dependencies>
<build>
<finalName>spring-rest-embedded-tomcat</finalName>
</build>
<properties>
<spring.version>5.0.1.RELEASE</spring.version>
<junit.version>4.12</junit.version>
<jackson.library>2.9.2</jackson.library>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
</project>

View File

@ -0,0 +1,22 @@
package org.baeldung.embedded.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { UserConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}

View File

@ -0,0 +1,12 @@
package org.baeldung.embedded.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.baeldung.embedded")
public class UserConfiguration {
}

View File

@ -0,0 +1,28 @@
package org.baeldung.embedded.controller;
import org.baeldung.embedded.domain.User;
import org.baeldung.embedded.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/")
public String welcome() {
return "Hello World!";
}
@RequestMapping(method = RequestMethod.GET, value = "/user/{userName}")
@ResponseBody
public User user(@PathVariable String userName) {
return this.userService.getUser(userName);
}
}

View File

@ -0,0 +1,23 @@
package org.baeldung.embedded.domain;
public class User {
private String name;
private String hobby;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
}

View File

@ -0,0 +1,38 @@
package org.baeldung.embedded.service;
import java.util.ArrayList;
import java.util.List;
import org.baeldung.embedded.domain.User;
import org.springframework.stereotype.Service;
@Service
public class UserService {
private List<User> users = new ArrayList<>();
public void addUser(String name) {
User user = new User();
user.setName(name);
if (name == "HarryPotter") {
user.setHobby("Quidditch");
} else {
user.setHobby("MuggleActivity");
}
users.add(user);
}
public User getUser(String name) {
for (User user : users) {
if (user.getName()
.equalsIgnoreCase(name)) {
return user;
}
}
User user = new User();
user.setName(name);
user.setHobby("None");
return user;
}
}

View File

@ -0,0 +1,70 @@
package org.baeldung.embedded;
import java.io.File;
import java.util.concurrent.CountDownLatch;
import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class EmbeddedTomcatApp {
private Tomcat tomcatInstance;
private WebApplicationContext webApplicationContext;
private CountDownLatch started = new CountDownLatch(1);
public void start() throws Exception {
tomcatInstance = new Tomcat();
tomcatInstance.setBaseDir(new File(getClass().getResource(".")
.toURI()).getAbsolutePath()); // Tomcat's temporary directory
tomcatInstance.setPort(0);
Context webapp = tomcatInstance.addWebapp("", new File("src/main/webapp/").getAbsolutePath());
webapp.addLifecycleListener(event -> {
if (event.getType()
.equals("after_stop")) {
started.countDown();
} else if (event.getType()
.equals("after_start")) {
webApplicationContext = WebApplicationContextUtils
.findWebApplicationContext(webapp.getServletContext());
((ConfigurableListableBeanFactory) webApplicationContext
.getAutowireCapableBeanFactory()).registerSingleton("baseUrl", getBaseUrl());
started.countDown();
}
});
tomcatInstance.start();
started.await();
}
public Tomcat getTomcatInstance() {
return this.tomcatInstance;
}
public String getBaseUrl() {
return String.format("http://localhost:%d%s", getLocalPort(), getWebApplicationContext().getServletContext()
.getContextPath());
}
public int getLocalPort() {
return tomcatInstance.getConnector()
.getLocalPort();
}
public WebApplicationContext getWebApplicationContext() {
return webApplicationContext;
}
public boolean isStarted() {
return started.getCount() == 0;
}
public boolean isStartedSucessfully() {
return webApplicationContext != null;
}
}

View File

@ -0,0 +1,45 @@
package org.baeldung.embedded;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
public class EmbeddedTomcatRunner extends BlockJUnit4ClassRunner {
public EmbeddedTomcatRunner(Class<?> klass) throws InitializationError {
super(klass);
}
// use one static Tomcat instance shared across all tests
private static EmbeddedTomcatApp embeddedTomcatApp = new EmbeddedTomcatApp();
@Override
protected Statement classBlock(RunNotifier notifier) {
ensureSharedTomcatStarted();
Statement result = super.classBlock(notifier);
return result;
}
private void ensureSharedTomcatStarted() {
if (!embeddedTomcatApp.isStarted()) {
try {
embeddedTomcatApp.start();
} catch (Exception e) {
throw new RuntimeException("Error while starting embedded Tomcat server", e);
}
}
}
@Override
protected Object createTest() throws Exception {
if (!embeddedTomcatApp.isStartedSucessfully()) {
throw new RuntimeException("Tomcat server not started successfully. Skipping test");
}
Object testInstance = super.createTest();
embeddedTomcatApp.getWebApplicationContext()
.getAutowireCapableBeanFactory()
.autowireBean(testInstance);
return testInstance;
}
}

View File

@ -0,0 +1,60 @@
package org.baeldung.embedded;
import java.io.IOException;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.baeldung.embedded.service.UserService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(EmbeddedTomcatRunner.class)
public class UserIntegrationTest {
@Autowired
protected String baseUrl;
@Autowired
private UserService userService;
private String userName = "HarryPotter";
@Before
public void setUp() {
userService.addUser(userName);
}
@Test
public void givenUserName_whenSendGetForHarryPotter_thenHobbyQuidditch() throws IOException {
String url = baseUrl + "/user/" + userName;
HttpClient httpClient = HttpClientBuilder.create()
.build();
HttpGet getUserRequest = new HttpGet(url);
getUserRequest.addHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(getUserRequest);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine()
.getStatusCode());
HttpEntity responseEntity = response.getEntity();
Assert.assertNotNull(responseEntity);
ObjectMapper mapper = new ObjectMapper();
String retSrc = EntityUtils.toString(responseEntity);
Map<String, Object> result = mapper.readValue(retSrc, Map.class);
Assert.assertEquals("Quidditch", result.get("hobby"));
}
}