aspose file tools*
The moose likes Java in General and the fly likes Loading classes from a jar which are not in ClassPath Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Loading classes from a jar which are not in ClassPath" Watch "Loading classes from a jar which are not in ClassPath" New topic
Author

Loading classes from a jar which are not in ClassPath

ravi D shankar
Ranch Hand

Joined: May 27, 2005
Posts: 41
Hi
I am trying to load classes in a jar file which is not in the ClassPath and read a static final variable in it .I have succeeded in doin that by unjaring the jar in temporary directory and then loading each class and reading the variable.I have written a standalone program that is running fine ....but when i use those methods from a jsp then I am getting an Servlet exception at point of reading the variable ...I dont understand what is the problem ....its working fine for a stand-alone program but not when I use methods in a web-based system....plz help in this regard...servlet exception is occuring that the point of reading the field that means after loading the class....bye ..thanx

public static void getDetails(String name,MapList dataList) throws Exception
{

try
{
if(name.endsWith(".jar"))
{

File topDir = new File("D:\\");
File tempDir = null;
boolean dirFlag = (new File(topDir,"temp1")).exists();
if(!dirFlag)
{
(new File(topDir,"temp1")).mkdir();
tempDir = new File(topDir,"temp1");
}
else
{
deleteDir(new File(topDir,"temp1"));
getDetails(name,dataList);
}
JarFile jarFile = new JarFile(name);
Enumeration entries = jarFile.entries();
while(entries.hasMoreElements())
{
JarEntry entry = (JarEntry)entries.nextElement();

if(entry.isDirectory())
{
(new File(tempDir,entry.getName())).mkdir();
continue;
}
copyInputStream(jarFile.getInputStream(entry),
new BufferedOutputStream(new FileOutputStream(new File(tempDir,entry.getName()))));
}
jarFile.close();


URL url = tempDir.toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
getAllFiles(cl,tempDir,dataList);

boolean flag = deleteDir(tempDir);

if(flag)
{
System.out.println("Directory deleted");
}
else
{
System.out.println("Directory could not be deleted");
}

}
else if(name.endsWith(".class")) {

}
}
catch(Exception e)
{
e.printStackTrace();
}

}

public static void getAllFiles(ClassLoader cl,File tempDir,MapList dataList) throws Exception
{

if(tempDir.isDirectory())
{
String[] children = tempDir.list();
for (int i=0; i<children.length; i++) {
getAllFiles(cl,new File(tempDir,children[i]),dataList);
}
}
else
{
if(tempDir.getName().endsWith(".class"))
{

String filePath = tempDir.getAbsolutePath().substring(0,(tempDir.getAbsolutePath().length()-6));
String[] fileArray = filePath.split("\\\\"); //for only windows
String packagePath="";
for(int i=(fileArray.length-1);i>1;i--)
{
packagePath=fileArray[i]+"."+packagePath;
}

packagePath = packagePath.substring(0,packagePath.length()-1);
loadClassFile(cl,packagePath,dataList);

}
}
}
public static void loadClassFile(ClassLoader cl,String className,MapList dataList)
{

try
{
Class cls = cl.loadClass(className);
String strValue="";
String archiveName="";
String revision="";
String lastmodified="";
String author="";
try
{
System.out.println("loaded "+className);
Field sourceControl = cls.getField("SOURCE_CONTROL");
strValue = (String)sourceControl.get(null);
String[] values = strValue.split(" ");
archiveName=values[1].trim();
revision=values[2].trim();
lastmodified=values[3].trim();
Date d = dateFormat.parse(lastmodified);
lastmodified = sdf.format(d);
author=values[4].trim();
}
catch (Exception e)
{

strValue= "does not exist";
archiveName="does not exist";
revision="does not exist";
lastmodified="does not exist";
author="does not exist";

}

HashMap map = putMapValues(className,archiveName,revision,lastmodified,author);
dataList.add(map);
}
catch(Exception ex)
{
HashMap map = putMapValues(className,"cant find","cant find","cant find","cant find");
dataList.add(map);

}
}
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

