Example usage for java.lang ClassNotFoundException ClassNotFoundException

List of usage examples for java.lang ClassNotFoundException ClassNotFoundException

Introduction

In this page you can find the example usage for java.lang ClassNotFoundException ClassNotFoundException.

Prototype

public ClassNotFoundException(String s) 

Source Link

Document

Constructs a ClassNotFoundException with the specified detail message.

Usage

From source file:com.gfactor.web.wicket.loader.OsgiClassResolver.java

/**
 * {@inheritDoc}//from   w ww .  ja v  a 2s  .  c om
 * 
 * @see org.apache.wicket.application.IClassResolver#resolveClass(java.lang.String)
 */
public Class<?> resolveClass(String classname) throws ClassNotFoundException {
    logger.info("resolveClass = " + classname);
    Class<?> clazz = null;

    try {
        ClassLoader loader = Application.get().getClass().getClassLoader();
        logger.info("clazz2 loader = " + loader);
        Class<?> clazz2 = Class.forName(classname, false, loader);
        logger.info("clazz2 = " + clazz2);
        logger.info("");
        clazz = this.wrappedClassResolver.resolveClass(classname);
        logger.info("clazz = " + clazz);
    } catch (ClassNotFoundException e) {

        // not found in parent classloader? look through the bundles...
        logger.info("resolveClass for bundles");
        logger.info("bundle context = " + bundleCtx);

        Bundle[] bundles = bundleCtx.getBundles();
        logger.info("bundles = " + bundles);
        if (bundles != null && bundles.length > 0) {
            logger.info("bundles[] length = " + bundles.length);
            for (Bundle bundle : bundles) {
                //               logger.info("   -> bundle id= = "+ bundle.getBundleId());
                if (bundle.getState() != Bundle.ACTIVE || !this.classIsExportedByBundle(classname, bundle))
                    continue;

                try {
                    clazz = bundle.loadClass(classname);
                    if (clazz != null)
                        break;
                } catch (ClassNotFoundException ex) {
                    ; // ignore and try next bundle..
                }
            }
        }

    }

    if (clazz == null)
        throw new ClassNotFoundException(classname);

    return clazz;
}

From source file:com.seer.datacruncher.eventtrigger.DynamicClassLoader.java

public Class loadClass(String className) throws ClassNotFoundException {

    LoadedClass loadedClass = null;//from  w  ww  .  j a v a 2 s .  c o  m
    synchronized (loadedClasses) {
        loadedClass = (LoadedClass) loadedClasses.get(className);
    }

    // first access of a class
    if (loadedClass == null) {

        String resource = className.replace('.', '/') + ".java";
        SourceDirectory src = locateResource(resource);
        if (src == null) {
            throw new ClassNotFoundException("Dynamic class not found " + className);
        }

        synchronized (this) {
            // compile and load class
            loadedClass = new LoadedClass(className, src);

            synchronized (loadedClasses) {
                loadedClasses.put(className, loadedClass);
            }
        }

        return loadedClass.clazz;
    }

    // subsequent access
    if (loadedClass.isChanged()) {
        // unload and load again
        unload(loadedClass.srcDir);
        return loadClass(className);
    }

    return loadedClass.clazz;
}

From source file:org.impalaframework.classloader.graph.GraphClassLoader.java

/**
 * Attempts to load class for given name. If {@link #loadParentFirst} is set true, 
 * then will first delegate to the parent class loader, which will typically either be the 
 * system class loader or the web application class loader for web applications.
 * It will then attempt to load the class from one of the modules, starting with the 
 * root module and modules without other dependencies, finally ending searching within
 * the current module (the module with with which this class loader instance is associated).
 * /*from  w  w  w. j  a  v  a  2s .  co m*/
 *  Note that if {@link #loadParentFirst} is set to false, then the module graph is searched 
 *  first before delegating to the parent class loader. This is particularly useful in environments
 *  where certain modules are on the system class path (for example, when running integration tests as a 
 *  test suite within Eclipse).
 */
@Override
public Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {

    if (logger.isDebugEnabled()) {
        logger.debug("Entering loading class '" + className + "' from " + this);
    }

    Class<?> loadClass = null;

    if (logger.isTraceEnabled()) {
        logger.trace("For class loader with options: " + options);
    }

    if (loadClass == null) {
        //attempt to load internal library class
        loadClass = loadLibraryClass(className, true);
    }

    if (!options.isParentLoaderFirst()) {
        if (loadClass == null) {
            loadClass = loadApplicationClass(className, true);
        }
    }

    if (loadClass == null) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Delegating to parent class loader to load " + className);
            }
            loadClass = getParent().loadClass(className);
        } catch (ClassNotFoundException e) {
        }
    }

    if (options.isParentLoaderFirst()) {
        if (loadClass == null) {
            loadClass = loadApplicationClass(className, true);
        }
    }

    if (loadClass != null) {
        if (resolve) {
            resolveClass(loadClass);
        }
        return loadClass;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Unable to find class " + className);
        logger.debug("Using class loader: " + this);
    }

    throw new ClassNotFoundException("Unable to find class " + className);
}

