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:net.ymate.platform.commons.util.ResourceUtils.java

/**
 * //ww w. ja  va  2 s  .  com
 * @param resourceName
 * @param callingClass
 * @param aggregate
 * @return
 * @throws IOException
 */
public static Iterator<URL> getResources(String resourceName, Class<?> callingClass, boolean aggregate)
        throws IOException {
    AggregateIterator<URL> iterator = new AggregateIterator<URL>();
    iterator.addEnumeration(Thread.currentThread().getContextClassLoader().getResources(resourceName));
    if ((!iterator.hasNext()) || (aggregate)) {
        iterator.addEnumeration(ClassUtils.getDefaultClassLoader().getResources(resourceName));
    }
    if ((!iterator.hasNext()) || (aggregate)) {
        ClassLoader cl = callingClass.getClassLoader();
        if (cl != null) {
            iterator.addEnumeration(cl.getResources(resourceName));
        }
    }
    if ((!iterator.hasNext()) && (resourceName != null)
            && (((resourceName.length() == 0) || (resourceName.charAt(0) != '/')))) {
        return getResources('/' + resourceName, callingClass, aggregate);
    }
    return iterator;
}

From source file:net.sourceforge.pmd.lang.java.qname.QualifiedNameFactory.java

/**
 * Gets the qualified name of a class./*from ww w .  j a va  2  s. c o  m*/
 *
 * @param clazz Class object
 *
 * @return The qualified name of the class, or null if the class is null
 */
public static JavaTypeQualifiedName ofClass(Class<?> clazz) {
    if (clazz == null) {
        return null;
    }

    String name = clazz.getName();
    if (name.indexOf('.') < 0) {
        name = '.' + name; // unnamed package, marked by a full stop. See ofString's format below
    }

    // Note: this assumes, that clazz has been loaded through the correct classloader,
    // specifically through the auxclasspath classloader.
    // But this method should only be used in tests anyway
    return (JavaTypeQualifiedName) ofStringWithClassLoader(name, clazz.getClassLoader());
}

From source file:org.eclipse.mylyn.commons.sdk.util.CommonTestUtil.java

public static InputStream getResource(Object source, String filename) throws IOException {
    Class<?> clazz = (source instanceof Class<?>) ? (Class<?>) source : source.getClass();
    ClassLoader classLoader = clazz.getClassLoader();
    InputStream in = classLoader.getResourceAsStream(filename);
    if (in == null) {
        File file = getFile(source, filename);
        if (file != null) {
            return new FileInputStream(file);
        }//www .  j  av  a  2  s  .com
    }
    if (in == null) {
        throw new IOException(NLS.bind("Failed to locate ''{0}'' for ''{1}''", filename, clazz.getName()));
    }
    return in;
}

From source file:com.microsoft.tfs.util.listeners.MulticastListenerProxy.java

/**
 * Creates a new multicasting listener proxy that implements the specified
 * listener interface and uses the specified {@link ListenerList}. The proxy
 * listener will use the specified {@link ListenerExceptionHandler} for
 * exception handling./*from w w w.ja  v a 2s.  c  om*/
 *
 * @param listenerInterface
 *        The listener interface that the returned object will implement
 *        (must not be <code>null</code>)
 * @param listenerList
 *        The {@link ListenerList} that is delegated to by the proxy (must
 *        not be <code>null</code>)
 * @param exceptionHandler
 *        the {@link ListenerExceptionHandler} used to handle any exceptions
 *        thrown by the real listeners
 * @return a new proxy instance as described above
 */
public static Object createProxy(final Class listenerInterface, final ListenerList listenerList,
        final ListenerExceptionHandler exceptionHandler) {
    Check.notNull(listenerInterface, "listenerInterface"); //$NON-NLS-1$
    Check.notNull(listenerList, "listenerList"); //$NON-NLS-1$
    Check.notNull(exceptionHandler, "exceptionHandler"); //$NON-NLS-1$

    final Class[] classesToProxy = new Class[] { listenerInterface };

    final InvocationHandler invocationHandler = new MLPInvocationHandler(listenerList, exceptionHandler);

    return Proxy.newProxyInstance(listenerInterface.getClassLoader(), classesToProxy, invocationHandler);
}

From source file:org.apache.cxf.common.logging.LogUtils.java

private static ClassLoader getClassLoader(final Class<?> clazz) {
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                return clazz.getClassLoader();
            }/*from w w  w  .  j  a v  a2  s  . c om*/
        });
    }
    return clazz.getClassLoader();
}

From source file:org.apdplat.qa.util.Tools.java

