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, Throwable ex) 

Source Link

Document

Constructs a ClassNotFoundException with the specified detail message and optional exception that was raised while loading the class.

Usage

From source file:org.gridgain.grid.kernal.managers.deployment.GridDeploymentClassLoader.java

/** {@inheritDoc} */
@Override/* w w  w  . j a  v  a2s. c o  m*/
public Class<?> loadClass(String name) throws ClassNotFoundException {
    assert !Thread.holdsLock(mux);

    // Check if we have package name on list of P2P loaded.
    // GridComputeJob must be always loaded locally to avoid
    // any possible class casting issues.
    Class<?> cls = null;

    try {
        if (!"org.gridgain.grid.GridComputeJob".equals(name)) {
            if (isLocallyExcluded(name))
                // P2P loaded class.
                cls = p2pLoadClass(name, true);
        }

        if (cls == null)
            cls = loadClass(name, true);
    } catch (ClassNotFoundException e) {
        throw e;
    }
    // Catch Throwable to secure against any errors resulted from
    // corrupted class definitions or other user errors.
    catch (Throwable e) {
        throw new ClassNotFoundException("Failed to load class due to unexpected error: " + name, e);
    }

    return cls;
}

From source file:org.apache.ignite.internal.managers.deployment.GridDeploymentClassLoader.java

/** {@inheritDoc} */
@Override/*  w  w w  . jav a 2 s .  co  m*/
public Class<?> loadClass(String name) throws ClassNotFoundException {
    assert !Thread.holdsLock(mux);

    // Check if we have package name on list of P2P loaded.
    // ComputeJob must be always loaded locally to avoid
    // any possible class casting issues.
    Class<?> cls = null;

    try {
        if (!"org.apache.ignite.compute.ComputeJob".equals(name)) {
            if (isLocallyExcluded(name))
                // P2P loaded class.
                cls = p2pLoadClass(name, true);
        }

        if (cls == null)
            cls = loadClass(name, true);
    } catch (ClassNotFoundException e) {
        throw e;
    }
    // Catch Throwable to secure against any errors resulted from
    // corrupted class definitions or other user errors.
    catch (Exception e) {
        throw new ClassNotFoundException("Failed to load class due to unexpected error: " + name, e);
    }

    return cls;
}

From source file:SearchlistClassLoader.java

/**
 *  Return a Class object for the specified class name.
 *
 *  @overloads java.lang.ClassLoader#findClass(String)
 *
 *  Traverses the searchlist looking for a classloader which can return
 *  the specified class./*from w ww  . java  2 s.c o m*/
 *
 *<br>This method is called by inherited loadClass() methods whenever
 *  a class cannot be found in the parent classloader.
 *
 *<br>If the class is found using a <i>shared</i> loader, then it is
 *  returned directly. If the class is found using a <i>non-shared</i>
 *  loader, then the actual class object is defined by the containing
 *  SearchlistClassLoader, which causes Java to associate the new class
 *  object with the SearchlistClassLaoder, rather then the non-shared
 *  loader.
 *
 *  @param name the fully-qualified name of the class
 *  @return the loaded class object
 *
 *  @throws ClassNotFoundException if the class could not be loaded.
 */
public Class findClass(String name) throws ClassNotFoundException {
    Loader ldr;
    Throwable err = null;
    Class result;
    byte[] data;

    for (int i = 0; (ldr = getLoader(i, searchMode)) != null; i++) {
        try {
            // for shared loaders - just try getting the class
            if (ldr.shared)
                return ldr.loader.loadClass(name);

            // for non-shared loaders, we have to define the class manually
            else {
                // check the cache first
                result = (cache != null ? (Class) cache.get(name) : null);
                if (result != null)
                    return result;

                // try loading the class
                data = loadClassData(ldr.loader, name);
                if (data != null) {

                    // data loaded, define the class
                    result = defineClass(name, data, 0, data.length);

                    if (result != null) {
                        //System.out.println("defined class: " + name);

                        // cache the result
                        if (cache == null)
                            cache = new Hashtable(1024);
                        cache.put(name, result);

                        return result;
                    }
                }
            }
        } catch (Throwable t) {
            err = t;
        }
    }

    throw (err != null ? new ClassNotFoundException(name, err) : new ClassNotFoundException(name));
}