From source file:org.bimserver.plugins.JarClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    String fileName = name.replace(".", "/") + ".class";
    if (loadedClasses.containsKey(fileName)) {
        return loadedClasses.get(fileName);
    }//  w ww .ja  va2s . c o  m
    if (map.containsKey(fileName)) {
        byte[] bs = map.get(fileName);
        Class<?> defineClass = defineClass(name, bs, 0, bs.length);
        loadedClasses.put(fileName, defineClass);

        /*
         * This is a fix to actually load the package-info.class file with
         * the annotations about for example namespaces required for JAXB to
         * work. Found this code here:
         * https://issues.jboss.org/browse/JBPM-1404
         */
        if (defineClass != null) {
            final int packageIndex = name.lastIndexOf('.');
            if (packageIndex != -1) {
                final String packageName = name.substring(0, packageIndex);
                final Package classPackage = getPackage(packageName);
                if (classPackage == null) {
                    definePackage(packageName, null, null, null, null, null, null, null);
                }
            }
        }
        return defineClass;
    }
    throw new ClassNotFoundException(name);
}

From source file:org.evosuite.instrumentation.InstrumentingClassLoader.java

private Class<?> instrumentClass(String fullyQualifiedTargetClass) throws ClassNotFoundException {
    logger.info("Instrumenting class '{}'.", fullyQualifiedTargetClass);

    InputStream is = null;//from  www .  j  ava2  s.  c o  m
    try {
        String className = fullyQualifiedTargetClass.replace('.', '/');

        is = ResourceList.getClassAsStream(fullyQualifiedTargetClass);

        if (is == null) {
            throw new ClassNotFoundException("Class '" + className + ".class"
                    + "' should be in target project, but could not be found!");
        }

        byte[] byteBuffer = instrumentation.transformBytes(this, className, new ClassReader(is));
        createPackageDefinition(fullyQualifiedTargetClass);
        Class<?> result = defineClass(fullyQualifiedTargetClass, byteBuffer, 0, byteBuffer.length);
        classes.put(fullyQualifiedTargetClass, result);
        logger.info("Keeping class: {}", fullyQualifiedTargetClass);
        return result;
    } catch (Throwable t) {
        logger.info("Error while loading class: {}", t);
        throw new ClassNotFoundException(t.getMessage(), t);
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                throw new Error(e);
            }
    }
}

