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.sshtools.j2ssh.util.DynamicClassLoader.java

/**
 *
 *
 * @param name// w  ww  . ja va2  s.  c  om
 * @param resolve
 *
 * @return
 *
 * @throws ClassNotFoundException
 */
protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException {
    // The class object that will be returned.
    Class c = null;

    // Use the cached value, if this class is already loaded into
    // this classloader.
    ClassCacheEntry entry = (ClassCacheEntry) cache.get(name);

    if (entry != null) {
        // Class found in our cache
        c = entry.loadedClass;

        if (resolve) {
            resolveClass(c);
        }

        return c;
    }

    if (!securityAllowsClass(name)) {
        return loadSystemClass(name, resolve);
    }

    // Attempt to load the class from the system
    try {
        c = loadSystemClass(name, resolve);

        if (c != null) {
            if (resolve) {
                resolveClass(c);
            }

            return c;
        }
    } catch (Exception e) {
        c = null;
    }

    // Try to load it from each classpath
    Iterator it = classpath.iterator();

    // Cache entry.
    ClassCacheEntry classCache = new ClassCacheEntry();

    while (it.hasNext()) {
        byte[] classData;

        File file = (File) it.next();

        try {
            if (file.isDirectory()) {
                classData = loadClassFromDirectory(file, name, classCache);
            } else {
                classData = loadClassFromZipfile(file, name, classCache);
            }
        } catch (IOException ioe) {
            // Error while reading in data, consider it as not found
            classData = null;
        }

        if (classData != null) {
            // Define the class
            c = defineClass(name, classData, 0, classData.length);

            // Cache the result;
            classCache.loadedClass = c;

            // Origin is set by the specific loader
            classCache.lastModified = classCache.origin.lastModified();
            cache.put(name, classCache);

            // Resolve it if necessary
            if (resolve) {
                resolveClass(c);
            }

            return c;
        }
    }

    // If not found in any classpath
    throw new ClassNotFoundException(name);
}

From source file:org.mule.util.ClassUtils.java

/**
 * Load a class with a given name. <p/> It will try to load the class in the
 * following order://from   w  ww .ja v a 2  s  .  c om
 * <ul>
 * <li>From
 * {@link Thread#getContextClassLoader() Thread.currentThread().getContextClassLoader()}
 * <li>Using the basic {@link Class#forName(java.lang.String) }
 * <li>From
 * {@link Class#getClassLoader() ClassLoaderUtil.class.getClassLoader()}
 * <li>From the {@link Class#getClassLoader() callingClass.getClassLoader() }
 * </ul>
 *
 * @param className    The name of the class to load
 * @param callingClass The Class object of the calling object
 * @param type the class type to expect to load
 * @return The Class instance
 * @throws ClassNotFoundException If the class cannot be found anywhere.
 */
public static <T extends Class> T loadClass(final String className, final Class<?> callingClass, T type)
        throws ClassNotFoundException {
    if (className.length() <= 8) {
        // Could be a primitive - likely.
        if (primitiveTypeNameMap.containsKey(className)) {
            return (T) primitiveTypeNameMap.get(className);
        }
    }

    Class<?> clazz = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
        public Class<?> run() {
            try {
                final ClassLoader cl = Thread.currentThread().getContextClassLoader();
                return cl != null ? cl.loadClass(className) : null;

            } catch (ClassNotFoundException e) {
                return null;
            }
        }
    });

    if (clazz == null) {
        clazz = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
            public Class<?> run() {
                try {
                    return Class.forName(className);
                } catch (ClassNotFoundException e) {
                    return null;
                }
            }
        });
    }

    if (clazz == null) {
        clazz = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
            public Class<?> run() {
                try {
                    return ClassUtils.class.getClassLoader().loadClass(className);
                } catch (ClassNotFoundException e) {
                    return null;
                }
            }
        });
    }

    if (clazz == null) {
        clazz = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() {
            public Class<?> run() {
                try {
                    return callingClass.getClassLoader().loadClass(className);
                } catch (ClassNotFoundException e) {
                    return null;
                }
            }
        });
    }

    if (clazz == null) {
        throw new ClassNotFoundException(className);
    }

    if (type.isAssignableFrom(clazz)) {
        return (T) clazz;
    } else {
        throw new IllegalArgumentException(String.format("Loaded class '%s' is not assignable from type '%s'",
                clazz.getName(), type.getName()));
    }
}

