Search in sources :

Example 16 with URLClassLoader

use of java.net.URLClassLoader in project druid by druid-io.

the class QueryGranularityTest method testDeadLock.

@Test(timeout = 10_000L)
public void testDeadLock() throws Exception {
    final URL[] urls = ((URLClassLoader) Granularity.class.getClassLoader()).getURLs();
    final String className = Granularity.class.getCanonicalName();
    for (int i = 0; i < 1000; ++i) {
        final ClassLoader loader = new URLClassLoader(urls, null);
        Assert.assertNotNull(String.valueOf(i), Class.forName(className, true, loader));
    }
}
Also used : URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) Granularity(io.druid.java.util.common.granularity.Granularity) DurationGranularity(io.druid.java.util.common.granularity.DurationGranularity) PeriodGranularity(io.druid.java.util.common.granularity.PeriodGranularity) URL(java.net.URL) Test(org.junit.Test)

Example 17 with URLClassLoader

use of java.net.URLClassLoader in project jetty.project by eclipse.

the class AnnotationParser method parse.

/**
     * Parse classes in the supplied classloader. 
     * Only class files in jar files will be scanned.
     * 
     * @param handlers the handlers to look for classes in 
     * @param loader the classloader for the classes
     * @param visitParents if true, visit parent classloaders too
     * @param nullInclusive if true, an empty pattern means all names match, if false, none match
     * @throws Exception if unable to parse
     */
public void parse(final Set<? extends Handler> handlers, ClassLoader loader, boolean visitParents, boolean nullInclusive) throws Exception {
    if (loader == null)
        return;
    if (!(loader instanceof URLClassLoader))
        //can't extract classes?
        return;
    final MultiException me = new MultiException();
    JarScanner scanner = new JarScanner() {

        @Override
        public void processEntry(URI jarUri, JarEntry entry) {
            try {
                parseJarEntry(handlers, Resource.newResource(jarUri), entry);
            } catch (Exception e) {
                me.add(new RuntimeException("Error parsing entry " + entry.getName() + " from jar " + jarUri, e));
            }
        }
    };
    scanner.scan(null, loader, nullInclusive, visitParents);
    me.ifExceptionThrow();
}
Also used : URLClassLoader(java.net.URLClassLoader) JarEntry(java.util.jar.JarEntry) MultiException(org.eclipse.jetty.util.MultiException) JarScanner(org.eclipse.jetty.webapp.JarScanner) URI(java.net.URI) MultiException(org.eclipse.jetty.util.MultiException) IOException(java.io.IOException)

Example 18 with URLClassLoader

use of java.net.URLClassLoader in project jetty.project by eclipse.

the class TestJettyJspServlet method setUp.

@Before
public void setUp() throws Exception {
    JspFactory.setDefaultFactory(new JspFactoryImpl());
    _dir = MavenTestingUtils.getTestResourceDir("base");
    _tester = new ServletTester("/context");
    _tester.getContext().setClassLoader(new URLClassLoader(new URL[0], Thread.currentThread().getContextClassLoader()));
    ServletHolder jspHolder = _tester.getContext().addServlet(JettyJspServlet.class, "/*");
    jspHolder.setInitParameter("scratchdir", MavenTestingUtils.getTargetTestingDir().getAbsolutePath());
    _tester.getContext().setResourceBase(_dir.getAbsolutePath());
    _tester.getContext().setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
    ServletHolder dfltHolder = new ServletHolder();
    dfltHolder.setName("default");
    dfltHolder.setHeldClass(DfltServlet.class);
    _tester.getContext().addServlet(dfltHolder, "/");
    _tester.start();
}
Also used : ServletTester(org.eclipse.jetty.servlet.ServletTester) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) InstanceManager(org.apache.tomcat.InstanceManager) SimpleInstanceManager(org.apache.tomcat.SimpleInstanceManager) JspFactoryImpl(org.apache.jasper.runtime.JspFactoryImpl) URLClassLoader(java.net.URLClassLoader) SimpleInstanceManager(org.apache.tomcat.SimpleInstanceManager) URL(java.net.URL) Before(org.junit.Before)

Example 19 with URLClassLoader

use of java.net.URLClassLoader 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 20 with URLClassLoader

use of java.net.URLClassLoader in project jetty.project by eclipse.

the class LibExtClassLoaderHelper method createLibExtClassLoader.

/* ------------------------------------------------------------ */
/**
     * @param jarsContainerOrJars the jars via file references
     * @param otherJarsOrFolder more jars via url references
     * @param parentClassLoader the parent classloader
     * @return a url classloader with the jars of resources, lib/ext and the
     *         jars passed in the other argument. The parent classloader usually
     *         is the JettyBootStrapper (an osgi classloader). If there was no
     *         extra jars to insert, then just return the parentClassLoader.
     * @throws MalformedURLException if there is a bad jar file reference
     */
public static ClassLoader createLibExtClassLoader(List<File> jarsContainerOrJars, List<URL> otherJarsOrFolder, ClassLoader parentClassLoader) throws MalformedURLException {
    if (jarsContainerOrJars == null && otherJarsOrFolder == null) {
        return parentClassLoader;
    }
    List<URL> urls = new ArrayList<URL>();
    if (otherJarsOrFolder != null) {
        urls.addAll(otherJarsOrFolder);
    }
    if (jarsContainerOrJars != null) {
        for (File libExt : jarsContainerOrJars) {
            if (libExt.isDirectory()) {
                for (File f : libExt.listFiles()) {
                    if (f.getName().endsWith(".jar")) {
                        // cheap to tolerate folders so let's do it.
                        URL url = f.toURI().toURL();
                        if (f.isFile()) {
                            // is this necessary anyways?
                            url = new URL("jar:" + url.toString() + "!/");
                        }
                        urls.add(url);
                    }
                }
            }
        }
    }
    return new URLClassLoader(urls.toArray(new URL[urls.size()]), parentClassLoader);
}
Also used : URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) File(java.io.File) URL(java.net.URL)

Aggregations

URLClassLoader (java.net.URLClassLoader)1351 URL (java.net.URL)872 File (java.io.File)514 Test (org.junit.Test)317 IOException (java.io.IOException)256 ArrayList (java.util.ArrayList)202 MalformedURLException (java.net.MalformedURLException)186 Method (java.lang.reflect.Method)177 InvocationTargetException (java.lang.reflect.InvocationTargetException)68 JarFile (java.util.jar.JarFile)54 InputStream (java.io.InputStream)50 HashSet (java.util.HashSet)49 HashMap (java.util.HashMap)44 URISyntaxException (java.net.URISyntaxException)41 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)35 Path (java.nio.file.Path)33 QuickTest (com.hazelcast.test.annotation.QuickTest)32 Test (org.junit.jupiter.api.Test)28 URI (java.net.URI)27 List (java.util.List)27