Search in sources :

Example 1 with WebAppClassLoader

use of org.eclipse.jetty.webapp.WebAppClassLoader in project jetty.project by eclipse.

the class OverlayedAppProvider method createContextHandler.

/**
     * Create Context Handler.
     * <p>
     * Callback from the deployment manager to create a context handler instance.
     * @see org.eclipse.jetty.deploy.AppProvider#createContextHandler(org.eclipse.jetty.deploy.App)
     */
public synchronized ContextHandler createContextHandler(App app) throws Exception {
    final OverlayedApp overlayed = (OverlayedApp) app;
    final String origin = overlayed.getOriginId();
    final Instance instance = overlayed.getInstance();
    final Template template = instance.getTemplate();
    final Webapp webapp = template.getWebapp();
    final Node node = _node;
    // remember the original loader
    ClassLoader orig_loader = Thread.currentThread().getContextClassLoader();
    try {
        // Look for existing shared resources
        String key = (node == null ? "" : node.getLoadedKey()) + template.getLoadedKey() + (webapp == null ? "" : webapp.getLoadedKey());
        instance.setSharedKey(key);
        TemplateContext shared = _shared.get(key);
        // Create shared resourced
        if (shared == null)
            shared = createTemplateContext(key, webapp, template, node, orig_loader);
        // Build the instance lib loader
        ClassLoader shared_loader = shared.getWebappLoader() != null ? shared.getWebappLoader() : (shared.getLibLoader() != null ? shared.getLibLoader() : orig_loader);
        ClassLoader loader = shared_loader;
        Resource instance_lib = instance.getResource(LIB);
        if (instance_lib.exists()) {
            List<URL> libs = new ArrayList<URL>();
            for (String jar : instance_lib.list()) {
                if (!jar.toLowerCase(Locale.ENGLISH).endsWith(".jar"))
                    continue;
                libs.add(instance_lib.addPath(jar).getURL());
            }
            __log.debug("{}: libs={}", origin, libs);
            loader = URLClassLoader.newInstance(libs.toArray(new URL[] {}), loader);
        }
        // set the thread loader
        Thread.currentThread().setContextClassLoader(loader);
        // Create properties to be shared by overlay.xmls
        Map<String, Object> idMap = new HashMap<String, Object>();
        idMap.putAll(shared.getIdMap());
        idMap.put(_serverID, getDeploymentManager().getServer());
        // Create the instance context for the template
        ContextHandler context = null;
        Resource template_context_xml = template.getResource(OVERLAY_XML);
        if (template_context_xml.exists()) {
            __log.debug("{}: overlay.xml={}", origin, template_context_xml);
            XmlConfiguration xmlc = newXmlConfiguration(template_context_xml.getURL(), idMap, template, instance);
            context = (ContextHandler) xmlc.configure();
            idMap = xmlc.getIdMap();
        } else if (webapp == null)
            // If there is no webapp, this is a plain context
            context = new ContextHandler();
        else
            // It is a webapp context
            context = new WebAppContext();
        // Set the resource base
        final Resource instance_webapp = instance.getResource(WEBAPP);
        if (instance_webapp.exists()) {
            context.setBaseResource(new ResourceCollection(instance_webapp, shared.getBaseResource()));
            // Create the resource cache
            ResourceCache cache = new ResourceCache(shared.getResourceCache(), instance_webapp, context.getMimeTypes(), false, false);
            context.setAttribute(ResourceCache.class.getCanonicalName(), cache);
        } else {
            context.setBaseResource(shared.getBaseResource());
            context.setAttribute(ResourceCache.class.getCanonicalName(), shared.getResourceCache());
        }
        __log.debug("{}: baseResource={}", origin, context.getResourceBase());
        // Set the shared session scavenger timer
        context.setAttribute("org.eclipse.jetty.server.session.timer", _sessionScavenger);
        // Apply any node or instance overlay.xml
        for (Resource context_xml : getLayeredResources(OVERLAY_XML, node, instance)) {
            __log.debug("{}: overlay.xml={}", origin, context_xml);
            XmlConfiguration xmlc = newXmlConfiguration(context_xml.getURL(), idMap, template, instance);
            xmlc.getIdMap().put("Cache", context.getAttribute(ResourceCache.class.getCanonicalName()));
            xmlc.configure(context);
            idMap = xmlc.getIdMap();
        }
        // Is it a webapp?
        if (context instanceof WebAppContext) {
            final WebAppContext webappcontext = (WebAppContext) context;
            if (Arrays.asList(((WebAppContext) context).getServerClasses()).toString().equals(Arrays.asList(WebAppContext.__dftServerClasses).toString())) {
                __log.debug("clear server classes");
                webappcontext.setServerClasses(null);
            }
            // set classloader
            webappcontext.setCopyWebDir(false);
            webappcontext.setCopyWebInf(false);
            webappcontext.setExtractWAR(false);
            if (instance_webapp.exists()) {
                final Resource classes = instance_webapp.addPath("WEB-INF/classes");
                final Resource lib = instance_webapp.addPath("WEB-INF/lib");
                if (classes.exists() || lib.exists()) {
                    final AtomicBoolean locked = new AtomicBoolean(false);
                    WebAppClassLoader webapp_loader = new WebAppClassLoader(loader, webappcontext) {

                        @Override
                        public void addClassPath(Resource resource) throws IOException {
                            if (!locked.get())
                                super.addClassPath(resource);
                        }

                        @Override
                        public void addClassPath(String classPath) throws IOException {
                            if (!locked.get())
                                super.addClassPath(classPath);
                        }

                        @Override
                        public void addJars(Resource lib) {
                            if (!locked.get())
                                super.addJars(lib);
                        }
                    };
                    if (classes.exists())
                        webapp_loader.addClassPath(classes);
                    if (lib.exists())
                        webapp_loader.addJars(lib);
                    locked.set(true);
                    loader = webapp_loader;
                }
            }
            // Make sure loader is unique for JNDI
            if (loader == shared_loader)
                loader = new URLClassLoader(new URL[] {}, shared_loader);
            // add default descriptor
            List<Resource> webdefaults = getLayeredResources(WEB_DEFAULT_XML, instance, node, template);
            if (webdefaults.size() > 0) {
                Resource webdefault = webdefaults.get(0);
                __log.debug("{}: defaultweb={}", origin, webdefault);
                webappcontext.setDefaultsDescriptor(webdefault.toString());
            }
            // add overlay descriptors
            for (Resource override : getLayeredResources(WEB_FRAGMENT_XML, template, node, instance)) {
                __log.debug("{}: web override={}", origin, override);
                webappcontext.addOverrideDescriptor(override.toString());
            }
        }
        context.setClassLoader(loader);
        __log.debug("{}: baseResource={}", origin, context.getBaseResource());
        Resource jetty_web_xml = context.getResource("/WEB-INF/" + JettyWebXmlConfiguration.JETTY_WEB_XML);
        if (jetty_web_xml != null && jetty_web_xml.exists())
            context.setAttribute(JettyWebXmlConfiguration.XML_CONFIGURATION, newXmlConfiguration(jetty_web_xml.getURL(), idMap, template, instance));
        // Add listener to expand parameters from descriptors before other listeners execute
        Map<String, String> params = new HashMap<String, String>();
        populateParameters(params, template, instance);
        context.addEventListener(new ParameterExpander(params, context));
        System.err.println("created:\n" + context.dump());
        return context;
    } finally {
        Thread.currentThread().setContextClassLoader(orig_loader);
    }
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) JettyWebXmlConfiguration(org.eclipse.jetty.webapp.JettyWebXmlConfiguration) URL(java.net.URL) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) URLClassLoader(java.net.URLClassLoader) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) ResourceCache(org.eclipse.jetty.server.ResourceCache) JarResource(org.eclipse.jetty.util.resource.JarResource) Resource(org.eclipse.jetty.util.resource.Resource) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) URLClassLoader(java.net.URLClassLoader) ResourceCollection(org.eclipse.jetty.util.resource.ResourceCollection)