From source file:alice.tuprolog.lib.OOLibrary.java

/**
 * Creates of a java object - not backtrackable case
 * @param className/*from   w ww.j a  v a 2 s.c  om*/
 * @param argl
 * @param id
 * @return
 * @throws JavaException
 */
public boolean new_object_3(PTerm className, PTerm argl, PTerm id) throws JavaException {
    className = className.getTerm();
    Struct arg = (Struct) argl.getTerm();
    id = id.getTerm();
    try {
        if (!className.isAtom()) {
            throw new JavaException(new ClassNotFoundException("Java class not found: " + className));
        }
        String clName = ((Struct) className).getName();
        // check for array type
        if (clName.endsWith("[]")) {
            Object[] list = getArrayFromList(arg);
            int nargs = ((Number) list[0]).intValue();
            if (java_array(clName, nargs, id))
                return true;
            else
                throw new JavaException(new Exception());
        }
        Signature args = parseArg(getArrayFromList(arg));
        if (args == null) {
            throw new IllegalArgumentException("Illegal constructor arguments  " + arg);
        }
        // object creation with argument described in args
        try {
            Class<?> cl = Class.forName(clName, true, dynamicLoader);
            Object[] args_value = args.getValues();
            Constructor<?> co = lookupConstructor(cl, args.getTypes(), args_value);
            if (co == null) {
                getEngine().logger.warn("Constructor not found: class " + clName);
                throw new JavaException(new NoSuchMethodException("Constructor not found: class " + clName));
            }

            Object obj = co.newInstance(args_value);
            if (bindDynamicObject(id, obj))
                return true;
            else
                throw new JavaException(new Exception());
        } catch (ClassNotFoundException ex) {
            getEngine().logger.warn("Java class not found: " + clName);
            throw new JavaException(ex);
        } catch (InvocationTargetException ex) {
            getEngine().logger.warn("Invalid constructor arguments.");
            throw new JavaException(ex);
        } catch (NoSuchMethodException ex) {
            getEngine().logger.warn("Constructor not found: " + args.getTypes());
            throw new JavaException(ex);
        } catch (InstantiationException ex) {
            getEngine().logger.warn("Objects of class " + clName + " cannot be instantiated");
            throw new JavaException(ex);
        } catch (IllegalArgumentException ex) {
            getEngine().logger.warn("Illegal constructor arguments  " + args);
            throw new JavaException(ex);
        }
    } catch (Exception ex) {
        throw new JavaException(ex);
    }
}

From source file:org.apache.axis2.description.ParameterIncludeMixin.java

/**
 * Restore the contents of the object that was previously saved.
 * <p/>/* w  w w  .j a  v  a  2 s.co  m*/
 * NOTE: The field data must read back in the same order and type
 * as it was written.  Some data will need to be validated when
 * resurrected.
 *
 * @param in The stream to read the object contents from
 * @throws IOException
 * @throws ClassNotFoundException
 */
public void readExternal(ObjectInput inObject) throws IOException, ClassNotFoundException {
    SafeObjectInputStream in = SafeObjectInputStream.install(inObject);
    // trace point
    if (log.isTraceEnabled()) {
        log.trace(getClass().getName() + ":readExternal():  BEGIN  bytes available in stream [" + in.available()
                + "]  ");
    }

    // serialization version ID
    long suid = in.readLong();

    // revision ID
    int revID = in.readInt();

    // make sure the object data is in a version we can handle
    if (suid != serialVersionUID) {
        throw new ClassNotFoundException(ExternalizeConstants.UNSUPPORTED_SUID);
    }

    // make sure the object data is in a revision level we can handle
    if (revID != REVISION_2) {
        throw new ClassNotFoundException(ExternalizeConstants.UNSUPPORTED_REVID);
    }

    //---------------------------------------------------------
    // collection of parameters
    //---------------------------------------------------------
    in.readMap(parameters);

    //---------------------------------------------------------
    // done
    //---------------------------------------------------------
}

