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.nebulaframework.deployment.classloading.service.ClassLoadingServiceImpl.java

/**
 * {@inheritDoc}//  w  w  w.j  a va2s .  c o  m
 */
public byte[] findClass(String jobId, String name) throws ClassNotFoundException {

    UUID ownerId = null;

    try {
        // Get the owner node
        ownerId = jobService.getProfile(jobId).getOwner();
    } catch (IllegalArgumentException e) {
        throw new ClassNotFoundException("Unable to load class " + name, e);
    }

    try {
        log.debug("[ClassLoadingService] Finding Class " + name);

        // Check for nulls
        Assert.notNull(ownerId);
        Assert.notNull(jobId);
        Assert.notNull(name);

        // Check in cache, if found, return
        synchronized (this) {
            if (this.cache.containsKey(name)) {

                CacheEntry entry = this.cache.get(name);
                byte[] bytes = entry.getBytes();

                // If same job, return class
                if (jobId.equals(entry.getJobId())) {
                    return bytes;

                }

            }
        }

        byte[] bytes = findClass(ownerId, name);

        // If found, put to local cache
        if (bytes != null) {
            synchronized (this) {
                cache.put(name, new CacheEntry(jobId, name, bytes));
            }
            return bytes;
        }

        throw new ClassNotFoundException("Unable to find class");

    } catch (Exception e) {
        log.debug("[ClassLoadingService] Cannot Find Class Due to Exception");
        throw new ClassNotFoundException("ClassLoaderService Cannot find class due to exception", e);
    }
}

From source file:org.cosmo.common.template.Parser.java

public static Page parsePageString(String pageString, File src, boolean reParse) throws Exception {
    ArrayList<byte[]> segmentContainer = new ArrayList();
    ArrayList<CharSequence> bindingContainer = new ArrayList();
    StringBuilder segment = new StringBuilder(256);
    StringBuilder binding = null;

    char[] pageChars = pageString.toCharArray();

    // extract args string
    int end = pageString.indexOf(PageEndToken, PageBeginTokenSize);
    String argString = pageString.substring(PageBeginTokenSize + 1, end);
    StringTokens args = StringTokens.on(argString);
    Options options = new Options(args);

    // extract get pageName and bindingSrc className , by default pageName IS The bindingSrc class name, unless options bindingSrc:xxx is specified
    String pageName = options._pageName;
    Class clazz = null;/*from   w w  w.ja  v a2  s.  co  m*/
    if (pageName.startsWith("!")) {
        // virtual page
        pageName = pageName.substring(1, pageName.length()); // strip ! so that it can be referenced without "!"
        clazz = options._bindingSrc == null ? BindingSrc.class : Class.forName(options._bindingSrc);
    } else {
        try {
            clazz = options._bindingSrc == null ? Class.forName(pageName) : Class.forName(options._bindingSrc);
        } catch (ClassNotFoundException e) {
            ClassNotFoundException cnfe = new ClassNotFoundException(e.getMessage() + " from page" + src, e);
            cnfe.fillInStackTrace();
            throw cnfe;

        }
    }

    // parse segments and bindings
    for (int i = end + PageEndTokenSize; i < pageChars.length; i++) {

        // handles bindings
        if (pageChars[i] == BindingChar) {
            if (binding == null) {
                binding = new StringBuilder();
                continue;
            } else {
                segmentContainer.add(options._jsonEncode ? Util.jsonQuoteBytes(segment) : Util.bytes(segment));
                segment = new StringBuilder(256);
                //indents.add(currentIndent);

                segmentContainer
                        .add(options._jsonEncode ? Page.BindingMarkerBytesQuoted : Page.BindingMarkerBytes);
                bindingContainer.add(binding.toString());
                binding = null;
                continue;
            }
        }
        if (binding != null) {
            binding.append(pageChars[i]);
        }

        // handles trim and escapeQuote
        if (binding == null) {

            if (pageChars[i] == '\n' || pageChars[i] == '\r') {
                if (!options._trim) {
                    segment.append(pageChars[i]);
                }
            } else {
                if (pageChars[i] == '\t') {
                    if (!options._trim) {
                        segment.append(pageChars[i]);
                    }
                } else {
                    if (options._escapeQuote && pageChars[i] == '\"') {
                        segment.append("\\");
                    }
                    segment.append(pageChars[i]);
                }
            }
        }
    }

    // convert segments to raw bytes
    Page page = new Page(pageName, clazz, src, options, reParse);
    segmentContainer.add(options._jsonEncode ? Util.jsonQuoteBytes(segment) : Util.bytes(segment));
    page._segmentArray = (byte[][]) segmentContainer.toArray(new byte[][] {});

    // convert binding string to parsed bindings
    BindingContainer bindingsContainer = Parser.parseBindings(page, bindingContainer, 0,
            page._segmentArray.length, 0);
    page._bindingArray = (Binding[]) bindingsContainer.toArray(new Binding[] {});

    for (Binding aBinding : page._bindingArray) {
        if (aBinding instanceof Binding.ValueBinding) {
            page._bindingMap.put(aBinding.name(), aBinding);
        }
    }
    return page;
}

