Example usage for java.lang Thread getContextClassLoader

List of usage examples for java.lang Thread getContextClassLoader

Introduction

In this page you can find the example usage for java.lang Thread getContextClassLoader.

Prototype

@CallerSensitive
public ClassLoader getContextClassLoader() 

Source Link

Document

Returns the context ClassLoader for this thread.

Usage

From source file:org.springframework.boot.devtools.restart.Restarter.java

/**
 * Internal constructor to create a new {@link Restarter} instance.
 * @param thread the source thread//from www. ja  va  2s .  com
 * @param args the application arguments
 * @param forceReferenceCleanup if soft/weak reference cleanup should be forced
 * @param initializer the restart initializer
 * @see #initialize(String[])
 */
protected Restarter(Thread thread, String[] args, boolean forceReferenceCleanup,
        RestartInitializer initializer) {
    Assert.notNull(thread, "Thread must not be null");
    Assert.notNull(args, "Args must not be null");
    Assert.notNull(initializer, "Initializer must not be null");
    this.logger.debug("Creating new Restarter for thread " + thread);
    SilentExitExceptionHandler.setup(thread);
    this.forceReferenceCleanup = forceReferenceCleanup;
    this.initialUrls = initializer.getInitialUrls(thread);
    this.mainClassName = getMainClassName(thread);
    this.applicationClassLoader = thread.getContextClassLoader();
    this.args = args;
    this.exceptionHandler = thread.getUncaughtExceptionHandler();
    this.leakSafeThreads.add(new LeakSafeThread());
}

From source file:com.moviejukebox.scanner.artwork.ArtworkScanner.java

/**
 * Set the Image Plugin/*from   w w  w.ja  v a 2s  .  c  om*/
 *
 * @param classNameString
 */
protected void setImagePlugin(String classNameString) {
    String className;
    if (StringTools.isNotValidString(classNameString)) {
        // Use the default image plugin
        className = PropertiesUtil.getProperty("mjb.image.plugin",
                "com.moviejukebox.plugin.DefaultImagePlugin");
    } else {
        className = classNameString;
    }

    try {
        Thread artThread = Thread.currentThread();
        ClassLoader cl = artThread.getContextClassLoader();
        Class<? extends MovieImagePlugin> pluginClass = cl.loadClass(className)
                .asSubclass(MovieImagePlugin.class);
        artworkImagePlugin = pluginClass.newInstance();

        return;
    } catch (ClassNotFoundException ex) {
        LOG.error("Error instantiating imagePlugin: {} - class not found!", className);
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (InstantiationException ex) {
        LOG.error("Failed instantiating imagePlugin: {}", className);
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (IllegalAccessException ex) {
        LOG.error("Unable instantiating imagePlugin: {}", className);
        LOG.error(SystemTools.getStackTrace(ex));
    }

    LOG.error("Default plugin will be used instead.");
    // Use the background plugin for fanart, the image plugin for all others
    if (artworkType == ArtworkType.FANART) {
        artworkImagePlugin = new DefaultBackgroundPlugin();
    } else {
        artworkImagePlugin = new DefaultImagePlugin();
    }
}

From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java

@SuppressWarnings("rawtypes")
public void execute() {
    if (!isEnabled()) {
        getLog().info("Skipping gatf-plugin execution....");
        return;/*w  w w.  j a  v a2 s  .  co m*/
    }

    if (configFile != null) {
        try {
            InputStream io = new FileInputStream(configFile);
            XStream xstream = new XStream(new DomDriver("UTF-8"));
            xstream.processAnnotations(new Class[] { GatfConfiguration.class });
            xstream.alias("testPaths", String[].class);
            xstream.alias("testPath", String.class);
            xstream.alias("soapWsdlKeyPairs", String[].class);
            xstream.alias("soapWsdlKeyPair", String.class);
            xstream.alias("string", String.class);

            GatfConfiguration config = (GatfConfiguration) xstream.fromXML(io);

            setDebugEnabled(config.isDebugEnabled());
            setEnabled(config.isEnabled());
            setInDataType(config.getRequestDataType());
            setTestPaths(config.getTestPaths());
            setSoapWsdlKeyPairs(config.getSoapWsdlKeyPairs());
            setUrlPrefix(config.getUrlPrefix());
            setResourcepath(config.getResourcepath());
            setInDataType(config.getRequestDataType());
            setOutDataType(config.getResponseDataType());
            setOverrideSecure(config.isOverrideSecure());
            setUrlSuffix(config.getUrlSuffix());
            setUseSoapClient(config.isUseSoapClient());
            setTestCaseFormat(config.getTestCaseFormat());
            setPostmanCollectionVersion(config.getPostmanCollectionVersion());
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }

    if (getResourcepath() == null) {
        setResourcepath(".");
        getLog().info(
                "No resource path specified, using the current working directory to generate testcases...");
    } else {
        File dir = new File(getResourcepath());
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    Thread currentThread = Thread.currentThread();
    ClassLoader oldClassLoader = currentThread.getContextClassLoader();
    try {
        currentThread.setContextClassLoader(getClassLoader());
        getLog().info("Inside execute");
        List<Class> allClasses = new ArrayList<Class>();
        if (getTestPaths() != null) {
            for (String item : getTestPaths()) {
                if (item.endsWith(".*")) {
                    List<Class> classes = ClassLoaderUtils.getClasses(item.substring(0, item.indexOf(".*")));
                    if (classes != null && classes.size() > 0) {
                        allClasses.addAll(classes);
                        getLog().info("Adding package " + item);
                    } else {
                        getLog().error("Error:package not found - " + item);
                    }
                } else {
                    try {
                        allClasses.add(Thread.currentThread().getContextClassLoader().loadClass(item));
                        getLog().info("Adding class " + item);
                    } catch (Exception e) {
                        getLog().error("Error:class not found - " + item);
                    }
                }
            }
            if (!allClasses.isEmpty()) {
                generateRestTestCases(allClasses);
            }
        } else {
            getLog().info("Nothing to generate..");
        }
        generateSoapTestCases();

        getLog().info("Done execute");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        currentThread.setContextClassLoader(oldClassLoader);
    }
}

From source file:com.moviejukebox.MovieJukebox.java

public static synchronized MovieImagePlugin getImagePlugin(String className) {
    try {//www.  j a va2s  .c om
        Thread t = Thread.currentThread();
        ClassLoader cl = t.getContextClassLoader();
        Class<? extends MovieImagePlugin> pluginClass = cl.loadClass(className)
                .asSubclass(MovieImagePlugin.class);
        return pluginClass.newInstance();
    } catch (InstantiationException ex) {
        LOG.error("Failed instanciating ImagePlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (IllegalAccessException ex) {
        LOG.error("Failed accessing ImagePlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (ClassNotFoundException ex) {
        LOG.error("ImagePlugin class not found: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    }
    LOG.error("Default poster plugin will be used instead.");
    return new DefaultImagePlugin();
}

From source file:com.moviejukebox.MovieJukebox.java

public static MovieImagePlugin getBackgroundPlugin(String className) {
    try {/*from w w  w.j  av a2s  .c o m*/
        Thread t = Thread.currentThread();
        ClassLoader cl = t.getContextClassLoader();
        Class<? extends MovieImagePlugin> pluginClass = cl.loadClass(className)
                .asSubclass(MovieImagePlugin.class);
        return pluginClass.newInstance();
    } catch (InstantiationException ex) {
        LOG.error("Failed instantiating BackgroundPlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (IllegalAccessException ex) {
        LOG.error("Failed accessing BackgroundPlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (ClassNotFoundException ex) {
        LOG.error("BackgroundPlugin class not found: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    }

    LOG.error("Default background plugin will be used instead.");
    return new DefaultBackgroundPlugin();
}

From source file:com.moviejukebox.MovieJukebox.java

public static MovieListingPlugin getListingPlugin(String className) {
    try {// w ww . j av  a 2s . co  m
        Thread t = Thread.currentThread();
        ClassLoader cl = t.getContextClassLoader();
        Class<? extends MovieListingPlugin> pluginClass = cl.loadClass(className)
                .asSubclass(MovieListingPlugin.class);
        return pluginClass.newInstance();
    } catch (InstantiationException ex) {
        LOG.error("Failed instanciating ListingPlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (IllegalAccessException ex) {
        LOG.error("Failed accessing ListingPlugin: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    } catch (ClassNotFoundException ex) {
        LOG.error("ListingPlugin class not found: {} - Error: {}", className, ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    }

    LOG.error("No listing plugin will be used.");
    return new MovieListingPluginBase();
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

protected boolean isThreadInWebApplication(Thread thread) {
    return isLoadedInWebApplication(thread) || // Custom Thread class in web app
            isWebAppClassLoaderOrChild(thread.getContextClassLoader()); // Running in web application
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Since Keep-Alive-Timer thread may have terminated, but still be referenced, we need to make sure it does not
 * reference this classloader.//  w w  w  . j  a  va2 s  . c o m
 */
protected void unsetCachedKeepAliveTimer() {
    Object keepAliveCache = getStaticFieldValue("sun.net.www.http.HttpClient", "kac", true);
    if (keepAliveCache != null) {
        final Thread keepAliveTimer = getFieldValue(keepAliveCache, "keepAliveTimer");
        if (keepAliveTimer != null) {
            if (isWebAppClassLoaderOrChild(keepAliveTimer.getContextClassLoader())) {
                keepAliveTimer.setContextClassLoader(getWebApplicationClassLoader().getParent());
                error("ContextClassLoader of sun.net.www.http.HttpClient cached Keep-Alive-Timer set to parent instead");
            }
        }
    }
}

From source file:org.apache.myfaces.trinidadbuild.plugin.tagdoc.TagdocReport.java

private ClassLoader createCompileClassLoader(MavenProject project) throws MavenReportException {
    Thread current = Thread.currentThread();
    ClassLoader cl = current.getContextClassLoader();

    try {/*from   w w  w  . ja  v a  2 s .c  o  m*/
        List classpathElements = project.getCompileClasspathElements();
        if (!classpathElements.isEmpty()) {
            String[] entries = (String[]) classpathElements.toArray(new String[0]);
            URL[] urls = new URL[entries.length];
            for (int i = 0; i < urls.length; i++) {
                urls[i] = new File(entries[i]).toURL();
            }
            cl = new URLClassLoader(urls, cl);
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MavenReportException("Error calculating scope classpath", e);
    } catch (MalformedURLException e) {
        throw new MavenReportException("Error calculating scope classpath", e);
    }

    return cl;
}

From source file:net.lightbody.bmp.proxy.jetty.http.HttpContext.java

/** Enter the context scope.
 * This method is called (by handle or servlet dispatchers) to indicate that
 * request handling is entering the scope of this context.  The opaque scope object
 * returned, should be passed to the leaveContextScope method.
 *//*from  ww  w  . j  ava 2s  .co m*/
public Object enterContextScope(HttpRequest request, HttpResponse response) {
    // Save the thread context loader
    Thread thread = Thread.currentThread();
    ClassLoader cl = thread.getContextClassLoader();
    HttpContext c = response.getHttpContext();

    Scope scope = null;
    if (cl != HttpContext.class.getClassLoader() || c != null) {
        scope = new Scope();
        scope._classLoader = cl;
        scope._httpContext = c;
    }

    if (_loader != null)
        thread.setContextClassLoader(_loader);
    response.setHttpContext(this);

    return scope;
}