use of org.apache.naming.resources.FileDirContext 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());
}
}
}
}
use of org.apache.naming.resources.FileDirContext in project tomcat70 by apache.
the class ContextConfig method processResourceJARs.
/**
* Scan JARs that contain web-fragment.xml files that will be used to
* configure this application to see if they also contain static resources.
* If static resources are found, add them to the context. Resources are
* added in web-fragment.xml priority order.
*/
protected void processResourceJARs(Set<WebXml> fragments) {
for (WebXml fragment : fragments) {
URL url = fragment.getURL();
Jar jar = null;
try {
// Note: Ignore file URLs for now since only jar URLs will be accepted
if ("jar".equals(url.getProtocol())) {
jar = JarFactory.newInstance(url);
jar.nextEntry();
String entryName = jar.getEntryName();
while (entryName != null) {
if (entryName.startsWith("META-INF/resources/")) {
context.addResourceJarUrl(url);
break;
}
jar.nextEntry();
entryName = jar.getEntryName();
}
} else if ("file".equals(url.getProtocol())) {
FileDirContext fileDirContext = new FileDirContext();
fileDirContext.setDocBase(new File(url.toURI()).getAbsolutePath());
try {
fileDirContext.lookup("META-INF/resources/");
// lookup succeeded
if (context instanceof StandardContext) {
((StandardContext) context).addResourcesDirContext(fileDirContext);
}
} catch (NamingException e) {
// not found, ignore
}
}
} catch (IOException ioe) {
log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName()));
} catch (URISyntaxException e) {
log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName()));
} finally {
if (jar != null) {
jar.close();
}
}
}
}
use of org.apache.naming.resources.FileDirContext in project Payara by payara.
the class WebappClassLoaderTest method check_findResourceInternalFromJars_thread_safety.
@Test
public void check_findResourceInternalFromJars_thread_safety() throws Exception {
final WebappClassLoader webappClassLoader = new WebappClassLoader(getClass().getClassLoader(), null);
webappClassLoader.start();
webappClassLoader.setResources(new FileDirContext());
CompletableFuture<Void> result = new CompletableFuture<>();
add(webappClassLoader);
// Create the tasks to run
Runnable lookupTask = waitAndDo(result, () -> lookup(webappClassLoader));
Runnable addTask = waitAndDo(result, () -> add(webappClassLoader));
Runnable closeTask = waitAndDo(result, () -> webappClassLoader.closeJARs(true));
try {
// Run the methods at the same time
for (int i = 0; i < EXECUTION_COUNT; i++) {
executor.execute(addTask);
executor.execute(lookupTask);
executor.execute(closeTask);
}
// Wait for tasks to execute
assertTrue("The tasks didn't finish in the allowed time.", latch.await(20, TimeUnit.SECONDS));
// Check to see if any tasks completed exceptionally
result.getNow(null);
} finally {
webappClassLoader.close();
}
}
use of org.apache.naming.resources.FileDirContext in project Payara by payara.
the class StandardContext method setAlternateResources.
private synchronized void setAlternateResources(AlternateDocBase alternateDocBase, DirContext resources) {
if (started) {
throw new IllegalStateException(rb.getString(LogFacade.RESOURCES_STARTED));
}
final DirContext oldResources = ContextsAdapterUtility.unwrap(alternateDocBase.getWebappResources());
if (oldResources == resources) {
return;
}
if (resources instanceof BaseDirContext) {
((BaseDirContext) resources).setCached(isCachingAllowed());
((BaseDirContext) resources).setCacheTTL(getCacheTTL());
((BaseDirContext) resources).setCacheMaxSize(getCacheMaxSize());
}
if (resources instanceof FileDirContext) {
filesystemBased = true;
((FileDirContext) resources).setCaseSensitive(isCaseSensitive());
((FileDirContext) resources).setAllowLinking(isAllowLinking());
}
alternateDocBase.setWebappResources(ContextsAdapterUtility.wrap(resources));
// The proxied resources will be refreshed on start
alternateDocBase.setResources(null);
}
use of org.apache.naming.resources.FileDirContext in project Payara by payara.
the class StandardContext method start.
/**
* Start this Context component.
*
* @exception LifecycleException if a startup error occurs
*/
@Override
public synchronized void start() throws LifecycleException {
if (started) {
if (log.isLoggable(Level.INFO)) {
log.log(Level.INFO, LogFacade.CONTAINER_ALREADY_STARTED_EXCEPTION, logName());
}
return;
}
long startupTimeStart = System.currentTimeMillis();
if (!initialized) {
try {
init();
} catch (Exception ex) {
throw new LifecycleException("Error initializaing ", ex);
}
}
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Starting {0}", "".equals(getName()) ? "ROOT" : getName());
}
// Set JMX object name for proper pipeline registration
preRegisterJMX();
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
setAvailable(false);
setConfigured(false);
// Add missing components as necessary
if (webappResources == null) {
// (1) Required by Loader
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Configuring default Resources");
}
try {
if ((docBase != null) && (docBase.endsWith(".war")) && (!(new File(docBase).isDirectory()))) {
setResources(new WARDirContext());
} else {
setResources(new WebDirContext());
}
} catch (IllegalArgumentException e) {
throw new LifecycleException(rb.getString(LogFacade.INIT_RESOURCES_EXCEPTION), e);
}
}
resourcesStart();
// Add alternate resources
if (alternateDocBases != null && !alternateDocBases.isEmpty()) {
for (AlternateDocBase alternateDocBase : alternateDocBases) {
String docBase = alternateDocBase.getDocBase();
if (log.isLoggable(Level.FINE)) {
log.log(Level.FINE, "Configuring alternate resources");
}
try {
if (docBase != null && docBase.endsWith(".war") && (!(new File(docBase).isDirectory()))) {
setAlternateResources(alternateDocBase, new WARDirContext());
} else {
setAlternateResources(alternateDocBase, new FileDirContext());
}
} catch (IllegalArgumentException e) {
throw new LifecycleException(rb.getString(LogFacade.INIT_RESOURCES_EXCEPTION), e);
}
}
alternateResourcesStart();
}
if (getLoader() == null) {
createLoader();
}
// Initialize character set mapper
getCharsetMapper();
// Post work directory
postWorkDirectory();
// Validate required extensions
try {
ExtensionValidator.validateApplication(getResources(), this);
} catch (IOException ioe) {
String msg = MessageFormat.format(rb.getString(LogFacade.DEPENDENCY_CHECK_EXCEPTION), this);
throw new LifecycleException(msg, ioe);
}
// Reading the "catalina.useNaming" environment variable
String useNamingProperty = System.getProperty("catalina.useNaming");
if ((useNamingProperty != null) && ("false".equals(useNamingProperty))) {
useNaming = false;
}
if (isUseNaming()) {
if (namingContextListener == null) {
namingContextListener = new NamingContextListener();
namingContextListener.setDebug(getDebug());
namingContextListener.setName(getNamingContextName());
addLifecycleListener(namingContextListener);
}
}
// Binding thread
// START OF SJSAS 8.1 6174179
// ClassLoader oldCCL = bindThread();
ClassLoader oldCCL = null;
try {
started = true;
// Start our subordinate components, if any
if ((loader != null) && (loader instanceof Lifecycle)) {
((Lifecycle) loader).start();
}
if ((logger != null) && (logger instanceof Lifecycle)) {
((Lifecycle) logger).start();
}
// Unbinding thread
// START OF SJSAS 8.1 6174179
// unbindThread(oldCCL);
// END OF SJSAS 8.1 6174179
// Binding thread
oldCCL = bindThread();
if ((realm != null) && (realm instanceof Lifecycle)) {
((Lifecycle) realm).start();
}
if ((resources != null) && (resources instanceof Lifecycle)) {
((Lifecycle) resources).start();
}
// Start our child containers, if any
for (Container child : findChildren()) {
if (child instanceof Lifecycle) {
((Lifecycle) child).start();
}
}
// if any
if (pipeline instanceof Lifecycle) {
((Lifecycle) pipeline).start();
}
// START SJSAS 8.1 5049111
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(START_EVENT, null);
// END SJSAS 8.1 5049111
} catch (Throwable t) {
throw new LifecycleException(t);
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
if (!getConfigured()) {
String msg = MessageFormat.format(rb.getString(LogFacade.STARTUP_CONTEXT_FAILED_EXCEPTION), getName());
throw new LifecycleException(msg);
}
// Store some required info as ServletContext attributes
postResources();
if (orderedLibs != null && !orderedLibs.isEmpty()) {
getServletContext().setAttribute(ServletContext.ORDERED_LIBS, orderedLibs);
context.setAttributeReadOnly(ServletContext.ORDERED_LIBS);
}
// Initialize associated mapper
mapper.setContext(getPath(), welcomeFiles, ContextsAdapterUtility.wrap(resources));
// Binding thread
oldCCL = bindThread();
try {
// Set up the context init params
mergeParameters();
// Notify our interested LifecycleListeners
lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
// Support for pluggability : this has to be done before
// listener events are fired
callServletContainerInitializers();
// Configure and call application event listeners
contextListenerStart();
// Start manager
if ((manager != null) && (manager instanceof Lifecycle)) {
((Lifecycle) getManager()).start();
}
// Start ContainerBackgroundProcessor thread
super.threadStart();
// Configure and call application filters
filterStart();
// Load and initialize all "load on startup" servlets
loadOnStartup(findChildren());
} catch (Throwable t) {
log.log(Level.SEVERE, LogFacade.STARTUP_CONTEXT_FAILED_EXCEPTION, getName());
try {
stop();
} catch (Throwable tt) {
log.log(Level.SEVERE, LogFacade.CLEANUP_FAILED_EXCEPTION, tt);
}
throw new LifecycleException(t);
} finally {
// Unbinding thread
unbindThread(oldCCL);
}
// Set available status depending upon startup success
if (log.isLoggable(Level.FINEST)) {
log.log(Level.FINEST, "Startup successfully completed");
}
setAvailable(true);
// JMX registration
registerJMX();
startTimeMillis = System.currentTimeMillis();
startupTime = startTimeMillis - startupTimeStart;
// Send j2ee.state.running notification
if (getObjectName() != null) {
Notification notification = new Notification("j2ee.state.running", this, sequenceNumber++);
sendNotification(notification);
}
// of files on startup
if (getLoader() instanceof WebappLoader) {
((WebappLoader) getLoader()).closeJARs(true);
}
}
Aggregations