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:org.wso2.carbon.ui.JspClassLoader.java

protected Class findClass(String name) throws ClassNotFoundException {
    throw new ClassNotFoundException(name);
}

From source file:io.hops.erasure_coding.ErasureCodingManager.java

private boolean loadRaidNodeClasses() {
    try {//from  www. j  a  v  a2  s.com
        Class<?> encodingManagerClass = getConf().getClass(DFSConfigKeys.ENCODING_MANAGER_CLASSNAME_KEY, null);
        if (encodingManagerClass == null) {
            encodingManagerClass = Class.forName(DFSConfigKeys.DEFAULT_ENCODING_MANAGER_CLASSNAME);
        }
        if (!EncodingManager.class.isAssignableFrom(encodingManagerClass)) {
            throw new ClassNotFoundException(encodingManagerClass + " is not an implementation of "
                    + EncodingManager.class.getCanonicalName());
        }
        Constructor<?> encodingManagerConstructor = encodingManagerClass.getConstructor(Configuration.class);
        encodingManager = (EncodingManager) encodingManagerConstructor.newInstance(getConf());

        Class<?> blockRepairManagerClass = getConf().getClass(DFSConfigKeys.BLOCK_REPAIR_MANAGER_CLASSNAME_KEY,
                null);
        if (blockRepairManagerClass == null) {
            blockRepairManagerClass = Class.forName(DFSConfigKeys.DEFAULT_BLOCK_REPAIR_MANAGER_CLASSNAME);
        }
        if (!BlockRepairManager.class.isAssignableFrom(blockRepairManagerClass)) {
            throw new ClassNotFoundException(blockRepairManagerClass + " is not an implementation of "
                    + BlockRepairManager.class.getCanonicalName());
        }
        Constructor<?> blockRepairManagerConstructor = blockRepairManagerClass
                .getConstructor(Configuration.class);
        blockRepairManager = (BlockRepairManager) blockRepairManagerConstructor.newInstance(getConf());
    } catch (Exception e) {
        LOG.error("Could not load erasure coding classes", e);
        return false;
    }

    return true;
}

From source file:org.ebayopensource.turmeric.tools.codegen.util.CodeGenClassLoader.java

protected Class<?> findClass(String name) throws ClassNotFoundException {

    Class<?> loadedClass = findLoadedClass(name);
    if (loadedClass != null) {
        return loadedClass;
    }//from w ww  .j a  va 2  s. com

    StringBuilder sb = new StringBuilder(name.length() + 6);
    sb.append(name.replace('.', '/')).append(".class");

    InputStream is = getResourceAsStream(sb.toString());
    if (is == null)
        throw new ClassNotFoundException("Class not found" + sb);

    ByteArrayOutputStream baos = null;
    try {
        baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) >= 0)
            baos.write(buf, 0, len);

        buf = baos.toByteArray();

        // define package if not defined yet
        int i = name.lastIndexOf('.');
        if (i != -1) {
            String pkgname = name.substring(0, i);
            Package pkg = getPackage(pkgname);
            if (pkg == null)
                definePackage(pkgname, null, null, null, null, null, null, null);
        }

        return defineClass(name, buf, 0, buf.length);
    } catch (IOException e) {
        throw new ClassNotFoundException(name, e);
    } finally {
        CodeGenUtil.closeQuietly(is);
        CodeGenUtil.closeQuietly(baos);
    }
}

From source file:org.springframework.instrument.classloading.ShadowingClassLoader.java

private Class<?> doLoadClass(String name) throws ClassNotFoundException {
    String internalName = StringUtils.replace(name, ".", "/") + ".class";
    InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName);
    if (is == null) {
        throw new ClassNotFoundException(name);
    }/* w  w  w. j a  v  a 2s. c  o  m*/
    try {
        byte[] bytes = FileCopyUtils.copyToByteArray(is);
        bytes = applyTransformers(name, bytes);
        Class<?> cls = defineClass(name, bytes, 0, bytes.length);
        // Additional check for defining the package, if not defined yet.
        if (cls.getPackage() == null) {
            int packageSeparator = name.lastIndexOf('.');
            if (packageSeparator != -1) {
                String packageName = name.substring(0, packageSeparator);
                definePackage(packageName, null, null, null, null, null, null, null);
            }
        }
        this.classCache.put(name, cls);
        return cls;
    } catch (IOException ex) {
        throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex);
    }
}

From source file:net.dataforte.commons.resources.ClassUtils.java

/**
 * Returns all classes within the specified package. Supports filesystem, JARs and JBoss VFS
 * /*  w w w  . ja v  a  2  s  .c o m*/
 * @param folder
 * @return
 * @throws IOException
 */
