Commit 826b18f6 authored by Phillip Webb's avatar Phillip Webb

Merge pull request #16892 from jpmsilva

* pr/16892:
  Polish "Allow Tomcat be destroyed regardless of exceptions"
  Allow Tomcat be destroyed regardless of exceptions
parents c5199322 09373622
/*
* 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) {
......
......@@ -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();
......
......@@ -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() {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment