Example usage for java.lang Class getClassLoader

List of usage examples for java.lang Class getClassLoader

Introduction

In this page you can find the example usage for java.lang Class getClassLoader.

Prototype

@CallerSensitive
@ForceInline 
public ClassLoader getClassLoader() 

Source Link

Document

Returns the class loader for the class.

Usage

From source file:com.attilax.zip.FileUtil.java

/**
 * ???/*w w  w .j a v a 2s  .c o m*/
 * 
 * @param clazz
 * @param name
 * @return
 */
@SuppressWarnings("unchecked")
public static InputStream getResourceAsStream(Class clazz, String name) {
    try {
        InputStream inputStream = clazz.getResourceAsStream(name);
        if (inputStream == null)
            inputStream = clazz.getClassLoader().getResourceAsStream(name);
        return inputStream;
    } catch (Exception e) {
        if (log.isWarnEnabled())
            log.warn("??", e);
        return null;
    }
}

From source file:com.github.yongchristophertang.config.PropertyHandler.java

public static void loadProperties(Class<?> testClass, Object[] testInstances) {
    Properties prop = new Properties();
    PropertyConfig[] propertyConfigs = getAnnotations(null, testClass, PropertyConfig.class);
    Lists.newArrayList(propertyConfigs).stream().filter(pc -> pc.value().endsWith(".properties"))
            .forEach(pc -> {//w  ww .  j a v  a  2 s  . c o m
                try {
                    prop.load(testClass.getClassLoader().getResourceAsStream(pc.value()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

    Field[] fields = testClass.getFields();
    Lists.newArrayList(fields).stream().filter(f -> f.isAnnotationPresent(Property.class))
            .filter(f -> f.getType() == String.class).peek(f -> f.setAccessible(true)).forEach(f -> {
                for (Object instance : testInstances) {
                    try {
                        f.set(instance, prop.getProperty(f.getAnnotation(Property.class).value()));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            });
}

From source file:com.netflix.nicobar.core.utils.ClassPathUtils.java

/**
 * Find the root path for the given class. If the class is found in a Jar file, then the
 * result will be an absolute path to the jar file. If the resource is found in a directory,
 * then the result will be the parent path of the given resource.
 *
 * @param clazz class to search for/* w w w  .j a v  a 2 s.c om*/
 * @return absolute path of the root of the resource.
 */
@Nullable
public static Path findRootPathForClass(Class<?> clazz) {
    Objects.requireNonNull(clazz, "resourceName");
    String resourceName = classToResourceName(clazz);
    return findRootPathForResource(resourceName, clazz.getClassLoader());
}

From source file:org.apache.hadoop.hive.ql.metadata.JarUtils.java

/**
 * Returns the full path to the Jar containing the class. It always return a JAR.
 *
 * @param klass/* w  ww .ja v a 2s .  c  o  m*/
 *          class.
 *
 * @return path to the Jar containing the class.
 */
@SuppressWarnings("rawtypes")
public static String jarFinderGetJar(Class klass) {
    Preconditions.checkNotNull(klass, "klass");
    ClassLoader loader = klass.getClassLoader();
    if (loader != null) {
        String class_file = klass.getName().replaceAll("\\.", "/") + ".class";
        try {
            for (Enumeration itr = loader.getResources(class_file); itr.hasMoreElements();) {
                URL url = (URL) itr.nextElement();
                String path = url.getPath();
                if (path.startsWith("file:")) {
                    path = path.substring("file:".length());
                }
                path = URLDecoder.decode(path, "UTF-8");
                if ("jar".equals(url.getProtocol())) {
                    path = URLDecoder.decode(path, "UTF-8");
                    return path.replaceAll("!.*$", "");
                } else if ("file".equals(url.getProtocol())) {
                    String klassName = klass.getName();
                    klassName = klassName.replace(".", "/") + ".class";
                    path = path.substring(0, path.length() - klassName.length());
                    File baseDir = new File(path);
                    File testDir = new File(System.getProperty("test.build.dir", "target/test-dir"));
                    testDir = testDir.getAbsoluteFile();
                    if (!testDir.exists()) {
                        testDir.mkdirs();
                    }
                    File tempJar = File.createTempFile("hadoop-", "", testDir);
                    tempJar = new File(tempJar.getAbsolutePath() + ".jar");
                    createJar(baseDir, tempJar);
                    return tempJar.getAbsolutePath();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}

From source file:org.eclipse.gemini.blueprint.test.FilteringProbeBuilder.java

/**
 * @param clazz to find the root classes folder for.
 * @return A File instance being the exact folder on disk or null, if it hasn't been found.
 * @throws java.io.IOException if a problem occurs (method crawls folders on disk..)
 *//*from   w  ww .  j  ava 2  s. c o  m*/
private static File findClassesFolder(Class<?> clazz) throws IOException {
    ClassLoader classLoader = clazz.getClassLoader();
    String clazzPath = convertClassToPath(clazz);
    URL url = classLoader.getResource(clazzPath);
    if (url == null || !"file".equals(url.getProtocol())) {
        return null;
    } else {
        try {
            File file = new File(url.toURI());
            String fullPath = file.getCanonicalPath();
            String parentDirPath = fullPath.substring(0, fullPath.length() - clazzPath.length());
            return new File(parentDirPath);
        } catch (URISyntaxException e) {
            // this should not happen as the uri was obtained from getResource
            throw new TestContainerException(e);
        }
    }
}

From source file:com.ibm.team.build.internal.hjplugin.RTCFacadeFactory.java

private static RTCFacadeWrapper newFacade(String fullClassName, File toolkitFile, PrintStream debugLog)
        throws Exception {

    if (!toolkitFile.exists()) {
        throw new IllegalArgumentException(
                Messages.RTCFacadeFactory_toolkit_not_found(toolkitFile.getAbsolutePath()));
    }//from   www .j av a2s.  c  o  m
    if (!toolkitFile.isDirectory()) {
        throw new IllegalArgumentException(
                Messages.RTCFacadeFactory_toolkit_path_not_directory(toolkitFile.getAbsolutePath()));
    }

    RTCFacadeWrapper result = new RTCFacadeWrapper();

    URL[] toolkitURLs = getToolkitJarURLs(toolkitFile, debugLog);

    Class<?> originalClass = RTCFacadeFactory.class;
    ClassLoader originalClassLoader = originalClass.getClassLoader();
    debug(debugLog, "Original class loader: " + originalClassLoader); //$NON-NLS-1$

    // Get the jar for the hjplugin-rtc jar.
    URL[] combinedURLs;
    URL hjplugin_rtcJar = getFacadeJarURL(debugLog);
    if (hjplugin_rtcJar != null) {
        combinedURLs = new URL[toolkitURLs.length + 1];
        combinedURLs[0] = hjplugin_rtcJar;
        System.arraycopy(toolkitURLs, 0, combinedURLs, 1, toolkitURLs.length);
    } else {
        combinedURLs = toolkitURLs;
    }
    debug(debugLog, "System class loader " + ClassLoader.getSystemClassLoader()); //$NON-NLS-1$

    // We want the parent class loader to exclude the class loader which would normally
    // load classes from the hjplugin-rtc jar (because that class loader doesn't include
    // the toolkit jars).
    ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader();

    // Normally the system class loader and the original class loader are different.
    // However in the case of running the tests within our build, the system class loader
    // is the original class loader with our single jar (and not its dependencies from the
    // toolkit) which results in ClassNotFound for classes we depend on (i.e. IProgressMonitor).
    // So use the parent in this case.
    if (parentClassLoader == originalClassLoader) {
        debug(debugLog, "System class loader and original are the same. Using parent " //$NON-NLS-1$
                + originalClassLoader.getParent());
        parentClassLoader = originalClassLoader.getParent();
    }
    if (Boolean.parseBoolean(System.getProperty(DISABLE_RTC_FACADE_CLASS_LOADER_PROPERTY, "false"))) { //$NON-NLS-1$
        debug(debugLog, "RTCFacadeClassLoader disabled, using URLClassLoader"); //$NON-NLS-1$
        result.newClassLoader = new URLClassLoader(combinedURLs, parentClassLoader);
    } else {
        result.newClassLoader = new RTCFacadeClassLoader(combinedURLs, parentClassLoader);
    }

    debug(debugLog, "new classloader: " + result.newClassLoader); //$NON-NLS-1$

    Class<?> facadeClass = result.newClassLoader.loadClass(fullClassName);
    debug(debugLog, "facadeClass: " + facadeClass); //$NON-NLS-1$
    debug(debugLog, "facadeClass classloader: " + facadeClass.getClassLoader()); //$NON-NLS-1$

    // using the new class loader get the facade instance
    // then revert immediately back to the original class loader
    ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(result.newClassLoader);
    try {
        result.facade = facadeClass.newInstance();
    } finally {
        Thread.currentThread().setContextClassLoader(originalContextClassLoader);
    }

    debug(debugLog, "facade: " + result.facade); //$NON-NLS-1$
    return result;
}

From source file:org.apache.hadoop.hive.ql.metadata.JarUtils.java

/**
 * Find a jar that contains a class of the same name, if any. It will return a jar file, even if
 * that is not the first thing on the class path that has a class with the same name. Looks first
 * on the classpath and then in the <code>packagedClasses</code> map.
 *
 * @param my_class/*from   w ww  .  j  av  a 2 s. c o m*/
 *          the class to find.
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
private static String findContainingJar(Class<?> my_class, Map<String, String> packagedClasses)
        throws IOException {
    ClassLoader loader = my_class.getClassLoader();
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";

    // first search the classpath
    for (Enumeration<URL> itr = loader.getResources(class_file); itr.hasMoreElements();) {
        URL url = itr.nextElement();
        if ("jar".equals(url.getProtocol())) {
            String toReturn = url.getPath();
            if (toReturn.startsWith("file:")) {
                toReturn = toReturn.substring("file:".length());
            }
            // URLDecoder is a misnamed class, since it actually decodes
            // x-www-form-urlencoded MIME type rather than actual
            // URL encoding (which the file path has). Therefore it would
            // decode +s to ' 's which is incorrect (spaces are actually
            // either unencoded or encoded as "%20"). Replace +s first, so
            // that they are kept sacred during the decoding process.
            toReturn = toReturn.replaceAll("\\+", "%2B");
            toReturn = URLDecoder.decode(toReturn, "UTF-8");
            return toReturn.replaceAll("!.*$", "");
        }
    }

    // now look in any jars we've packaged using JarFinder. Returns null
    // when
    // no jar is found.
    return packagedClasses.get(class_file);
}

From source file:Main.java

/**
 * Finds a resource with the given name.  Checks the Thread Context
 * classloader, then uses the System classloader.  Should replace all
 * calls to <code>Class.getResourceAsString</code> when the resource
 * might come from a different classloader.  (e.g. a webapp).
 * @param claz Class to use when getting the System classloader (used if no Thread
 * Context classloader available or fails to get resource).
 * @param name name of the resource/*from   ww  w. j a  v  a2  s .co m*/
 * @return InputStream for the resource.
 */
public static InputStream getResourceAsStream(Class claz, String name) {
    InputStream result = null;

    /**
     * remove leading slash so path will work with classes in a JAR file
     */
    while (name.startsWith("/")) {
        name = name.substring(1);
    }

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    if (classLoader == null) {
        classLoader = claz.getClassLoader();
        result = classLoader.getResourceAsStream(name);
    } else {
        result = classLoader.getResourceAsStream(name);

        /**
        * for compatibility with texen / ant tasks, fall back to
        * old method when resource is not found.
        */

        if (result == null) {
            classLoader = claz.getClassLoader();
            if (classLoader != null)
                result = classLoader.getResourceAsStream(name);
        }
    }

    return result;

}

From source file:com.googlecode.fightinglayoutbugs.FindBugsRunner.java

private static List<String> getClassPath(Class<?> suiteClass) {
    List<String> classPath = new ArrayList<String>();
    URLClassLoader classLoader = (URLClassLoader) suiteClass.getClassLoader();
    do {//from  w w w.j a v  a 2s.  co  m
        for (URL url : classLoader.getURLs()) {
            final String temp = url.toString();
            if (temp.startsWith("file:")) {
                @SuppressWarnings("deprecation")
                String path = URLDecoder.decode(temp.substring("file:".length()));
                classPath.add(path);
            } else {
                throw new RuntimeException(
                        "Don't know how to convert class path URL '" + temp + "' into a path.");
            }
        }
        ClassLoader parentClassLoader = classLoader.getParent();
        classLoader = (parentClassLoader instanceof URLClassLoader && parentClassLoader != classLoader
                ? (URLClassLoader) parentClassLoader
                : null);
    } while (classLoader != null);
    return classPath;
}

From source file:main.java.refinement_class.Useful.java

static public InputStream getInputStream(Class c, String fileName) throws IOException {
    return new java.io.BufferedInputStream(c.getClassLoader().getResourceAsStream(fileName));
}