Merge pull request #16892 from jpmsilva

* pr/16892:
  Polish "Allow Tomcat be destroyed regardless of exceptions"
  Allow Tomcat be destroyed regardless of exceptions
This commit is contained in:
Phillip Webb 2019-05-28 16:31:13 -07:00
commit 826b18f63e
3 changed files with 41 additions and 1 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2018 the original author or authors.
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -122,6 +122,7 @@ public class TomcatWebServer implements WebServer {
}
catch (Exception ex) {
stopSilently();
destroySilently();
throw new WebServerException("Unable to start embedded Tomcat", ex);
}
}
@ -242,6 +243,15 @@ public class TomcatWebServer implements WebServer {
}
}
private void destroySilently() {
try {
this.tomcat.destroy();
}
catch (LifecycleException ex) {
// Ignore
}
}
private void stopTomcat() throws LifecycleException {
if (Thread.currentThread()
.getContextClassLoader() instanceof TomcatEmbeddedWebappClassLoader) {

View File

@ -523,6 +523,27 @@ public class TomcatServletWebServerFactoryTests
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
}
@Test
public void exceptionThrownOnContextListenerDestroysServer() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(0) {
@Override
protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
try {
return super.getTomcatWebServer(tomcat);
}
finally {
assertThat(tomcat.getServer().getState())
.isEqualTo(LifecycleState.DESTROYED);
}
}
};
assertThatExceptionOfType(WebServerException.class)
.isThrownBy(() -> factory.getWebServer((context) -> context
.addListener(new FailingServletContextListener())));
}
@Override
protected JspServlet getJspServlet() throws ServletException {
Tomcat tomcat = ((TomcatWebServer) this.webServer).getTomcat();

View File

@ -1401,6 +1401,15 @@ public abstract class AbstractServletWebServerFactoryTests {
}
public static class FailingServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
throw new FailingServletException();
}
}
private static class FailingServletException extends RuntimeException {
FailingServletException() {