Loading an entire JAR via a classloader
Hi how would I load an entire JAR file via a classloader. Currently I'm able to load one file at a time (in this case org.w3c.dom.Node) as shown below:
import java.net.*;
public class MyJarLoader {
public static void main(String [] args) throws Exception {
URL[] urlsToLoadFrom = new URL[]{new URL("file:subdir3/xml-apis.jar")};
URLClassLoader loader1 = new URLClassLoader(urlsToLoadFrom);
Class cls1 = Class.forName("org.w3c.dom.Node", true, loader1);
System.out.println("Loaded '"+cls1.getName()+"'");
org.w3c.dom.Node Node = (org.w3c.dom.Node) cls1.newInstance();
Thanks
Figured this one out as below. Note this is the simplistic solution since it requires that the jar files be present in the classpath. If not, you will have to write your own loadClass method to read the data from the zip (& then can't use the method 'Class.forName()').
Regards
//Load Apache JAR files
URL[] urlArrToLoadFrom = new URL[]{new URL("file:xalan-j_2_5_0/xml-apis.jar"),
new URL("file:xalan-j_2_5_0/xercesImpl.jar"), new URL("file:xalan-j_2_5_0/xalan.jar")};
//Create a URLClassLoader to access jar files
URLClassLoader urlLoaderGeneric = new URLClassLoader(urlArrToLoadFrom);
//Foreach jar file, open, load class files & close
for(int i=0; i<urlArrToLoadFrom.length; i++) {
//Debug
System.out.println(urlArrToLoadFrom.toString());
//Open zip file
ZipFile zf = new ZipFile(urlArrToLoadFrom[i].getFile());
for (Enumeration enum = zf.entries(); enum.hasMoreElements();) {
//Get entry
ZipEntry ze = (ZipEntry) enum.nextElement();
//Only load if it's not a directory and it's a class file
int iIndexClass = -1;
if (!ze.isDirectory() && ((iIndexClass = ze.getName().indexOf(".class")) != -1)) {
//Remove .class & replace / with .
String strApacheClassName = (ze.getName().substring(0,iIndexClass)).replace('/','.');
//Load class file
Class classApache = Class.forName(strApacheClassName, true, urlLoaderGeneric);
System.out.println("Loaded '"+classApache.getName()+"'");
//Close zip
zf.close();
Similar Messages
-
Loading a jar via a custom classloader
Hi,
I have written a custom class loader that allows me to load a compiled java program as a collection of class files at runtime.
This is nice however I now need to consider the runtime execution of more complex java programs that have custom library dependencies.
This means loading a .jar library into the classloader. I can get the contents of a jar and load specific classes by name via reflection but I want to load the entire jar into the classloader so that its contents can be used 'as needed' much like a jar on the system classpath.
Is this possible? If so I would like to know how as I have been struggling with this problem and cannot see a solution.
Regards,
StephenHowever I still don't understand why you need to
actually load all those classes initially. Afterall,
URLClassLoader (which sounds a lot like what youare
describing) only loads classes as needed.i have just built a swing app that accesses an oracle
database, i jared together all the classes, and i did
something in the manfest file so that you can just
double clisk the jar and it fires up like an exe.
doing it this way everything is fine except it cannot
access the database, the reason is those oracle
classes are not loaded, even they are on the path - i
can run the app using a batch file but i dont like it
as it opens up a dos window. this is an example, as i
was told, where it is necessary to load all thoses
oracle database classes initially. Dear, daFei.
I believe that you are getting confused between the way the system will ignore that CLASPPATH environment variable when you run a java application packaged as a jar file with the -jar switch (the classpath for the jar can be set in the manifest) and what I am attempting to-do which is to run a compiled java program at runtime and dynamically load any dependant libraries.
Stephen -
Problem loading image (from JAR)
Hi
I was wondering why this code works when running the app in my IDE, but not once exported in a JAR file:
public static BufferedImage loadDefaultCover()
try
return ImageIO.read(new File("./images/default.png"));
}catch(IOException e)
logger.severe("Failed loading default img: "+e.getMessage());
return null;
} NOTE 1: The cover is located (project root)/images/default.png
NOTE 2: It works when I have a folder named images (with the image in it) next to the JAR.
NOTE 3: I tried:
return ImageIO.read(new File("images/default.png"));
return ImageIO.read(new File("/images/default.png"));Any ideas? Thanks!
Andrew
Edited by: Andrew_ on Jan 4, 2009 12:45 PMYou can't use File references to access resources in a jar file (technically, they are not presen in the file system but part of a zip file). Instead, you can load those resources via the classloader:
return ImageIO.read(getClass().getClassLoader().getResourceAsStream("images/default.png")); -
Hi all,
My question is can we load library from jar file using System.load() method.
ex:
myJar.jar
|
|----com.test.common.Util
which conatins a method to load library from jar file itself, before that i used to load from File
|---libraries/MozillaParser/......
Iam able load from Local system,
File parserLibraryFile = new File("libraries/MozillaParser" + EnviromentController.getSharedLibraryExtension());
File mozillaDistBinDirectory = new File("libraries/mozilla.dist.bin."+EnviromentController.getOperatingSystemName());
MozillaParser.init(parserLibraryFile.getAbsolutePath() , mozillaDistBinDirectory.getAbsolutePath());
but i am unable to load from jar file
URL url = ClassLoader.getSystemClassLoader().getResource("libraries/MozillaParser" + EnviromentController.getSharedLibraryExtension());
URL url1 = ClassLoader.getSystemClassLoader().getResource("libraries/mozilla.dist.bin."+EnviromentController.getOperatingSystemName());
MozillaParser.init(url.toString(), url1.toString());
Thanks in advance.That's a really confusing post.
The easiest way to make sure you can use the classes in a jar file is to copy the jar file to the "/jre/lib/ext" subfolder of your JDK. These classes will be visible to all applications. -
Problem loading image from jar file referenced by jar file
First, I searched this one and no, I didn't find an answer. Loading images from jar files has been pretty much done to death but my problem is different. Please read on.
I have my application, a straight up executable running from Eclipse. It uses a jar file, call it JarA. JarA launches a GUI that is located in another jar file. Call it JarB. To recap:
My application calls JarA -> JarA loads classes from JarB -> JarB looks for images to place in a GUI it wants to show on the screen
When JarB goes to load an image the following happens:
java.lang.NullPointerException
at sun.misc.URLClassPath$3.run(URLClassPath.java:316)
at java.security.AccessController.doPrivileged(Native Method)
at sun.misc.URLClassPath.getLoader(URLClassPath.java:313)
at sun.misc.URLClassPath.getLoader(URLClassPath.java:290)
at sun.misc.URLClassPath.findResource(URLClassPath.java:141)
at java.net.URLClassLoader$2.run(URLClassLoader.java:362)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findResource(URLClassLoader.java:359)
at java.lang.ClassLoader.getResource(ClassLoader.java:977)
at org.cubrc.gmshell.gui.MainWin.preInit(MainWin.java:152)
at org.cubrc.gmshell.gui.MainWin.<init>(MainWin.java:135)
The code from JarB that loads the image looks like this:
URL[] oSearch = {Main.class.getResource("images/")};
URLClassLoader oLoader = new URLClassLoader(oSearch);
imgIcon = new ImageIcon(oLoader.getResource("icon.gif"));
imgMatchRunning = new ImageIcon(oLoader.getResource("gears.gif"));
imgMatchStill = new ImageIcon(oLoader.getResource("gears-still.gif"));
imgMagnify = new ImageIcon(oLoader.getResource("magnify.gif"));This looks right to me and JarB certainly has an images directory with those files. But I'm in hell right now because I don't know where to place the images to make this work or if you can even attempt to load images with a dependency chain like this.
Any help very appreciated!Have you tried to move your image-files out of the jar file and place them in the sam folder as the jar-file? I think that would help.
When you try to load the image-file you get the NullPointerException because the program tries to read a file it can't find. Remember that a jar file IS a file and not a directory.
If you want to read somthing inside the jar-file you need to encode it first.
Have you tried to read the jar-file with winRar. It makes it easy to add and remove files in your jar-file. -
WAR meta-inf/manifest Class-Path jars use which classloader ?
If using an expanded EAR structure, my Web App requires some utility classes. I
can either put these in my :-
meta-inf/manifest.mf
Class-Path : utility.jar
OR
web-inf/lib
can contain the utility.jar
Is there any difference in terms of which classloader is used to load these classes,
the EAR/EJB classloader or the Web App child classloader ?
What is recommended ?If have found out the answer myself by testing it :-
A jar in the meta-inf/manifest.mf e.g. Class-Path : utility.jar
will be loaded by the EAR/EJB level classloader
whereas
web-inf/lib containing utility.jar
will be loaded by the Web App level child classloader.
Dimitri Rakitine <[email protected]> wrote:
I have this question too - it appears that 6.1sp2 attempts to use Class-Path
in jars in WEB-INF/lib - what this Class-Path: is supposed to do ???
Pete <[email protected]> wrote:
If using an expanded EAR structure, my Web App requires some utilityclasses. I
can either put these in my :-
meta-inf/manifest.mf
Class-Path : utility.jar
OR
web-inf/lib
can contain the utility.jar
Is there any difference in terms of which classloader is used to loadthese classes,
the EAR/EJB classloader or the Web App child classloader ?
What is recommended ?--
Dimitri -
Does resteasy API have class loader issues when using via OSGi
Does resteasy API have class loader issues when using via OSGi
Hi Scott,
THis isnt an answer to ur Question, but could u tell me which jar files are needed for the packages:
com.sap.portal.pcm.system.ISystems
com.sap.portal.pcm.system.ISystem
and under which path I coul dfind them.
Thnx
Regards
Meesum. -
Loading resources from jar - problem
I've got a problem when loading resources from jar.
My code:
package game.player;
import javax.swing.ImageIcon;
import java.awt.Image;
import game.map.Map;
import game.map.MapReader;
import game.emptyclass.EmptyClass;
import java.net.URL;
public class Data
ClassLoader cl = EmptyClass.class.getClassLoader();
Image image1 = new ImageIcon(cl.getResource("data/sprites/man6.png")).getImage();
Image image2 = new ImageIcon(cl.getResource("data/sprites/man5.png")).getImage();
Image image3 = new ImageIcon(cl.getResource("data/sprites/man4.png")).getImage();
Image image4 = new ImageIcon(cl.getResource("data/sprites/man3.png")).getImage();
Image image5 = new ImageIcon(cl.getResource("data/sprites/man2.png")).getImage();
Image image6 = new ImageIcon(cl.getResource("data/sprites/man1.png")).getImage();
public Image tile1 = new ImageIcon(cl.getResource("data/maps/test/tile1.png")).getImage();
public Image bg = new ImageIcon(cl.getResource("data/maps/default/bg.png")).getImage();
public Map map = new MapReader(cl.getResource("data/maps/test/test.map").getPath()).getMap();
public int getImageWidth()
return image1.getWidth(null);
public int getImageHeight()
return image1.getHeight(null);
}I get a NullPointerException.
Thanks in advance!Hi ,
getResource() method argument is not begin with the
character '/' , ex.
Image image1 = new
ImageIcon(cl.getResource("/data/sprites/man6.png")).ge
tImage();
I thought of that, but it's not applicable here because getResource is being called on the ClassLoader, not the Class. -
Data loaded to Power Pivot via Power Query is not yet supported in SSAS Tabular Cube
Hello, I'm trying to create a SSAS Tabular cube from a data loaded to Power Pivot via Power Query (SAP BOBJ connector) but looks like is not yet supported.
Any one tried this before? any workaround that make sense?
The final goal is pull data from SAP BW, BO Universe (using PowerQuery) and be able to create a SSAS Tabular cube.
Thanks in advance
SebastianSebastian,
Depending on the size of the data from Analysis Services, one work around could be to import the data into into Excel and then make an Excel table and then use the Excel table as a data source.
Reeves
Denver, CO -
Error while loading the runtime repository via HTTP
Hi Experts,
I am trying to delete an enhancement and when I enter the component name and the enhancement set in BSP_WD_CMPWB. I get the following error when right click the enhanced view and select delete : Error while loading the runtime repository via HTTP. How do I delete this enhancement?
Regards
Abdullah Ismail.if for some reason the runtime repository is not coherent, you get an error each time you try to read it (and this is the case when you open a component using the transaction BSP_WD_CMPWB)
this is because the XML file is interpreted by a CALL TRANSFORMATION statement, and any incorrect node will raise an uncaught exception
solution:
enhanced view is contained into BSP application you have created the first time you enhanced the component
go to SE80 and enter the BSP application where your objects are stored (the name you provided the first time)
there you can modify directly the objects, including the runtime repository which is stored under node "Pages with flow Logic"
once the correction is done, you can access again your component through transaction BSP_WD_CMPWB (and delete it properly if this is what you want to do) -
Batch loading with sdordf.jar.
Hi Guys
I have just tried a batch load with sdordf.jar.
In my first attempt there was a mistake in the n3 file.
After correcting the file and re running I now get the error.
Connecting to jdbc:oracle:thin:...........
Append mode
Copy existing data out
Just load triples into one column
Temporary table already exists!
java.sql.SQLException: ORA-00955: name is already used by an existing object
ORA-06512: at "MDSYS.SDO_RDF_INTERNAL", line 3326
ORA-06512: at "MDSYS.SDO_RDF_INTERNAL", line 3362
ORA-06512: at "MDSYS.RDF_APIS", line 786
ORA-06512: at line 1
Can anyone tell me what the name of this temporary table is, so that I can get rid of it.
Cheers
PhilHi Mellie
After having a little break I have installed the jena patch during which I had to drop the network and model created before.
I tried running a batch load as before but I still get the error message saying the temporary table already exists.
I tried the clean up routine as suggested but get the error.
SQL> exec sdo_rdf.cleanup_batch_load('researchdata')
BEGIN sdo_rdf.cleanup_batch_load('researchdata'); END;
ERROR at line 1:
ORA-13199: Batch load cleanup failed. ORA-00942: table or view does not exist
ORA-06512: at "MDSYS.MD", line 1723
ORA-06512: at "MDSYS.MDERR", line 17
ORA-06512: at "MDSYS.SDO_RDF", line 1016
ORA-06512: at "MDSYS.SDO_RDF", line 1022
ORA-06512: at line 1
I run it as mdsys as you said.
Any other suggestions?
Cheers
Phil -
I have loaded windows 8.1 via bootcamp on my macbook air 11 inch how can i adjust font size. I have to do a lot of work in office 2013 and it is very very difficult to see the screen.
Thank youMicrosoft store will provide a download manager (.exe) using your Product Key, which needs to be run on a PC. This manager will then let you download an ISO image to a USB and/or DVD.
-
How to load an applet jar file?
Hello everyone,
I have an applet that uses my own jar file and approximately 6 third party jar files. I set up jar indexing (jar -i) which will download the jar files when they are needed. All seems to work well, but now I want to manually load the jar files which I cannot get working.
When the applet starts, about 1/2 of the jar files are downloaded (because they are needed at startup). I then want to load the additional jar files in the background, after the gui is initialized. I have tried this using the below thread which is executed from within the applet's start method:
// Try to load additional jar files in background by loading a class from each jar file.
Thread loadClass = new Thread() {
public void run() {
System.out.println("Loading classes...");
try {
// Tried loading classes this way, doesn't work.
getClass().getClassLoader().loadClass("pkg1.Class1");
getClass().getClassLoader().loadClass("pkg2.Class2");
getClass().getClassLoader().loadClass("pkg3.Class4");
getClass().getClassLoader().loadClass("pkg4.Class4");
/* Loading classes this way doesn't work either.
Class.forName("pkg1.Class1");
Class.forName("pkg2.Class2");
Class.forName("pkg3.Class3");
Class.forName("pkg4.Class4");
catch(ClassNotFoundException e) {
// First attempt to load a class (pkg1.Class1) throws exception.
System.out.println("Can't find class: " + e.getMessage());
loadClass.start();As you can see from above I am trying to load a class from each of the jar files so that the jar files would load into memory/cache. Unfortunately, it cannot find the classes. These are the errors from the java console:
Loading classes...
Loading: pkg1.Class1
Connecting http://my.server.com/my_dir/pkg1/Class1.class with no proxy
Connecting http://my.server.com/my_dir/pkg1/Class1.class with cookie "JSESSIONID=some_big_long_char_list"
Can't find class: pkg1.Class1
So it appears the jar file is not being downloaded. When I take away the dynamic jar loading (removing the "jar -i" & adding them all to the applet archive list) the thread executes correctly. So I know the class names, etc, are correct. How does one load an applet jar file?
Any help/suggestions are appreciated.The above error I posted was because I forgot to index the jar files. That is why it couldn't find the jar file. I thought I was getting farther along with my problem, but I apparently just forgot to index the jars. I am now getting the problem that I got yesterday...
The applet freezes/hangs when it hits the thread. The GUI never opens (even though I'm running this thread right after the gui shows). The java console quits responding and the applet just stays the grey screen. I also tried the invoke later that you suggested.
public void start() {
// ...initialize gui...
// Applet freezes and remains grey, also the java console freezes.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Loading classes...");
try {
// When I comment out the below forName calls, the thread will still run evidenced through the done print statement.
Class.forName("pkg1.Class1");
Class.forName("pkg2.Class2");
Class.forName("pkg3.Class3");
Class.forName("pkg4.Class4");
System.out.println("...Done loading classes");
catch(Exception e) {
System.out.println("Can't find class: " + e.getMessage());
} -
If my FXML und image files are in a JAR-file then I have the Exception:
Caused by: java.lang.IllegalArgumentException: URL must not be empty
at javafx.scene.image.Image.validateUrl(Image.java:966)
at javafx.scene.image.Image.<init>(Image.java:611)
at com.sun.javafx.fxml.builder.JavaFXImageBuilder.build(JavaFXImageBuilder.java:27)
My FXML file:
<Button>
<graphic>
<ImageView>
<image>
<Image url="@/images/Printer_48.png" />
</image>
</ImageView>
</graphic>
</Button>
Is there a Problem with the JavaFXImageBuilder which can't not load Images in JAR files?In jars it is case-sensitive:
<Image url="@/images/myImage.png"/>
is not the same as
<Image url="@/images/myImage.PNG"/>
Edited by: 961538 on Sep 27, 2012 4:03 AM -
There is not enough free memory to load the entire file
I saw an older reference to this error in a previous post which apparently got resolved, but didn't explain precisely how it got resolved:
Michael Kitzmiller, "There is not enough free memory to load the entire file" #, 27 Jul 2007 5:23 am
I presume that one answer is to rebuild the document from scratch, changing imported images to referenced images. But I want to recover the file as I put hours of work into it and expected that anything I can save that I also should be able to read back in. I will certainly change to referenced images, but I have to be able to open it first.
thank youWeb...
Here is a smattering of ideas.
Do you have ample unused HDD space? If not, defrag it, although in myu experience, this hardly makes a difference. Check your TEMP/TMP folders and clean them out. Consider downloading cCleaner and running it. Do everything you can to make ample room on your HDD and in places like your TEMP folders. If your HDD is congested, temporarily remove big but relatively unimportant applications and move data elsewhere for a while.
Even with 4GB of RAM, Frame can only use somewhere between 2.7 - 3.2 GB of it under the very best of conditions, and that includes the application as well as the files. Unpacking image files can consume considerably more space than it takes to store them. For example, a 1024 x 768 color image requires more than 3.1MB to describe it as a 32-bit color image, yet when stored in JPEG format, it can be as small as 50kB, a compression of 65:1. Of course, it's not reasonable to assume that your document is comprised entirely of such highly-compressed images, but in the unachievable extreme, it would take 980MB to simultaneously open 15MB worth of those kind of files. The point here is to not fall into the trap of thinking a 15MB file comprising a lot of images needs little more than 15MB of RAM.
Make sure ALL other applications are closed when trying to open your file...Outlook, IE or FireFox, Anti-Virus and Spyware apps, Word, etc.
Consider sending a copy of the file to someone else to see if they can open it for you and delete some of the images before resaving it. If you have a backup copy, rename your current file and restore the backup. Maybe your working copy is corrupt. Who knows? Anything is probably worth trying as long as you have a save copy stored somewhere.
Dennis...
Maybe you are looking for
-
Report needed to conbine stock movement and corresponding balance
Hi Friends, End user need a report to show stock movement trasaction and it's coresponding stock balance. In MB51, we can see all the stock movements against one material, is there any way a report could show stocks' corresponding iventory balance un
-
I've recently started using my first Mac, and I hooked my work email (Forwarded to Google Mail) and my personal email (Gmail) into the MacOSX mail client. Everything seemed to be going smoothly, until I noticed that sent mail from my work email throu
-
Error message cancelled disk burn error 4000 unknown error
i have burned music before now all of a sudden this error message comes up about not being able to burn the disk with an unknown error the only thing i can think of is that the other day i made a back up of my library that i know is the only thing th
-
Create failover cluster to host Windows 2012 DC, Exchange 2013 and SQL as VMs
One of our clients has running Windows Essential 2012, SQL and exchange 2007 as VM on VMware for 4 years without major issue. However, the physical server is getting old and have some hardware issues recently. They have budgets to buy two Dell server
-
Converting SWF file for publication and secure distribution.
I'm looking for advise on how to securely publish .swf files created in inDesign CS6 How to build a launcher and how to convert into iPad and Android apps.