From source file:ffx.FFXClassLoader.java

/**
 * {@inheritDoc}/*www . j av  a 2s.c  o m*/
 *
 * Finds and defines the given class among the extension JARs given in
 * constructor, then among resources.
 */
@Override
protected Class findClass(String name) throws ClassNotFoundException {

    /*
     if (name.startsWith("com.jogamp")) {
     System.out.println(" Class requested:" + name);
     } */
    if (!extensionsLoaded) {
        loadExtensions();
    }

    // Build class file from its name
    String classFile = name.replace('.', '/') + ".class";
    InputStream classInputStream = null;
    if (extensionJars != null) {
        for (JarFile extensionJar : extensionJars) {
            JarEntry jarEntry = extensionJar.getJarEntry(classFile);
            if (jarEntry != null) {
                try {
                    classInputStream = extensionJar.getInputStream(jarEntry);
                } catch (IOException ex) {
                    throw new ClassNotFoundException("Couldn't read class " + name, ex);
                }
            }
        }
    }

    // If it's not an extension class, search if its an application
    // class that can be read from resources
    if (classInputStream == null) {
        URL url = getResource(classFile);
        if (url == null) {
            throw new ClassNotFoundException("Class " + name);
        }
        try {
            classInputStream = url.openStream();
        } catch (IOException ex) {
            throw new ClassNotFoundException("Couldn't read class " + name, ex);
        }
    }

    ByteArrayOutputStream out = null;
    BufferedInputStream in = null;
    try {
        // Read class input content to a byte array
        out = new ByteArrayOutputStream();
        in = new BufferedInputStream(classInputStream);
        byte[] buffer = new byte[8192];
        int size;
        while ((size = in.read(buffer)) != -1) {
            out.write(buffer, 0, size);
        }
        // Define class
        return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain);
    } catch (IOException ex) {
        throw new ClassNotFoundException("Class " + name, ex);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            throw new ClassNotFoundException("Class " + name, e);
        }

    }
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.LogListenerTest.java

