List of usage examples for java.lang ClassNotFoundException ClassNotFoundException
public ClassNotFoundException(String s)
ClassNotFoundException
with the specified detail message. From source file:com.hc.wx.server.common.bytecode.ReflectUtils.java
/** * desc to class.//from w w w .j a va2s .co m * "[Z" => boolean[].class * "[[Ljava/util/Map;" => java.util.Map[][].class * * @param cl ClassLoader instance. * @param desc desc. * @return Class instance. * @throws ClassNotFoundException */ private static Class<?> desc2class(ClassLoader cl, String desc) throws ClassNotFoundException { switch (desc.charAt(0)) { case JVM_VOID: return void.class; case JVM_BOOLEAN: return boolean.class; case JVM_BYTE: return byte.class; case JVM_CHAR: return char.class; case JVM_DOUBLE: return double.class; case JVM_FLOAT: return float.class; case JVM_INT: return int.class; case JVM_LONG: return long.class; case JVM_SHORT: return short.class; case 'L': desc = desc.substring(1, desc.length() - 1).replace('/', '.'); // "Ljava/lang/Object;" ==> "java.lang.Object" break; case '[': desc = desc.replace('/', '.'); // "[[Ljava/lang/Object;" ==> "[[Ljava.lang.Object;" break; default: throw new ClassNotFoundException("Class not found: " + desc); } if (cl == null) cl = ClassHelper.getClassLoader(); Class<?> clazz = DESC_CLASS_CACHE.get(desc); if (clazz == null) { clazz = Class.forName(desc, true, cl); DESC_CLASS_CACHE.put(desc, clazz); } return clazz; }
From source file:org.java.plugin.standard.StandardPluginClassLoader.java
protected void checkClassVisibility(final Class cls, final StandardPluginClassLoader requestor) throws ClassNotFoundException { if (this == requestor) { return;/*ww w .j av a 2 s . c o m*/ } URL lib = getClassBaseUrl(cls); if (lib == null) { return; // cls is a system class } ClassLoader loader = cls.getClassLoader(); if (!(loader instanceof StandardPluginClassLoader)) { return; } if (loader != this) { ((StandardPluginClassLoader) loader).checkClassVisibility(cls, requestor); } else { ResourceFilter filter = (ResourceFilter) resourceFilters.get(lib.toExternalForm()); if (filter == null) { log.warn("class not visible, no class filter found, lib=" + lib //$NON-NLS-1$ + ", class=" + cls + ", this=" + this //$NON-NLS-1$ //$NON-NLS-2$ + ", requestor=" + requestor); //$NON-NLS-1$ throw new ClassNotFoundException("class " //$NON-NLS-1$ + cls.getName() + " is not visible for plug-in " //$NON-NLS-1$ + requestor.getPluginDescriptor().getId() + ", no filter found for library " + lib); //$NON-NLS-1$ } if (!filter.isClassVisible(cls.getName())) { log.warn("class not visible, lib=" + lib //$NON-NLS-1$ + ", class=" + cls + ", this=" + this //$NON-NLS-1$ //$NON-NLS-2$ + ", requestor=" + requestor); //$NON-NLS-1$ throw new ClassNotFoundException("class " //$NON-NLS-1$ + cls.getName() + " is not visible for plug-in " //$NON-NLS-1$ + requestor.getPluginDescriptor().getId()); } } }
From source file:org.openmrs.module.ModuleClassLoader.java
/** * Custom loadClass implementation to allow for loading from a given ModuleClassLoader and skip * the modules that have been tried already * //from w ww . ja va 2s . c o m * @param name String path and name of the class to load * @param resolve boolean whether or not to resolve this class before returning * @param requestor ModuleClassLoader with which to try loading * @param seenModules Set<String> moduleIds that have been tried already * @return Class that has been loaded * @throws ClassNotFoundException if no class found */ protected synchronized Class<?> loadClass(final String name, final boolean resolve, final ModuleClassLoader requestor, Set<String> seenModules) throws ClassNotFoundException { if (log.isTraceEnabled()) { log.trace("Loading " + name + " " + getModule() + ", seenModules: " + seenModules + ", requestor: " + requestor + ", resolve? " + resolve); StringBuilder output = new StringBuilder(); for (StackTraceElement element : Thread.currentThread().getStackTrace()) { if (element.getClassName().contains("openmrs")) { output.append("+ "); } output.append(element); output.append("\n"); } log.trace("Stacktrace: " + output.toString()); } // Check if we already tried this class loader if ((seenModules != null) && seenModules.contains(getModule().getModuleId())) { throw new ClassNotFoundException("Can't load class " + name + " from module " + getModule().getModuleId() + ". It has been tried before."); } // Make sure the module is started if ((this != requestor) && !ModuleFactory.isModuleStarted(getModule())) { String msg = "Can't load class " + name + ", because module " + getModule().getModuleId() + " is not yet started."; log.warn(msg); throw new ClassNotFoundException(msg); } // Check if the class has already been loaded by this class loader Class<?> result = findLoadedClass(name); // Try loading the class with this class loader if (result == null) { try { result = findClass(name); } catch (ClassNotFoundException e) { // Continue trying... } } // We were able to "find" a class if (result != null) { checkClassVisibility(result, requestor); return result; } // Look through this module's imports to see if the class // can be loaded from them. if (seenModules == null) { seenModules = new HashSet<String>(); } // Add this module to the list of modules we've tried already seenModules.add(getModule().getModuleId()); List<Module> importedModules = new ArrayList<Module>(); if (requiredModules != null) { Collections.addAll(importedModules, requiredModules); } if (awareOfModules != null) { Collections.addAll(importedModules, awareOfModules); } for (Module importedModule : importedModules) { if (seenModules.contains(importedModule.getModuleId())) { continue; } ModuleClassLoader moduleClassLoader = ModuleFactory.getModuleClassLoader(importedModule); // Module class loader may be null if module has not been started yet if (moduleClassLoader != null) { try { result = moduleClassLoader.loadClass(name, resolve, requestor, seenModules); return result; } catch (ClassNotFoundException e) { // Continue trying... } } } throw new ClassNotFoundException(name); }
From source file:org.apache.axis2.addressing.EndpointReference.java
/** * Read the EPR to the specified InputStream. */// w w w .ja v a 2 s . c om public void readExternal(java.io.ObjectInput inObject) throws IOException, ClassNotFoundException { SafeObjectInputStream in = SafeObjectInputStream.install(inObject); // revision ID int revID = in.readInt(); // make sure the object data is in a revision level we can handle if (revID != REVISION_2) { throw new ClassNotFoundException(ExternalizeConstants.UNSUPPORTED_REVID); } // String object id logCorrelationIDString = (String) in.readObject(); // Read xml content in.readUTF(); // read marker int numBytes = in.readInt(); byte[] serBytes = new byte[numBytes]; // read the data from the input stream int bytesRead = 0; int numberOfBytesLastRead; while (bytesRead < numBytes) { numberOfBytesLastRead = in.read(serBytes, bytesRead, numBytes - bytesRead); if (numberOfBytesLastRead == -1) { // TODO: What should we do if the reconstitution fails? // For now, log the event and throw an exception if (log.isDebugEnabled()) { log.debug("readObject(): EPR logCorrelationID [" + logCorrelationIDString + "] " + " ***WARNING*** unexpected end to data: data read from input stream [" + bytesRead + "] expected data size [" + numBytes + "]"); } IOException ioe = new IOException( "Unable to deserialize the EndpointReference with logCorrelationID [" + logCorrelationIDString + "]" + " Cause: Unexpected end to data from input stream"); throw ioe; } bytesRead += numberOfBytesLastRead; } if (bytesRead == 0) { IOException ioe = new IOException("Unable to deserialize the EndpointReference with logCorrelationID [" + logCorrelationIDString + "]" + " Cause: No data from input stream"); throw ioe; } in.readUTF(); // read marker ByteArrayInputStream bais = new ByteArrayInputStream(serBytes); if (log.isDebugEnabled()) { String content = new String(serBytes); log.debug("readObject(): EPR logCorrelationID [" + logCorrelationIDString + "] " + " expected content size [" + numBytes + "]" + " content size [" + content.length() + "]" + " EPR buffered content [" + content + "]"); } XMLStreamReader xmlReader = null; try { OMElement om = OMXMLBuilderFactory.createOMBuilder(bais).getDocumentElement(); // expand the OM so we can close the stream reader om.build(); // trace point if (log.isDebugEnabled()) { log.debug(myClassName + ":readObject(): " + " EPR [" + logCorrelationIDString + "]" + " EPR OM content [" + om.toString() + "]"); } EndpointReferenceHelper.fromOM(this, om, AddressingConstants.Final.WSA_NAMESPACE); } catch (Exception e) { IOException ioe = new IOException("Unable to deserialize the EndpointReference with logCorrelationID [" + logCorrelationIDString + "]"); ioe.initCause(e); if (log.isDebugEnabled()) { log.debug("readObject(): Unable to deserialize the EPR with logCorrelationID [" + logCorrelationIDString + "] original error [" + e.getClass().getName() + "] message [" + e.getMessage() + "]", e); } throw ioe; } finally { // Make sure that the reader is properly closed // Note that closing a ByteArrayInputStream has no effect if (xmlReader != null) { try { xmlReader.close(); } catch (Exception e2) { IOException ioe2 = new IOException( "Unable to close the XMLStreamReader for the EndpointReference with logCorrelationID [" + logCorrelationIDString + "]"); ioe2.initCause(e2); if (log.isDebugEnabled()) { log.debug( "readObject(): Unable to close the XMLStreamReader for the EPR with logCorrelationID [" + logCorrelationIDString + "] original error [" + e2.getClass().getName() + "] message [" + e2.getMessage() + "]", e2); } throw ioe2; } } } }
From source file:org.josso.gateway.SSOGatewayImpl.java
protected Class loadClass(String fqcn) throws ClassNotFoundException { Class c = null;//w w w .j a v a 2 s .c o m try { c = this.getClass().getClassLoader().loadClass(fqcn); return c; } catch (ClassNotFoundException e) { } try { c = Thread.currentThread().getContextClassLoader().loadClass(fqcn); return c; } catch (ClassNotFoundException e) { } try { Class.forName(fqcn); return c; } catch (ClassNotFoundException e) { } throw new ClassNotFoundException(fqcn); }
From source file:com.squid.kraken.v4.caching.redis.datastruct.RawMatrix.java
public static RawMatrix deserialize(byte[] serializedMatrix) throws IOException, ClassNotFoundException { Input in = new Input(new ByteArrayInputStream(serializedMatrix)); try {//from w ww . j a v a 2 s . c o m HashMap<String, Integer> registration = new HashMap<String, Integer>(); // read header first // classes registration for kryo int nbClasses = in.readInt(); for (int i = 0; i < nbClasses; i++) { String className = in.readString(); int id = in.readInt(); registration.put(className, id); } // get version int position = in.position(); // in case there is no version available; int version; int type; int check_version = in.readInt(); if (check_version == -1) { // version>=1, read the version in the stream version = in.readInt();// read the version if (version < 2) { type = RedisCacheType.RAW_MATRIX.ordinal(); } else { type = in.readInt(); } } else { // version=0, no information in stream version = 0; type = RedisCacheType.RAW_MATRIX.ordinal(); in.setPosition(position); } if (type == RedisCacheType.RAW_MATRIX.ordinal()) { RawMatrix res = new RawMatrix(version, registration); res.readObject(in); return res; } else { throw new ClassNotFoundException("Could not deserialize"); } } finally { in.close(); } }
From source file:org.formix.dsx.serialization.XmlSerializer.java
private Class<?> getType(String simpleName) throws ClassNotFoundException { if (this.generalTypeMapper.containsKey(simpleName)) return this.generalTypeMapper.get(simpleName); List<String> packages = new ArrayList<String>(this.classResolutionPackages); packages.add("java.lang"); packages.add("java.util"); packages.add("java.sql"); for (String packageName : packages) { String className = packageName + "." + simpleName; try {//from ww w . ja va 2s.c o m Class<?> type = Class.forName(className); this.registerClass(type); return this.generalTypeMapper.get(simpleName); } catch (Exception e) { // In this algorithm, catching an exception and doing nothing // with it is a normal behavior. This is a violation of the // Exception Pattern which says that an exception should be // exceptional and handled properly. // // This "bad" algorithm is a quick and simple (for the // programmer(myself)) but rather slow (at runtime) replacement // for the correct implementation that should look for the // specific classes in the related class path defined by // packageSearchOrder and instantiate it if found. // // Greatly improved efficiency through the usage of the // generalTypeMapper but still not a good pattern for class // resolution. } } throw new ClassNotFoundException( "Unable to instanciate the given type " + simpleName + " with the internal packageSearchOrder " + this.classResolutionPackages + ". Please add the correct package for the type " + simpleName + " using XmlSerializer.getPackageSearchOrder().add(\"{package_name}\")"); }
From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java
/** Loads strategy class and creates instance by calling constructor. @param strategyText contains full class name followed by parameter list for constructor. Constructor parameters may be int, double, boolean, String. Constructor parameters are parsed by splitting on commas and trimming whitespace. <pre>// w w w. ja v a 2 s. c o m mypkg.MyStrategy(12, -345.67, true, false, Alpha Strategy) </pre> **/ protected TradingStrategy loadStrategy(String strategyText) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, ExceptionInInitializerError, InstantiationException, InvocationTargetException { Pattern strategyPattern = // matches full.class.Name(args...) Pattern.compile("^([A-Za-z](?:[A-Za-z0-9_.]*))\\s*[(](.*)[)]$"); Matcher matcher = strategyPattern.matcher(strategyText); if (!matcher.matches()) throw new IllegalArgumentException( "Bad Strategy: " + strategyText + "\n" + "Expected: full.class.name(-123.45, 67, true, false)"); final String strategyClassName = matcher.group(1).trim(); String parameters[] = matcher.group(2).split(","); // clean parameters for (int i = 0; i < parameters.length; i++) parameters[i] = parameters[i].trim(); if (parameters.length == 1 && parameters[0].length() == 0) parameters = new String[] {}; // 0 parameters // build classpath String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator); ArrayList<URL> classPathURLs = new ArrayList<URL>(); for (int i = 0; i < classPath.length; i++) { String path = classPath[i]; if (".".equals(path)) path = System.getProperty("user.dir"); path = path.replace(File.separatorChar, '/'); if (!path.endsWith("/") && !path.endsWith(".jar")) path += "/"; try { classPathURLs.add(new File(path).toURL()); } catch (MalformedURLException e) { // bad directory in class path, skip } } final String strategyPackagePrefix = strategyClassName.substring(0, Math.max(0, strategyClassName.lastIndexOf('.') + 1)); ClassLoader loader = new URLClassLoader(classPathURLs.toArray(new URL[] {}), this.getClass().getClassLoader()) { /** Don't search parent for classes with strategyPackagePrefix. Exception: interface TradingStrategy **/ protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException { Class<?> loadedClass = findLoadedClass(className); if (loadedClass != null) return loadedClass; if (!className.startsWith(strategyPackagePrefix) || className.equals(TradingStrategy.class.getName())) { loadedClass = this.getParent().loadClass(className); if (loadedClass != null) return loadedClass; } loadedClass = findClass(className); if (loadedClass != null) { if (resolve) resolveClass(loadedClass); return loadedClass; } else throw new ClassNotFoundException(className); } }; // load class. Throws ClassNotFoundException if not found. Class<?> strategyClass = loader.loadClass(strategyClassName); // Make sure it is a TradingStrategy. if (!TradingStrategy.class.isAssignableFrom(strategyClass)) throw new ClassCastException(strategyClass.getName() + " does not implement TradingStrategy"); // Find constructor compatible with parameters Constructor[] constructors = strategyClass.getConstructors(); findConstructor: for (Constructor constructor : constructors) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length != parameters.length) continue; Object[] values = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { if (boolean.class.equals(parameterTypes[i])) { String parameter = parameters[i].toLowerCase(); if ("false".equals(parameter)) values[i] = Boolean.FALSE; else if ("true".equals(parameter)) values[i] = Boolean.TRUE; else continue findConstructor; } else if (int.class.equals(parameterTypes[i])) { try { values[i] = new Integer(parameters[i]); } catch (NumberFormatException e) { continue findConstructor; } } else if (double.class.equals(parameterTypes[i])) { try { values[i] = new Double(parameters[i]); } catch (NumberFormatException e) { continue findConstructor; } } else if (String.class.equals(parameterTypes[i])) { values[i] = parameters[i]; } else continue findConstructor; // unsupported parameter type, skip } // all values matched types, so create instance return (TradingStrategy) constructor.newInstance(values); } throw new NoSuchMethodException(strategyText); }
From source file:io.github.tavernaextras.biocatalogue.model.Util.java
/** * This method is "clones" an object supplied as an argument. It uses * serialisation to achieve this (as opposed to manually implementing deep * copying of all referenced objects in the graph of the provided object). * This technique is used to make sure that the new object will be exact * replica, but totally independent of the original one. * //from www .j av a 2s .c om * Note that this code works ~100 times slower than it would do if deep copying * was implemented. However, this will not be used in tight loops (and in loops * at all), so for one-off tasks it is fine. * * @author Dave Miller<br/> * Original version of the code in this method is taken from * <a href="http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2"> * http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2 * </a> [accessed on 25/Feb/2010]. * <br/><br/> * * @author Subhajit Dasgupta<br/> * Example of using an alternative class loader during object de-serialisation * was taken from * <a href="http://blogs.sun.com/adventures/entry/desrializing_objects_custom_class_loaders"> * http://blogs.sun.com/adventures/entry/desrializing_objects_custom_class_loaders * </a> [accessed on 29/Mar/2010]. * * @return Deep copy of the provided object. If deep copying doesn't succeed, * <code>null</code> is returned. */ public static Object deepCopy(Object objectToCopy) { // a "safety net" - a class loader of BioCatalogue perspective may be used in // de-serialisation process to make sure that all classes are recognised // (system class loader may not be able to "see" all BioCatalogue plugin's files, // but just those in Taverna's /lib folder) final ClassLoader[] customClassLoaders = new ClassLoader[] { BioCataloguePerspective.class.getClassLoader() }; try { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); // serialise and pass the object oos.writeObject(objectToCopy); oos.flush(); // read and return the new object ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bin) { /** * <code>resolveClass()</code> method is overridden to make use of * custom ClassLoader in the de-serialisation process. * <br/> * This is needed to make sure that the ClassLoader of the BioCatalogue * perspective is used as opposed to the system ClassLoader which will * only be able to see classes from Taverna's /lib folder. */ protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String className = desc.getName(); try { // attempt to use default class loader return Class.forName(className); } catch (ClassNotFoundException exc) { // default class loader was unable to locate a required class - // attempt to use one of the provided class loaders for (ClassLoader cl : customClassLoaders) { try { return cl.loadClass(className); } catch (ClassNotFoundException e) { /* do nothing here - there may be other class loaders to try */ } } // none of the class loaders was able to recognise the currently // de-serialised class, so it's indeed an exception throw new ClassNotFoundException(className + " -- neither system, nor alternative class loaders were able to load this class"); } } }; return ois.readObject(); } catch (Exception e) { logger.error("Could not perform deep copy of " + objectToCopy.getClass() + " instance", e); } finally { oos.close(); ois.close(); } } catch (Exception e) { logger.error( "Could not close object streams during deep copy of " + objectToCopy.getClass() + " instance"); } // Error occurred - couldn't produce the deep copy... return null; }
From source file:org.jahia.data.templates.JahiaTemplatesPackage.java
/** * Returns a class loader which is a chain of class loaders, starting from the Web application one, then this modules class loader and * at the end the list of class loaders of modules this module depends on. * * @return a class loader which is a chain of class loaders, starting from the Web application one, then this modules class loader and * at the end the list of class loaders of modules this module depends on *///from www .ja v a 2 s .co m public ClassLoader getChainedClassLoader() { if (chainedClassLoader != null) { return chainedClassLoader; } final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(); classLoaders.add(Jahia.class.getClassLoader()); final ClassLoader classLoader = getClassLoader(); if (classLoader != null) { classLoaders.add(classLoader); } for (JahiaTemplatesPackage dependentPack : getDependencies()) { if (dependentPack != null && dependentPack.getClassLoader() != null) { classLoaders.add(dependentPack.getClassLoader()); } } chainedClassLoader = new ClassLoader() { @Override public URL getResource(String name) { URL url = null; for (ClassLoader loader : classLoaders) { url = loader.getResource(name); if (url != null) return url; } return url; } @Override public Enumeration<URL> getResources(String name) throws IOException { final List<Enumeration<URL>> urlsEnums = new ArrayList<Enumeration<URL>>(); for (ClassLoader loader : classLoaders) { Enumeration<URL> urls = loader.getResources(name); if (urls != null && urls.hasMoreElements()) { // we only add enumerations that have elements, make things simpler urlsEnums.add(urls); } } if (urlsEnums.size() == 0) { return java.util.Collections.emptyEnumeration(); } return new Enumeration<URL>() { int i = 0; Enumeration<URL> currentEnum = urlsEnums.get(i); @Override public boolean hasMoreElements() { if (currentEnum.hasMoreElements()) { return true; } int j = i; do { j++; } while (j < (urlsEnums.size() - 1) && !urlsEnums.get(j).hasMoreElements()); if (j <= (urlsEnums.size() - 1)) { return urlsEnums.get(j).hasMoreElements(); } else { return false; } } @Override public URL nextElement() { if (currentEnum.hasMoreElements()) { return currentEnum.nextElement(); } do { i++; currentEnum = urlsEnums.get(i); } while (!currentEnum.hasMoreElements() && i < (urlsEnums.size() - 1)); if (currentEnum.hasMoreElements()) { return currentEnum.nextElement(); } else { throw new NoSuchElementException(); } } }; } @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { for (ClassLoader classLoader : classLoaders) { try { Class<?> clazz = classLoader.loadClass(name); if (resolve) { resolveClass(clazz); } return clazz; } catch (ClassNotFoundException e) { // keep moving through the classloaders } } throw new ClassNotFoundException(name); } }; return chainedClassLoader; }