From source file:org.apache.axis2.jaxws.message.databinding.impl.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {//from ww  w .j a va 2  s. c om
        ArrayList<Class> classes = new ArrayList<Class>();
        URLClassLoader ucl = (URLClassLoader) cl;
        URL[] srcURL = ucl.getURLs();
        String path = pkg.replace('.', '/');
        //Read resources as URL from class loader.
        for (URL url : srcURL) {
            if ("file".equals(url.getProtocol())) {
                File f = new File(url.toURI().getPath());
                //If file is not of type directory then its a jar file
                if (f.exists() && !f.isDirectory()) {
                    try {
                        JarFile jf = new JarFile(f);
                        Enumeration<JarEntry> entries = jf.entries();
                        //read all entries in jar file
                        while (entries.hasMoreElements()) {
                            JarEntry je = entries.nextElement();
                            String clazzName = je.getName();
                            if (clazzName != null && clazzName.endsWith(".class")) {
                                //Add to class list here.
                                clazzName = clazzName.substring(0, clazzName.length() - 6);
                                clazzName = clazzName.replace('/', '.').replace('\\', '.').replace(':', '.');
                                //We are only going to add the class that belong to the provided package.
                                if (clazzName.startsWith(pkg + ".")) {
                                    try {
                                        Class clazz = forName(clazzName, false, cl);
                                        // Don't add any interfaces or JAXWS specific classes.
                                        // Only classes that represent data and can be marshalled
                                        // by JAXB should be added.
                                        if (!clazz.isInterface() && clazz.getPackage().getName().equals(pkg)
                                                && ClassUtils.getDefaultPublicConstructor(clazz) != null
                                                && !ClassUtils.isJAXWSClass(clazz)) {
                                            if (log.isDebugEnabled()) {
                                                log.debug("Adding class: " + clazzName);
                                            }
                                            classes.add(clazz);

                                        }
                                        //catch Throwable as ClassLoader can throw an NoClassDefFoundError that
                                        //does not extend Exception, so lets catch everything that extends Throwable
                                        //rather than just Exception.
                                    } catch (Throwable e) {
                                        if (log.isDebugEnabled()) {
                                            log.debug("Tried to load class " + clazzName
                                                    + " while constructing a JAXBContext.  This class will be skipped.  Processing Continues.");
                                            log.debug("  The reason that class could not be loaded:"
                                                    + e.toString());
                                            log.trace(JavaUtils.stackToString(e));
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        throw new ClassNotFoundException(Messages.getMessage("ClassUtilsErr4"));
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

From source file:io.neba.core.spring.web.filter.NebaRequestContextFilterTest.java

@Test
public void testFilterToleratesAbsenceOfOptionalDependencyToBgHttpServletRequest() throws Exception {
    ClassLoader classLoaderWithoutBgServlets = new ClassLoader(getClass().getClassLoader()) {
        @Override//  ww w  .j  a va2  s.c om
        public Class<?> loadClass(String name) throws ClassNotFoundException {
            if (BackgroundHttpServletRequest.class.getName().equals(name)) {
                // This optional dependency is not present on the class path in this test scenario.
                throw new ClassNotFoundException(
                        "THIS IS AN EXPECTED TEST EXCEPTION. The dependency to bgservlets is optional.");
            }
            if (NebaRequestContextFilter.class.getName().equals(name)) {
                // Define the test subject's class class in this class loader, thus its dependencies -
                // such as the background servlet request - are also loaded via this class loader.
                try {
                    byte[] classFileData = toByteArray(
                            getResourceAsStream(name.replace('.', '/').concat(".class")));
                    return defineClass(name, classFileData, 0, classFileData.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException("Unable to load " + name + ".", e);
                }
            }

            return super.loadClass(name);
        }
    };

    Class<?> filterClass = classLoaderWithoutBgServlets.loadClass(NebaRequestContextFilter.class.getName());

    assertThat(field("IS_BGSERVLETS_PRESENT").ofType(boolean.class).in(filterClass).get()).isFalse();

    Object filter = filterClass.newInstance();

    method("doFilter").withParameterTypes(ServletRequest.class, ServletResponse.class, FilterChain.class)
            .in(filter).invoke(request, response, chain);
}

From source file:org.springframework.boot.devtools.restart.classloader.RestartClassLoader.java

@Override
protected Class<?> findClass(final String name) throws ClassNotFoundException {
    String path = name.replace('.', '/').concat(".class");
    final ClassLoaderFile file = this.updatedFiles.getFile(path);
    if (file == null) {
        return super.findClass(name);
    }/*from www . ja  v a  2  s .  c om*/
    if (file.getKind() == Kind.DELETED) {
        throw new ClassNotFoundException(name);
    }
    return AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
        @Override
        public Class<?> run() {
            byte[] bytes = file.getContents();
            return defineClass(name, bytes, 0, bytes.length);
        }
    });
}

From source file:org.springframework.security.config.SecurityNamespaceHandlerTests.java

@Test
public void filterChainProxyClassNotFoundExceptionNoHttpBlock() throws Exception {
    String className = FILTER_CHAIN_PROXY_CLASSNAME;
    spy(ClassUtils.class);
    doThrow(new ClassNotFoundException(className)).when(ClassUtils.class, "forName",
            eq(FILTER_CHAIN_PROXY_CLASSNAME), any(ClassLoader.class));
    new InMemoryXmlApplicationContext(XML_AUTHENTICATION_MANAGER);
    // should load just fine since no http block
}

From source file:javarestart.WebClassLoader.java

@Override
protected Class<?> findClass(final String name) throws ClassNotFoundException {
    String res = name.replace('.', '/') + ".class";
    try {// w w w . j a  v  a2s  .c  o m
        if (initialBundle.containsKey(res)) {
            byte[] classBytes = initialBundle.get(res);
            if (classBytes == null) {
                throw new ClassNotFoundException("resource " + name + " not found");
            }
            initialBundle.remove(res);
            Class c = defineClass(null, classBytes, 0, classBytes.length);
            fireClassLoaded(name);
            return c;
        }
        URL resource = findResourceImpl(name.replace('.', '/') + ".class");
        if (resource == null) {
            throw new ClassNotFoundException("resource " + name + " not found");
        }
        Class c = tryToLoadClass(resource.openStream());
        fireClassLoaded(name);
        return c;
    } catch (ClassNotFoundException e) {
        throw e;
    } catch (final Exception e) {
        throw new ClassNotFoundException(e.getMessage(), e);
    }
}