error when running from jar - reflection class.forname exception - java

I am doing a project in java and all things were working great until i tried to run my program from the jar file. I managed to locate the problem and it goes like this:
I tried to implement a plug-in based methodology. I have a conf file from where i read the paths for the classes i want to use, and then i load them dynamically with class.forname. This is my code if it helps:
for (i=0; i<classPathsArray.size(); i++) {
Class c = Class.forName(classPathsArray.get(i)); //error line
Object class2Add = (LibraryWrapper)c.newInstance();
wrappers.add((LibraryWrapper)class2Add);
}
the library paths are something like: "path.path.path.path.className" and they seem ok either i run my project from an IDE or from the jar (when i am saying "seem ok" i mean that they are exactly what is written to the file).
I indicate the exact line that creates the exception and here is a snapshot of the exception i get:
I emphasize (again) that things are ok when execute my project from IDE, the problem is when i run it from jar which is in the dist folder.
Does anyone know why i have this problem and how to fix it?
PS: All my classes are in the "Source Packages" Folder

NoClassDefFoundError occurs due to incomplete classpath. Make sure all your required jars are in classpath before running jar file. If you are creating an executable jar file then you can define your classpath in manifest file something like this:
Class-Path: servlet.jar infobus.jar
Hope this helps.

Related

How to export to a runnable jar with Proccessing (Eclipse)