From source file:org.apache.axis2.description.Parameter.java

/**
 * Restore the contents of the object that was previously saved.
 * <p/>/*from   w  w w.  j  a  v a2 s.  co m*/
 * NOTE: The field data must read back in the same order and type
 * as it was written.  Some data will need to be validated when
 * resurrected.
 *
 * @param in The stream to read the object contents from
 * @throws IOException
 * @throws ClassNotFoundException
 */
public void readExternal(ObjectInput inObject) throws IOException, ClassNotFoundException {
    SafeObjectInputStream in = SafeObjectInputStream.install(inObject);
    // trace point
    if (log.isTraceEnabled()) {
        log.trace(
                myClassName + ":readExternal():  BEGIN  bytes available in stream [" + in.available() + "]  ");
    }

    // serialization version ID
    long suid = in.readLong();

    // revision ID
    int revID = in.readInt();

    // make sure the object data is in a version we can handle
    if (suid != serialVersionUID) {
        throw new ClassNotFoundException(ExternalizeConstants.UNSUPPORTED_SUID);
    }

    // make sure the object data is in a revision level we can handle
    if (revID != REVISION_2) {
        throw new ClassNotFoundException(ExternalizeConstants.UNSUPPORTED_REVID);
    }

    //---------------------------------------------------------
    // simple fields
    //---------------------------------------------------------

    type = in.readInt();
    locked = in.readBoolean();
    name = (String) in.readObject();

    //---------------------------------------------------------
    // object fields
    //---------------------------------------------------------

    // TODO: investigate serializing the OMElement more efficiently
    // This currently will basically serialize the given OMElement
    // to a String but will build the OMTree in the memory

    // treat as an object, don't do UTF
    String tmp = (String) in.readObject();

    // convert to an OMElement
    if (tmp != null) {
        try {
            OMElement docElement = AXIOMUtil.stringToOM(tmp);

            if (docElement != null) {
                parameterElement = docElement;
            } else {
                // TODO: error handling if can't create an OMElement
                parameterElement = null;
            }
        } catch (Exception exc) {
            // TODO: error handling if can't create an OMElement
            parameterElement = null;
        }
    } else {
        parameterElement = null;
    }

    // TODO: error handling if this can't be serialized
    value = in.readObject();

    //---------------------------------------------------------
    // done
    //---------------------------------------------------------

}

From source file:org.openmrs.logic.CompilingClassLoader.java

/**
 * @see java.lang.ClassLoader#loadClass(String, boolean)
 * @should compile and load java file at runtime
 *//*from w w w .j ava2s. co m*/