Example 2 with WebAppClassLoader

use of org.eclipse.jetty.webapp.WebAppClassLoader in project jetty.project by eclipse.

the class TestConfiguration method testIt.

@Test
public void testIt() throws Exception {
    ClassLoader old_loader = Thread.currentThread().getContextClassLoader();
    try {
        InitialContext ic = new InitialContext();
        Server server = new Server();
        WebAppContext wac = new WebAppContext();
        wac.setServer(server);
        wac.setClassLoader(new WebAppClassLoader(Thread.currentThread().getContextClassLoader(), wac));
        MetaData metaData = new MetaData();
        PlusDescriptorProcessor plusProcessor = new PlusDescriptorProcessor();
        //bind some EnvEntrys at the server level
        EnvEntry ee1 = new EnvEntry(server, "xxx/a", "100", true);
        EnvEntry ee2 = new EnvEntry(server, "yyy/b", "200", false);
        EnvEntry ee3 = new EnvEntry(server, "zzz/c", "300", false);
        EnvEntry ee4 = new EnvEntry(server, "zzz/d", "400", false);
        EnvEntry ee5 = new EnvEntry(server, "zzz/f", "500", true);
        //bind some EnvEntrys at the webapp level
        EnvEntry ee6 = new EnvEntry(wac, "xxx/a", "900", true);
        EnvEntry ee7 = new EnvEntry(wac, "yyy/b", "910", true);
        EnvEntry ee8 = new EnvEntry(wac, "zzz/c", "920", false);
        EnvEntry ee9 = new EnvEntry(wac, "zzz/e", "930", false);
        assertNotNull(NamingEntryUtil.lookupNamingEntry(server, "xxx/a"));
        assertNotNull(NamingEntryUtil.lookupNamingEntry(server, "yyy/b"));
        assertNotNull(NamingEntryUtil.lookupNamingEntry(server, "zzz/c"));
        assertNotNull(NamingEntryUtil.lookupNamingEntry(server, "zzz/d"));
        assertNotNull(NamingEntryUtil.lookupNamingEntry(wac, "xxx/a"));
        assertNotNull(NamingEntryUtil.lookupNamingEntry(wac, "yyy/b"));
        assertNotNull(NamingEntryUtil.lookupNamingEntry(wac, "zzz/c"));
        assertNotNull(NamingEntryUtil.lookupNamingEntry(wac, "zzz/e"));
        //make a new env configuration
        EnvConfiguration envConfig = new EnvConfiguration();
        Thread.currentThread().setContextClassLoader(wac.getClassLoader());
        MetaData metadata = new MetaData();
        envConfig.preConfigure(wac);
        envConfig.configure(wac);
        envConfig.bindEnvEntries(wac);
        String val = (String) ic.lookup("java:comp/env/xxx/a");
        //webapp naming overrides server
        assertEquals("900", val);
        val = (String) ic.lookup("java:comp/env/yyy/b");
        //webapp overrides server
        assertEquals("910", val);
        val = (String) ic.lookup("java:comp/env/zzz/c");
        //webapp overrides server
        assertEquals("920", val);
        val = (String) ic.lookup("java:comp/env/zzz/d");
        //from server naming
        assertEquals("400", val);
        val = (String) ic.lookup("java:comp/env/zzz/e");
        //from webapp naming
        assertEquals("930", val);
        NamingEntry ne = (NamingEntry) ic.lookup("java:comp/env/" + NamingEntry.__contextName + "/xxx/a");
        assertNotNull(ne);
        ne = (NamingEntry) ic.lookup("java:comp/env/" + NamingEntry.__contextName + "/yyy/b");
        assertNotNull(ne);
        ne = (NamingEntry) ic.lookup("java:comp/env/" + NamingEntry.__contextName + "/zzz/c");
        assertNotNull(ne);
        ne = (NamingEntry) ic.lookup("java:comp/env/" + NamingEntry.__contextName + "/zzz/d");
        assertNotNull(ne);
        ne = (NamingEntry) ic.lookup("java:comp/env/" + NamingEntry.__contextName + "/zzz/e");
        assertNotNull(ne);
        plusProcessor.bindEnvEntry("foo", "99");
        assertEquals("99", ic.lookup("java:comp/env/foo"));
        plusProcessor.bindEnvEntry("xxx/a", "7");
        //webapp overrides web.xml
        assertEquals("900", ic.lookup("java:comp/env/xxx/a"));
        plusProcessor.bindEnvEntry("yyy/b", "7");
        //webapp overrides web.xml
        assertEquals("910", ic.lookup("java:comp/env/yyy/b"));
        plusProcessor.bindEnvEntry("zzz/c", "7");
        //webapp does NOT override web.xml
        assertEquals("7", ic.lookup("java:comp/env/zzz/c"));
        plusProcessor.bindEnvEntry("zzz/d", "7");
        //server does NOT override web.xml
        assertEquals("7", ic.lookup("java:comp/env/zzz/d"));
        plusProcessor.bindEnvEntry("zzz/e", "7");
        //webapp does NOT override web.xml
        assertEquals("7", ic.lookup("java:comp/env/zzz/e"));
        plusProcessor.bindEnvEntry("zzz/f", "7");
        //server overrides web.xml
        assertEquals("500", ic.lookup("java:comp/env/zzz/f"));
        ((Context) ic.lookup("java:comp")).destroySubcontext("env");
        ic.destroySubcontext("xxx");
        ic.destroySubcontext("yyy");
        ic.destroySubcontext("zzz");
    } finally {
        Thread.currentThread().setContextClassLoader(old_loader);
    }
}
Also used : InitialContext(javax.naming.InitialContext) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) Context(javax.naming.Context) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) Server(org.eclipse.jetty.server.Server) MetaData(org.eclipse.jetty.webapp.MetaData) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) NamingEntry(org.eclipse.jetty.plus.jndi.NamingEntry) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) InitialContext(javax.naming.InitialContext) EnvEntry(org.eclipse.jetty.plus.jndi.EnvEntry) Test(org.junit.Test)

