下面列出了怎么用javax.servlet.ServletContainerInitializer的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@SuppressWarnings("unchecked")
public void testInitializerFromClasspath() throws IOException {
URL url = new URL("file://test");
loader = EasyMock.createMockBuilder(WebappServiceLoader.class)
.addMockedMethod("parseConfigFile", LinkedHashSet.class, URL.class)
.withConstructor(context).createMock(control);
EasyMock.expect(servletContext.getAttribute(ServletContext.ORDERED_LIBS))
.andReturn(null);
EasyMock.expect(cl.getResources(CONFIG_FILE))
.andReturn(Collections.enumeration(Collections.singleton(url)));
loader.parseConfigFile(EasyMock.isA(LinkedHashSet.class), EasyMock.same(url));
control.replay();
Assert.assertTrue(loader.load(ServletContainerInitializer.class).isEmpty());
control.verify();
}
@Test
@SuppressWarnings("unchecked")
public void testWithOrdering() throws IOException {
URL url1 = new URL("file://jar1.jar");
URL sci1 = new URL("jar:file://jar1.jar!/" + CONFIG_FILE);
URL url2 = new URL("file://dir/");
URL sci2 = new URL("file://dir/" + CONFIG_FILE);
loader = EasyMock.createMockBuilder(WebappServiceLoader.class)
.addMockedMethod("parseConfigFile", LinkedHashSet.class, URL.class)
.withConstructor(context).createMock(control);
List<String> jars = Arrays.asList("jar1.jar", "dir/");
EasyMock.expect(servletContext.getAttribute(ServletContext.ORDERED_LIBS))
.andReturn(jars);
EasyMock.expect(servletContext.getResource("/WEB-INF/lib/jar1.jar"))
.andReturn(url1);
loader.parseConfigFile(EasyMock.isA(LinkedHashSet.class), EasyMock.eq(sci1));
EasyMock.expect(servletContext.getResource("/WEB-INF/lib/dir/"))
.andReturn(url2);
loader.parseConfigFile(EasyMock.isA(LinkedHashSet.class), EasyMock.eq(sci2));
EasyMock.expect(parent.getResources(CONFIG_FILE))
.andReturn(Collections.<URL>emptyEnumeration());
control.replay();
Assert.assertTrue(loader.load(ServletContainerInitializer.class).isEmpty());
control.verify();
}
@Test
public void testLoadServices() throws Exception {
Class<?> sci = TesterServletContainerInitializer1.class;
loader = new WebappServiceLoader<>(context);
cl.loadClass(sci.getName());
EasyMock.expectLastCall()
.andReturn(sci);
LinkedHashSet<String> names = new LinkedHashSet<>();
names.add(sci.getName());
control.replay();
Collection<ServletContainerInitializer> initializers =
loader.loadServices(ServletContainerInitializer.class, names);
Assert.assertEquals(1, initializers.size());
Assert.assertTrue(sci.isInstance(initializers.iterator().next()));
control.verify();
}
@Test
public void testServiceIsNotExpectedType() throws Exception {
Class<?> sci = Object.class;
loader = new WebappServiceLoader<>(context);
cl.loadClass(sci.getName());
EasyMock.expectLastCall()
.andReturn(sci);
LinkedHashSet<String> names = new LinkedHashSet<>();
names.add(sci.getName());
control.replay();
try {
loader.loadServices(ServletContainerInitializer.class, names);
} catch (IOException e) {
Assert.assertTrue(e.getCause() instanceof ClassCastException);
} finally {
control.verify();
}
}
@Test
public void testServiceCannotBeConstructed() throws Exception {
Class<?> sci = Integer.class;
loader = new WebappServiceLoader<>(context);
cl.loadClass(sci.getName());
EasyMock.expectLastCall()
.andReturn(sci);
LinkedHashSet<String> names = new LinkedHashSet<>();
names.add(sci.getName());
control.replay();
try {
loader.loadServices(ServletContainerInitializer.class, names);
} catch (IOException e) {
Assert.assertTrue(e.getCause() instanceof ReflectiveOperationException);
} finally {
control.verify();
}
}
@Test
public void testUncoveredMethods() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("/test", null);
ctx.setDenyUncoveredHttpMethods(true);
ServletContainerInitializer sci = new SCI();
ctx.addServletContainerInitializer(sci, null);
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
rc = getUrl("http://localhost:" + getPort() + "/test/foo", bc, false);
Assert.assertEquals(403, rc);
}
private void runInitializers(StartupContext startupContext, Promise<Void> promise, Map<Class<?>, Set<Class<?>>> classes) {
Function<ServletContainerInitializer, Handler<Promise<Void>>> initializerFactory = initializer -> event2 -> {
try {
initializer.onStartup(classes.get(initializer.getClass()), startupContext.servletContext());
event2.complete();
} catch (Exception ex) {
event2.fail(ex);
}
};
CompositeFuture.join(
runInitializer(initializerFactory.apply(new RouteRegistryInitializer())),
runInitializer(initializerFactory.apply(new ErrorNavigationTargetInitializer())),
runInitializer(initializerFactory.apply(new WebComponentConfigurationRegistryInitializer())),
runInitializer(initializerFactory.apply(new AnnotationValidator())),
runInitializer(initializerFactory.apply(new WebComponentExporterAwareValidator())),
runInitializer(event2 -> initializeDevModeHandler(event2, startupContext, classes.get(DevModeInitializer.class)))
).setHandler(event2 -> {
if (event2.succeeded()) {
promise.complete();
} else {
promise.fail(event2.cause());
}
});
}
/**
* Configure the web application.
*
* @param webApplication the web application.
*/
@Override
public void configure(WebApplication webApplication) {
try {
ClassLoader classLoader = webApplication.getClassLoader();
Class<? extends ServletContainerInitializer> clazz
= classLoader.
loadClass(WebXmlInitializer.class.getName())
.asSubclass(ServletContainerInitializer.class);
ServletContainerInitializer initializer = clazz.getDeclaredConstructor().newInstance();
webApplication.addInitializer(initializer);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException ex) {
LOGGER.log(Level.WARNING, "Unable to enable the WebXmlExtension", ex);
}
}
/**
* Configure the web application.
*
* @param webApplication the web application.
*/
@Override
public void configure(WebApplication webApplication) {
try {
ClassLoader classLoader = webApplication.getClassLoader();
Class<? extends ServletContainerInitializer> clazz
= classLoader
.loadClass(AnnotationScanInitializer.class.getName())
.asSubclass(ServletContainerInitializer.class);
ServletContainerInitializer initializer = clazz.getDeclaredConstructor().newInstance();
webApplication.addInitializer(initializer);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException ex) {
LOGGER.log(Level.WARNING, "Unable to enable AnnotationScanExtension", ex);
}
}
/**
* Configure the web application.
*
* @param webApplication the web application.
*/
@Override
public void configure(WebApplication webApplication) {
try {
ClassLoader classLoader = webApplication.getClassLoader();
Class<? extends ServletContainerInitializer> clazz
= classLoader.
loadClass(TempDirInitializer.class.getName())
.asSubclass(ServletContainerInitializer.class);
ServletContainerInitializer initializer
= clazz.getDeclaredConstructor().newInstance();
webApplication.addInitializer(initializer);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException ex) {
LOGGER.log(Level.WARNING, "Unable to enable TEMPDIR WebApplicationExtension", ex);
}
}
/**
* Initialize the servlet container initializers.
*/
@Override
public void initializeInitializers() {
boolean error = false;
for (ServletContainerInitializer initializer : initializers) {
try {
initializer.onStartup(annotationManager.getAnnotatedClasses(), this);
} catch (Throwable t) {
LOGGER.log(WARNING, t, () -> "Initializer " + initializer.getClass().getName() + " failing onStartup");
error = true;
}
}
if (!error) {
@SuppressWarnings("unchecked")
List<ServletContextListener> listeners = (List<ServletContextListener>) contextListeners.clone();
listeners.stream().forEach((listener) -> {
listener.contextInitialized(new ServletContextEvent(this));
});
} else {
status = ERROR;
}
}
/**
* Configure the web application.
*
* @param webApplication the web application.
*/
@Override
public void configure(WebApplication webApplication) {
try {
ClassLoader classLoader = webApplication.getClassLoader();
Class<? extends ServletContainerInitializer> clazz
= classLoader
.loadClass(WebAnnotationInitializer.class.getName())
.asSubclass(ServletContainerInitializer.class);
ServletContainerInitializer initializer = clazz.getDeclaredConstructor().newInstance();
webApplication.addInitializer(initializer);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException ex) {
LOGGER.log(Level.WARNING, "Unable to enable the WebAnnotationExtension", ex);
}
}
/**
* Configure the web application.
*
* @param webApplication the web application.
*/
@Override
public void configure(WebApplication webApplication) {
if (LOGGER.isLoggable(FINER)) {
LOGGER.log(FINER, "Starting ServletContainerInitializer processing");
}
ServiceLoader<ServletContainerInitializer> serviceLoader = ServiceLoader.load(
ServletContainerInitializer.class, webApplication.getClassLoader());
for (ServletContainerInitializer initializer : serviceLoader) {
if (LOGGER.isLoggable(FINE)) {
LOGGER.log(INFO, "Adding initializer: {0}", initializer.getClass().getName());
}
webApplication.addInitializer(initializer);
}
if (LOGGER.isLoggable(FINER)) {
LOGGER.log(FINER, "Finished ServletContainerInitializer processing");
}
}
/**
* Configure the web application.
*
* @param webApplication the web application.
*/
@Override
public void configure(WebApplication webApplication) {
try {
ClassLoader classLoader = webApplication.getClassLoader();
Class<? extends ServletContainerInitializer> clazz
= classLoader.
loadClass(JasperInitializer.class.getName())
.asSubclass(ServletContainerInitializer.class);
ServletContainerInitializer initializer = clazz.getDeclaredConstructor().newInstance();
webApplication.addInitializer(initializer);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException
| InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException ex) {
LOGGER.log(Level.WARNING, "Unable to enable the Jasper extension", ex);
}
}
@Override
public void onStartup(final Set<Class<?>> classes, final ServletContext ctx) throws ServletException {
if (System.getProperty("openejb.embedder.source") != null) {
ctx.log("TomEE already initialized");
return;
}
ctx.log("Embedded TomEE starting");
final Properties properties = new Properties();
properties.putAll(System.getProperties());
properties.setProperty("openejb.system.apps", Boolean.toString(Boolean.getBoolean("openejb.system.apps")));
properties.setProperty("tomee.war", new File(ctx.getRealPath("WEB-INF")).getParentFile().getAbsolutePath());
properties.setProperty("openejb.embedder.source", getClass().getSimpleName());
TomcatEmbedder.embed(properties, ServletContainerInitializer.class.getClassLoader());
ctx.log("Embedded TomEE started");
Deployer.deploy(ctx);
ctx.log("Application '" + ctx.getContextPath() + "' TomEE-ised");
}
private Set<ServletContainerInitializer> getSCIsForClass(String className) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry :
typeInitializerMap.entrySet()) {
Class<?> clazz = entry.getKey();
if (!clazz.isAnnotation()) {
if (clazz.getName().equals(className)) {
return entry.getValue();
}
}
}
return EMPTY_SCI_SET;
}
@Test
public void testNoInitializersFound() throws IOException {
loader = new WebappServiceLoader<>(context);
EasyMock.expect(servletContext.getAttribute(ServletContext.ORDERED_LIBS))
.andReturn(null);
EasyMock.expect(cl.getResources(CONFIG_FILE))
.andReturn(Collections.<URL>emptyEnumeration());
control.replay();
Assert.assertTrue(loader.load(ServletContainerInitializer.class).isEmpty());
control.verify();
}
@Test
public void testBug50015() throws Exception {
// Test that configuring servlet security constraints programmatically
// does work.
// Set up a container
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
// Setup realm
TesterMapRealm realm = new TesterMapRealm();
realm.addUser("tomcat", "tomcat");
realm.addUserRole("tomcat", "tomcat");
ctx.setRealm(realm);
// Configure app for BASIC auth
LoginConfig lc = new LoginConfig();
lc.setAuthMethod("BASIC");
ctx.setLoginConfig(lc);
ctx.getPipeline().addValve(new BasicAuthenticator());
// Add ServletContainerInitializer
ServletContainerInitializer sci = new Bug50015SCI();
ctx.addServletContainerInitializer(sci, null);
// Start the context
tomcat.start();
// Request the first servlet
ByteChunk bc = new ByteChunk();
int rc = getUrl("http://localhost:" + getPort() + "/bug50015",
bc, null);
// Check for a 401
Assert.assertNotSame("OK", bc.toString());
Assert.assertEquals(401, rc);
}
private void doTestSecurityAnnotationsAddServlet(boolean useCreateServlet)
throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Servlet s = new DenyAllServlet();
ServletContainerInitializer sci = new SCI(s, useCreateServlet);
ctx.addServletContainerInitializer(sci, null);
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
rc = getUrl("http://localhost:" + getPort() + "/", bc, null, null);
if (useCreateServlet) {
Assert.assertTrue(bc.getLength() > 0);
Assert.assertEquals(403, rc);
} else {
Assert.assertEquals("OK", bc.toString());
Assert.assertEquals(200, rc);
}
}
public ServletContainerInitializerInfo(final Class<? extends ServletContainerInitializer> servletContainerInitializerClass, final Set<Class<?>> handlesTypes) {
this.servletContainerInitializerClass = servletContainerInitializerClass;
this.handlesTypes = handlesTypes;
try {
final Constructor<ServletContainerInitializer> ctor = (Constructor<ServletContainerInitializer>) servletContainerInitializerClass.getDeclaredConstructor();
ctor.setAccessible(true);
this.instanceFactory = new ConstructorInstanceFactory<>(ctor);
} catch (NoSuchMethodException e) {
throw UndertowServletMessages.MESSAGES.componentMustHaveDefaultConstructor("ServletContainerInitializer", servletContainerInitializerClass);
}
}
private void addJasperInitializer(StandardContext context) {
try {
ServletContainerInitializer initializer = (ServletContainerInitializer) ClassUtils
.forName("org.apache.jasper.servlet.JasperInitializer", null).newInstance();
context.addServletContainerInitializer(initializer, null);
} catch (Exception ex) {
// Probably not Tomcat 8
}
}
/**
* Initialize Jakarta Security
*
* @param classes the classes.
* @param servletContext the Servlet context.
* @throws ServletException when a Servlet error occurs.
*/
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
System.getProperties().put(INITIAL_CONTEXT_FACTORY, DynamicInitialContextFactory.class.getName());
// The default Jakarta Authorization module, which implements authorization as defined
// by the Jakarta Servlet and Jakarta Enterprise Beans specifications
servletContext.setAttribute(AUTHZ_FACTORY_CLASS, DefaultPolicyConfigurationFactory.class);
servletContext.setAttribute(AUTHZ_POLICY_CLASS, DefaultPolicy.class);
for (ServletContainerInitializer initializer : initializers) {
initializer.onStartup(classes, servletContext);
}
}
/**
* Add a servlet container initializer.
*
* @param className the class name.
*/
@Override
public void addInitializer(String className) {
try {
@SuppressWarnings("unchecked")
Class<ServletContainerInitializer> clazz = (Class<ServletContainerInitializer>) getClassLoader().loadClass(className);
initializers.add(clazz.newInstance());
} catch (Throwable throwable) {
if (LOGGER.isLoggable(WARNING)) {
LOGGER.log(WARNING, "Unable to add initializer: " + className, throwable);
}
}
}
private Set<ServletContainerInitializer> getSCIsForClass(String className) {
for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry :
typeInitializerMap.entrySet()) {
Class<?> clazz = entry.getKey();
if (!clazz.isAnnotation()) {
if (clazz.getName().equals(className)) {
return entry.getValue();
}
}
}
return EMPTY_SCI_SET;
}
@Test
public void testWebapp() throws Exception {
Tomcat tomcat = getTomcatInstance();
File appDir = new File("test/webapp-3.0-fragments-empty-absolute-ordering");
StandardContext ctxt = (StandardContext) tomcat.addContext(null, "/test", appDir.getAbsolutePath());
ctxt.addLifecycleListener(new ContextConfig());
tomcat.start();
WebappServiceLoader<ServletContainerInitializer> loader =
new WebappServiceLoader<ServletContainerInitializer>(ctxt);
@SuppressWarnings("unused")
Collection<ServletContainerInitializer> initializers = loader.load(ServletContainerInitializer.class);
}
@Test
public void testBug50015() throws Exception {
// Test that configuring servlet security constraints programmatically
// does work.
// Set up a container
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
// Setup realm
MapRealm realm = new MapRealm();
realm.addUser("tomcat", "tomcat");
realm.addUserRole("tomcat", "tomcat");
ctx.setRealm(realm);
// Configure app for BASIC auth
LoginConfig lc = new LoginConfig();
lc.setAuthMethod("BASIC");
ctx.setLoginConfig(lc);
ctx.getPipeline().addValve(new BasicAuthenticator());
// Add ServletContainerInitializer
ServletContainerInitializer sci = new Bug50015SCI();
ctx.addServletContainerInitializer(sci, null);
// Start the context
tomcat.start();
// Request the first servlet
ByteChunk bc = new ByteChunk();
int rc = getUrl("http://localhost:" + getPort() + "/bug50015",
bc, null);
// Check for a 401
assertNotSame("OK", bc.toString());
assertEquals(401, rc);
}
private void doTestSecurityAnnotationsAddServlet(boolean useCreateServlet)
throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
Servlet s = new DenyAllServlet();
ServletContainerInitializer sci = new SCI(s, useCreateServlet);
ctx.addServletContainerInitializer(sci, null);
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc;
rc = getUrl("http://localhost:" + getPort() + "/", bc, null, null);
if (useCreateServlet) {
assertTrue(bc.getLength() > 0);
assertEquals(403, rc);
} else {
assertEquals("OK", bc.toString());
assertEquals(200, rc);
}
}
public ServletContainerInitializerInfo(final Class<? extends ServletContainerInitializer> servletContainerInitializerClass, final Set<Class<?>> handlesTypes) {
this.servletContainerInitializerClass = servletContainerInitializerClass;
this.handlesTypes = handlesTypes;
try {
final Constructor<ServletContainerInitializer> ctor = (Constructor<ServletContainerInitializer>) servletContainerInitializerClass.getDeclaredConstructor();
ctor.setAccessible(true);
this.instanceFactory = new ConstructorInstanceFactory<>(ctor);
} catch (NoSuchMethodException e) {
throw UndertowServletMessages.MESSAGES.componentMustHaveDefaultConstructor("ServletContainerInitializer", servletContainerInitializerClass);
}
}
@Bean
public ServletContainerInitializerRegistrationBean<?> omnifacesServletContainerInitializer() throws ClassNotFoundException {
@SuppressWarnings("unchecked")
Class<? extends ServletContainerInitializer> facesViewsInitializerClass = (Class<? extends ServletContainerInitializer>) Class.forName("org.omnifaces.facesviews.FacesViewsInitializer");
return new ServletContainerInitializerRegistrationBean<>(facesViewsInitializerClass);
}
@Bean
public ServletContainerInitializerRegistrationBean<?> omnifacesServletContainerInitializer() throws ClassNotFoundException {
@SuppressWarnings("unchecked")
Class<? extends ServletContainerInitializer> applicationInitializerClass = (Class<? extends ServletContainerInitializer>) Class.forName("org.omnifaces.ApplicationInitializer");
return new ServletContainerInitializerRegistrationBean<>(applicationInitializerClass);
}