Search in sources :

Example 11 with Resource

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

the class ScanningAppProvider method doStart.

/* ------------------------------------------------------------ */
@Override
protected void doStart() throws Exception {
    if (LOG.isDebugEnabled())
        LOG.debug(this.getClass().getSimpleName() + ".doStart()");
    if (_monitored.size() == 0)
        throw new IllegalStateException("No configuration dir specified");
    LOG.info("Deployment monitor " + _monitored + " at interval " + _scanInterval);
    List<File> files = new ArrayList<>();
    for (Resource resource : _monitored) {
        if (resource.exists() && resource.getFile().canRead())
            files.add(resource.getFile());
        else
            LOG.warn("Does not exist: " + resource);
    }
    _scanner = new Scanner();
    _scanner.setScanDirs(files);
    _scanner.setScanInterval(_scanInterval);
    _scanner.setRecursive(_recursive);
    _scanner.setFilenameFilter(_filenameFilter);
    _scanner.setReportDirs(true);
    _scanner.addListener(_scannerListener);
    _scanner.start();
}
Also used : Scanner(org.eclipse.jetty.util.Scanner) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Resource(org.eclipse.jetty.util.resource.Resource) File(java.io.File)

Example 12 with Resource

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

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

the class ServerInstanceWrapper method configure.

/* ------------------------------------------------------------ */
public static Server configure(Server server, List<URL> jettyConfigurations, Dictionary props) throws Exception {
    if (jettyConfigurations == null || jettyConfigurations.isEmpty()) {
        return server;
    }
    Map<String, Object> id_map = new HashMap<String, Object>();
    if (server != null) {
        //Put in a mapping for the id "Server" and the name of the server as the instance being configured
        id_map.put("Server", server);
        id_map.put((String) props.get(OSGiServerConstants.MANAGED_JETTY_SERVER_NAME), server);
    }
    Map<String, String> properties = new HashMap<String, String>();
    if (props != null) {
        Enumeration<Object> en = props.keys();
        while (en.hasMoreElements()) {
            Object key = en.nextElement();
            Object value = props.get(key);
            String keyStr = String.valueOf(key);
            String valStr = String.valueOf(value);
            properties.put(keyStr, valStr);
            if (server != null)
                server.setAttribute(keyStr, valStr);
        }
    }
    for (URL jettyConfiguration : jettyConfigurations) {
        try (Resource r = Resource.newResource(jettyConfiguration)) {
            // Execute a Jetty configuration file
            if (!r.exists()) {
                LOG.warn("File does not exist " + r);
                throw new IllegalStateException("No such jetty server config file: " + r);
            }
            XmlConfiguration config = new XmlConfiguration(r.getURL());
            config.getIdMap().putAll(id_map);
            config.getProperties().putAll(properties);
            // #334062 compute the URL of the folder that contains the
            // conf file and set it as a property so we can compute relative paths
            // from it.
            String urlPath = jettyConfiguration.toString();
            int lastSlash = urlPath.lastIndexOf('/');
            if (lastSlash > 4) {
                urlPath = urlPath.substring(0, lastSlash);
                config.getProperties().put(PROPERTY_THIS_JETTY_XML_FOLDER_URL, urlPath);
            }
            Object o = config.configure();
            if (server == null)
                server = (Server) o;
            id_map = config.getIdMap();
        } catch (Exception e) {
            LOG.warn("Configuration error in " + jettyConfiguration);
            throw e;
        }
    }
    return server;
}
Also used : Server(org.eclipse.jetty.server.Server) HashMap(java.util.HashMap) Resource(org.eclipse.jetty.util.resource.Resource) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) URL(java.net.URL)

Example 14 with Resource

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

the class OSGiWebappClassLoader method addClassPath.

/* ------------------------------------------------------------ */
/**
     * Parse the classpath ourselves to be able to filter things. This is a
     * derivative work of the super class
     */
@Override
public void addClassPath(String classPath) throws IOException {
    StringTokenizer tokenizer = new StringTokenizer(classPath, ",;");
    while (tokenizer.hasMoreTokens()) {
        String path = tokenizer.nextToken();
        Resource resource = getContext().newResource(path);
        // Resolve file path if possible
        File file = resource.getFile();
        if (file != null && isAcceptableLibrary(file, JAR_WITH_SUCH_CLASS_MUST_BE_EXCLUDED)) {
            super.addClassPath(path);
        } else {
            __logger.info("Did not add " + path + " to the classloader of the webapp " + getContext());
        }
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) Resource(org.eclipse.jetty.util.resource.Resource) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 15 with Resource

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

the class ContextHandler method getClassPath.

/* ------------------------------------------------------------ */
/**
     * Make best effort to extract a file classpath from the context classloader
     *
     * @return Returns the classLoader.
     */
@ManagedAttribute("The file classpath")
public String getClassPath() {
    if (_classLoader == null || !(_classLoader instanceof URLClassLoader))
        return null;
    URLClassLoader loader = (URLClassLoader) _classLoader;
    URL[] urls = loader.getURLs();
    StringBuilder classpath = new StringBuilder();
    for (int i = 0; i < urls.length; i++) {
        try {
            Resource resource = newResource(urls[i]);
            File file = resource.getFile();
            if (file != null && file.exists()) {
                if (classpath.length() > 0)
                    classpath.append(File.pathSeparatorChar);
                classpath.append(file.getAbsolutePath());
            }
        } catch (IOException e) {
            LOG.debug(e);
        }
    }
    if (classpath.length() == 0)
        return null;
    return classpath.toString();
}
Also used : URLClassLoader(java.net.URLClassLoader) Resource(org.eclipse.jetty.util.resource.Resource) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL) ManagedAttribute(org.eclipse.jetty.util.annotation.ManagedAttribute)

Aggregations

Resource (org.eclipse.jetty.util.resource.Resource)196 Test (org.junit.Test)79 File (java.io.File)46 URL (java.net.URL)39 ArrayList (java.util.ArrayList)38 Matchers.containsString (org.hamcrest.Matchers.containsString)31 IOException (java.io.IOException)28 ResourceCollection (org.eclipse.jetty.util.resource.ResourceCollection)18 JarResource (org.eclipse.jetty.util.resource.JarResource)16 XmlConfiguration (org.eclipse.jetty.xml.XmlConfiguration)16 Server (org.eclipse.jetty.server.Server)13 HashSet (java.util.HashSet)12 InputStream (java.io.InputStream)9 HashMap (java.util.HashMap)9 URI (java.net.URI)8 MalformedURLException (java.net.MalformedURLException)7 StringTokenizer (java.util.StringTokenizer)7 URISyntaxException (java.net.URISyntaxException)6 Properties (java.util.Properties)6 Set (java.util.Set)6