From source file:org.wso2.carbon.webapp.mgt.loader.CarbonWebappClassLoader.java

@Override
public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {

    if (log.isDebugEnabled())
        log.debug("loadClass(" + name + ", " + resolve + ")");
    Class<?> clazz;//from   www. jav a 2 s . co m

    // Log access to stopped classloader
    if (!started) {
        try {
            throw new IllegalStateException();
        } catch (IllegalStateException e) {
            log.info(sm.getString("webappClassLoader.stopped", name), e);
        }
    }

    // (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
    try {
        clazz = j2seClassLoader.loadClass(name);
        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);
            }
        }
    }

    // 1) Load from the parent if the parent-first is true and if package matches with the
    //    list of delegated packages
    boolean delegatedPkg = webappCC.isDelegatedPackage(name);
    boolean excludedPkg = webappCC.isExcludedPackage(name);

    if (webappCC.isParentFirst() && delegatedPkg && !excludedPkg) {
        clazz = findClassFromParent(name, resolve);
        if (clazz != null) {
            return clazz;
        }
    }

    // 2) Load the class from the local(webapp) classpath
    clazz = findLocalClass(name, resolve);
    if (clazz != null) {
        return clazz;
    }

    // 3) TODO load from the shared repositories

    // 4) Load from the parent if the parent-first is false and if the package matches with the
    //    list of delegated packages.
    if (!webappCC.isParentFirst() && delegatedPkg && !excludedPkg) {
        clazz = findClassFromParent(name, resolve);
        if (clazz != null) {
            return clazz;
        }
    }

    throw new ClassNotFoundException(name);
}

From source file:hudson.remoting.DummyClassLoader.java

protected Class<?> findClass(String name) throws ClassNotFoundException {
    for (Entry e : entries) {
        if (name.equals(e.logicalName)) {
            // rename a class
            try {
                byte[] bytes = e.loadTransformedClassImage();
                return defineClass(name, bytes, 0, bytes.length);
            } catch (IOException x) {
                throw new ClassNotFoundException("Bytecode manipulation failed", x);
            }/*  w  w w  .  j  a  v  a  2 s . c  om*/
        }
    }

    return super.findClass(name);
}

From source file:com.wso2telco.claims.RemoteClaimsRetriever.java

public Map<String, Object> getTotalClaims(String operatorName, CustomerInfo customerInfo)
        throws IllegalAccessException, InstantiationException, ClassNotFoundException {

    Map<String, Object> totalClaims;

    try {/*from www .  j  a v  a 2  s .co m*/
        totalClaims = getRemoteTotalClaims(operatorName, customerInfo);
    } catch (ClassNotFoundException e) {
        log.error("Class Not Found Exception occurred when calling operator'd endpoint - " + operatorName + ":"
                + e);
        throw new ClassNotFoundException(e.getMessage(), e);
    } catch (InstantiationException e) {
        log.error("Instantiation Exception occurred when calling operator'd endpoint - " + operatorName + ":"
                + e);
        throw new InstantiationException(e.getMessage());
    } catch (IllegalAccessException e) {
        log.error("Illegal Access Exception occurred when calling operator'd endpoint - " + operatorName + ":"
                + e);
        throw new IllegalAccessException(e.getMessage());
    }
    return totalClaims;
}

From source file:org.jboss.web.tomcat.service.WebAppClassLoader.java

/**
 * <p>//www .j  av  a 2s. c o  m
 * Generate iiop stubs dynamically for any name ending in _Stub.
 * </p>
 * 
 * @param name   a <code>String</code> representing the stub fully-qualified class name.
 * @return   the <code>Class</code> of the generated stub.
 * @throws ClassNotFoundException    if the stub class could not be created.
 */
private Class generateStub(String name) throws ClassNotFoundException {
    boolean trace = log.isTraceEnabled();
    int start = name.lastIndexOf('.') + 1;
    String pkg = name.substring(0, start);
    String interfaceName = pkg + name.substring(start + 1, name.length() - 5);

    // This is a workaround for a problem in the RMI/IIOP
    // stub loading code in SUN JDK 1.4.x, which prepends
    // "org.omg.stub." to classes in certain name spaces,
    // such as "com.sun". This non-compliant behavior
    // results in failures when deploying SUN example code,
    // including ECPerf and PetStore, so we remove the prefix.
    if (interfaceName.startsWith("org.omg.stub.com.sun."))
        interfaceName = interfaceName.substring(13);

    Class intf = super.loadClass(interfaceName);
    if (trace)
        log.trace("loaded class " + interfaceName);

    byte[] code = IIOPStubCompiler.compile(intf, name);
    if (trace)
        log.trace("compiled stub class for " + interfaceName);

    Class clz = super.defineClass(name, code, 0, code.length);
    if (trace)
        log.trace("defined stub class for " + interfaceName);

    super.resolveClass(clz);
    try {
        clz.newInstance();
    } catch (Throwable t) {
        ClassNotFoundException cnfe = new ClassNotFoundException(interfaceName, t);
        throw cnfe;
    }
    if (trace)
        log.trace("resolved stub class for " + interfaceName);
    return clz;
}