@Test
public void testLinkageErrorCommentAdded() {
    Throwable e3 = new RuntimeException();
    e3.fillInStackTrace();/*  w  w w . ja  v a  2  s . c  om*/
    ClassNotFoundException e2 = new ClassNotFoundException(StringUtils.class.getName(), e3);
    Throwable e1 = new Throwable("test", e2);
    Status status = new Status(IStatus.ERROR, TEST_PLUGIN_ID, "test message", e1);

    sut.logging(status, "");

    ErrorReport report = pollEvent().report;
    assertThat(report.getComment(), not(isEmptyOrNullString()));
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Find the specified class in our local repositories, if possible.  If
 * not found, throw <code>ClassNotFoundException</code>.
 *
 * @param name Name of the class to be loaded
 *
 * @exception ClassNotFoundException if the class was not found
 *///from w ww. jav  a2  s.c  o  m
public Class findClass(String name) throws ClassNotFoundException {

    if (log.isDebugEnabled())
        log.debug("    findClass(" + name + ")");

    // (1) Permission to define this class when using a SecurityManager
    if (securityManager != null) {
        int i = name.lastIndexOf('.');
        if (i >= 0) {
            try {
                if (log.isTraceEnabled())
                    log.trace("      securityManager.checkPackageDefinition");
                securityManager.checkPackageDefinition(name.substring(0, i));
            } catch (Exception se) {
                if (log.isTraceEnabled())
                    log.trace("      -->Exception-->ClassNotFoundException", se);
                throw new ClassNotFoundException(name, se);
            }
        }
    }

    // Ask our superclass to locate this class, if possible
    // (throws ClassNotFoundException if it is not found)
    Class clazz = null;
    try {
        if (log.isTraceEnabled())
            log.trace("      findClassInternal(" + name + ")");
        try {
            clazz = findClassInternal(name);
        } catch (ClassNotFoundException cnfe) {
            if (!hasExternalRepositories) {
                throw cnfe;
            }
        } catch (AccessControlException ace) {
            throw new ClassNotFoundException(name, ace);
        } catch (RuntimeException e) {
            if (log.isTraceEnabled())
                log.trace("      -->RuntimeException Rethrown", e);
            throw e;
        }
        if ((clazz == null) && hasExternalRepositories) {
            try {
                clazz = super.findClass(name);
            } catch (AccessControlException ace) {
                throw new ClassNotFoundException(name, ace);
            } catch (RuntimeException e) {
                if (log.isTraceEnabled())
                    log.trace("      -->RuntimeException Rethrown", e);
                throw e;
            }
        }
        if (clazz == null) {
            if (log.isDebugEnabled())
                log.debug("    --> Returning ClassNotFoundException");
            throw new ClassNotFoundException(name);
        }
    } catch (ClassNotFoundException e) {
        if (log.isTraceEnabled())
            log.trace("    --> Passing on ClassNotFoundException");
        throw e;
    }

    // Return the class we have located
    if (log.isTraceEnabled())
        log.debug("      Returning class " + clazz);
    if ((log.isTraceEnabled()) && (clazz != null))
        log.debug("      Loaded by " + clazz.getClassLoader());
    return (clazz);

}

From source file:org.apache.flink.client.CliFrontend.java

/**
 * Sends a {@link org.apache.flink.runtime.messages.JobManagerMessages.DisposeSavepoint}
 * message to the job manager.//from ww w  . j a  v  a 2s  .c  o m
 */
private int disposeSavepoint(SavepointOptions options) {
    try {
        String savepointPath = options.getSavepointPath();
        if (savepointPath == null) {
            throw new IllegalArgumentException("Missing required argument: savepoint path. "
                    + "Usage: bin/flink savepoint -d <savepoint-path>");
        }

        String jarFile = options.getJarFilePath();

        ActorGateway jobManager = getJobManagerGateway(options);

        List<BlobKey> blobKeys = null;
        if (jarFile != null) {
            logAndSysout("Disposing savepoint '" + savepointPath + "' with JAR " + jarFile + ".");

            List<File> libs = null;
            try {
                libs = PackagedProgram.extractContainedLibraries(new File(jarFile).toURI().toURL());
                if (!libs.isEmpty()) {
                    List<Path> libPaths = new ArrayList<>(libs.size());
                    for (File f : libs) {
                        libPaths.add(new Path(f.toURI()));
                    }

                    logAndSysout("Uploading JAR files.");
                    LOG.debug("JAR files: " + libPaths);
                    blobKeys = BlobClient.uploadJarFiles(jobManager, clientTimeout, config, libPaths);
                    LOG.debug("Blob keys: " + blobKeys.toString());
                }
            } finally {
                if (libs != null) {
                    PackagedProgram.deleteExtractedLibraries(libs);
                }
            }
        } else {
            logAndSysout("Disposing savepoint '" + savepointPath + "'.");
        }

        Object msg = new DisposeSavepoint(savepointPath);
        Future<Object> response = jobManager.ask(msg, clientTimeout);

        Object result;
        try {
            logAndSysout("Waiting for response...");
            result = Await.result(response, clientTimeout);
        } catch (Exception e) {
            throw new Exception("Disposing the savepoint with path" + savepointPath + " failed.", e);
        }

        if (result.getClass() == JobManagerMessages.getDisposeSavepointSuccess().getClass()) {
            logAndSysout("Savepoint '" + savepointPath + "' disposed.");
            return 0;
        } else if (result instanceof DisposeSavepointFailure) {
            DisposeSavepointFailure failure = (DisposeSavepointFailure) result;

            if (failure.cause() instanceof ClassNotFoundException) {
                throw new ClassNotFoundException("Savepoint disposal failed, because of a "
                        + "missing class. This is most likely caused by a custom state "
                        + "instance, which cannot be disposed without the user code class "
                        + "loader. Please provide the program jar with which you have created "
                        + "the savepoint via -j <JAR> for disposal.", failure.cause().getCause());
            } else {
                throw failure.cause();
            }
        } else {
            throw new IllegalStateException("Unknown JobManager response of type " + result.getClass());
        }
    } catch (Throwable t) {
        return handleError(t);
    }
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Load the class with the specified name, searching using the following
 * algorithm until it finds and returns the class.  If the class cannot
 * be found, returns <code>ClassNotFoundException</code>.
 * <ul>//from   w  w  w  . j  ava 2  s . c om
 * <li>Call <code>findLoadedClass(String)</code> to check if the
 *     class has already been loaded.  If it has, the same
 *     <code>Class</code> object is returned.</li>
 * <li>If the <code>delegate</code> property is set to <code>true</code>,
 *     call the <code>loadClass()</code> method of the parent class
 *     loader, if any.</li>
 * <li>Call <code>findClass()</code> to find this class in our locally
 *     defined repositories.</li>
 * <li>Call the <code>loadClass()</code> method of our parent
 *     class loader, if any.</li>
 * </ul>
 * If the class was found using the above steps, and the
 * <code>resolve</code> flag is <code>true</code>, this method will then
 * call <code>resolveClass(Class)</code> on the resulting Class object.
 *
 * @param name Name of the class to be loaded
 * @param resolve If <code>true</code> then resolve the class
 *
 * @exception ClassNotFoundException if the class was not found
 */
public Class loadClass(String name, boolean resolve) throws ClassNotFoundException {

    if (log.isDebugEnabled())
        log.debug("loadClass(" + name + ", " + resolve + ")");
    Class clazz = null;

    // Don't load classes if class loader is stopped
    if (!started) {
        log.info(sm.getString("webappClassLoader.stopped"));
        throw new ThreadDeath();
    }

    // (0) Check our previously loaded local class cache
    clazz = findLoadedClass0(name);
    if (clazz != null) {
        if (log.isDebugEnabled())
            log.debug("  Returning class from cache");
        if (resolve)
            resolveClass(clazz);
        return (clazz);
    }

    // (0.1) Check our previously loaded class cache
    clazz = findLoadedClass(name);
    if (clazz != null) {
        if (log.isDebugEnabled())
            log.debug("  Returning class from cache");
        if (resolve)
            resolveClass(clazz);
        return (clazz);
    }

    // (0.2) Try loading the class with the system class loader, to prevent
    //       the webapp from overriding J2SE classes
    // GOOGLE: use the bootstrap loader, not the system loader; it breaks
    //       embedding.
    try {
        // clazz = system.loadClass(name);
        clazz = Class.forName(name, false, null);
        if (clazz != null) {
            if (resolve)
                resolveClass(clazz);
            return (clazz);
        }
    } catch (ClassNotFoundException e) {
        // Ignore
    }

    // (0.5) Permission to access this class when using a SecurityManager
    if (securityManager != null) {
        int i = name.lastIndexOf('.');
        if (i >= 0) {
            try {
                securityManager.checkPackageAccess(name.substring(0, i));
            } catch (SecurityException se) {
                String error = "Security Violation, attempt to use " + "Restricted Class: " + name;
                log.info(error, se);
                throw new ClassNotFoundException(error, se);
            }
        }
    }

    boolean delegateLoad = delegate || filter(name);

    // (1) Delegate to our parent if requested
    if (delegateLoad) {
        if (log.isDebugEnabled())
            log.debug("  Delegating to parent classloader1 " + parent);
        ClassLoader loader = parent;
        if (loader == null)
            loader = system;
        try {
            clazz = loader.loadClass(name);
            if (clazz != null) {
                if (log.isDebugEnabled())
                    log.debug("  Loading class from parent");
                if (resolve)
                    resolveClass(clazz);
                return (clazz);
            }
        } catch (ClassNotFoundException e) {
            ;
        }
    }

    // (2) Search local repositories
    if (log.isDebugEnabled())
        log.debug("  Searching local repositories");
    try {
        clazz = findClass(name);
        if (clazz != null) {
            if (log.isDebugEnabled())
                log.debug("  Loading class from local repository");
            if (resolve)
                resolveClass(clazz);
            return (clazz);
        }
    } catch (ClassNotFoundException e) {
        ;
    }

    // (3) Delegate to parent unconditionally
    if (!delegateLoad) {
        if (log.isDebugEnabled())
            log.debug("  Delegating to parent classloader at end: " + parent);
        ClassLoader loader = parent;
        if (loader == null)
            loader = system;
        try {
            clazz = loader.loadClass(name);
            if (clazz != null) {
                if (log.isDebugEnabled())
                    log.debug("  Loading class from parent");
                if (resolve)
                    resolveClass(clazz);
                return (clazz);
            }
        } catch (ClassNotFoundException e) {
            ;
        }
    }

    throw new ClassNotFoundException(name);
}

From source file:edu.gsgp.experiment.config.PropertiesManager.java

private Breeder[] getBreederObjects() throws Exception {
    String[] strBreeders = getStringProperty(ParameterList.BREEDERS_LIST, false).split(",");
    ArrayList<Breeder> breeders = new ArrayList<Breeder>();
    for (String sBreeder : strBreeders) {
        try {//from  w w w  .j  a v  a 2  s .co  m
            sBreeder = sBreeder.trim();
            String[] strBreedersSplitted = sBreeder.split("\\*");
            Class<?> breederClass = Class.forName(strBreedersSplitted[0].trim());
            Constructor<?> breederConstructor = breederClass.getConstructor(PropertiesManager.class,
                    Double.class);
            Breeder newBreeder = (Breeder) breederConstructor.newInstance(this,
                    Double.parseDouble(strBreedersSplitted[1].trim()));
            breeders.add(newBreeder);
        } catch (ClassNotFoundException e) {
            String msg = "Error loading the breeder list. ";
            if (sBreeder.isEmpty()) {
                msg += "No breeder was specified.";
            } else {
                msg += "It was not possible to parse the input \"" + sBreeder + "\".";
            }
            throw new ClassNotFoundException(msg, e);
        }
    }
    return breeders.toArray(new Breeder[breeders.size()]);
}

From source file:edu.gsgp.experiment.config.PropertiesManager.java

/**
 *
 * @return @throws Exception/*from  w  w w . j  a  v a 2s.  c o m*/
 */
private Terminal[] getTerminalObjects() throws Exception {
    String[] sTerminals = getStringProperty(ParameterList.TERMINAL_LIST, false).split(",");
    boolean useAllInputs = true;
    for (String str : sTerminals) {
        str = str.trim();
        if (str.toLowerCase().matches("x\\d+")) {
            useAllInputs = false;
            break;
        }
    }
    ArrayList<Terminal> terminals = new ArrayList<Terminal>();
    if (useAllInputs) {
        for (int i = 0; i < dataProducer.getNumInputs(); i++) {
            terminals.add(new Input(i));
        }
        for (String str : sTerminals) {
            try {
                str = str.trim();
                Class<?> terminal = Class.forName(str);
                Terminal newTerminal = (Terminal) terminal.newInstance();
                terminals.add(newTerminal);
            } catch (ClassNotFoundException e) {
                throw new ClassNotFoundException("Error loading the terminal set. Class " + str + " not found",
                        e);
            }
        }
    } else {
        // ************************ TO IMPLEMENT ************************
    }
    return terminals.toArray(new Terminal[terminals.size()]);
}