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.hadoop.ipc.AvroRpcEngine.java

/** Construct a client-side proxy object that implements the named protocol,
 * talking to a server at the named address. */
public Object getProxy(Class<?> protocol, long clientVersion, InetSocketAddress addr,
        UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout)
        throws IOException {
    return Proxy.newProxyInstance(protocol.getClassLoader(), new Class[] { protocol },
            new Invoker(protocol, addr, ticket, conf, factory, rpcTimeout));
}

From source file:org.apache.cactus.integration.maven.CactusScanner.java

/**
 * @param theClassName the fully qualified name of the class to check
 * @param theClasspath the classpaths needed to load the test classes
 * @return true if the class is a JUnit test case
 *//*from   w  w  w . j a  v a  2  s  .c  o  m*/
private boolean isJUnitTestCase(String theClassName, Path theClasspath) {
    Class clazz = loadClass(theClassName, theClasspath);
    if (clazz == null) {
        return false;
    }

    Class testCaseClass = null;
    try {
        testCaseClass = clazz.getClassLoader().loadClass(TestCase.class.getName());
    } catch (ClassNotFoundException e) {
        log.debug("Cannot load class", e);
        return false;
    }

    if (!testCaseClass.isAssignableFrom(clazz)) {
        log.debug("Not a JUnit test as class [" + theClassName + "] does " + "not inherit from ["
                + TestCase.class.getName() + "]");
        return false;
    }

    // the class must not be abstract
    if (Modifier.isAbstract(clazz.getModifiers())) {
        log.debug("Not a JUnit test as class [" + theClassName + "] is " + "abstract");
        return false;
    }

    // the class must have at least one test, i.e. a public method
    // starting with "test" and that takes no parameters
    boolean hasTestMethod = false;
    Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getName().startsWith("test") && (methods[i].getReturnType() == Void.TYPE)
                && (methods[i].getParameterTypes().length == 0)) {
            hasTestMethod = true;
            break;
        }
    }

    if (!hasTestMethod) {
        log.debug("Not a JUnit test as class [" + theClassName + "] has "
                + "no method that start with \"test\", returns void and has " + "no parameters");
        return false;
    }

    return true;
}

From source file:brooklyn.management.osgi.OsgiStandaloneTest.java

