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.liferay.portal.template.velocity.internal.VelocityManager.java

@Override
public void init() throws TemplateException {
    if (_velocityEngine != null) {
        return;//from  w  ww  .  j  a  v a 2  s. co  m
    }

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    Class<?> clazz = getClass();

    currentThread.setContextClassLoader(clazz.getClassLoader());

    try {
        _velocityEngine = new VelocityEngine();

        ExtendedProperties extendedProperties = new FastExtendedProperties();

        extendedProperties.setProperty(VelocityEngine.DIRECTIVE_IF_TOSTRING_NULLCHECK,
                String.valueOf(_velocityEngineConfiguration.directiveIfToStringNullCheck()));

        extendedProperties.setProperty(VelocityEngine.EVENTHANDLER_METHODEXCEPTION,
                LiferayMethodExceptionEventHandler.class.getName());

        extendedProperties.setProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,
                StringUtil.merge(_velocityEngineConfiguration.restrictedClasses()));

        extendedProperties.setProperty(RuntimeConstants.INTROSPECTOR_RESTRICT_PACKAGES,
                StringUtil.merge(_velocityEngineConfiguration.restrictedPackages()));

        extendedProperties.setProperty(RuntimeConstants.PARSER_POOL_CLASS, VelocityParserPool.class.getName());

        extendedProperties.setProperty(VelocityEngine.RESOURCE_LOADER, "liferay");

        extendedProperties.setProperty(StringBundler.concat("liferay.", VelocityEngine.RESOURCE_LOADER, ".",
                VelocityTemplateResourceLoader.class.getName()), templateResourceLoader);

        boolean cacheEnabled = false;

        if (_velocityEngineConfiguration.resourceModificationCheckInterval() != 0) {

            cacheEnabled = true;
        }

        extendedProperties.setProperty("liferay." + VelocityEngine.RESOURCE_LOADER + ".cache",
                String.valueOf(cacheEnabled));

        extendedProperties.setProperty("liferay." + VelocityEngine.RESOURCE_LOADER + ".class",
                LiferayResourceLoader.class.getName());

        extendedProperties.setProperty(
                "liferay." + VelocityEngine.RESOURCE_LOADER + ".resourceModificationCheckInterval",
                _velocityEngineConfiguration.resourceModificationCheckInterval() + "");

        extendedProperties.setProperty(VelocityEngine.RESOURCE_MANAGER_CLASS,
                LiferayResourceManager.class.getName());

        extendedProperties.setProperty(
                "liferay." + VelocityEngine.RESOURCE_MANAGER_CLASS + ".resourceModificationCheckInterval",
                _velocityEngineConfiguration.resourceModificationCheckInterval() + "");

        extendedProperties.setProperty(VelocityTemplateResourceLoader.class.getName(), templateResourceLoader);

        extendedProperties.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS,
                _velocityEngineConfiguration.logger());

        extendedProperties.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM + ".log4j.category",
                _velocityEngineConfiguration.loggerCategory());

        extendedProperties.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME, SecureUberspector.class.getName());

        extendedProperties.setProperty(VelocityEngine.VM_LIBRARY,
                StringUtil.merge(_velocityEngineConfiguration.velocimacroLibrary()));

        extendedProperties.setProperty(VelocityEngine.VM_LIBRARY_AUTORELOAD, String.valueOf(!cacheEnabled));

        extendedProperties.setProperty(VelocityEngine.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL,
                String.valueOf(!cacheEnabled));

        _velocityEngine.setExtendedProperties(extendedProperties);

        _velocityEngine.init();
    } catch (Exception e) {
        throw new TemplateException(e);
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);
    }
}

From source file:com.asakusafw.runtime.util.hadoop.ConfigurationProvider.java

private static void prepareClasspath(File temporary, Class<?> aClass) throws IOException {
    assert temporary != null;
    assert aClass != null;
    File current = temporary;/* w w w  . ja  va  2  s . c o  m*/
    String name = aClass.getName();
    int start = 0;
    while (true) {
        int index = name.indexOf('.', start);
        if (index < 0) {
            break;
        }
        current = new File(current, name.substring(start, index));
        if (current.mkdirs() == false && current.isDirectory() == false) {
            LOG.warn(MessageFormat.format("Failed to create a directory: {0}", current));
        }
        start = index + 1;
    }
    File target = new File(current, name.substring(start) + CLASS_EXTENSION);

    String path = name.replace('.', '/') + CLASS_EXTENSION;
    try (InputStream in = aClass.getClassLoader().getResourceAsStream(path)) {
        if (in == null) {
            throw new FileNotFoundException(
                    MessageFormat.format("A class file binary does not found in classpath: {0}", path));
        }
        try (OutputStream out = new FileOutputStream(target)) {
            byte[] buf = new byte[1024];
            while (true) {
                int read = in.read(buf);
                if (read < 0) {
                    break;
                }
                out.write(buf, 0, read);
            }
        }
    }
}

From source file:org.auraframework.system.AuraSystemUITest.java

