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:org.apache.ibatis.plugin.Plugin.java

public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
        return Proxy.newProxyInstance(type.getClassLoader(), interfaces,
                new Plugin(target, interceptor, signatureMap));
    }/*  w ww  . j a  v  a2s.c o  m*/
    return target;
}

From source file:org.apache.xmlgraphics.util.Service.java

/**
 * Returns an iterator where each element should implement the
 * interface (or subclass the baseclass) described by cls.  The
 * Classes are found by searching the classpath for service files
 * named: 'META-INF/services/&lt;fully qualified classname&gt; that list
 * fully qualifted classnames of classes that implement the
 * service files classes interface.  These classes must have
 * default constructors if returnInstances is true.
 *
 * @param cls The class/interface to search for providers of.
 * @param returnInstances true if the iterator should return instances rather than class names.
 *//*from w  w  w .  ja v a2s  .co  m*/
public static synchronized Iterator providers(Class cls, boolean returnInstances) {
    String serviceFile = "META-INF/services/" + cls.getName();
    Map cacheMap = (returnInstances ? instanceMap : classMap);

    List l = (List) cacheMap.get(serviceFile);
    if (l != null) {
        return l.iterator();
    }

    l = new java.util.ArrayList();
    cacheMap.put(serviceFile, l);

    ClassLoader cl = null;
    try {
        cl = cls.getClassLoader();
    } catch (SecurityException se) {
        // Ooops! can't get his class loader.
    }
    // Can always request your own class loader. But it might be 'null'.
    if (cl == null) {
        cl = Service.class.getClassLoader();
    }
    if (cl == null) {
        cl = ClassLoader.getSystemClassLoader();
    }

    // No class loader so we can't find 'serviceFile'.
    if (cl == null) {
        return l.iterator();
    }

    Enumeration e;
    try {
        e = cl.getResources(serviceFile);
    } catch (IOException ioe) {
        return l.iterator();
    }

    while (e.hasMoreElements()) {
        try {
            URL u = (URL) e.nextElement();

            InputStream is = u.openStream();
            Reader r = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(r);
            try {
                String line = br.readLine();
                while (line != null) {
                    try {
                        // First strip any comment...
                        int idx = line.indexOf('#');
                        if (idx != -1) {
                            line = line.substring(0, idx);
                        }

                        // Trim whitespace.
                        line = line.trim();

                        // If nothing left then loop around...
                        if (line.length() == 0) {
                            line = br.readLine();
                            continue;
                        }

                        if (returnInstances) {
                            // Try and load the class
                            Object obj = cl.loadClass(line).newInstance();
                            // stick it into our vector...
                            l.add(obj);
                        } else {
                            l.add(line);
                        }
                    } catch (Exception ex) {
                        // Just try the next line
                    }
                    line = br.readLine();
                }
            } finally {
                IOUtils.closeQuietly(br);
                IOUtils.closeQuietly(is);
            }
        } catch (Exception ex) {
            // Just try the next file...
        } catch (LinkageError le) {
            // Just try the next file...
        }
    }
    return l.iterator();
}

From source file:org.apache.abdera2.common.Discover.java

public static URL locateResource(String id, ClassLoader loader, Class<?> callingClass) {
    URL url = loader.getResource(id);
    if (url == null && id.startsWith("/"))
        url = loader.getResource(id.substring(1));
    if (url == null)
        url = locateResource(id, Discover.class.getClassLoader(), callingClass);
    if (url == null && callingClass != null)
        url = locateResource(id, callingClass.getClassLoader(), null);
    if (url == null)
        url = callingClass.getResource(id);
    if ((url == null) && id.startsWith("/"))
        url = callingClass.getResource(id.substring(1));
    return url;/*from w w w .  j  av  a  2s.c o  m*/
}

From source file:edu.umn.cs.spatialHadoop.core.SpatialSite.java