@Test
public void testBootBundle() throws Exception {
    Bundle bundle = installFromClasspath(BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    Class<?> bundleCls = bundle.loadClass("brooklyn.osgi.tests.SimpleEntity");
    Assert.assertEquals(Entity.class, bundle.loadClass(Entity.class.getName()));
    Assert.assertEquals(Entity.class, bundleCls.getClassLoader().loadClass(Entity.class.getName()));
}

From source file:io.teak.sdk.Amazon.java

public void init(Context context) {
    skuDetailsRequestMap = new HashMap<>();
    skuPriceMap = new HashMap<>();
    try {//w  w w  .  j  a  va 2 s.  c  o  m
        Class<?> purchasingListenerClass = Class.forName("com.amazon.device.iap.PurchasingListener");
        InvocationHandler handler = new PurchasingListenerInvocationHandler();
        Object proxy = Proxy.newProxyInstance(purchasingListenerClass.getClassLoader(),
                new Class[] { purchasingListenerClass }, handler);

        Class<?> purchasingServiceClass = Class.forName("com.amazon.device.iap.PurchasingService");
        Method m = purchasingServiceClass.getMethod("registerListener", Context.class, purchasingListenerClass);
        m.invoke(null, context, proxy);

        if (Teak.isDebug) {
            Field sandbox = purchasingServiceClass.getDeclaredField("IS_SANDBOX_MODE");

            Log.d(LOG_TAG, "Amazon In-App Purchasing 2.0 registered.");
            Log.d(LOG_TAG, "   Sandbox Mode: " + sandbox.getBoolean(null));
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Reflection error: " + Log.getStackTraceString(e));
        Teak.sdkRaven.reportException(e);
    }
}

From source file:com.haulmont.cuba.core.config.AppPropertiesLocator.java

protected List<AppPropertyEntity> findDatabaseStoredProperties(Set<Class> configInterfaces) {
    List<AppPropertyEntity> result = new ArrayList<>();

    Map<Method, Object> propertyMethods = new HashMap<>();
    for (Class configInterface : configInterfaces) {
        if (configInterface.getClassLoader() != getClass().getClassLoader()) {
            // happens when deployed to single WAR with separate classloaders for core and web
            continue;
        }/*from ww  w  . j a  va  2 s .  c  o  m*/
        Config config = configuration.getConfig(configInterface);
        boolean interfaceSourceIsDb = false;
        Source sourceAnn = (Source) configInterface.getAnnotation(Source.class);
        if (sourceAnn != null && sourceAnn.type() == SourceType.DATABASE) {
            interfaceSourceIsDb = true;
        }
        Method[] declaredMethods = configInterface.getDeclaredMethods();
        for (Method method : declaredMethods) {
            if (method.getName().startsWith("get")) {
                Source methodSourceAnn = method.getAnnotation(Source.class);
                if ((methodSourceAnn == null && interfaceSourceIsDb)
                        || (methodSourceAnn != null && methodSourceAnn.type() == SourceType.DATABASE)) {
                    propertyMethods.put(method, config);
                }
            }
        }
    }

    List<com.haulmont.cuba.core.entity.Config> dbContent = loadDbContent();

    for (Map.Entry<Method, Object> entry : propertyMethods.entrySet()) {
        Method method = entry.getKey();
        Property propertyAnn = method.getAnnotation(Property.class);
        if (propertyAnn == null)
            continue;

        String name = propertyAnn.value();
        AppPropertyEntity entity = new AppPropertyEntity();
        entity.setName(name);
        entity.setDefaultValue(getDefaultValue(method));
        entity.setCurrentValue(getCurrentValue(method, entry.getValue()));
        entity.setOverridden(StringUtils.isNotEmpty(AppContext.getProperty(name)));
        entity.setSecret(method.getAnnotation(Secret.class) != null);
        if (!entity.getOverridden()) {
            assignLastUpdated(entity, dbContent);
        }
        setDataType(method, entity);
        result.add(entity);
    }

    return result;
}

From source file:adept.io.Reader.java

/**
 * List directory contents for a resource folder. Not recursive.
 * This is basically a brute-force implementation.
 * Works for regular files and also JARs.
 *
 * @param clazz Any java class that lives in the same place as the resources you want.
 * @param path  Should end with "/", but not start with one.
 * @return Just the name of each member item, not the full paths.
 * @throws URISyntaxException the uRI syntax exception
 * @throws IOException        Signals that an I/O exception has occurred.
 * @author Greg Briggs/* ww w.  j  a  va 2  s. c  o m*/
 */
public static 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();
    }

    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:de.static_interface.sinkscripts.SinkScripts.java

public void runInjection(File file) throws Exception {
    String[] lines = Util.readLines(file);

    String code = "";
    String targetClass = null;//from w  w w  .j  av a2 s .com
    boolean constructor = false;
    InjectTarget target = InjectTarget.AFTER_METHOD;
    String method = null;
    List<Class> methodArgs = new ArrayList<>();
    boolean codeStart = false;

    for (String line : lines) {
        if (line.equals("@@INJECT@@")) {
            codeStart = true;
            continue;
        }

        if (!codeStart) {
            if (line.startsWith("[") && line.endsWith("]")) {
                line = line.replaceFirst("\\Q[\\E", "");
                line = StringUtil.replaceLast(line, "]", "");
                String[] parts = line.split(":", 2);
                parts[0] = parts[0].trim();
                if (parts[0].equalsIgnoreCase("Constructor")) {
                    constructor = true;
                }

                if (parts.length < 2)
                    continue;
                parts[1] = parts[1].trim();

                switch (parts[0].toLowerCase()) {
                case "method":
                    method = parts[1];
                    break;
                case "at":
                case "injecttarget":
                    target = InjectTarget.valueOf(parts[1].toUpperCase());
                    break;
                case "arg":
                case "methodarg":
                    methodArgs.add(Class.forName(parts[1]));
                    break;
                case "class":
                case "targetclass":
                case "target":
                    targetClass = parts[1];
                    break;
                }
                continue;
            }

            if (constructor && method != null) {
                throw new Exception("Invalid config: construct & method specified at the same time!");
            }

            continue;
        }

        if (code.equals("")) {
            code = line;
            continue;
        }
        code += System.lineSeparator() + line;
    }

    Validate.notNull(target, "injecttarget is not specified");
    Validate.notNull(targetClass, "class is not specified");
    if (!constructor) {
        Validate.notNull(method, "method or constructor is not specified");
    }
    Validate.notEmpty(code, "no code found");

    Class clazz = Class.forName(targetClass);
    if (!constructor) {
        Injector.injectCode(targetClass, clazz.getClassLoader(), method,
                methodArgs.toArray(new Class[methodArgs.size()]), code, target);
    } else {
        Injector.injectCodeConstructor(targetClass, clazz.getClassLoader(),
                methodArgs.toArray(new Class[methodArgs.size()]), code, target);
    }
}

From source file:org.apache.brooklyn.core.mgmt.osgi.OsgiStandaloneTest.java

@Test
public void testBootBundle() throws Exception {
    Bundle bundle = installFromClasspath(BROOKLYN_TEST_OSGI_ENTITIES_PATH);
    Class<?> bundleCls = bundle.loadClass("org.apache.brooklyn.test.osgi.entities.SimpleEntity");
    Assert.assertEquals(Entity.class, bundle.loadClass(Entity.class.getName()));
    Assert.assertEquals(Entity.class, bundleCls.getClassLoader().loadClass(Entity.class.getName()));
}

From source file:com.netflix.paas.config.base.DynamicProxyArchaeusConfigurationFactory.java

@SuppressWarnings({ "unchecked", "static-access" })
public <T> T get(Class<T> configClass, DynamicPropertyFactory propertyFactory,
        AbstractConfiguration configuration) throws Exception {
    final Map<String, Supplier<?>> methods = ConfigurationProxyUtils.getMethodSuppliers(configClass,
            propertyFactory, configuration);

    if (configClass.isInterface()) {
        Class<?> proxyClass = Proxy.getProxyClass(configClass.getClassLoader(), new Class[] { configClass });

        return (T) proxyClass.getConstructor(new Class[] { InvocationHandler.class })
                .newInstance(new Object[] { new InvocationHandler() {
                    @Override//w  ww. ja v a 2s.c o  m
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Supplier<?> supplier = (Supplier<?>) methods.get(method.getName());
                        return supplier.get();
                    }
                } });
    } else {
        final Enhancer enhancer = new Enhancer();
        final Object obj = (T) enhancer.create(configClass, new net.sf.cglib.proxy.InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Supplier<?> supplier = (Supplier<?>) methods.get(method.getName());
                if (supplier == null) {
                    return method.invoke(proxy, args);
                }
                return supplier.get();
            }
        });

        ConfigurationProxyUtils.assignFieldValues(obj, configClass, propertyFactory, configuration);
        return (T) obj;
    }
}

From source file:org.compass.core.config.binding.AbstractInputStreamMappingBinding.java

public boolean addClass(Class clazz) throws ConfigurationException, MappingException {
    boolean addedAtLeaseOne = false;
    for (String suffix : getSuffixes()) {
        String fileName = clazz.getName().replace('.', '/') + suffix;
        InputStream rsrc = clazz.getClassLoader().getResourceAsStream(fileName);
        if (rsrc == null) {
            continue;
        }/*from  w w  w. j a  va 2 s .  c  o  m*/
        try {
            addedAtLeaseOne |= internalAddInputStream(rsrc, fileName, true);
        } catch (ConfigurationException me) {
            throw new ConfigurationException("Error reading resource [" + fileName + "]", me);
        }
    }
    return addedAtLeaseOne;
}