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.wildfly.extension.camel.handler.ModuleClassLoaderAssociationHandler.java

@Override
public void setup(CamelContext camelctx) {

    Module contextModule = null;/*from www. j  a  v a2s  . c  o  m*/

    // Case #1: The context has already been initialized
    ClassLoader applicationClassLoader = camelctx.getApplicationContextClassLoader();
    if (applicationClassLoader instanceof ModuleClassLoader) {
        contextModule = ((ModuleClassLoader) applicationClassLoader).getModule();
    }

    // Case #2: The context is a system context
    if (contextModule == null) {
        ClassLoader thiscl = CamelContextRegistryService.class.getClassLoader();
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        if (tccl == thiscl) {
            contextModule = ((ModuleClassLoader) thiscl).getModule();
        }
    }

    // Case #3: The context is created as part of a deployment
    if (contextModule == null) {
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        if (tccl instanceof ModuleClassLoader) {
            Module tcm = ((ModuleClassLoader) tccl).getModule();
            if (tcm.getIdentifier().getName().startsWith("deployment.")) {
                contextModule = tcm;
            }
        }
    }

    // Case #4: The context is created through user API
    if (contextModule == null) {
        Class<?> callingClass = CallerContext.getCallingClass();
        contextModule = ((ModuleClassLoader) callingClass.getClassLoader()).getModule();
    }

    IllegalStateAssertion.assertNotNull(contextModule, "Cannot obtain module for: " + camelctx);
    ModuleClassLoader moduleClassLoader = contextModule.getClassLoader();
    camelctx.setApplicationContextClassLoader(moduleClassLoader);
}

From source file:br.msf.commons.util.IOUtils.java

/**
 * Reads the properties of a classpath resource file, named after a class.
 * <p/>/*from w  ww. j a v a2s  .  co m*/
 * Example:<br/>
 * if the given class fully qualified name is:
 * <pre>"org.mycomp.MyClass"</pre>
 * this method will look for a properties file named:
 * <pre>"/org/mycomp/MyClass.properties"</pre>
 * on the classpath.
 * <p/>
 * Accordingly to the Standard Java Specifications, Properties files are ISO-8859-1 encoded.
 *
 * @param clazz The class witch the resource is named after.
 * @return The properties of the resource file pointed by the given path.
 * @throws RuntimeIOException If something goes wrong opening the file stream.
 */
public static Properties readProperties(final Class clazz) {
    if (clazz == null) {
        return null;
    }
    return readProperties(clazz.getPackage(), clazz.getSimpleName(), clazz.getClassLoader());
}

From source file:com.wavemaker.commons.io.ClassPathFile.java

/**
 * Create a new {@link ClassPathFile} instance.
 * /*from   w ww  . j ava2  s  . c  om*/
 * @param sourceClass the source class used to load the resource
 * @param path the path of the resource (relative to the sourceClass)
 */
public ClassPathFile(Class<?> sourceClass, String path) {
    Assert.notNull(sourceClass, "SourceClass must not be null");
    Assert.hasLength(path, "Name must not be empty");
    this.classLoader = sourceClass.getClassLoader();
    this.path = new ResourcePath().get(sourceClass.getPackage().getName().replace(".", "/")).get(path);
}

From source file:org.gradle.api.internal.project.antbuilder.DefaultIsolatedAntBuilder.java

protected void disposeBuilder(Object antBuilder, Object antLogger) {
    try {/*from   ww w . j a  v  a2  s .c  o  m*/
        Object project = getProject(antBuilder);
        Class<?> projectClass = project.getClass();
        ClassLoader cl = projectClass.getClassLoader();
        // remove build listener
        Class<?> buildListenerClass = cl.loadClass("org.apache.tools.ant.BuildListener");
        Method removeBuildListener = projectClass.getDeclaredMethod("removeBuildListener", buildListenerClass);
        removeBuildListener.invoke(project, antLogger);
        antBuilder.getClass().getDeclaredMethod("close").invoke(antBuilder);
    } catch (Exception ex) {
        throw UncheckedException.throwAsUncheckedException(ex);
    }
}

From source file:org.jabsorb.client.Client.java

/**
 * Create a proxy for communicating with the remote service.
 * //from   w w  w  . j  ava2 s.  c  om
 * @param key
 *          the remote object key
 * @param klass
 *          the class of the interface the remote object should adhere to
 * @return created proxy
 */
public Object openProxy(String key, Class klass) {
    Object result = java.lang.reflect.Proxy.newProxyInstance(klass.getClassLoader(), new Class[] { klass },
            this);
    proxyMap.put(result, key);
    return result;
}

From source file:info.archinnov.achilles.internal.context.ConfigurationContext.java

public ClassLoader selectClassLoader(Class<?> entityClass) {
    return OSGIClassLoader != null ? OSGIClassLoader : entityClass.getClassLoader();
}

From source file:org.gradle.api.internal.project.antbuilder.DefaultIsolatedAntBuilder.java