public static String getAppPath(Class cls) {
    // ??/*w  w  w .j ava  2  s  . c  om*/
    if (cls == null) {
        throw new IllegalArgumentException("???");
    }
    ClassLoader loader = cls.getClassLoader();
    // ????
    String clsName = cls.getName() + ".class";
    // ?
    Package pack = cls.getPackage();
    String path = "";
    // ?????
    if (pack != null) {
        String packName = pack.getName();
        // ??JavaJDK
        if (packName.startsWith("java.") || packName.startsWith("javax.")) {
            throw new IllegalArgumentException("????");
        }
        // ??????
        clsName = clsName.substring(packName.length() + 1);
        // ?????????
        if (packName.indexOf(".") < 0) {
            path = packName + "/";
        } else {
            // ???????
            int start = 0, end = 0;
            end = packName.indexOf(".");
            while (end != -1) {
                path = path + packName.substring(start, end) + "/";
                start = end + 1;
                end = packName.indexOf(".", start);
            }
            path = path + packName.substring(start) + "/";
        }
    }
    // ClassLoadergetResource????
    URL url = loader.getResource(path + clsName);
    // URL??
    String realPath = url.getPath();
    // ?????"file:"
    int pos = realPath.indexOf("file:");
    if (pos > -1) {
        realPath = realPath.substring(pos + 5);
    }
    // ????
    pos = realPath.indexOf(path + clsName);
    realPath = realPath.substring(0, pos - 1);
    // JARJAR??
    if (realPath.endsWith("!")) {
        realPath = realPath.substring(0, realPath.lastIndexOf("/"));
    }
    /*------------------------------------------------------------  
     ClassLoadergetResourceutf-8??  
     ???  
     URLDecoderdecode?  
     ?  
     -------------------------------------------------------------*/
    try {
        realPath = URLDecoder.decode(realPath, "utf-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return realPath;
}

From source file:org.drombler.commons.client.util.ResourceBundleUtils.java

public static ResourceBundle getResourceBundle(Class<?> type, String resourceBundleBaseName,
        String resourceKey) {//from   w ww.j  a va  2s.c o  m
    ResourceBundle resourceBundle = null;
    if (isPrefixedResourceString(resourceKey)) {
        resourceBundleBaseName = StringUtils.stripToNull(resourceBundleBaseName);
        if (resourceBundleBaseName == null) {
            resourceBundle = getClassResourceBundle(type);
        } else if (resourceBundleBaseName.equals(PACKAGE_RESOURCE_BUNDLE_BASE_NAME)) {
            resourceBundle = getPackageResourceBundle(type);
        } else {
            resourceBundle = getResourceBundle(resourceBundleBaseName, type.getClassLoader());
        }
    }
    return resourceBundle;
}

From source file:io.coala.enterprise.Fact.java

/**
 * @param subtype the type of {@link Fact} to mimic
 * @param callObserver an {@link Observer} of method call, or {@code null}
 * @return the {@link Proxy} instance/*w  ww . ja va2  s .  c  om*/
 */
@SuppressWarnings("unchecked")
static <F extends Fact> F proxyAs(final Fact impl, final Class<F> subtype,
        final Observer<Method> callObserver) {
    final F proxy = (F) Proxy.newProxyInstance(subtype.getClassLoader(), new Class<?>[] { subtype },
            (self, method, args) -> {
                try {
                    final Object result = method.isDefault() && Proxy.isProxyClass(self.getClass())
                            ? ReflectUtil.invokeDefaultMethod(self, method, args)
                            : method.invoke(impl, args);
                    if (callObserver != null)
                        callObserver.onNext(method);
                    return result;
                } catch (Throwable e) {
                    if (e instanceof IllegalArgumentException)
                        try {
                            return ReflectUtil.invokeAsBean(impl.properties(), subtype, method, args);
                        } catch (final Exception ignore) {
                            LogUtil.getLogger(Fact.class).warn("{}method call failed: {}",
                                    method.isDefault() ? "default " : "", method, ignore);
                        }
                    if (e instanceof InvocationTargetException)
                        e = e.getCause();
                    if (callObserver != null)
                        callObserver.onError(e);
                    throw e;
                }
            });
    return proxy;
}

From source file:org.apache.kudu.mapreduce.KuduTableMapReduceUtil.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 myClass the class to find.//  ww w  . j  a v a 2  s  .  c o  m
 * @return a jar file that contains the class, or null.
 * @throws IOException
 */
private static String findContainingJar(Class<?> myClass, Map<String, String> packagedClasses)
        throws IOException {
    ClassLoader loader = myClass.getClassLoader();
    String classFile = myClass.getName().replaceAll("\\.", "/") + ".class";

    // first search the classpath
    for (Enumeration<URL> itr = loader.getResources(classFile); 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(classFile);
}

From source file:org.eclipse.e4.tools.services.impl.ResourceBundleHelper.java

/**
 * Parses the specified contributor URI and loads the {@link ResourceBundle} for the specified {@link Locale}
 * out of an OSGi {@link Bundle}./*from  w  ww  .j a  v a  2s .c o  m*/
 * <p>Following URIs are supported:
 * <ul>
 * <li>platform:/[plugin|fragment]/[Bundle-SymbolicName]<br>
 * Load the OSGi resource bundle out of the bundle/fragment named [Bundle-SymbolicName]</li>
 * <li>platform:/[plugin|fragment]/[Bundle-SymbolicName]/[Path]/[Basename]<br>
 * Load the resource bundle specified by [Path] and [Basename] out of the bundle/fragment named [Bundle-SymbolicName].</li>
 * <li>bundleclass://[plugin|fragment]/[Full-Qualified-Classname]<br>
 * Instantiate the class specified by [Full-Qualified-Classname] out of the bundle/fragment named [Bundle-SymbolicName].
 * Note that the class needs to be a subtype of {@link ResourceBundle}.</li>
 * </ul>
 * </p>
 * @param contributorURI The URI that points to a {@link ResourceBundle}
 * @param locale The {@link Locale} to use for loading the {@link ResourceBundle}
 * @param localization The service for retrieving a {@link ResourceBundle} for a given {@link Locale} out of
 *          the given {@link Bundle} which is specified by URI.
 * @return
 */
public static ResourceBundle getResourceBundleForUri(String contributorURI, Locale locale,
        BundleLocalization localization) {
    if (contributorURI == null)
        return null;

    LogService logService = ToolsServicesActivator.getDefault().getLogService();

    URI uri;
    try {
        uri = new URI(contributorURI);
    } catch (URISyntaxException e) {
        if (logService != null)
            logService.log(LogService.LOG_ERROR, "Invalid contributor URI: " + contributorURI); //$NON-NLS-1$
        return null;
    }

    String bundleName = null;
    Bundle bundle = null;
    String resourcePath = null;
    String classPath = null;

    //the uri follows the platform schema, so we search for .properties files in the bundle
    if (PLATFORM_SCHEMA.equals(uri.getScheme())) {
        bundleName = uri.getPath();
        if (bundleName.startsWith(PLUGIN_SEGMENT))
            bundleName = bundleName.substring(PLUGIN_SEGMENT.length());
        else if (bundleName.startsWith(FRAGMENT_SEGMENT))
            bundleName = bundleName.substring(FRAGMENT_SEGMENT.length());

        resourcePath = ""; //$NON-NLS-1$
        if (bundleName.contains(PATH_SEPARATOR)) {
            resourcePath = bundleName.substring(bundleName.indexOf(PATH_SEPARATOR) + 1);
            bundleName = bundleName.substring(0, bundleName.indexOf(PATH_SEPARATOR));
        }
    } else if (BUNDLECLASS_SCHEMA.equals(uri.getScheme())) {
        if (uri.getAuthority() == null) {
            if (logService != null)
                logService.log(LogService.LOG_ERROR, "Failed to get bundle for: " + contributorURI); //$NON-NLS-1$
        }
        bundleName = uri.getAuthority();
        //remove the leading /
        classPath = uri.getPath().substring(1);
    }

    ResourceBundle result = null;

    if (bundleName != null) {
        bundle = getBundleForName(bundleName);

        if (bundle != null) {
            if (resourcePath == null && classPath != null) {
                //the URI points to a class within the bundle classpath
                //therefore we are trying to instantiate the class
                try {
                    Class<?> resourceBundleClass = bundle.loadClass(classPath);
                    result = getEquinoxResourceBundle(classPath, locale, resourceBundleClass.getClassLoader());
                } catch (Exception e) {
                    if (logService != null)
                        logService.log(LogService.LOG_ERROR,
                                "Failed to load specified ResourceBundle: " + contributorURI, e); //$NON-NLS-1$
                }
            } else if (resourcePath.length() > 0) {
                //the specified URI points to a resource 
                //therefore we try to load the .properties files into a ResourceBundle
                result = getEquinoxResourceBundle(resourcePath.replace('.', '/'), locale, bundle);
            } else {
                //there is no class and no special resource specified within the URI 
                //therefore we load the OSGi resource bundle out of the specified Bundle
                //for the current Locale
                result = localization.getLocalization(bundle, locale.toString());
            }
        }
    }

    return result;
}