I have tried to export my processing applet to a runnable jar file from eclipse (which I am using to code it) and it exports successfully but when opened just causes a blank (grey) screen. If I run it with command prompt I get this error:
java.lang.NullPointerException: Cannot invoke "String.contains(java.lang.CharSequence)" because "jarPath" is null
When I extracted the jar sample the folders and directories seem to be incorrect too.
before
(the dependencies are in the dependencies folder)
after
(the dependencies are outside of the now missing dependencies folder)
I'm sure its an issue with the file structuring on generation, more specifically the dependencies. when I run it as an application eclipse it runs perfectly fine with no exceptions.
Full message:
java.lang.NullPointerException: Cannot invoke "String.contains(java.lang.CharSequence)" because "jarPath" is null
at processing.core.PApplet.dataFile(PApplet.java:7673)
at processing.core.PApplet.dataPath(PApplet.java:7650)
at processing.core.PApplet.createInputRaw(PApplet.java:6741)
at processing.core.PApplet.createInput(PApplet.java:6659)
at processing.core.PApplet.loadBytes(PApplet.java:6959)
at processing.awt.ShimAWT.loadImage(ShimAWT.java:384)
at processing.core.PSurfaceNone.loadImage(PSurfaceNone.java:61)
at processing.core.PApplet.loadImage(PApplet.java:5311)
at processing.core.PApplet.loadImage(PApplet.java:5296)
at net.turke1034.shootergame.game.ShooterGame.draw(ShooterGame.java:55)
at processing.core.PApplet.handleDraw(PApplet.java:2201)
at processing.awt.PSurfaceAWT$10.callDraw(PSurfaceAWT.java:1422)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:354)
java.lang.NullPointerException: Cannot invoke "String.contains(java.lang.CharSequence)" because "jarPath" is null
at processing.core.PApplet.dataFile(PApplet.java:7673)
at processing.core.PApplet.dataPath(PApplet.java:7650)
at processing.core.PApplet.createInputRaw(PApplet.java:6741)
at processing.core.PApplet.createInput(PApplet.java:6659)
at processing.awt.ShimAWT.loadImageIO(ShimAWT.java:454)
at processing.awt.ShimAWT.loadImage(ShimAWT.java:439)
at processing.core.PSurfaceNone.loadImage(PSurfaceNone.java:61)
at processing.core.PApplet.loadImage(PApplet.java:5311)
at processing.core.PApplet.loadImage(PApplet.java:5296)
at net.turke1034.shootergame.game.ShooterGame.draw(ShooterGame.java:55)
at processing.core.PApplet.handleDraw(PApplet.java:2201)
at processing.awt.PSurfaceAWT$10.callDraw(PSurfaceAWT.java:1422)
at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:354)
I have tried the same thing with a test project that requires no dependencies, and it runs as expected (when run in command prompt)
had the same issue, so troubleshooted for a while until i found the following solution. i'm assuming that you are using a data file similar to the data file in Processing projects to contain your dependencies.
in Eclipse, export as a runnable jar and select the option "Extract required libraries into generated JAR". once the jar is created, put this jar into a new folder. put your data folder into this folder as well. this worked for me.
no idea why this works - just threw stuff at the wall until this stuck. one troubleshooting technique i used was making a printwriter before loading any data so i could see where the computer was searching for the dependencies. the snippet below outputs the file to the same place that Processing looks for data.
PrintWriter pw = createWriter(dataPath("test.txt"));
pw.print("over here");
pw.close();
i used this in combination with dataPath("") to find that it was looking for dependencies outside of the jar.
In the past (older answer here) I had success exporting runnable .jar projects from eclipse which use Processing's libraries by using the Copy required libraries into a sub-folder next to the generated jar option in Runnable Jar File Export options:
This made it easier to debug java classpath issues (-cp flag when running from command line) and native library paths(-D.java.library.path command line flag).
If you're using java packages remember to specify them in PApplet.main():
public static void main(String[] args) {
PApplet.main(ShooterGame.class.getCannonicalName());
}
The above is useful only if you can't execute the jar files due to missing libraries (class not found, missing native libraries, etc.)
Regarding loading external assets, as Shivoum B mentions, you can make use of dataPath() but also sketchPath().(See this similar answer).
Without seeing the path to the loadImage() call you're making I can only make assumptions, but you might be able to get away with something like this in ShooterGame.java:
loadImage(sketchPath("data" + File.separator + "yourImageName.png");
(Off-topic, if I read this correctly you're trying to load images in draw() ?
I'd recommend loading all assets in setup() once instead of multiple times in draw(). A special case might be with the loading large assets that take time and using P2D or P3D where the OpenGL context setup might time out (in which you can load in draw() but should use a "debouncing" boolean to ensure assets are loaded only once)

Running .jar File Java 8

I've run .jar files before, but I've encountered a "different" situation, and I'm not sure what to do. I'd appreciate if someone could help me out.
Previously, I programmed with Java 6 and Eclipse Juno exported all my programs to runnable jar files. I'd get a .jar file that I could run by just double clicking on it. The files always looked something like this (note the jar file icon):
Recently, I wrote a program in Java 8 with Eclipse Luna (Release 4.4.0) and exported it to a runnable jar file, and I got something different (note the different file icon):
It no longer runs when I double click it. Instead, my computer uncompresses the jar, as it would a zip file. I tried running it from terminal. I cd'd to the directory and typed
java -jar graph3D.jar
I got the following error message:
Error: Unable to access jarfile graph3D.jar
After uncompressing the jar file, I found a folder named META-INF with the manifest file, MANIFEST.MF in it. It was the only file that seemed to resemble an executable file. Do I have to do something with that?
Could someone explain how I can run the second jar file graph3D.jar? Is it something new with Java 8, or something different about Eclipse Luna, or something else?
(Both programs run fine in Eclipse, by the way)
Thanks for your time and help.
Edit:
Below was the dialog box Eclipse displayed if anyone is interested.
Selecting "Use .jar;.zip" makes the filename "graph3D.jar;.jar;*.zip" .
Selecting "Use .zip" makes the filename "graph3D.jar;*.zip"
Selecting "Cancel" doesn't let you go forward.
You'd have to manually delete the extra file extension.
Somehow when you exported the file, the filters for the file dialog box (*.jar;*.zip) got attached to the filename, which is graph3D.jar;*.jar;*.zip, not graph3D.jar. Java can't find it because it doesn't have the name you supplied. Rename the file and pay close attention next time you export; either you fat-fingered something, or you're triggering a significant bug that needs fixing.
I recommend that you will access the build folder after you've built your project on the IDE under your project folder (in your workspace) and copy both the libraries folder and the .jar and post them wherever you want the program to be "installed", you'll then have an executable jar that should run smoothly without problems, just as I said don't forget the lib folder.
I think there is nothing new in Java 8 related with the running jar, I guess you need to check the the Eclipse export issues, it seems your classes are missing from your second jar file.

java.lang.NoClassDefFoundError with jar files

Uploaded a jar file from my computer to a server and tried to run it. When I run it I get java.lang.NoClassDefFoundError and it seems to be related to the twitter4j jar that my main method depends on.
However, I have this jar file in my libraries so shouldn't this be included when I build my code in to a jar? Here's a pic in case it helps.
is the error that I'm getting. (can't upload a pic just yet.
Not sure what this has to do with twitter, but anyway, the issue is that you do not have the correct class files. In other words, when you are running your fat JAR in the command prompt, you do not have any libraries exported with it (Or if you do, you don't have that specific one).
Sometimes such an error can be because there is an incorrect version of java, however that is not the case here since java has got no "twitter" packages or classes in it.
Using something like JarSplice would fix this.
Assuming you did not package the twitter4j classes inside your application jar, you need to tell Java where it can look for classes that are not inside your application jar. You typically use the classpath flag for that. In your case, it should look something like
java -cp /tmp/twitter4j.jar -jar /tmp/myapp.jar
An alternative would be to package all twitter4j's classes inside your application jar. This is called a 'fat' jar. How to make one depends on how you build your application jar.
The JAR file that you are trying to use needs to be in the classpath. This can be done by using the -cp attribute from the command line. However, when using java -jar, you cannot use the -cp attribute.
To get around this, you can do the following:
java -cp /tmp/myapp.jar;\path\to\external.jar com.example.package.MyClass
where MyClass has the main() method defined.
Alternately, you can specify jar files on the classpath using the manifest.mf file. See http://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html for details.

Use project's own .java files as resource files

I have made a small program in Java that displays its .java source with a gui. It does not use FileChooser to do this. I am reading the .java sources with the aid of following statements
String resName = "/dev/classes/"+name+".java"
Scanner s = new Scanner(FilePrinter.class.getResourceAsStream(resName));
where name is the name of the .java file i.e. if the file is MyProg.java then name==Myprog. Of course my program is inside the dev.classes package
The thing is that when I export my project to JAR and include source files this works because source files reside inside the /dev/classes/ directory.
However, I haven't yet discovered a way to make my program run in Eclipse or from the command line without giving me exception.
And of course when someone tries to add those source files to be used automatically as resource files the process fails.
Can I somehow use the same code both when running from Eclipse and from the JAR? It must be something very trivial but because I am not Java expert I cannot see.
I found how to do it. Actually you either have to use Ant or Maven. However, this can be done in Eclipse as well as follows:
On the Eclipse Project Properties>Java Build Path you can choose on the bottom Default Output folder: <your_project_name>/src.
This causes class files be compiled in the same directory as the .java files and finally does what I wanted.
Thanks to #AndrewThompson for suggesting to try this

.Jar file, created by netbeans doesn't open anymore on windows

For some reason, my application stopped working when I used "clean and build" at NetBeans and try to run it from dist folder. Application used to open from the jar file, but now it only blinks, and even doesn't give any error messages. Application runs, if I test run it with F6 using NetBeans. Jar file is created by NetBeans, so I guess the manifest should be okay.
Here's the link for the jar file...
Executing the jar in the terminal gives this exception trace:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:155)
at tbs.ImageLoader.loadImage(ImageLoader.java:11)
at tbs.Flag.<init>(Flag.java:21)
at tbs.Model.<init>(Model.java:58)
at tbs.GameView.<init>(GameView.java:33)
at tbs.GUI.<init>(GUI.java:36)
at tbs.Main.main(Main.java:6)
So it looks like you had something like this here:
public Image loadImage(String name) {
return new ImageIcon(getClass().getResource(name));
}
... and the getResource() method returned null, which caused the ImageIcon constructor to throw the Exception.
In line 21 of Flag.java you used "images/flagNeutral.png" as the image string, but your jar file contains images/flagneutral.png (inside the tbs directory). See the difference?
If it worked on your local system outside of the jar, you are using a case-insensitive file system there. (Windows or Mac?)
In the jar, as well as over HTTP and on "real" file systems, the URLs are case sensitive, which means you have to name the resource precisely as the file is named.
And yeah, normally you should have at least tried your program yourself, and posted the stack trace as well as the relevant code lines.
There may be a lib folder in the dist directory. If so, it contains jar files for any libraries you included. Make sure that is the case. You need to distribute the jar as well as the entire lib folder and store both in the same folder just like Netbeans creates them.
I am hoping you have created a Java application project and not a Java Class library project.
You can check if the main-class attribute and any library paths are added properly when you "clean and build" the project.
You can run it like java -jar tbs.jar and see the response.
Typical error when you don't define the main class before clean and run.
Click right on the project -> properties ->run section ->define the main class.

Categories