Search in sources :

Example 6 with ResourceCollection

use of org.eclipse.jetty.util.resource.ResourceCollection in project jetty.project by eclipse.

the class JettyWebAppContext method setResourceBases.

/* ------------------------------------------------------------ */
/**
     * This method is provided as a convenience for jetty maven plugin configuration 
     * @param resourceBases Array of resources strings to set as a {@link ResourceCollection}. Each resource string may be a comma separated list of resources
     * @see Resource
     */
public void setResourceBases(String[] resourceBases) {
    List<String> resources = new ArrayList<String>();
    for (String rl : resourceBases) {
        String[] rs = StringUtil.csvSplit(rl);
        for (String r : rs) resources.add(r);
    }
    setBaseResource(new ResourceCollection(resources.toArray(new String[resources.size()])));
}
Also used : ArrayList(java.util.ArrayList) ResourceCollection(org.eclipse.jetty.util.resource.ResourceCollection)

Example 7 with ResourceCollection

use of org.eclipse.jetty.util.resource.ResourceCollection 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 8 with ResourceCollection

use of org.eclipse.jetty.util.resource.ResourceCollection in project druid by druid-io.

the class CoordinatorJettyServerInitializer method initialize.

@Override
public void initialize(Server server, Injector injector) {
    final ServletContextHandler root = new ServletContextHandler(ServletContextHandler.SESSIONS);
    root.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
    root.addServlet(holderPwd, "/");
    if (config.getConsoleStatic() == null) {
        ResourceCollection staticResources;
        if (beOverlord) {
            staticResources = new ResourceCollection(Resource.newClassPathResource("io/druid/console"), Resource.newClassPathResource("static"), Resource.newClassPathResource("indexer_static"));
        } else {
            staticResources = new ResourceCollection(Resource.newClassPathResource("io/druid/console"), Resource.newClassPathResource("static"));
        }
        root.setBaseResource(staticResources);
    } else {
        // used for console development
        root.setResourceBase(config.getConsoleStatic());
    }
    JettyServerInitUtils.addExtensionFilters(root, injector);
    // /status should not redirect, so add first
    root.addFilter(GuiceFilter.class, "/status/*", null);
    // redirect anything other than status to the current lead
    root.addFilter(new FilterHolder(injector.getInstance(RedirectFilter.class)), "/*", null);
    // The coordinator really needs a standarized api path
    // Can't use '/*' here because of Guice and Jetty static content conflicts
    root.addFilter(GuiceFilter.class, "/info/*", null);
    root.addFilter(GuiceFilter.class, "/druid/coordinator/*", null);
    if (beOverlord) {
        root.addFilter(GuiceFilter.class, "/druid/indexer/*", null);
    }
    // this will be removed in the next major release
    root.addFilter(GuiceFilter.class, "/coordinator/*", null);
    if (!beOverlord) {
        root.addServlet(new ServletHolder(injector.getInstance(OverlordProxyServlet.class)), "/druid/indexer/*");
    }
    HandlerList handlerList = new HandlerList();
    handlerList.setHandlers(new Handler[] { JettyServerInitUtils.getJettyRequestLogHandler(), JettyServerInitUtils.wrapWithDefaultGzipHandler(root) });
    server.setHandler(handlerList);
}
Also used : HandlerList(org.eclipse.jetty.server.handler.HandlerList) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ResourceCollection(org.eclipse.jetty.util.resource.ResourceCollection)

Example 9 with ResourceCollection

use of org.eclipse.jetty.util.resource.ResourceCollection in project dropwizard by dropwizard.

the class ServletEnvironmentTest method setsBaseResourceStringList.

@Test
public void setsBaseResourceStringList() throws Exception {
    String wooResource = tempDir.newFolder().getAbsolutePath();
    String fooResource = tempDir.newFolder().getAbsolutePath();
    final String[] testResources = new String[] { wooResource, fooResource };
    environment.setBaseResource(testResources);
    ArgumentCaptor<Resource> captor = ArgumentCaptor.forClass(Resource.class);
    verify(handler).setBaseResource(captor.capture());
    Resource actualResource = captor.getValue();
    assertThat(actualResource).isInstanceOf(ResourceCollection.class);
    ResourceCollection actualResourceCollection = (ResourceCollection) actualResource;
    assertThat(actualResourceCollection.getResources()).contains(Resource.newResource(wooResource), Resource.newResource(fooResource));
}
Also used : Resource(org.eclipse.jetty.util.resource.Resource) ResourceCollection(org.eclipse.jetty.util.resource.ResourceCollection) Test(org.junit.Test)

Example 10 with ResourceCollection

use of org.eclipse.jetty.util.resource.ResourceCollection in project spring-boot by spring-projects.

the class JettyServletWebServerFactory method configureDocumentRoot.

private void configureDocumentRoot(WebAppContext handler) {
    File root = getValidDocumentRoot();
    root = (root != null ? root : createTempDir("jetty-docbase"));
    try {
        List<Resource> resources = new ArrayList<>();
        resources.add(root.isDirectory() ? Resource.newResource(root.getCanonicalFile()) : JarResource.newJarResource(Resource.newResource(root)));
        for (URL resourceJarUrl : this.getUrlsOfJarsWithMetaInfResources()) {
            Resource resource = createResource(resourceJarUrl);
            // https://github.com/eclipse/jetty.project/issues/518
            if (resource.exists() && resource.isDirectory()) {
                resources.add(resource);
            }
        }
        handler.setBaseResource(new ResourceCollection(resources.toArray(new Resource[resources.size()])));
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}
Also used : ArrayList(java.util.ArrayList) JarResource(org.eclipse.jetty.util.resource.JarResource) Resource(org.eclipse.jetty.util.resource.Resource) File(java.io.File) URL(java.net.URL) ServletException(javax.servlet.ServletException) WebServerException(org.springframework.boot.web.server.WebServerException) IOException(java.io.IOException) ResourceCollection(org.eclipse.jetty.util.resource.ResourceCollection)

Aggregations

ResourceCollection (org.eclipse.jetty.util.resource.ResourceCollection)30 Resource (org.eclipse.jetty.util.resource.Resource)22 File (java.io.File)13 ArrayList (java.util.ArrayList)8 URL (java.net.URL)7 IOException (java.io.IOException)6 Test (org.junit.Test)6 JarResource (org.eclipse.jetty.util.resource.JarResource)5 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)4 MimeTypes (org.eclipse.jetty.http.MimeTypes)3 Server (org.eclipse.jetty.server.Server)3 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)3 MalformedURLException (java.net.MalformedURLException)2 URLClassLoader (java.net.URLClassLoader)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 LinkedList (java.util.LinkedList)2 Set (java.util.Set)2 TreeMap (java.util.TreeMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2