下面列出了org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer#org.apache.catalina.Wrapper 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
WebServer start() throws Exception {
WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
.filter(new IndexRewriteFilter())
.build();
Tomcat tomcat = new Tomcat();
tomcat.setHostname("localhost");
tomcat.setPort(9090);
Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
servletWrapper.setAsyncSupported(true);
rootContext.addServletMappingDecoded("/", "httpHandlerServlet");
TomcatWebServer server = new TomcatWebServer(tomcat);
server.start();
return server;
}
@Test
public void run() throws IOException {
final Configuration configuration = new Configuration().randomHttpPort();
configuration.setDir(Files.mkdirs(new File("target/" + getClass().getSimpleName() + "-tomcat")).getAbsolutePath());
try (final Container container = new Container(configuration)) {
// tomee-embedded (this "container url" is filtered: name prefix + it is a directory (target/test-classes)
final File parent = Files.mkdirs(new File("target/" + getClass().getSimpleName()));
final File war = ShrinkWrap.create(WebArchive.class, "the-webapp")
.addClass(Foo.class)
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") // activate CDI
.as(ExplodedExporter.class)
.exportExploded(parent);
final Context ctx = container.addContext("", war.getAbsolutePath());
final Wrapper wrapper = Tomcat.addServlet(ctx, "awesome", AServlet.class.getName());
ctx.addServletMappingDecoded("/awesome", wrapper.getName());
assertEquals("Awesome", IO.slurp(new URL("http://localhost:" + configuration.getHttpPort() + "/awesome")).trim());
} catch (final Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void testBug56042() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Bug56042Servlet bug56042Servlet = new Bug56042Servlet();
Wrapper wrapper =
Tomcat.addServlet(ctx, "bug56042Servlet", bug56042Servlet);
wrapper.setAsyncSupported(true);
ctx.addServletMapping("/bug56042Servlet", "bug56042Servlet");
tomcat.start();
StringBuilder url = new StringBuilder(48);
url.append("http://localhost:");
url.append(getPort());
url.append("/bug56042Servlet");
ByteChunk res = new ByteChunk();
int rc = getUrl(url.toString(), res, null);
Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
}
/**
* Unregister wrapper.
*/
private void unregisterWrapper(Wrapper wrapper) {
Context context = ((Context) wrapper.getParent());
String contextPath = context.getPath();
String wrapperName = wrapper.getName();
if ("/".equals(contextPath)) {
contextPath = "";
}
String version = context.getWebappVersion();
String hostName = context.getParent().getName();
String[] mappings = wrapper.findMappings();
for (String mapping : mappings) {
mapper.removeWrapper(hostName, contextPath, version, mapping);
}
if(log.isDebugEnabled()) {
log.debug(sm.getString("mapperListener.unregisterWrapper",
wrapperName, contextPath, service));
}
}
/**
* Return a <code>RequestDispatcher</code> object that acts as a
* wrapper for the named servlet.
*
* @param name Name of the servlet for which a dispatcher is requested
*/
@Override
public RequestDispatcher getNamedDispatcher(String name) {
// Validate the name argument
if (name == null)
return null;
// Create and return a corresponding request dispatcher
Wrapper wrapper = (Wrapper) context.findChild(name);
if (wrapper == null)
return null;
return new ApplicationDispatcher(wrapper, null, null, null, null, null, name);
}
private boolean isFacesServletPresent(final ServletContext ctx) {
if (ctx instanceof ApplicationContextFacade) {
try {
final ApplicationContext appCtx = (ApplicationContext) get(ApplicationContextFacade.class, ctx);
final Context tomcatCtx = (Context) get(ApplicationContext.class, appCtx);
if (tomcatCtx instanceof StandardContext) {
final Container[] servlets = tomcatCtx.findChildren();
if (servlets != null) {
for (final Container s : servlets) {
if (s instanceof Wrapper) {
if ("javax.faces.webapp.FacesServlet".equals(((Wrapper) s).getServletClass())
|| "Faces Servlet".equals(s.getName())) {
return true;
}
}
}
}
}
} catch (final Exception e) {
// no-op
}
}
return false;
}
@Test
public void testBug56042() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Bug56042Servlet bug56042Servlet = new Bug56042Servlet();
Wrapper wrapper =
Tomcat.addServlet(ctx, "bug56042Servlet", bug56042Servlet);
wrapper.setAsyncSupported(true);
ctx.addServletMappingDecoded("/bug56042Servlet", "bug56042Servlet");
tomcat.start();
StringBuilder url = new StringBuilder(48);
url.append("http://localhost:");
url.append(getPort());
url.append("/bug56042Servlet");
ByteChunk res = new ByteChunk();
int rc = getUrl(url.toString(), res, null);
Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
}
private DefaultInstanceManager doClassUnloadingPrep() throws Exception {
Tomcat tomcat = getTomcatInstance();
// Create the context (don't use addWebapp as we want to modify the
// JSP Servlet settings).
File appDir = new File("test/webapp");
StandardContext ctxt = (StandardContext) tomcat.addContext(
null, "/test", appDir.getAbsolutePath());
ctxt.addServletContainerInitializer(new JasperInitializer(), null);
// Configure the defaults and then tweak the JSP servlet settings
// Note: Min value for maxLoadedJsps is 2
Tomcat.initWebappDefaults(ctxt);
Wrapper w = (Wrapper) ctxt.findChild("jsp");
w.addInitParameter("maxLoadedJsps", "2");
tomcat.start();
return (DefaultInstanceManager) ctxt.getInstanceManager();
}
/**
* Construct a new instance of this class, configured according to the
* specified parameters. If both servletPath and pathInfo are
* <code>null</code>, it will be assumed that this RequestDispatcher
* was acquired by name, rather than by path.
*
* @param wrapper The Wrapper associated with the resource that will
* be forwarded to or included (required)
* @param requestURI The request URI to this resource (if any)
* @param servletPath The revised servlet path to this resource (if any)
* @param pathInfo The revised extra path information to this resource
* (if any)
* @param queryString Query string parameters included with this request
* (if any)
* @param name Servlet name (if a named dispatcher was created)
* else <code>null</code>
*/
public ApplicationDispatcher
(Wrapper wrapper, String requestURI, String servletPath,
String pathInfo, String queryString, String name) {
super();
// Save all of our configuration parameters
this.wrapper = wrapper;
this.context = (Context) wrapper.getParent();
this.requestURI = requestURI;
this.servletPath = servletPath;
this.pathInfo = pathInfo;
this.queryString = queryString;
this.name = name;
if (wrapper instanceof StandardWrapper)
this.support = ((StandardWrapper) wrapper).getInstanceSupport();
else
this.support = new InstanceSupport(wrapper);
}
private void doTestDispatchWithSpaces(boolean async) throws Exception {
Tomcat tomcat = getTomcatInstance();
Context context = tomcat.addContext("", null);
if (async) {
Servlet s = new AsyncDispatchUrlWithSpacesServlet();
Wrapper w = Tomcat.addServlet(context, "space", s);
w.setAsyncSupported(true);
} else {
Tomcat.addServlet(context, "space", new ForwardDispatchUrlWithSpacesServlet());
}
context.addServletMapping("/space/*", "space");
tomcat.start();
ByteChunk responseBody = new ByteChunk();
int rc = getUrl("http://localhost:" + getPort() + "/sp%61ce/foo%20bar", responseBody, null);
Assert.assertEquals(200, rc);
}
private void ensureMyFacesDontLooseFacesContext(final StandardContext standardContext) {
for (final Container w : standardContext.findChildren()) {
if (!Wrapper.class.isInstance(w)) {
continue;
}
final Wrapper wrapper = Wrapper.class.cast(w);
if ("FacesServlet".equals(wrapper.getName()) && "javax.faces.webapp.FacesServlet".equals(wrapper.getServletClass())) {
final ClassLoader loader = standardContext.getLoader().getClassLoader();
try {
if (Files.toFile(loader.getResource("javax/faces/webapp/FacesServlet.class")).getName().startsWith("myfaces")) {
loader.loadClass("org.apache.tomee.myfaces.TomEEWorkaroundFacesServlet");
wrapper.setServletClass("org.apache.tomee.myfaces.TomEEWorkaroundFacesServlet");
break;
}
} catch (final Throwable t) {
// not there, not a big deal in most of cases
}
}
}
}
private void doTestAsyncIoEnd(boolean useThread, boolean useComplete) throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
AsyncIoEndServlet asyncIoEndServlet = new AsyncIoEndServlet(useThread, useComplete);
Wrapper wrapper = Tomcat.addServlet(ctx, "asyncIoEndServlet", asyncIoEndServlet);
wrapper.setAsyncSupported(true);
ctx.addServletMappingDecoded("/asyncIoEndServlet", "asyncIoEndServlet");
SimpleServlet simpleServlet = new SimpleServlet();
Tomcat.addServlet(ctx, "simpleServlet", simpleServlet);
ctx.addServletMappingDecoded("/simpleServlet", "simpleServlet");
tomcat.start();
ByteChunk body = new ByteChunk();
int rc = getUrl("http://localhost:" + getPort() + "/asyncIoEndServlet", body, null);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
Assert.assertEquals("OK", body.toString());
Assert.assertFalse(asyncIoEndServlet.getInvalidStateDetected());
}
public static void launchService(int port, String indexPath)
throws IOException, LifecycleException {
Tomcat server = new Tomcat();
Context context = server.addContext("/", new File(".").getAbsolutePath());
System.setProperty(INDEX_PATH_PROP, indexPath);
Wrapper servlet = context.createWrapper();
servlet.setName("CXFNonSpringJaxrs");
servlet.setServletClass(CXFNonSpringJaxrsServlet.class.getName());
servlet.addInitParameter("jaxrs.serviceClasses", SearchResource.class.getName() + " " + HealthCheckAPI.class.getName());
servlet.setLoadOnStartup(1);
context.addChild(servlet);
context.addServletMapping("/api/*", "CXFNonSpringJaxrs");
System.out.println("Starting Embedded Tomcat on port : " + port );
server.setPort(port);
server.start();
server.getServer().await();
}
/**
* Static version of {@link #addServlet(String, String, String)}
* @param ctx Context to add Servlet to
* @param servletName Servlet name (used in mappings)
* @param servletClass The class to be used for the Servlet
* @return The wrapper for the servlet
*/
public static Wrapper addServlet(Context ctx,
String servletName,
String servletClass) {
// will do class for name and set init params
Wrapper sw = ctx.createWrapper();
sw.setServletClass(servletClass);
sw.setName(servletName);
ctx.addChild(sw);
return sw;
}
private void doTestAsyncISE(boolean useGetRequest) throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
AsyncISEServlet servlet = new AsyncISEServlet();
Wrapper w = Tomcat.addServlet(ctx, "AsyncISEServlet", servlet);
w.setAsyncSupported(true);
ctx.addServletMapping("/test", "AsyncISEServlet");
tomcat.start();
ByteChunk response = new ByteChunk();
int rc = getUrl("http://localhost:" + getPort() +"/test", response,
null);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
boolean hasIse = false;
try {
if (useGetRequest) {
servlet.getAsyncContext().getRequest();
} else {
servlet.getAsyncContext().getResponse();
}
} catch (IllegalStateException ise) {
hasIse = true;
}
Assert.assertTrue(hasIse);
}
/**
* Static version of {@link #addServlet(String, String, Servlet)}.
* @param ctx Context to add Servlet to
* @param servletName Servlet name (used in mappings)
* @param servlet The Servlet to add
* @return The wrapper for the servlet
*/
public static Wrapper addServlet(Context ctx,
String servletName,
Servlet servlet) {
// will do class for name and set init params
Wrapper sw = new ExistingStandardWrapper(servlet);
sw.setName(servletName);
ctx.addChild(sw);
return sw;
}
/**
* Static version of {@link #initWebappDefaults(String)}
* @param ctx The context to set the defaults for
*/
public static void initWebappDefaults(Context ctx) {
// Default servlet
Wrapper servlet = addServlet(
ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
servlet.setLoadOnStartup(1);
servlet.setOverridable(true);
// JSP servlet (by class name - to avoid loading all deps)
servlet = addServlet(
ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
servlet.addInitParameter("fork", "false");
servlet.setLoadOnStartup(3);
servlet.setOverridable(true);
// Servlet mappings
ctx.addServletMappingDecoded("/", "default");
ctx.addServletMappingDecoded("*.jsp", "jsp");
ctx.addServletMappingDecoded("*.jspx", "jsp");
// Sessions
ctx.setSessionTimeout(30);
// MIME mappings
for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {
ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++],
DEFAULT_MIME_MAPPINGS[i++]);
}
// Welcome files
ctx.addWelcomeFile("index.html");
ctx.addWelcomeFile("index.htm");
ctx.addWelcomeFile("index.jsp");
}
/**
* Process the annotations for the servlets.
*
* @param context The context which will have its annotations processed
*/
protected static void loadApplicationServletAnnotations(Context context) {
Container[] children = context.findChildren();
for (Container child : children) {
if (child instanceof Wrapper) {
Wrapper wrapper = (Wrapper) child;
if (wrapper.getServletClass() == null) {
continue;
}
Class<?> clazz = Introspection.loadClass(context, wrapper.getServletClass());
if (clazz == null) {
continue;
}
loadClassAnnotation(context, clazz);
loadFieldsAnnotation(context, clazz);
loadMethodsAnnotation(context, clazz);
/* Process RunAs annotation which can be only on servlets.
* Ref JSR 250, equivalent to the run-as element in
* the deployment descriptor
*/
RunAs runAs = clazz.getAnnotation(RunAs.class);
if (runAs != null) {
wrapper.setRunAs(runAs.value());
}
// Process ServletSecurity annotation
ServletSecurity servletSecurity = clazz.getAnnotation(ServletSecurity.class);
if (servletSecurity != null) {
context.addServletSecurity(
new ApplicationServletRegistration(wrapper, context),
new ServletSecurityElement(servletSecurity));
}
}
}
}
@Test
public void testFlagFailCtxIfServletStartFails() throws Exception {
Tomcat tomcat = getTomcatInstance();
File docBase = new File(System.getProperty("java.io.tmpdir"));
StandardContext context = (StandardContext) tomcat.addContext("",
docBase.getAbsolutePath());
// first we test the flag itself, which can be set on the Host and
// Context
assertFalse(context.getComputedFailCtxIfServletStartFails());
StandardHost host = (StandardHost) tomcat.getHost();
host.setFailCtxIfServletStartFails(true);
assertTrue(context.getComputedFailCtxIfServletStartFails());
context.setFailCtxIfServletStartFails(Boolean.FALSE);
assertFalse("flag on Context should override Host config",
context.getComputedFailCtxIfServletStartFails());
// second, we test the actual effect of the flag on the startup
Wrapper servlet = Tomcat.addServlet(context, "myservlet",
new FailingStartupServlet());
servlet.setLoadOnStartup(1);
tomcat.start();
assertTrue("flag false should not fail deployment", context.getState()
.isAvailable());
tomcat.stop();
assertFalse(context.getState().isAvailable());
host.removeChild(context);
context = (StandardContext) tomcat.addContext("",
docBase.getAbsolutePath());
servlet = Tomcat.addServlet(context, "myservlet",
new FailingStartupServlet());
servlet.setLoadOnStartup(1);
tomcat.start();
assertFalse("flag true should fail deployment", context.getState()
.isAvailable());
}
@Test
public void testCommitOnComplete() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
AsyncStatusServlet asyncStatusServlet =
new AsyncStatusServlet(HttpServletResponse.SC_BAD_REQUEST);
Wrapper wrapper =
Tomcat.addServlet(ctx, "asyncStatusServlet", asyncStatusServlet);
wrapper.setAsyncSupported(true);
ctx.addServletMapping("/asyncStatusServlet", "asyncStatusServlet");
TesterAccessLogValve alv = new TesterAccessLogValve();
ctx.getPipeline().addValve(alv);
tomcat.start();
StringBuilder url = new StringBuilder(48);
url.append("http://localhost:");
url.append(getPort());
url.append("/asyncStatusServlet");
int rc = getUrl(url.toString(), new ByteChunk(), null);
assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
// Without this test may complete before access log has a chance to log
// the request
Thread.sleep(REQUEST_TIME);
// Check the access log
alv.validateAccessLog(1, HttpServletResponse.SC_BAD_REQUEST, 0,
REQUEST_TIME);
}
private void load(Wrapper wrapper) {
try {
wrapper.load();
}
catch (ServletException ex) {
String message = sm.getString("standardContext.loadOnStartup.loadException", getName(), wrapper.getName());
if (getComputedFailCtxIfServletStartFails()) {
throw new RuntimeException(message, ex);
}
getLogger().error(message, StandardWrapper.getRootCause(ex));
}
}
@Test
public void testBug49567() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Bug49567Servlet servlet = new Bug49567Servlet();
Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
wrapper.setAsyncSupported(true);
ctx.addServletMapping("/", "servlet");
TesterAccessLogValve alv = new TesterAccessLogValve();
ctx.getPipeline().addValve(alv);
tomcat.start();
// Call the servlet once
ByteChunk bc = getUrl("http://localhost:" + getPort() + "/");
assertEquals("OK", bc.toString());
// Give the async thread a chance to finish (but not too long)
int counter = 0;
while (!servlet.isDone() && counter < 10) {
Thread.sleep(1000);
counter++;
}
assertEquals("1false2true3true4true5false", servlet.getResult());
// Check the access log
alv.validateAccessLog(1, 200, Bug49567Servlet.THREAD_SLEEP_TIME,
Bug49567Servlet.THREAD_SLEEP_TIME + REQUEST_TIME);
}
/**
* {@inheritDoc}
*
* This method or {@link #hasRoleInternal(Principal,
* String)} can be overridden by Realm implementations, but the default is
* adequate when an instance of <code>GenericPrincipal</code> is used to
* represent authenticated Principals from this Realm.
*/
@Override
public boolean hasRole(Wrapper wrapper, Principal principal, String role) {
// Check for a role alias
if (wrapper != null) {
String realRole = wrapper.findSecurityReference(role);
if (realRole != null) {
role = realRole;
}
}
// Should be overridden in JAASRealm - to avoid pretty inefficient conversions
if (principal == null || role == null) {
return false;
}
boolean result = hasRoleInternal(principal, role);
if (log.isDebugEnabled()) {
String name = principal.getName();
if (result)
log.debug(sm.getString("realmBase.hasRoleSuccess", name, role));
else
log.debug(sm.getString("realmBase.hasRoleFailure", name, role));
}
return result;
}
@Bean
public EmbeddedServletContainerCustomizer servletContainerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
if (container instanceof TomcatEmbeddedServletContainerFactory) {
customizeTomcat((TomcatEmbeddedServletContainerFactory)container);
}
}
private void customizeTomcat(TomcatEmbeddedServletContainerFactory tomcatFactory) {
tomcatFactory.addContextCustomizers(new TomcatContextCustomizer() {
@Override
public void customize(Context context) {
Container jsp = context.findChild("jsp");
if (jsp instanceof Wrapper) {
((Wrapper)jsp).addInitParameter("development", "false");
}
}
});
}
};
}
public void addWrapper(String hostName, String contextPath, String version,
String path, Wrapper wrapper, boolean jspWildCard,
boolean resourceOnly) {
hostName = renameWildcardHost(hostName);
ContextVersion contextVersion = findContextVersion(hostName,
contextPath, version, false);
if (contextVersion == null) {
return;
}
addWrapper(contextVersion, path, wrapper, jspWildCard, resourceOnly);
}
@Test
public void testBug53843() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Bug53843ServletA servletA = new Bug53843ServletA();
Wrapper a = Tomcat.addServlet(ctx, "ServletA", servletA);
a.setAsyncSupported(true);
Tomcat.addServlet(ctx, "ServletB", new Bug53843ServletB());
ctx.addServletMapping("/ServletA", "ServletA");
ctx.addServletMapping("/ServletB", "ServletB");
tomcat.start();
StringBuilder url = new StringBuilder(48);
url.append("http://localhost:");
url.append(getPort());
url.append("/ServletA");
ByteChunk body = new ByteChunk();
int rc = getUrl(url.toString(), body, null);
assertEquals(HttpServletResponse.SC_OK, rc);
assertEquals("OK", body.toString());
assertTrue(servletA.isAsyncWhenExpected());
}
@Test
public void testAsyncStartWithComplete() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
AsyncStartWithCompleteServlet servlet =
new AsyncStartWithCompleteServlet();
Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
wrapper.setAsyncSupported(true);
ctx.addServletMapping("/", "servlet");
TesterAccessLogValve alv = new TesterAccessLogValve();
ctx.getPipeline().addValve(alv);
tomcat.start();
// Call the servlet once
ByteChunk bc = new ByteChunk();
Map<String,List<String>> headers = new HashMap<String,List<String>>();
getUrl("http://localhost:" + getPort() + "/", bc, headers);
assertEquals("OK", bc.toString());
List<String> contentLength = headers.get("Content-Length");
Assert.assertNotNull(contentLength);
Assert.assertEquals(1, contentLength.size());
Assert.assertEquals("2", contentLength.get(0));
// Check the access log
alv.validateAccessLog(1, 200, 0, REQUEST_TIME);
}
@Override
public ServletRegistration getServletRegistration(String servletName) {
Wrapper wrapper = (Wrapper) context.findChild(servletName);
if (wrapper == null) {
return null;
}
return new ApplicationServletRegistration(wrapper, context);
}
/**
* Calculate the key properties string to be added to an object's
* {@link ObjectName} to indicate that it is associated with that container.
*
* @param container The container the object is associated with
* @return A string suitable for appending to the ObjectName
* @deprecated To be removed since to creates a circular dependency. Will
* be replaced in Tomcat 8 by a new method on {@link
* Container}.
*/
@Deprecated
public static String getContainerKeyProperties(Container container) {
Container c = container;
StringBuilder keyProperties = new StringBuilder();
int containerCount = 0;
// Work up container hierarchy, add a component to the name for
// each container
while (!(c instanceof Engine)) {
if (c instanceof Wrapper) {
keyProperties.append(",servlet=");
keyProperties.append(c.getName());
} else if (c instanceof Context) {
keyProperties.append(",context=");
ContextName cn = new ContextName(c.getName(), false);
keyProperties.append(cn.getDisplayName());
} else if (c instanceof Host) {
keyProperties.append(",host=");
keyProperties.append(c.getName());
} else if (c == null) {
// May happen in unit testing and/or some embedding scenarios
keyProperties.append(",container");
keyProperties.append(containerCount++);
keyProperties.append("=null");
break;
} else {
// Should never happen...
keyProperties.append(",container");
keyProperties.append(containerCount++);
keyProperties.append('=');
keyProperties.append(c.getName());
}
c = c.getParent();
}
return keyProperties.toString();
}
@Override
public String getMBeanKeyProperties() {
Container c = this;
StringBuilder keyProperties = new StringBuilder();
int containerCount = 0;
// Work up container hierarchy, add a component to the name for
// each container
while (!(c instanceof Engine)) {
if (c instanceof Wrapper) {
keyProperties.insert(0, ",servlet=");
keyProperties.insert(9, c.getName());
} else if (c instanceof Context) {
keyProperties.insert(0, ",context=");
ContextName cn = new ContextName(c.getName(), false);
keyProperties.insert(9,cn.getDisplayName());
} else if (c instanceof Host) {
keyProperties.insert(0, ",host=");
keyProperties.insert(6, c.getName());
} else if (c == null) {
// May happen in unit testing and/or some embedding scenarios
keyProperties.append(",container");
keyProperties.append(containerCount++);
keyProperties.append("=null");
break;
} else {
// Should never happen...
keyProperties.append(",container");
keyProperties.append(containerCount++);
keyProperties.append('=');
keyProperties.append(c.getName());
}
c = c.getParent();
}
return keyProperties.toString();
}