@Override
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {

    // Our goal is to get a Class object
    Class<?> clas = null;

    // First, see if we've already dealt with this one
    clas = findLoadedClass(name);

    // Create a pathname from the class name
    // E.g. java.lang.Object => java/lang/Object
    String fileStub = name.replace('.', File.separatorChar);

    // Build objects pointing to the source code (.java) and object
    // code (.class)
    String javaFilename = fileStub + ".java";
    String classFilename = fileStub + ".class";

    String ruleClassDir = Context.getAdministrationService()
            .getGlobalProperty(LogicConstants.RULE_DEFAULT_CLASS_FOLDER);
    String ruleJavaDir = Context.getAdministrationService()
            .getGlobalProperty(LogicConstants.RULE_DEFAULT_SOURCE_FOLDER);

    File javaFile = new File(OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleJavaDir), javaFilename);
    File classFile = new File(OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir), classFilename);

    // First, see if we want to try compiling.  We do if (a) there
    // is source code, and either (b0) there is no object code,
    // or (b1) there is object code, but it's older than the source
    if (javaFile.exists() && (!classFile.exists() || javaFile.lastModified() > classFile.lastModified())) {

        try {
            // Try to compile it.  If this doesn't work, then
            // we must declare failure.  (It's not good enough to use
            // an already-existing, but out-of-date, class file)
            String error = compile(javaFile.getAbsolutePath());
            if (error != null)
                throw new LogicException(error);
            if (!classFile.exists())
                throw new ClassNotFoundException("Compilation process failed for " + javaFilename);
        } catch (IOException ie) {

            // Another place where we might come to if we fail
            // to compile
            throw new ClassNotFoundException(ie.toString(), ie);
        }
    }

    // Let's try to load up the raw bytes, assuming they were
    // properly compiled, or didn't need to be compiled
    try {

        // read the bytes
        byte raw[] = getBytes(classFile.getAbsolutePath());

        // try to turn them into a class
        clas = defineClass(name, raw, 0, raw.length);
    } catch (IOException ie) {
        // This is not a failure!  If we reach here, it might
        // mean that we are dealing with a class in a library,
        // such as java.lang.Object
    }

    // Maybe it is in the openmrs loader
    if (clas == null)
        clas = OpenmrsClassLoader.getInstance().loadClass(name);

    // Maybe the class is in a library -- try loading
    // the normal way
    if (clas == null)
        clas = findSystemClass(name);

    // Resolve the class, if any, but only if the "resolve"
    // flag is set to true
    if (resolve && clas != null)
        resolveClass(clas);

    // If we still don't have a class, it's an error
    if (clas == null)
        throw new ClassNotFoundException(name);

    // Otherwise, return the class
    return clas;
}

From source file:com.asakusafw.runtime.io.ModelIoFactory.java

private Class<?> findClassFromModel(String format) throws ClassNotFoundException {
    Matcher m = MODEL_CLASS_NAME_PATTERN.matcher(modelClass.getName());
    if (m.matches() == false) {
        throw new ClassNotFoundException(
                MessageFormat.format("Invalid model class name pattern: {0}", modelClass.getName()));
    }//from ww  w .ja  v  a2 s .co m
    String qualifier = m.group(1);
    String simpleName = m.group(2);

    String result = MessageFormat.format(format, qualifier, simpleName);

    return Class.forName(result, false, modelClass.getClassLoader());
}

From source file:org.apache.axis2.context.SessionContext.java

/**
 * Restore the contents of the MessageContext that was
 * previously saved.//w  w w  .j a v  a  2s . c om
 * <p/>
 * NOTE: The field data must read back in the same order and type
 * as it was written.  Some data will need to be validated when
 * resurrected.
 *
 * @param in The stream to read the object contents from
 * @throws IOException
 * @throws ClassNotFoundException
 */
public void readExternal(ObjectInput inObject) throws IOException, ClassNotFoundException {
    SafeObjectInputStream in = SafeObjectInputStream.install(inObject);
    // trace point
    if (log.isTraceEnabled()) {
        log.trace(
                myClassName + ":readExternal():  BEGIN  bytes available in stream [" + in.available() + "]  ");
    }

    // serialization version ID
    long suid = in.readLong();

    // revision ID
    int revID = in.readInt();

    // make sure the object data is in a version we can handle
    if (suid != serialVersionUID) {
        throw new ClassNotFoundException(ExternalizeConstants.UNSUPPORTED_SUID);
    }

    // make sure the object data is in a revision level we can handle
    if (revID != REVISION_2) {
        throw new ClassNotFoundException(ExternalizeConstants.UNSUPPORTED_REVID);
    }

    //---------------------------------------------------------
    // various simple fields
    //---------------------------------------------------------
    long time = in.readLong();
    setLastTouchedTime(time);

    sessionContextTimeoutInterval = in.readLong();
    cookieID = (String) in.readObject();

    //---------------------------------------------------------
    // properties
    //---------------------------------------------------------
    properties = in.readMap(new HashMap());

    //---------------------------------------------------------
    // "nested"
    //---------------------------------------------------------

    // parent
    parent = (AbstractContext) in.readObject();

    //---------------------------------------------------------
    // done
    //---------------------------------------------------------

    serviceContextMap = new HashMap<String, ServiceContext>();
    serviceGroupContextMap = new HashMap<String, ServiceGroupContext>();
}