private static String findContainingJar(Class my_class) {
    ClassLoader loader = my_class.getClassLoader();
    String class_file = my_class.getName().replaceAll("\\.", "/") + ".class";
    try {/*from  ww w .j  av  a 2 s.c  om*/
        for (Enumeration<URL> itr = loader.getResources(class_file); itr.hasMoreElements();) {
            URL url = (URL) itr.nextElement();
            if ("jar".equals(url.getProtocol())) {
                String toReturn = url.getPath();
                if (toReturn.startsWith("file:")) {
                    toReturn = toReturn.substring("file:".length());
                }
                toReturn = URLDecoder.decode(toReturn, "UTF-8");
                return toReturn.replaceAll("!.*$", "");
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return null;
}

From source file:org.cloudata.core.common.ipc.CRPC.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
public static CVersionedProtocol getProxy(Class<?> protocol, long clientVersion, InetSocketAddress addr,
        CloudataConf conf, SocketFactory factory) throws IOException {

    CVersionedProtocol proxy = (CVersionedProtocol) Proxy.newProxyInstance(protocol.getClassLoader(),
            new Class[] { protocol }, new Invoker(addr, conf, factory));

    Long serverVersion = null;//w w  w.  j a v  a 2 s.  c  om
    try {
        synchronized (versionCheckMap) {
            if ((serverVersion = versionCheckMap.get(addr)) == null) {
                serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion);
                versionCheckMap.put(addr, serverVersion);
            }
        }
    } catch (IOException e) {
        LOG.warn("Error proxy.getProtocolVersion:" + addr + "," + e.getMessage());
        throw e;
    } catch (Exception e) {
        IOException err = new IOException(e.getMessage());
        err.initCause(e);
        throw err;
    }

    if (serverVersion == clientVersion) {
        return proxy;
    } else {
        throw new VersionMismatch(protocol.getName(), clientVersion, serverVersion);
    }
}

From source file:eu.esdihumboldt.hale.common.align.model.impl.AbstractCellExplanation.java

/**
 * Determine the locales a resource is available for.
 * /*from  w ww.  j  a  va  2s .  com*/
 * @param clazz the clazz the resource resides next to
 * @param baseName the base name of the resource
 * @param suffix the suffix of the resource file, e.g.
 *            <code>properties</code>
 * @param defaultLocale the default locale to be assumed for an unqualified
 *            resource
 * @return the set of locales the resource is available for
 * @throws IOException if an error occurs trying to determine the resource
 *             files
 */
public static Set<Locale> findLocales(final Class<?> clazz, final String baseName, final String suffix,
        Locale defaultLocale) throws IOException {
    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
            clazz.getClassLoader());
    String pkg = clazz.getPackage().getName().replaceAll("\\.", "/");
    String pattern = pkg + "/" + baseName + "*." + suffix;
    return Arrays.stream(resolver.getResources(pattern)).map(resource -> {
        String fileName = resource.getFilename();

        if (fileName != null && fileName.startsWith(baseName)) {
            fileName = fileName.substring(baseName.length());
            if (fileName.endsWith("." + suffix)) {
                if (fileName.length() == suffix.length() + 1) {
                    // default locale file
                    return defaultLocale;
                } else {
                    String localeIdent = fileName.substring(0, fileName.length() - suffix.length() - 1);

                    String language = "";
                    String country = "";
                    String variant = "";

                    String[] parts = localeIdent.split("_");
                    int index = 0;
                    if (parts.length > index && parts[index].isEmpty()) {
                        index++;
                    }

                    if (parts.length > index) {
                        language = parts[index++];
                    }

                    if (parts.length > index) {
                        country = parts[index++];
                    }

                    if (parts.length > index) {
                        variant = parts[index++];
                    }

                    return new Locale(language, country, variant);
                }
            } else {
                log.error("Invalid resource encountered");
                return null;
            }
        } else {
            log.error("Invalid resource encountered");
            return null;
        }
    }).filter(locale -> locale != null).collect(Collectors.toSet());
}

From source file:com.agimatec.validation.jsr303.util.SecureActions.java

public static Class<?> loadClass(final String className, final Class<?> caller) {
    return run(new PrivilegedAction<Class<?>>() {
        public Class<?> run() {
            try {
                ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                if (contextClassLoader != null) {
                    return contextClassLoader.loadClass(className);
                }//from  w  ww .  java  2 s.c o m
            } catch (Throwable e) {
                // ignore
            }
            try {
                return Class.forName(className, true, caller.getClassLoader());
            } catch (ClassNotFoundException e) {
                throw new ValidationException("Unable to load class: " + className, e);
            }
        }
    });
}

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

/**
 * @param actorType the type of {@link Actor} to mimic
 * @param callObserver an {@link Observer} of method call, or {@code null}
 * @return the {@link Proxy} instance//from   w  w w . ja  va2s. c  om
 */
@SuppressWarnings("unchecked")
static <A extends Actor<T>, F extends Fact, T extends F> A proxyAs(final Actor<F> impl,
        final Class<A> actorType, final Observer<Method> callObserver) {
    final A proxy = (A) Proxy.newProxyInstance(actorType.getClassLoader(), new Class<?>[] { actorType },
            (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(), actorType, 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.xml.security.utils.ClassLoaderUtils.java

private static Class<?> loadClass2(String className, Class<?> callingClass) throws ClassNotFoundException {
    try {//from   w  w w  .  j  a v  a 2 s. c  om
        return Class.forName(className);
    } catch (ClassNotFoundException ex) {
        try {
            if (ClassLoaderUtils.class.getClassLoader() != null) {
                return ClassLoaderUtils.class.getClassLoader().loadClass(className);
            }
        } catch (ClassNotFoundException exc) {
            if (callingClass != null && callingClass.getClassLoader() != null) {
                return callingClass.getClassLoader().loadClass(className);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug(ex);
        }
        throw ex;
    }
}

From source file:org.apache.abdera2.common.Discover.java

public static Enumeration<URL> locateResources(String id, ClassLoader loader, Class<?> callingClass)
        throws IOException {
    Enumeration<URL> urls = loader.getResources(id);
    if (urls == null && id.startsWith("/"))
        urls = loader.getResources(id.substring(1));
    if (urls == null)
        urls = locateResources(id, Discover.class.getClassLoader(), callingClass);
    if (urls == null)
        urls = locateResources(id, callingClass.getClassLoader(), callingClass);
    return urls;/* w  w w.  jav a 2s .  co  m*/
}