From source file:testful.runner.RemoteClassLoader.java

@Override
public Class<?> findClass(String name) throws ClassNotFoundException {

    final byte[] b;
    try {/*from w ww  .  j a v a  2  s  .c o  m*/

        synchronized (finder) {

            final long start = System.currentTimeMillis();
            b = finder.getData(ClassType.NAME, name);
            final long end = System.currentTimeMillis();

            time += (end - start);
        }

    } catch (RemoteException e) {
        final ClassNotFoundException exc = new ClassNotFoundException("Cannot retrieve the class " + name, e);
        logger.log(Level.WARNING, exc.getMessage(), exc);
        throw exc;
    }

    if (b == null)
        throw new ClassNotFoundException("Cannot find class " + name);

    Class<?> c = defineClass(name, b, 0, b.length);
    loaded.add(name);
    return c;

}

From source file:org.eclipse.gemini.blueprint.util.BundleDelegatingClassLoader.java

protected Class<?> findClass(String name) throws ClassNotFoundException {
    try {//ww  w  .ja  v a 2 s  .co m
        return this.backingBundle.loadClass(name);
    } catch (ClassNotFoundException cnfe) {
        DebugUtils.debugClassLoading(backingBundle, name, null);
        throw new ClassNotFoundException(
                name + " not found from bundle [" + backingBundle.getSymbolicName() + "]", cnfe);
    } catch (NoClassDefFoundError ncdfe) {
        // This is almost always an error
        // This is caused by a dependent class failure,
        // so make sure we search for the right one.
        String cname = ncdfe.getMessage().replace('/', '.');
        DebugUtils.debugClassLoading(backingBundle, cname, name);
        NoClassDefFoundError e = new NoClassDefFoundError(name + " not found from bundle ["
                + OsgiStringUtils.nullSafeNameAndSymName(backingBundle) + "]");
        e.initCause(ncdfe);
        throw e;
    }
}

From source file:org.javascool.compiler.JVSClassLoader.java

/**
 * Cherche une classe dans le classpath actuel et dans le rpertoire fournit au classloader
 *
 * @param className La classe  charger// www . j a  va  2 s .  c  om
 * @return L'objet reprsentant une classe en Java
 * @throws ClassNotFoundException Dans le cas o aucune classe n'as pu tre trouv.
 */
@Override
public Class<?> findClass(String className) throws ClassNotFoundException {
    byte classByte[];
    Class<?> result;

    result = classes.get(className); // On vrifie qu'elle n'est pas dans le cache
    if (result != null) {
        return result;
    }

    try { // On cherche si c'est une classe systme
        return findSystemClass(className);
    } catch (Exception e) {
        Logger.getAnonymousLogger().log(Level.OFF, className + " n'est pas une classe systme");
    }

    try { // Ou qu'elle est dans le chargeur parent
        return JVSClassLoader.class.getClassLoader().loadClass(className);
    } catch (Exception e) {
        Logger.getAnonymousLogger().log(Level.OFF, className + " n'est pas une classe du chargeur parent");
    }

    try { // On regarde aprs si elle n'est pas chez nous.
          // On en cre le pointeur vers le fichier de la classe
        File clazz = FileUtils.getFile(location, decomposePathForAClass(className));
        if (!clazz.exists()) { // Si le fichier de la classe n'existe pas, alors on cre une erreur
            throw new FileNotFoundException("Le fichier : " + clazz.toString() + " n'existe pas");
        }
        // On lit le fichier
        classByte = FileUtils.readFileToByteArray(clazz);
        // On dfinit la classe
        result = defineClass(className, classByte, 0, classByte.length, null);
        // On la stocke en cache
        classes.put(className, result);
        // On retourne le rsultat
        return result;
    } catch (Exception e) {
        throw new ClassNotFoundException(e.getMessage(), e);
    }
    //
}

From source file:org.elasticsearch.hadoop.script.GroovyScriptEngineService.java

public GroovyScriptEngineService(Settings settings) {
    super(settings);

    deprecationLogger.deprecated("[groovy] scripts are deprecated, use [painless] scripts instead");

    // Creates the classloader here in order to isolate Groovy-land code
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new SpecialPermission());
    }//from  w w w  .  j  av a  2 s  .  com
    this.loader = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> {
        // snapshot our context (which has permissions for classes), since the script has none
        AccessControlContext context = AccessController.getContext();
        return new ClassLoader(getClass().getClassLoader()) {
            @Override
            protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
                if (sm != null) {
                    try {
                        context.checkPermission(new ClassPermission(name));
                    } catch (SecurityException e) {
                        throw new ClassNotFoundException(name, e);
                    }
                }
                return super.loadClass(name, resolve);
            }
        };
    });
}