private URL checkClassLocation(String className) throws Exception {
    URL url = null;//w  w  w .j  av  a2s.  c  o m
    try {
        Class<?> clazz = Class.forName(className);
        String resourceName = clazz.getName().replace('.', '/') + ".class";
        url = clazz.getClassLoader().getResource(resourceName);
        LOG.println(url.toString());
    } catch (Throwable t) {
        LOG.println();
        t.printStackTrace(LOG);
    }
    return url;
}

From source file:com.isencia.passerelle.hmi.HMIBase.java

/**
 * Given the name of a file or a URL, convert it to a URL. This first
 * attempts to do that directly by invoking a URL constructor. If that
 * fails, then it tries to interpret the spec as a file name on the local
 * file system. If that fails, then it tries to interpret the spec as a
 * resource accessible to the classloader, which uses the classpath to find
 * the resource. If that fails, then it throws an exception. The
 * specification can give a file name relative to current working directory,
 * or the directory in which this application is started up.
 * //from  www. jav a  2  s . c  om
 * @param spec
 *            The specification.
 * @exception IOException
 *                If it cannot convert the specification to a URL.
 */
public static URL specToURL(final String spec) throws IOException {
    try {
        // First argument is null because we are only
        // processing absolute URLs this way. Relative
        // URLs are opened as ordinary files.
        return new URL(null, spec);
    } catch (final MalformedURLException ex) {
        try {
            final File file = new File(spec);
            if (!file.exists()) {
                throw new MalformedURLException();
            }
            return file.getCanonicalFile().toURL();
        } catch (final MalformedURLException ex2) {
            try {
                // Try one last thing, using the classpath.
                // Need a class context, and this is a static method, so...
                // NOTE: There doesn't seem to be any way to convert
                // this a canonical name, so if a model is opened this
                // way, and then later opened as a file, the model
                // directory will think it has two different files.
                final Class refClass = Class.forName("ptolemy.kernel.util.NamedObj");
                final URL inurl = refClass.getClassLoader().getResource(spec);
                if (inurl == null) {
                    throw new Exception();
                } else {
                    return inurl;
                }
            } catch (final Exception exception) {
                throw new IOException("File not found: " + spec);
            }
        }
    }
}

From source file:ch.sourcepond.utils.mdcwrapper.impl.DefaultMdcWrapper.java

@Override
public <T extends Executor> T wrap(final T pExecutor, final Class<T> pInterface) {
    notNull(pExecutor, "Executor to wrapped is null!");
    notNull(pInterface, "Executor interface is null!");
    isTrue(pInterface.isInterface(), "Class specified is not an interface!");
    return createProxyIfNecessary(pExecutor, pInterface.getClassLoader(), pInterface);
}

From source file:org.bigtester.ate.experimentals.DynamicClassLoader.java

@Test
public void test5() throws Exception {
    Class cls = Class.forName("org.testng.TestNG");

    // returns the ClassLoader object associated with this Class
    ClassLoader cLoader = cls.getClassLoader();

    ((URLClassLoader) cLoader).getURLs();

    System.out.println(Arrays.toString(((URLClassLoader) cLoader).getURLs()));
}

From source file:org.eclipse.wb.tests.designer.core.TestBundle.java

/**
 * Creates in this {@link TestBundle} same class as it exists in given {@link ClassLoader}. Note,
 * that {@link ClassLoader} should be able to provide <code>*.class</code> resource.
 *///w ww  . j  a  v a2 s . c o  m
public void addClass(Class<?> clazz) throws Exception {
    ClassLoader classLoader = clazz.getClassLoader();
    String name = clazz.getName();
    // add main class
    addClass(classLoader, name);
    // add anonymous inner classes
    try {
        for (int i = 1;; i++) {
            addClass(classLoader, name + "$" + i);
        }
    } catch (Throwable e) {
    }
}

From source file:com.liferay.portal.osgi.web.wab.generator.internal.processor.WabProcessorTest.java

protected ClassLoader getClassLoader() {
    Class<?> clazz = getClass();

    return clazz.getClassLoader();
}

From source file:org.impalaframework.classloader.ModuleTestClassLoader.java

public Class<?> loadClass(String className) throws ClassNotFoundException {

    Class<?> toReturn = loadCustomClass(className);

    if (toReturn == null) {
        toReturn = loadParentClass(className);
    }/*from  ww  w  .j a  v  a  2  s  .  co m*/

    if (toReturn == null) {
        toReturn = getAlreadyLoadedClass(className);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Loaded " + " class " + className + ": " + toReturn.getClassLoader());
    }

    if (toReturn == null) {
        if (logger.isDebugEnabled())
            logger.debug("Class not found: " + className);
        throw new ClassNotFoundException(className);
    }

    return toReturn;

}

From source file:org.motechproject.server.osgi.OsgiFrameworkService.java

/**
 * @param bundle//from   w w w .java 2  s  .  c o  m
 * @throws Exception
 */
private void storeClassCloader(Bundle bundle) throws Exception {
    String key = bundle.getSymbolicName();
    String activator = (String) bundle.getHeaders().get(BUNDLE_ACTIVATOR_HEADER);
    if (activator != null) {
        @SuppressWarnings("rawtypes")
        Class activatorClass = bundle.loadClass(activator);
        if (activatorClass != null) {
            bundleClassLoaderLookup.put(key, activatorClass.getClassLoader());
        }
    }
}