Example 3 with WebAppClassLoader

use of org.eclipse.jetty.webapp.WebAppClassLoader in project jetty.project by eclipse.

the class QuickStartConfiguration method configure.

/**
     * @see org.eclipse.jetty.webapp.AbstractConfiguration#configure(org.eclipse.jetty.webapp.WebAppContext)
     */
@Override
public void configure(WebAppContext context) throws Exception {
    LOG.debug("configure {}", this);
    if (context.isStarted()) {
        LOG.warn("Cannot configure webapp after it is started");
        return;
    }
    //Temporary:  set up the classpath here. This should be handled by the QuickStartDescriptorProcessor
    Resource webInf = context.getWebInf();
    if (webInf != null && webInf.isDirectory() && context.getClassLoader() instanceof WebAppClassLoader) {
        // Look for classes directory
        Resource classes = webInf.addPath("classes/");
        if (classes.exists())
            ((WebAppClassLoader) context.getClassLoader()).addClassPath(classes);
        // Look for jars
        Resource lib = webInf.addPath("lib/");
        if (lib.exists() || lib.isDirectory())
            ((WebAppClassLoader) context.getClassLoader()).addJars(lib);
    }
    //add the processor to handle normal web.xml content
    context.getMetaData().addDescriptorProcessor(new StandardDescriptorProcessor());
    //add a processor to handle extended web.xml format
    context.getMetaData().addDescriptorProcessor(new QuickStartDescriptorProcessor());
    //add a decorator that will find introspectable annotations
    //this must be the last Decorator because they are run in reverse order!
    context.getObjectFactory().addDecorator(new AnnotationDecorator(context));
    //add a context bean that will run ServletContainerInitializers as the context starts
    ServletContainerInitializersStarter starter = (ServletContainerInitializersStarter) context.getAttribute(AnnotationConfiguration.CONTAINER_INITIALIZER_STARTER);
    if (starter != null)
        throw new IllegalStateException("ServletContainerInitializersStarter already exists");
    starter = new ServletContainerInitializersStarter(context);
    context.setAttribute(AnnotationConfiguration.CONTAINER_INITIALIZER_STARTER, starter);
    context.addBean(starter, true);
    LOG.debug("configured {}", this);
}
Also used : StandardDescriptorProcessor(org.eclipse.jetty.webapp.StandardDescriptorProcessor) ServletContainerInitializersStarter(org.eclipse.jetty.annotations.ServletContainerInitializersStarter) Resource(org.eclipse.jetty.util.resource.Resource) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) AnnotationDecorator(org.eclipse.jetty.annotations.AnnotationDecorator)