From source file:org.ireland.jnetty.loader.WebAppClassLoader.java

/**
 * Load class but not resolve/* w w w  .  j a v  a 2 s .co m*/
 * @param name
 * @return
 * @throws ClassNotFoundException
 */
protected synchronized Class<?> loadClass0(String name) throws ClassNotFoundException {
    // (0) Check our previously loaded class cache

    Class<?> clazz = findLoadedClass(name);

    if (clazz != null) {
        //if (isDebugEnabled) LOG.debug("  Returning class from cache,class: "+clazz);

        return (clazz);
    }

    // (1) Delegate to our parent if requested
    if (delegate) {
        if (isDebugEnabled)
            LOG.debug("  Delegating to parent classloader1: " + _parent);

        ClassLoader loader = _parent;
        try {
            clazz = Class.forName(name, false, loader);
            if (clazz != null) {
                if (isDebugEnabled)
                    LOG.debug("  Loaded class from parent,class: " + clazz);
                return (clazz);
            }
        } catch (ClassNotFoundException e) {
            // Ignore
        }
    }

    // (2) Search local resources
    if (isDebugEnabled)
        LOG.debug("  Searching local ClassPaths @ " + name);

    try {
        clazz = findClass(name);
        if (clazz != null) {
            if (isDebugEnabled)
                LOG.debug("  Loaded class from local ClassPaths,class: " + clazz);
            return (clazz);
        }
    } catch (ClassNotFoundException e) {
        // Ignore
    }

    // (3) Delegate to parent unconditionally
    if (!delegate) {
        if (isDebugEnabled)
            LOG.debug("  Delegating to parent classloader at end: " + _parent);

        ClassLoader loader = _parent;

        try {
            clazz = Class.forName(name, false, loader);
            if (clazz != null) {
                if (isDebugEnabled)
                    LOG.debug("  Loaded class from parent,class: " + clazz);
                return (clazz);
            }
        } catch (ClassNotFoundException e) {
            // Ignore
        }
    }

    throw new ClassNotFoundException(name);
}

From source file:plum.mybatis.PaginationInterceptor.java

/**
 * ???/*from   www.j  av  a2  s  . c om*/
 * <p>
 * <code>dialectClass</code>,???
 * <ode>dbms</ode> ????
 * <code>sqlRegex</code> ?SQL ID
 * </p>
 * ??<code>dialectClass</code><code>dbms</code>,<code>dbms</code>
 *
 * @param p 
 */
@Override
public void setProperties(Properties p) {
    String dialectClass = p.getProperty("dialectClass");
    DBMS dbms;
    if (!StringUtils.isEmpty(dialectClass)) {
        Dialect dialect1 = (Dialect) Reflections.instance(dialectClass);
        if (dialect1 == null) {
            throw new RuntimeException(new ClassNotFoundException("dialectClass is not found!"));
        }
        DialectClient.putEx(dialect1);
        dbms = DBMS.EX;
    }

    String dialect = p.getProperty("dbms");
    if (StringUtils.isEmpty(dialect)) {
        try {
            throw new PropertyException("dialect property is not found!");
        } catch (PropertyException e) {
            LOG.error("", e);
        }
    }
    //DBMS_THREAD_LOCAL.set(DBMS.valueOf(dialect.toUpperCase()));
    dbms = DBMS.valueOf(dialect.toUpperCase());
    if (dbms == null) {
        try {
            throw new PropertyException("???");
        } catch (PropertyException e) {
            LOG.error("", e);
        }
    }
    _dialect = DialectClient.getDbmsDialect(dbms);

    String sql_regex = p.getProperty("sqlRegex");
    if (!StringUtils.isEmpty(sql_regex)) {
        _sql_regex = sql_regex;
    }
    clean();
}