package org.jboss.mx.loading;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.jboss.logging.Logger;
import org.jboss.mx.loading.LoadMgr3.PkgClassLoader;
public class ClassLoaderUtils
{
private static Logger log = Logger.getLogger(ClassLoaderUtils.class);
private static final Comparator repostiroyClassLoaderComparator = new RepositoryClassLoaderComparator();
public static void displayClassInfo(Class clazz, StringBuffer results)
{
ClassLoader cl = clazz.getClassLoader();
results.append("\n"+clazz.getName()+"("+Integer.toHexString(clazz.hashCode())+").ClassLoader="+cl);
ClassLoader parent = cl;
while( parent != null )
{
results.append("\n.."+parent);
URL[] urls = getClassLoaderURLs(parent);
int length = urls != null ? urls.length : 0;
for(int u = 0; u < length; u ++)
{
results.append("\n...."+urls[u]);
}
if( parent != null )
parent = parent.getParent();
}
CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
if( clazzCS != null )
results.append("\n++++CodeSource: "+clazzCS);
else
results.append("\n++++Null CodeSource");
results.append("\nImplemented Interfaces:");
Class[] ifaces = clazz.getInterfaces();
for(int i = 0; i < ifaces.length; i ++)
{
Class iface = ifaces[i];
results.append("\n++"+iface+"("+Integer.toHexString(iface.hashCode())+")");
ClassLoader loader = ifaces[i].getClassLoader();
results.append("\n++++ClassLoader: "+loader);
ProtectionDomain pd = ifaces[i].getProtectionDomain();
CodeSource cs = pd.getCodeSource();
if( cs != null )
results.append("\n++++CodeSource: "+cs);
else
results.append("\n++++Null CodeSource");
}
}
public static URL[] getClassLoaderURLs(ClassLoader cl)
{
URL[] urls = {};
try
{
Class returnType = urls.getClass();
Class[] parameterTypes = {};
Class clClass = cl.getClass();
Method getURLs = clClass.getMethod("getURLs", parameterTypes);
if( returnType.isAssignableFrom(getURLs.getReturnType()) )
{
Object[] args = {};
urls = (URL[]) getURLs.invoke(cl, args);
}
if( urls == null || urls.length == 0 )
{
Method getCp = clClass.getMethod("getClasspath", parameterTypes);
if( returnType.isAssignableFrom(getCp.getReturnType()) )
{
Object[] args = {};
urls = (URL[]) getCp.invoke(cl, args);
}
}
}
catch(Exception ignore)
{
}
return urls;
}
public static URLClassLoader[] getClassLoaderStack(ClassLoader cl)
{
ArrayList stack = new ArrayList();
while( cl != null )
{
if( cl instanceof URLClassLoader )
{
stack.add(cl);
}
cl = cl.getParent();
}
URLClassLoader[] ucls = new URLClassLoader[stack.size()];
stack.toArray(ucls);
return ucls;
}
public static String getJarClassName(String className)
{
String jarClassName = className.replace('.', '/');
return jarClassName + ".class";
}
public static String getPackageName(String className)
{
int startIndex = 0;
if( className.length() > 0 && className.charAt(0) == '[' )
{
startIndex = className.indexOf('L') + 1;
}
String pkgName = "";
int endIndex = className.lastIndexOf('.');
if( endIndex > 0 )
pkgName = className.substring(startIndex, endIndex);
return pkgName;
}
public static String getResourceName(String className)
{
int startIndex = 0;
if( className.length() > 0 && className.charAt(0) == '[' )
{
startIndex = className.indexOf('L') + 1;
}
String resName = "";
int endIndex = className.lastIndexOf('.');
if( endIndex > 0 )
resName = className.substring(startIndex, endIndex);
return resName.replace('.', '/');
}
public static Set newPackageSet()
{
return new TreeSet(repostiroyClassLoaderComparator);
}
public static Set clonePackageSet(Object toClone)
{
TreeSet original = (TreeSet) toClone;
return (Set) original.clone();
}
public static String[] updatePackageMap(RepositoryClassLoader cl, Map packagesMap)
throws Exception
{
URL url = cl.getURL();
ClassPathIterator cpi = new ClassPathIterator(url);
HashSet pkgNameSet = new HashSet();
return updatePackageMap(cl, packagesMap, cpi, pkgNameSet);
}
public static String[] updatePackageMap(RepositoryClassLoader cl, Map packagesMap,
URL url, String[] prevPkgNames)
throws Exception
{
ClassPathIterator cpi = new ClassPathIterator(url);
HashSet pkgNameSet = null;
if (prevPkgNames == null)
pkgNameSet = new HashSet();
else
pkgNameSet = new HashSet(Arrays.asList(prevPkgNames));
return updatePackageMap(cl, packagesMap, cpi, pkgNameSet);
}
public static String[] updateClassNamesMap(RepositoryClassLoader cl,
Map classNamesMap)
throws Exception
{
URL url = cl.getURL();
ClassPathIterator cpi = new ClassPathIterator(url);
HashSet classNameSet = new HashSet();
return updateClassNamesMap(cl, classNamesMap, cpi, classNameSet);
}
public static String[] updateClassNamesMap(RepositoryClassLoader cl,
Map classNamesMap, URL url, String[] prevClassNames)
throws Exception
{
ClassPathIterator cpi = new ClassPathIterator(url);
HashSet classNameSet = null;
if (prevClassNames == null)
classNameSet = new HashSet();
else
classNameSet = new HashSet(Arrays.asList(prevClassNames));
return updateClassNamesMap(cl, classNamesMap, cpi, classNameSet);
}
static String[] updatePackageMap(RepositoryClassLoader cl, Map packagesMap,
ClassPathIterator cpi, HashSet pkgNameSet)
throws Exception
{
boolean trace = log.isTraceEnabled();
ClassPathEntry entry;
while( (entry = cpi.getNextEntry()) != null )
{
String name = entry.getName();
if( name.equals("META-INF/INDEX.LIST") )
{
readJarIndex(cl, cpi, packagesMap, pkgNameSet);
break;
}
if( entry.isDirectory() == true )
continue;
String pkgName = entry.toPackageName();
addPackage(pkgName, packagesMap, pkgNameSet, cl, trace);
}
cpi.close();
String[] pkgNames = new String[pkgNameSet.size()];
pkgNameSet.toArray(pkgNames);
return pkgNames;
}
static String[] updateClassNamesMap(RepositoryClassLoader cl, Map classNamesMap,
ClassPathIterator cpi, HashSet classNameSet)
throws Exception
{
boolean trace = log.isTraceEnabled();
ClassPathEntry entry;
while( (entry = cpi.getNextEntry()) != null )
{
String name = entry.getName();
if( entry.isDirectory() == true )
continue;
if( name.endsWith(".class") == false )
continue;
addClass(name, classNamesMap, cl, trace);
classNameSet.add(name);
}
cpi.close();
String[] classNames = new String[classNameSet.size()];
classNameSet.toArray(classNames);
return classNames;
}
private static void readJarIndex(RepositoryClassLoader cl, ClassPathIterator cpi,
Map packagesMap, Set pkgNameSet)
throws Exception
{
boolean trace = log.isTraceEnabled();
InputStream zis = cpi.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(zis));
String line;
while( (line = br.readLine()) != null )
{
if( line.length() == 0 )
break;
}
String jarName = br.readLine();
if( trace )
log.trace("Reading INDEX.LIST for jar: "+jarName);
while( (line = br.readLine()) != null )
{
if( line.length() == 0 )
break;
String pkgName = line.replace('/', '.');
addPackage(pkgName, packagesMap, pkgNameSet, cl, trace);
}
br.close();
}
private static void addPackage(String pkgName, Map packagesMap,
Set pkgNameSet, RepositoryClassLoader cl, boolean trace)
{
if( pkgName.startsWith("META-INF") || pkgName.startsWith("WEB-INF") )
return;
Set pkgSet = (Set) packagesMap.get(pkgName);
if( pkgSet == null )
{
pkgSet = newPackageSet();
packagesMap.put(pkgName, pkgSet);
}
if( pkgSet.contains(cl) == false )
{
pkgSet.add(cl);
pkgNameSet.add(pkgName);
if( pkgSet.size() > 1 )
{
log.debug("Multiple class loaders found for pkg: "+pkgName);
}
if( trace )
log.trace("Indexed pkg: "+pkgName+", UCL: "+cl);
}
}
private static void addClass(String jarClassName, Map classNamesMap,
RepositoryClassLoader cl, boolean trace)
{
LinkedList ucls = (LinkedList) classNamesMap.get(jarClassName);
if( ucls == null )
{
ucls = new LinkedList();
ucls.add(cl);
classNamesMap.put(jarClassName, ucls);
}
else
{
boolean uclIsMapped = ucls.contains(cl);
if( uclIsMapped == false )
{
log.debug("Multiple class loaders found for class: "+jarClassName
+ ", duplicate UCL: "+cl);
ucls.add(cl);
}
}
if( trace )
log.trace("Indexed class: "+jarClassName+", UCL: "+ucls.get(0));
}
static class FileIterator
{
LinkedList subDirectories = new LinkedList();
FileFilter filter;
File[] currentListing;
int index = 0;
FileIterator(File start)
{
String name = start.getName();
boolean isWar = name.endsWith(".war");
if( isWar )
currentListing = new File[0];
else
currentListing = start.listFiles();
}
FileIterator(File start, FileFilter filter)
{
String name = start.getName();
boolean isWar = name.endsWith(".war");
if( isWar )
currentListing = new File[0];
else
currentListing = start.listFiles(filter);
this.filter = filter;
}
File getNextEntry()
{
File next = null;
if( index >= currentListing.length && subDirectories.size() > 0 )
{
do
{
File nextDir = (File) subDirectories.removeFirst();
currentListing = nextDir.listFiles(filter);
} while( currentListing.length == 0 && subDirectories.size() > 0 );
index = 0;
}
if( index < currentListing.length )
{
next = currentListing[index ++];
if( next.isDirectory() )
subDirectories.addLast(next);
}
return next;
}
}
static class ClassPathEntry
{
String name;
ZipEntry zipEntry;
File fileEntry;
ClassPathEntry(ZipEntry zipEntry)
{
this.zipEntry = zipEntry;
this.name = zipEntry.getName();
}
ClassPathEntry(File fileEntry, int rootLength)
{
this.fileEntry = fileEntry;
this.name = fileEntry.getPath().substring(rootLength);
}
String getName()
{
return name;
}
String toPackageName()
{
String pkgName = name;
char separatorChar = zipEntry != null ? '/' : File.separatorChar;
int index = name.lastIndexOf(separatorChar);
if( index > 0 )
{
pkgName = name.substring(0, index);
pkgName = pkgName.replace(separatorChar, '.');
}
else
{
pkgName = "";
}
return pkgName;
}
boolean isDirectory()
{
boolean isDirectory = false;
if( zipEntry != null )
isDirectory = zipEntry.isDirectory();
else
isDirectory = fileEntry.isDirectory();
return isDirectory;
}
}
static class ClassPathIterator
{
ZipInputStream zis;
FileIterator fileIter;
File file;
int rootLength;
ClassPathIterator(URL url) throws IOException
{
String protocol = url != null ? url.getProtocol() : null;
if( protocol == null )
{
}
else if( protocol.equals("file") )
{
File tmp = new File(url.getFile());
if( tmp.isDirectory() )
{
rootLength = tmp.getPath().length() + 1;
fileIter = new FileIterator(tmp);
}
else
{
InputStream is = new FileInputStream(tmp);
zis = new ZipInputStream(is);
}
}
else
{
InputStream is = url.openStream();
zis = new ZipInputStream(is);
}
}
ClassPathEntry getNextEntry() throws IOException
{
ClassPathEntry entry = null;
if( zis != null )
{
ZipEntry zentry = zis.getNextEntry();
if( zentry != null )
entry = new ClassPathEntry(zentry);
}
else if( fileIter != null )
{
File fentry = fileIter.getNextEntry();
if( fentry != null )
entry = new ClassPathEntry(fentry, rootLength);
file = fentry;
}
return entry;
}
InputStream getInputStream() throws IOException
{
InputStream is = zis;
if( zis == null )
{
is = new FileInputStream(file);
}
return is;
}
void close() throws IOException
{
if( zis != null )
zis.close();
}
}
private static class RepositoryClassLoaderComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
if (o1 instanceof PkgClassLoader)
{
PkgClassLoader pkg1 = (PkgClassLoader) o1;
PkgClassLoader pkg2 = (PkgClassLoader) o2;
RepositoryClassLoader rcl1 = pkg1.ucl;
RepositoryClassLoader rcl2 = pkg2.ucl;
int test = (pkg1.order - pkg2.order);
if (test != 0)
return test;
else
return rcl1.getAddedOrder() - rcl2.getAddedOrder();
}
else
{
RepositoryClassLoader rcl1 = (RepositoryClassLoader) o1;
RepositoryClassLoader rcl2 = (RepositoryClassLoader) o2;
return rcl1.getAddedOrder() - rcl2.getAddedOrder();
}
}
}
}