What line does it fail on?
Does your app server/servlet container have a SecurityManager running? eg what happens if you try to create a file in the same location? (ClassLoaders and File access require different priviledges, but it's a useful test)

It would be easier to see what was happening if you formatted your code using the [code] and [/code] tags.

Dave
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

...and welcome to the Ranch!
ravi D shankar
Ranch Hand

Joined: May 27, 2005
Posts: 41
Hi
The program is failing at the line

" Field sourceControl = cls.getField("SOURCE_CONTROL"); "

in the loadClassFile method.Nothing is getting executed after this line.
The class is getting loaded but it is failing when I try to access the variable.Different classes are giving different exceptions.Its working fine in standalone mode but when I try to use in functions in web-based mode then each class throwing diffrent exceptions when I try to access the variable.
The application is deployed on tomcat 4.1.24 on my windows machine..calling methods from a jsp ....dont know about the Security Manager.....
ravi D shankar
Ranch Hand

Joined: May 27, 2005
Posts: 41
the files are getting unjarred ..thats not a problem ...I dont know how thats related to security manager ....As a stand-alone the methods are working perfectly ...everything happening smoothly after keeping some dependent jars in CLASSPATH...but I am not sure Why it isnt working with tomcat or jsps
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459



You gobble up the thrown exception, but any chance you can tell us what it is? Are you sure there is a VERSION_CONTROL field in the loaded class?
bparanj
Greenhorn

Joined: May 27, 2002
Posts: 27
Sounds like some class loader issue. You might find this article helpful :

http://www-128.ibm.com/developerworks/java/library/j-onejar/


Moderator : <a href="http://groups.yahoo.com/group/OOAD_UML/" target="_blank" rel="nofollow">http://groups.yahoo.com/group/OOAD_UML/</a> <br />Home : <a href="http://www.zepho.com" target="_blank" rel="nofollow">http://www.zepho.com</a>
ravi D shankar
Ranch Hand

Joined: May 27, 2005
Posts: 41
hi
If the version control field isnt there its going to throw some exception for which I am just assing values to the variables which will be stored in a map.I am just going to display this in a report .Thats all.The whole thing about this program is to check whether the field exists or not in a class or classes in a jar or in a jsp.I am only failing when I run the methods in a web-based application using jsps ....but it works perfectly when I run that in a stand-alone mode using main(String args[]).

When I use the methods from a jsp .I get some

java.lang.NoClassDefFoundError: javax/mail/MessagingException for the first class

I dont have the source of the class file thats why I am not able analyze how the class is dependent on the above error.I have put every jar file in CLASSPATH but its still the same result with a jsp but in a stand alone mode its working perfectly fine.
Please help in this regard.
Bye
Ravi
Mark Wuest
Ranch Hand

Joined: Jun 07, 2003
Posts: 88
Originally posted by ravi D shankar:
...but it works perfectly when I run that in a stand-alone mode using main(String args[]).

When I use the methods from a jsp .I get some

java.lang.NoClassDefFoundError: javax/mail/MessagingException for the first class



Can I take a stab that it might be unrelated to your code, but that the tomcat container just needs to make sure it has mail.jar (and perhaps activation.jar - IIRC, some parts of mail need activation) in its classpath. Honestly I'd have thought it already did (but maybe not, since it's just servlets and not the whole enchilada).

Mark
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Sounds likely. You may also be able to change yor code so it doesn't resolve them as they are loaded, but I believe Mark's point is the thing to try first.
Karan Chandra
Greenhorn

Joined: May 17, 2005
Posts: 6
I too agree with Mark, and David,
If you have ur .jar files in classpath, please check the versions of the .jar files that you are using.

Thanks & Regards,
Prasad
ravi D shankar
Ranch Hand

Joined: May 27, 2005
Posts: 41
Hi guys
Thats great to see so many suggestions...thanx
I am using tomcat 4.1.24 on Windows 2000 ....I have put each and every jar from tomcat/common/lib in user defined CLASSPATH variable ....it includes mail.jar and others.....
When I was running the class in stand-alone mode ...it was giving the same errors ...but when I put mail.jar and other jars in classpath ...it started working.....but in tomcat it isnt even though each and every jar is in the CLASSPATH....am I missing something? is there something related to tomcat that I have to check?....I am not able track the reason for errors occured ....

And I am not changing the code when I am using it from a jsp....They are all static methods with parameters of a string or file object and a list to store details....From a jsp I am just taking a string parameter and passing it to the methods along with a List .....and later I will be just iterating the List to print details...Thats all...bye
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

web applications don't use the system defined classpath, they use a classpath specified by the app server. This allows several web apps in the same container to see different code-bases and run differently.
There are ways around this, and you can set things up to make JARs common to all web apps in a container, but in general you don't since it is better to have each as a completely separate entity, even if they are running in the same container.

Dave
ravi D shankar
Ranch Hand

Joined: May 27, 2005
Posts: 41
Hi guys
Thanx Dave
Can anyone help me in setting a appserver specific or an webapp specific classpath.My appserver is tomcat 4.1.24 on windows 2000....I have been using it since a lot of time...but I never knew that there are also container specific Classpaths ...Thanx for your information...I have been googling for that settings but I ahvent able to find till now...Can anyone help me to find a source for the specific classpath settings....
Thanks
Bye
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

The 'best' way to make code available to a web application (according to my own preferences) is to place ay JARs for a web app in the WEB-INF/lib directory. If the directory doesn't exist, just create it and drop the JARs there. When the container starts and loads the web app, it will see the JARs here and make them available to the web app. It also means that the 'classpath' for this web app is completely controlled by this directory. You can also places classes in the WEB-INF/classes directory in the same manner.

Another way in Tomcat is to place JARs in the <tomcat home>/common/lib. THis make the JARs available to all weapps running in that container. THis causes problems if you need different versions or have ClassLoader heirarchy requirements (we won't cover this here).

You can also place JARs in the <java home>/jre/lib/ext directory and the JAR will be available to every java app that runs using that Java version. I tend recommend avoiding this at all costs but there are situations where it is required.

I hope this clears things up for you a little.

Dave
ravi D shankar
Ranch Hand

Joined: May 27, 2005
Posts: 41
Thanx Dave ....I already follow the same thing that you have said ....But it was giving me the same problem......

What I did was to check the CLASSPATH settings that tomcat initialises when it starts up ....in windows when it starts up it executes Catalina.bat and then Catalina.bat executes setClassPath.bat .....in setClassPath.bat it only takes the tools.jar library into the ClassPath.....So I just appended the remaining jars to this line in that file and it started working fine....if I miss some library I just add it to that line ...now its working fine and probably continues to work

I have read somewhere that tomcat doesnt cache the libraries in common/lib ...I dont know till what extent this is true.....

I have atlast got it(probably....) .....Thanx Java Ranch and all you guys

I will be back if my problem persists or I get some more peculiar cases...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Loading classes from a jar which are not in ClassPath