Example 4 with WebAppClassLoader

use of org.eclipse.jetty.webapp.WebAppClassLoader in project jetty.project by eclipse.

the class AntWebAppContext method doStart.

/**
     * 
     */
public void doStart() {
    try {
        TaskLog.logWithTimestamp("Starting web application " + this.getDescriptor());
        if (jettyEnvXml != null && jettyEnvXml.exists())
            envConfiguration.setJettyEnvXml(Resource.toURL(jettyEnvXml));
        ClassLoader parentLoader = this.getClass().getClassLoader();
        if (parentLoader instanceof AntClassLoader)
            parentLoader = new AntURLClassLoader((AntClassLoader) parentLoader);
        setClassLoader(new WebAppClassLoader(parentLoader, this));
        if (attributes != null && attributes.getAttributes() != null) {
            for (Attribute a : attributes.getAttributes()) setAttribute(a.getName(), a.getValue());
        }
        //apply a context xml file if one was supplied
        if (contextXml != null) {
            XmlConfiguration xmlConfiguration = new XmlConfiguration(Resource.toURL(contextXml));
            TaskLog.log("Applying context xml file " + contextXml);
            xmlConfiguration.configure(this);
        }
        super.doStart();
    } catch (Exception e) {
        TaskLog.log(e.toString());
    }
}
Also used : Attribute(org.eclipse.jetty.ant.types.Attribute) AntClassLoader(org.apache.tools.ant.AntClassLoader) URLClassLoader(java.net.URLClassLoader) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) AntClassLoader(org.apache.tools.ant.AntClassLoader) WebXmlConfiguration(org.eclipse.jetty.webapp.WebXmlConfiguration) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) JettyWebXmlConfiguration(org.eclipse.jetty.webapp.JettyWebXmlConfiguration) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) IOException(java.io.IOException) BuildException(org.apache.tools.ant.BuildException)

