use of javax.servlet.ServletContainerInitializer in project meecrowave by apache.
the class Meecrowave method deployWebapp.
public Meecrowave deployWebapp(final DeploymentMeta meta) {
if (contexts.containsKey(meta.context)) {
throw new IllegalArgumentException("Already deployed: '" + meta.context + "'");
}
// always nice to see the deployment with something else than internals
final String base = tomcat.getService().findConnectors().length > 0 ? (configuration.getActiveProtocol() + "://" + tomcat.getHost().getName() + ':' + configuration.getActivePort()) : "";
new LogFacade(Meecrowave.class.getName()).info("--------------- " + base + meta.context);
final OWBJarScanner scanner = new OWBJarScanner();
final StandardContext ctx = new StandardContext() {
@Override
public void setApplicationEventListeners(final Object[] listeners) {
if (listeners == null) {
super.setApplicationEventListeners(null);
return;
}
// if we don't -> no @RequestScoped in request listeners :(
for (int i = 1; i < listeners.length; i++) {
if (OWBAutoSetup.EagerBootListener.class.isInstance(listeners[i])) {
final Object first = listeners[0];
listeners[0] = listeners[i];
listeners[i] = first;
break;
}
}
// and finally let it go after our re-ordering
super.setApplicationEventListeners(listeners);
}
};
ctx.setPath(meta.context);
ctx.setName(meta.context);
ctx.setJarScanner(scanner);
ctx.setInstanceManager(new CDIInstanceManager());
ofNullable(meta.docBase).ifPresent(d -> {
try {
ctx.setDocBase(meta.docBase.getCanonicalPath());
} catch (final IOException e) {
ctx.setDocBase(meta.docBase.getAbsolutePath());
}
});
ofNullable(configuration.getTomcatFilter()).ifPresent(filter -> {
try {
scanner.setJarScanFilter(JarScanFilter.class.cast(Thread.currentThread().getContextClassLoader().loadClass(filter).newInstance()));
} catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
});
final AtomicReference<Runnable> releaseSCI = new AtomicReference<>();
final ServletContainerInitializer meecrowaveInitializer = (c, ctx1) -> {
ctx1.setAttribute("meecrowave.configuration", getConfiguration());
ctx1.setAttribute("meecrowave.instance", Meecrowave.this);
new OWBAutoSetup().onStartup(c, ctx1);
if (Cxfs.IS_PRESENT) {
new CxfCdiAutoSetup().onStartup(c, ctx1);
}
new TomcatAutoInitializer().onStartup(c, ctx1);
if (configuration.isInjectServletContainerInitializer()) {
final Field f;
try {
// now cdi is on, we can inject cdi beans in ServletContainerInitializer
f = StandardContext.class.getDeclaredField("initializers");
if (!f.isAccessible()) {
f.setAccessible(true);
}
} catch (final Exception e) {
throw new IllegalStateException("Bad tomcat version", e);
}
final List<AutoCloseable> cc;
try {
cc = ((Map<ServletContainerInitializer, Set<Class<?>>>) f.get(ctx)).keySet().stream().filter(i -> !i.getClass().getName().startsWith(Meecrowave.class.getName())).map(i -> {
try {
return this.inject(i);
} catch (final IllegalArgumentException iae) {
return null;
}
}).filter(Objects::nonNull).collect(toList());
} catch (final IllegalAccessException e) {
throw new IllegalStateException("Can't read initializers", e);
}
releaseSCI.set(() -> cc.forEach(closeable -> {
try {
closeable.close();
} catch (final Exception e) {
throw new IllegalStateException(e);
}
}));
}
};
ctx.addLifecycleListener(new MeecrowaveContextConfig(configuration, meta.docBase != null, meecrowaveInitializer, meta.redeployCallback));
ctx.addLifecycleListener(event -> {
switch(event.getType()) {
case Lifecycle.BEFORE_START_EVENT:
if (configuration.getWebSessionCookieConfig() != null) {
final Properties p = new Properties();
try {
p.load(new StringReader(configuration.getWebSessionCookieConfig()));
} catch (final IOException e) {
throw new IllegalArgumentException(e);
}
if (p.containsKey("domain")) {
ctx.setSessionCookieDomain(p.getProperty("domain"));
}
if (p.containsKey("path")) {
ctx.setSessionCookiePath(p.getProperty("path"));
}
if (p.containsKey("name")) {
ctx.setSessionCookieName(p.getProperty("name"));
}
if (p.containsKey("use-trailing-slash")) {
ctx.setSessionCookiePathUsesTrailingSlash(Boolean.parseBoolean(p.getProperty("use-trailing-slash")));
}
if (p.containsKey("http-only")) {
ctx.setUseHttpOnly(Boolean.parseBoolean(p.getProperty("http-only")));
}
if (p.containsKey("secured")) {
final SessionCookieConfig sessionCookieConfig = ctx.getServletContext().getSessionCookieConfig();
sessionCookieConfig.setSecure(Boolean.parseBoolean(p.getProperty("secured")));
}
}
break;
case Lifecycle.AFTER_START_EVENT:
ctx.getResources().setCachingAllowed(configuration.isWebResourceCached());
break;
case Lifecycle.BEFORE_INIT_EVENT:
if (configuration.getLoginConfig() != null) {
ctx.setLoginConfig(configuration.getLoginConfig().build());
}
for (final SecurityConstaintBuilder sc : configuration.getSecurityConstraints()) {
ctx.addConstraint(sc.build());
}
if (configuration.getWebXml() != null) {
ctx.getServletContext().setAttribute(Globals.ALT_DD_ATTR, configuration.getWebXml());
}
break;
default:
}
});
// after having configured the security!!!
ctx.addLifecycleListener(new Tomcat.FixContextListener());
ctx.addServletContainerInitializer(meecrowaveInitializer, emptySet());
if (configuration.isUseTomcatDefaults()) {
ctx.setSessionTimeout(configuration.getWebSessionTimeout() != null ? configuration.getWebSessionTimeout() : 30);
ctx.addWelcomeFile("index.html");
ctx.addWelcomeFile("index.htm");
Tomcat.addDefaultMimeTypeMappings(ctx);
} else if (configuration.getWebSessionTimeout() != null) {
ctx.setSessionTimeout(configuration.getWebSessionTimeout());
}
ofNullable(meta.consumer).ifPresent(c -> c.accept(ctx));
if (configuration.isQuickSession() && ctx.getManager() == null) {
final StandardManager manager = new StandardManager();
manager.setSessionIdGenerator(new StandardSessionIdGenerator() {
@Override
protected void getRandomBytes(final byte[] bytes) {
ThreadLocalRandom.current().nextBytes(bytes);
}
@Override
public String toString() {
return "MeecrowaveSessionIdGenerator@" + System.identityHashCode(this);
}
});
ctx.setManager(manager);
}
if (configuration.isAntiResourceLocking() && StandardContext.class.isInstance(ctx)) {
StandardContext.class.cast(ctx).setAntiResourceLocking(true);
}
configuration.getInitializers().forEach(i -> ctx.addServletContainerInitializer(i, emptySet()));
configuration.getGlobalContextConfigurers().forEach(it -> it.accept(ctx));
final Host host = tomcat.getHost();
host.addChild(ctx);
final ClassLoader classLoader = ctx.getLoader().getClassLoader();
if (host.getState().isAvailable()) {
fire(new StartListening(findFirstConnector(), host, ctx), classLoader);
}
contexts.put(meta.context, () -> {
if (host.getState().isAvailable()) {
fire(new StopListening(findFirstConnector(), host, ctx), classLoader);
}
ofNullable(releaseSCI.get()).ifPresent(Runnable::run);
tomcat.getHost().removeChild(ctx);
});
return this;
}
use of javax.servlet.ServletContainerInitializer in project sofa-ark by alipay.
the class ArkTomcatServletWebServerFactory method addJasperInitializer.
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
}
}
use of javax.servlet.ServletContainerInitializer in project tomcat70 by apache.
the class StandardContext method startInternal.
/**
* Start this component and implement the requirements
* of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected synchronized void startInternal() throws LifecycleException {
if (log.isDebugEnabled())
log.debug("Starting " + getBaseName());
// Send j2ee.state.starting notification
if (this.getObjectName() != null) {
Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
setConfigured(false);
boolean ok = true;
// ensure the NamingResources follows the correct lifecycle
if (namingResources != null) {
namingResources.start();
}
// Add missing components as necessary
if (webappResources == null) {
// (1) Required by Loader
if (log.isDebugEnabled())
log.debug("Configuring default Resources");
try {
String docBase = getDocBase();
if (docBase == null) {
setResources(new EmptyDirContext());
} else if (docBase.endsWith(".war") && !(new File(getBasePath())).isDirectory()) {
setResources(new WARDirContext());
} else {
setResources(new FileDirContext());
}
} catch (IllegalArgumentException e) {
log.error(sm.getString("standardContext.resourcesInit"), e);
ok = false;
}
}
if (ok) {
if (!resourcesStart()) {
throw new LifecycleException("Error in resourceStart()");
}
}
if (getLoader() == null) {
WebappLoader webappLoader = new WebappLoader(getParentClassLoader());
webappLoader.setDelegate(getDelegate());
setLoader(webappLoader);
}
// Initialize character set mapper
getCharsetMapper();
// Post work directory
postWorkDirectory();
// Validate required extensions
boolean dependencyCheck = true;
try {
dependencyCheck = ExtensionValidator.validateApplication(getResources(), this);
} catch (IOException ioe) {
log.error(sm.getString("standardContext.extensionValidationError"), ioe);
dependencyCheck = false;
}
if (!dependencyCheck) {
// do not make application available if dependency check fails
ok = false;
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) {
useNaming = false;
}
if (ok && isUseNaming()) {
if (getNamingContextListener() == null) {
NamingContextListener ncl = new NamingContextListener();
ncl.setName(getNamingContextName());
ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite());
addLifecycleListener(ncl);
setNamingContextListener(ncl);
}
}
// Standard container startup
if (log.isDebugEnabled())
log.debug("Processing standard container startup");
// Binding thread
ClassLoader oldCCL = bindThread();
try {
if (ok) {
// Start our subordinate components, if any
Loader loader = getLoaderInternal();
if ((loader != null) && (loader instanceof Lifecycle))
((Lifecycle) loader).start();
// since the loader just started, the webapp classloader is now
// created.
// By calling unbindThread and bindThread in a row, we setup the
// current Thread CCL to be the webapp classloader
unbindThread(oldCCL);
oldCCL = bindThread();
// Initialize logger again. Other components might have used it
// too early, so it should be reset.
logger = null;
getLogger();
Cluster cluster = getClusterInternal();
if ((cluster != null) && (cluster instanceof Lifecycle))
((Lifecycle) cluster).start();
Realm realm = getRealmInternal();
if ((realm != null) && (realm instanceof Lifecycle))
((Lifecycle) realm).start();
DirContext resources = getResourcesInternal();
if ((resources != null) && (resources instanceof Lifecycle))
((Lifecycle) resources).start();
// Notify our interested LifecycleListeners
fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null);
// Start our child containers, if not already started
for (Container child : findChildren()) {
if (!child.getState().isAvailable()) {
child.start();
}
}
// if any
if (pipeline instanceof Lifecycle) {
((Lifecycle) pipeline).start();
}
// Acquire clustered manager
Manager contextManager = null;
Manager manager = getManagerInternal();
if (manager == null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("standardContext.cluster.noManager", Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable)));
}
if ((getCluster() != null) && distributable) {
try {
contextManager = getCluster().createManager(getName());
} catch (Exception ex) {
log.error("standardContext.clusterFail", ex);
ok = false;
}
} else {
contextManager = new StandardManager();
}
manager = contextManager;
}
// Configure default manager if none was specified
if (contextManager != null) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName()));
}
setManager(contextManager);
}
if (manager != null && (getCluster() != null) && distributable) {
// let the cluster know that there is a context that is distributable
// and that it has its own manager
getCluster().registerManager(manager);
}
}
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
if (!getConfigured()) {
log.error(sm.getString("standardContext.configurationFail"));
ok = false;
}
// We put the resources into the servlet context
if (ok)
getServletContext().setAttribute(Globals.RESOURCES_ATTR, getResources());
// Initialize associated mapper
mapper.setContext(getPath(), welcomeFiles, getResources());
// Binding thread
oldCCL = bindThread();
if (ok) {
if (getInstanceManager() == null) {
javax.naming.Context context = null;
if (isUseNaming() && getNamingContextListener() != null) {
context = getNamingContextListener().getEnvContext();
}
Map<String, Map<String, String>> injectionMap = buildInjectionMap(getIgnoreAnnotations() ? new NamingResources() : getNamingResources());
setInstanceManager(new DefaultInstanceManager(context, injectionMap, this, this.getClass().getClassLoader()));
getServletContext().setAttribute(InstanceManager.class.getName(), getInstanceManager());
}
}
try {
// Create context attributes that will be required
if (ok) {
getServletContext().setAttribute(JarScanner.class.getName(), getJarScanner());
}
// Set up the context init params
mergeParameters();
// Call ServletContainerInitializers
for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) {
try {
entry.getKey().onStartup(entry.getValue(), getServletContext());
} catch (ServletException e) {
log.error(sm.getString("standardContext.sciFail"), e);
ok = false;
break;
}
}
// Configure and call application event listeners
if (ok) {
if (!listenerStart()) {
log.error(sm.getString("standardContext.listenerFail"));
ok = false;
}
}
try {
// Start manager
Manager manager = getManagerInternal();
if ((manager != null) && (manager instanceof Lifecycle)) {
((Lifecycle) getManager()).start();
}
} catch (Exception e) {
log.error(sm.getString("standardContext.managerFail"), e);
ok = false;
}
// Configure and call application filters
if (ok) {
if (!filterStart()) {
log.error(sm.getString("standardContext.filterFail"));
ok = false;
}
}
// Load and initialize all "load on startup" servlets
if (ok) {
if (!loadOnStartup(findChildren())) {
log.error(sm.getString("standardContext.servletFail"));
ok = false;
}
}
// Start ContainerBackgroundProcessor thread
super.threadStart();
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
// Set available status depending upon startup success
if (ok) {
if (log.isDebugEnabled())
log.debug("Starting completed");
} else {
log.error(sm.getString("standardContext.startFailed", getName()));
}
startTime = System.currentTimeMillis();
// Send j2ee.state.running notification
if (ok && (this.getObjectName() != null)) {
Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber.getAndIncrement());
broadcaster.sendNotification(notification);
}
// of files on startup
if (getLoader() instanceof WebappLoader) {
((WebappLoader) getLoader()).closeJARs(true);
}
// Reinitializing if something went wrong
if (!ok) {
setState(LifecycleState.FAILED);
} else {
setState(LifecycleState.STARTING);
}
}
use of javax.servlet.ServletContainerInitializer in project tomcat70 by apache.
the class TestContextConfigAnnotation method testCheckHandleTypes.
@Test
public void testCheckHandleTypes() throws Exception {
ContextConfig config = new ContextConfig();
config.handlesTypesAnnotations = true;
config.handlesTypesNonAnnotations = true;
// Need a Context, Loader and ClassLoader for checkHandleTypes
StandardContext context = new StandardContext();
context.setLoader(new TesterLoader());
config.context = context;
// Add an SCI that has no interest in any type
SCI sciNone = new SCI();
config.initializerClassMap.put(sciNone, new HashSet<Class<?>>());
// Add an SCI with an interest in Servlets
SCI sciServlet = new SCI();
config.initializerClassMap.put(sciServlet, new HashSet<Class<?>>());
config.typeInitializerMap.put(Servlet.class, new HashSet<ServletContainerInitializer>());
config.typeInitializerMap.get(Servlet.class).add(sciServlet);
// Add an SCI with an interest in Objects - i.e. everything
SCI sciObject = new SCI();
config.initializerClassMap.put(sciObject, new HashSet<Class<?>>());
config.typeInitializerMap.put(Object.class, new HashSet<ServletContainerInitializer>());
config.typeInitializerMap.get(Object.class).add(sciObject);
// Scan Servlet, Filter, Servlet, Listener
WebXml ignore = new WebXml();
File file = paramClassResource("org/apache/catalina/startup/ParamServlet");
config.processAnnotationsFile(file, ignore, false);
file = paramClassResource("org/apache/catalina/startup/ParamFilter");
config.processAnnotationsFile(file, ignore, false);
file = paramClassResource("org/apache/catalina/startup/TesterServlet");
config.processAnnotationsFile(file, ignore, false);
file = paramClassResource("org/apache/catalina/startup/TestListener");
config.processAnnotationsFile(file, ignore, false);
// Check right number of classes were noted to be handled
Assert.assertEquals(0, config.initializerClassMap.get(sciNone).size());
Assert.assertEquals(2, config.initializerClassMap.get(sciServlet).size());
Assert.assertEquals(4, config.initializerClassMap.get(sciObject).size());
}
use of javax.servlet.ServletContainerInitializer in project tomcat70 by apache.
the class ContextConfig method webConfig.
/**
* Scan the web.xml files that apply to the web application and merge them
* using the rules defined in the spec. For the global web.xml files,
* where there is duplicate configuration, the most specific level wins. ie
* an application's web.xml takes precedence over the host level or global
* web.xml file.
*/
protected void webConfig() {
/*
* Anything and everything can override the global and host defaults.
* This is implemented in two parts
* - Handle as a web fragment that gets added after everything else so
* everything else takes priority
* - Mark Servlets as overridable so SCI configuration can replace
* configuration from the defaults
*/
/*
* The rules for annotation scanning are not as clear-cut as one might
* think. Tomcat implements the following process:
* - As per SRV.1.6.2, Tomcat will scan for annotations regardless of
* which Servlet spec version is declared in web.xml. The EG has
* confirmed this is the expected behaviour.
* - As per http://java.net/jira/browse/SERVLET_SPEC-36, if the main
* web.xml is marked as metadata-complete, JARs are still processed
* for SCIs.
* - If metadata-complete=true and an absolute ordering is specified,
* JARs excluded from the ordering are also excluded from the SCI
* processing.
* - If an SCI has a @HandlesType annotation then all classes (except
* those in JARs excluded from an absolute ordering) need to be
* scanned to check if they match.
*/
Set<WebXml> defaults = new HashSet<WebXml>();
defaults.add(getDefaultWebXmlFragment());
WebXml webXml = createWebXml();
// Parse context level web.xml
InputSource contextWebXml = getContextWebXmlSource();
parseWebXml(contextWebXml, webXml, false);
ServletContext sContext = context.getServletContext();
// Ordering is important here
// Step 1. Identify all the JARs packaged with the application
// If the JARs have a web-fragment.xml it will be parsed at this
// point.
Map<String, WebXml> fragments = processJarsForWebFragments(webXml);
// Step 2. Order the fragments.
Set<WebXml> orderedFragments = null;
orderedFragments = WebXml.orderWebFragments(webXml, fragments, sContext);
// Step 3. Look for ServletContainerInitializer implementations
if (ok) {
processServletContainerInitializers();
}
if (!webXml.isMetadataComplete() || typeInitializerMap.size() > 0) {
// Step 4. Process /WEB-INF/classes for annotations
if (ok) {
// Hack required by Eclipse's "serve modules without
// publishing" feature since this backs WEB-INF/classes by
// multiple locations rather than one.
NamingEnumeration<Binding> listBindings = null;
try {
try {
listBindings = context.getResources().listBindings("/WEB-INF/classes");
} catch (NameNotFoundException ignore) {
// Safe to ignore
}
while (listBindings != null && listBindings.hasMoreElements()) {
Binding binding = listBindings.nextElement();
if (binding.getObject() instanceof FileDirContext) {
File webInfClassDir = new File(((FileDirContext) binding.getObject()).getDocBase());
processAnnotationsFile(webInfClassDir, webXml, webXml.isMetadataComplete());
} else if ("META-INF".equals(binding.getName())) {
// Skip the META-INF directory from any JARs that have been
// expanded in to WEB-INF/classes (sometimes IDEs do this).
} else {
String resource = "/WEB-INF/classes/" + binding.getName();
try {
URL url = sContext.getResource(resource);
processAnnotationsUrl(url, webXml, webXml.isMetadataComplete());
} catch (MalformedURLException e) {
log.error(sm.getString("contextConfig.webinfClassesUrl", resource), e);
}
}
}
} catch (NamingException e) {
log.error(sm.getString("contextConfig.webinfClassesUrl", "/WEB-INF/classes"), e);
}
}
// those fragments we are going to use
if (ok) {
processAnnotations(orderedFragments, webXml.isMetadataComplete());
}
// Cache, if used, is no longer required so clear it
javaClassCache.clear();
}
if (!webXml.isMetadataComplete()) {
// file.
if (ok) {
ok = webXml.merge(orderedFragments);
}
// Step 7. Apply global defaults
// Have to merge defaults before JSP conversion since defaults
// provide JSP servlet definition.
webXml.merge(defaults);
// Step 8. Convert explicitly mentioned jsps to servlets
if (ok) {
convertJsps(webXml);
}
// Step 9. Apply merged web.xml to Context
if (ok) {
webXml.configureContext(context);
}
} else {
webXml.merge(defaults);
convertJsps(webXml);
webXml.configureContext(context);
}
// Step 9a. Make the merged web.xml available to other
// components, specifically Jasper, to save those components
// from having to re-generate it.
// TODO Use a ServletContainerInitializer for Jasper
String mergedWebXml = webXml.toXml();
sContext.setAttribute(org.apache.tomcat.util.scan.Constants.MERGED_WEB_XML, mergedWebXml);
if (context.getLogEffectiveWebXml()) {
log.info("web.xml:\n" + mergedWebXml);
}
// Step 10. Look for static resources packaged in JARs
if (ok) {
// Spec does not define an order.
// Use ordered JARs followed by remaining JARs
Set<WebXml> resourceJars = new LinkedHashSet<WebXml>();
for (WebXml fragment : orderedFragments) {
resourceJars.add(fragment);
}
for (WebXml fragment : fragments.values()) {
if (!resourceJars.contains(fragment)) {
resourceJars.add(fragment);
}
}
processResourceJARs(resourceJars);
// See also StandardContext.resourcesStart() for
// WEB-INF/classes/META-INF/resources configuration
}
// context
if (ok) {
for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializerClassMap.entrySet()) {
if (entry.getValue().isEmpty()) {
context.addServletContainerInitializer(entry.getKey(), null);
} else {
context.addServletContainerInitializer(entry.getKey(), entry.getValue());
}
}
}
}
Aggregations