protected void configureAntBuilder(Object antBuilder, Object antLogger) {
    try {//from   w ww. j a va  2 s  . com
        Object project = getProject(antBuilder);
        Class<?> projectClass = project.getClass();
        ClassLoader cl = projectClass.getClassLoader();
        Class<?> buildListenerClass = cl.loadClass("org.apache.tools.ant.BuildListener");
        Method addBuildListener = projectClass.getDeclaredMethod("addBuildListener", buildListenerClass);
        Method removeBuildListener = projectClass.getDeclaredMethod("removeBuildListener", buildListenerClass);
        Method getBuildListeners = projectClass.getDeclaredMethod("getBuildListeners");
        Vector listeners = (Vector) getBuildListeners.invoke(project);
        removeBuildListener.invoke(project, listeners.get(0));
        addBuildListener.invoke(project, antLogger);
    } catch (Exception ex) {
        throw UncheckedException.throwAsUncheckedException(ex);
    }
}

From source file:org.apache.openejb.cdi.OptimizedLoaderService.java

private boolean isFiltered(final Collection<Extension> extensions, final Extension next) {
    final ClassLoader containerLoader = ParentClassLoaderFinder.Helper.get();
    final Class<? extends Extension> extClass = next.getClass();
    if (extClass.getClassLoader() != containerLoader) {
        return false;
    }/*from  w w  w. j av  a  2  s .  co  m*/

    final String name = extClass.getName();
    switch (name) {
    case "org.apache.bval.cdi.BValExtension":
        for (final Extension e : extensions) {
            final String en = e.getClass().getName();

            // org.hibernate.validator.internal.cdi.ValidationExtension but allowing few evolutions of packages
            if (en.startsWith("org.hibernate.validator.") && en.endsWith("ValidationExtension")) {
                log.info("Skipping BVal CDI integration cause hibernate was found in the application");
                return true;
            }
        }
        break;
    case "org.apache.batchee.container.cdi.BatchCDIInjectionExtension": // see org.apache.openejb.batchee.BatchEEServiceManager
        return "true".equals(SystemInstance.get().getProperty("tomee.batchee.cdi.use-extension", "false"));
    case "org.apache.commons.jcs.jcache.cdi.MakeJCacheCDIInterceptorFriendly":
        final String spi = "META-INF/services/javax.cache.spi.CachingProvider";
        try {
            final Enumeration<URL> appResources = Thread.currentThread().getContextClassLoader()
                    .getResources(spi);
            if (appResources != null && appResources.hasMoreElements()) {
                final Collection<URL> containerResources = Collections.list(containerLoader.getResources(spi));
                do {
                    if (!containerResources.contains(appResources.nextElement())) {
                        log.info(
                                "Skipping JCS CDI integration cause another provide was found in the application");
                        return true;
                    }
                } while (appResources.hasMoreElements());
            }
        } catch (final Exception e) {
            // no-op
        }
        break;
    default:
    }
    return false;
}

From source file:com.imaginabit.yonodesperdicion.gcm.RegistrationIntentService.java

String[] getResourceListing(Class clazz, String path) throws URISyntaxException, IOException {
    URL dirURL = clazz.getClassLoader().getResource(path);
    if (dirURL != null && dirURL.getProtocol().equals("file")) {
        /* A file path: easy enough */
        return new File(dirURL.toURI()).list();
    }/*from   w  ww .  j  ava  2 s .  co  m*/

    if (dirURL == null) {
        /*
         * In case of a jar file, we can't actually find a directory.
         * Have to assume the same jar as clazz.
         */
        String me = clazz.getName().replace(".", "/") + ".class";
        dirURL = clazz.getClassLoader().getResource(me);
    }

    if (dirURL.getProtocol().equals("jar")) {
        /* A JAR path */
        String jarPath = dirURL.getPath().substring(5, dirURL.getPath().indexOf("!")); //strip out only the JAR file
        JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        Set<String> result = new HashSet<String>(); //avoid duplicates in case it is a subdirectory
        while (entries.hasMoreElements()) {
            String name = entries.nextElement().getName();
            if (name.startsWith(path)) { //filter according to the path
                String entry = name.substring(path.length());
                int checkSubdir = entry.indexOf("/");
                if (checkSubdir >= 0) {
                    // if it is a subdirectory, we just return the directory name
                    entry = entry.substring(0, checkSubdir);
                }
                result.add(entry);
            }
        }
        return result.toArray(new String[result.size()]);
    }

    throw new UnsupportedOperationException("Cannot list files for URL " + dirURL);
}

From source file:org.codice.ddf.itests.common.AbstractIntegrationTest.java

/**
 * Variables to be replaced in a resource file should be in the format: $variableName$ The
 * variable to replace in the file should also also match the parameter names of the method
 * calling getFileContent./*from   w w w. j  a v  a 2  s .  c o  m*/
 *
 * @param filePath
 * @param params
 * @param classRelativeToResource
 * @return
 */
@SuppressWarnings({ "squid:S00112" /* A generic RuntimeException is perfectly reasonable in this case. */
})
public static String getFileContent(String filePath, ImmutableMap<String, String> params,
        Class classRelativeToResource) {

    StrSubstitutor strSubstitutor = new StrSubstitutor(params);

    strSubstitutor.setVariablePrefix(RESOURCE_VARIABLE_DELIMETER);
    strSubstitutor.setVariableSuffix(RESOURCE_VARIABLE_DELIMETER);
    String fileContent;

    try {
        fileContent = IOUtils.toString(classRelativeToResource.getClassLoader().getResourceAsStream(filePath),
                "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException("Failed to read filepath: " + filePath);
    }

    return strSubstitutor.replace(fileContent);
}