Example 5 with WebAppClassLoader

use of org.eclipse.jetty.webapp.WebAppClassLoader in project jetty.project by eclipse.

the class PlusDescriptorProcessorTest method setUp.

@Before
public void setUp() throws Exception {
    context = new WebAppContext();
    context.setClassLoader(new WebAppClassLoader(Thread.currentThread().getContextClassLoader(), context));
    ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(context.getClassLoader());
    Context icontext = new InitialContext();
    Context compCtx = (Context) icontext.lookup("java:comp");
    compCtx.createSubcontext("env");
    Thread.currentThread().setContextClassLoader(oldLoader);
    org.eclipse.jetty.plus.jndi.Resource ds = new org.eclipse.jetty.plus.jndi.Resource(context, "jdbc/mydatasource", new Object());
    URL webXml = Thread.currentThread().getContextClassLoader().getResource("web.xml");
    webDescriptor = new WebDescriptor(org.eclipse.jetty.util.resource.Resource.newResource(webXml));
    webDescriptor.parse();
    URL frag1Xml = Thread.currentThread().getContextClassLoader().getResource("web-fragment-1.xml");
    fragDescriptor1 = new FragmentDescriptor(org.eclipse.jetty.util.resource.Resource.newResource(frag1Xml));
    fragDescriptor1.parse();
    URL frag2Xml = Thread.currentThread().getContextClassLoader().getResource("web-fragment-2.xml");
    fragDescriptor2 = new FragmentDescriptor(org.eclipse.jetty.util.resource.Resource.newResource(frag2Xml));
    fragDescriptor2.parse();
    URL frag3Xml = Thread.currentThread().getContextClassLoader().getResource("web-fragment-3.xml");
    fragDescriptor3 = new FragmentDescriptor(org.eclipse.jetty.util.resource.Resource.newResource(frag3Xml));
    fragDescriptor3.parse();
    URL frag4Xml = Thread.currentThread().getContextClassLoader().getResource("web-fragment-4.xml");
    fragDescriptor4 = new FragmentDescriptor(org.eclipse.jetty.util.resource.Resource.newResource(frag4Xml));
    fragDescriptor4.parse();
}
Also used : InitialContext(javax.naming.InitialContext) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) Context(javax.naming.Context) WebDescriptor(org.eclipse.jetty.webapp.WebDescriptor) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) InitialContext(javax.naming.InitialContext) URL(java.net.URL) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) FragmentDescriptor(org.eclipse.jetty.webapp.FragmentDescriptor) Before(org.junit.Before)

Aggregations

WebAppClassLoader (org.eclipse.jetty.webapp.WebAppClassLoader)5 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)3 URL (java.net.URL)2 URLClassLoader (java.net.URLClassLoader)2 Context (javax.naming.Context)2 InitialContext (javax.naming.InitialContext)2 Resource (org.eclipse.jetty.util.resource.Resource)2 JettyWebXmlConfiguration (org.eclipse.jetty.webapp.JettyWebXmlConfiguration)2 XmlConfiguration (org.eclipse.jetty.xml.XmlConfiguration)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1 AntClassLoader (org.apache.tools.ant.AntClassLoader)1 BuildException (org.apache.tools.ant.BuildException)1 AnnotationDecorator (org.eclipse.jetty.annotations.AnnotationDecorator)1 ServletContainerInitializersStarter (org.eclipse.jetty.annotations.ServletContainerInitializersStarter)1 Attribute (org.eclipse.jetty.ant.types.Attribute)1 EnvEntry (org.eclipse.jetty.plus.jndi.EnvEntry)1