public static Class<?>[] getClassesForPackage(String pckgname) throws ClassNotFoundException {
    // This will hold a list of directories matching the pckgname.
    // There may be more than one if a package is split over multiple
    // jars/paths
    List<Class<?>> classes = new ArrayList<Class<?>>();
    ArrayList<File> directories = new ArrayList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(pckgname.replace('.', '/'));
        while (resources.hasMoreElements()) {
            URL res = resources.nextElement();
            if (res.getProtocol().equalsIgnoreCase("jar")) {
                JarURLConnection conn = (JarURLConnection) res.openConnection();
                JarFile jar = conn.getJarFile();
                for (JarEntry e : Collections.list(jar.entries())) {

                    if (e.getName().startsWith(pckgname.replace('.', '/')) && e.getName().endsWith(".class")
                            && !e.getName().contains("$")) {
                        String className = e.getName().replace("/", ".").substring(0, e.getName().length() - 6);
                        classes.add(Class.forName(className, true, cld));
                    }
                }
            } else if (res.getProtocol().equalsIgnoreCase("vfszip")) { // JBoss 5+
                try {
                    Object content = res.getContent();
                    Method getChildren = content.getClass().getMethod("getChildren");
                    List<?> files = (List<?>) getChildren.invoke(res.getContent());
                    Method getPathName = null;
                    for (Object o : files) {
                        if (getPathName == null) {
                            getPathName = o.getClass().getMethod("getPathName");
                        }
                        String pathName = (String) getPathName.invoke(o);
                        if (pathName.endsWith(".class")) {
                            String className = pathName.replace("/", ".").substring(0, pathName.length() - 6);
                            classes.add(Class.forName(className, true, cld));
                        }
                    }
                } catch (Exception e) {
                    throw new IOException("Error while scanning " + res.toString(), e);
                }
            } else {
                directories.add(new File(URLDecoder.decode(res.getPath(), "UTF-8")));
            }
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)", x);
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)", encex);
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname, ioex);
    }

    // For every directory identified capture all the .class files
    for (File directory : directories) {
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (String file : files) {
                // we are only interested in .class files
                if (file.endsWith(".class")) {
                    // removes the .class extension
                    classes.add(Class.forName(pckgname + '.' + file.substring(0, file.length() - 6)));
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    Class<?>[] classesA = new Class[classes.size()];
    classes.toArray(classesA);
    return classesA;
}

From source file:org.fusesource.meshkeeper.distribution.PluginClassLoader.java

@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    Class<?> c = findLoadedClass(name);
    if (c == null) {

        int pDelim = name.lastIndexOf(".");
        if (USE_PARENT_FIRST || (pDelim > 0 && SPI_PACKAGES.contains(name.substring(0, pDelim)))) {
            c = super.loadClass(name, resolve);
        } else {//from ww  w. j ava  2s . c  o  m
            for (String prefix : PARENT_FIRST) {
                if (name.startsWith(prefix)) {
                    try {
                        c = super.loadClass(name, resolve);
                    } catch (ClassNotFoundException cnfe) {
                    }
                }
            }

            if (c == null) {
                try {
                    c = findClass(name);
                } catch (ClassNotFoundException cnfe) {
                    c = super.loadClass(name, resolve);
                }
            }
        }
    }

    if (c == null) {
        throw new ClassNotFoundException(name);
    }

    if (resolve) {
        resolveClass(c);
    }
    return c;
}

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

@Test
public void filterChainProxyClassNotFoundException() throws Exception {
    String className = FILTER_CHAIN_PROXY_CLASSNAME;
    thrown.expect(BeanDefinitionParsingException.class);
    thrown.expectMessage("ClassNotFoundException: " + 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 + XML_HTTP_BLOCK);
}

From source file:org.atricore.idbus.kernel.main.util.ClassFinderImpl.java

public ArrayList<Class> getClassesFromJarFile(String pkg, ClassLoader cl) throws ClassNotFoundException {
    try {/*from  w  w  w . ja  v  a 2 s  .com*/
        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(
                                "An IOException error was thrown when trying to read the jar file.");
                    }
                }
            }
        }
        return classes;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage());
    }

}

From source file:org.nuxeo.ecm.webengine.loader.store.ResourceStoreClassLoader.java

@Override
public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
    // log.debug(getId() + " looking for: " + name);
    Class<?> clazz = findLoadedClass(name);

    if (clazz == null) {
        clazz = fastFindClass(name);//from  w  w  w  . j  a  v  a2  s  . c om

        if (clazz == null) {

            final ClassLoader parent = getParent();
            if (parent != null) {
                clazz = parent.loadClass(name);
                // log.debug(getId() + " delegating loading to parent: " + name);
            } else {
                throw new ClassNotFoundException(name);
            }

        } else {
            if (log.isDebugEnabled()) {
                log.debug(getId() + " loaded from store: " + name);
            }
        }
    }

    if (resolve) {
        resolveClass(clazz);
    }

    return clazz;
}

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

@Test
public void testFilterToleratesAbsenceOfOptionalDependencyToBgHttpServletRequest() throws Exception {
    ClassLoader classLoaderWithoutBgServlets = new ClassLoader(getClass().getClassLoader()) {
        @Override//from ww  w  .  ja va 2 s . co m
        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(valueOfField(filterClass, "IS_BGSERVLETS_PRESENT")).isFalse();

    Object filter = filterClass.newInstance();

    invoke(filter, "doFilter", request, response, chain);
}