Netbeans-NullPointerException: Location is Required - javafx

Exception in Application start method
java.lang.reflect.InvocationTargetException
Caused by: java.lang.NullPointerException: Location is required.
These were the errors I got after compiling my code. My code is pretty simple and looks like this. I'm using net beans to compile this if that helps. Thanks!
Edit: Took out .getClassLoader() and nothing happened. Same errors.
My file place:
fx:controller="test.FXMLDocumentController
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("FXMLDocument.fxml"));

You need to do getClass().getResource("FXMLDocument.fxml"). What're you're asking for is a file in a path relative to the classloader, that's not what you want.
Also make sure that NetBeans is copying the fxml-file to your build directory. Maybe it's just copying class files, not resources by default?

Related

Error while running JavaFX from terminal - Could not find or load main class

Need some clever advice to solve this - well, some kind of problem while using simple JavaFX app.
However, there was some problems while all is set-up (module path, for example), but what now when I just cannot run .jar file from terminal? Ok, start talk about mission-impossible-with-javafx:
I got Apache NetBeans 12 installed on Linux Mint 20. JDK is already installed, so 'java -version' returns 'openjdk version "11.0.7" 2020-04-14'...
When start project there is no problem at all - JavaFX app works.
I need this app to work on Windows 8.1, but before that I tried to run this .jar file on my linux terminal using java -jar MyFile.jar.
Here the problem starts: it said no main manifest attribute, in MyFile.jar.
Then I decide to set the main class directly in jar file (opened using Archive Manager):
MyFile.jar -> META-INF -> MANIFEST.MF and add on last line: Main-Class: mypackage.MyClass
Now I have: Error: Could not find or load main class mypackage.MyClass Caused by: java.lang.NoClassDefFoundError: javafx/application/Application
Ok, how and why?
Just to said that in NetBeans I also set main class in:
Project -> Properties -> Run -> Main class: mypackage.MyClass
and in VM options I added:
--module-path "/locationToJavaFX/javafx-sdk-11.0.2/lib" --add-modules javafx.controls,javafx.fxml
In pom file, main class is also set (generated by IDE):
// other lines
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.4</version>
<configuration>
<mainClass>mypackage.MyClass</mainClass>
</configuration>
// other lines
and module-info looks like:
module mypackage {
requires javafx.controls;
requires javafx.fxml;
requires org.jsoup;
opens mypackage to javafx.fxml;
exports mypackage; // some people advice without this line, I tried but same problem
}
Just want to be clear - I tried probably everything (I don't count) that is available here on stackoverflow. I try to fix this yesterday and today (almost 2 whole days) and I can't.
Just a thought: Java programming is not so difficult as configuration is.
Cheers and thanks for helping!
EDIT:
Just to said that I tried what José suggested : first creating launcher class, follow 'fat jar' step-by-step then run 'semi-fat jar' command which he added to the post. Interestingly enough, this return me: Error occurred during initialization of boot layer java.lang.module.FindException: Module javafx-fxml not found. Why not found javafx-fxml if I aready defined it as said above in question? Also, why Netbeans doesn't provide me the main class in manifest (in jar) file? When I add main class in manifest, I get this:
Exception in thread "main" java.lang.NoClassDefFoundError: javafx/application/Application
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1017)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:800)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:698)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:621)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:579)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at Main.main(Main.java:5) Caused by: java.lang.ClassNotFoundException: javafx.application.Application
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 10 more
Ok, how Application does not found? :)
EDIT 2:
Yeap, mister José has a right. This command in his 'semi-fat jar' post actually works BUT not for Maven (I use it on same Ant project and it works). Maven somehow cannot recognize JSoup class (even I add it in dependency) and java returns:
Exception in Application start method Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:834) Caused by: java.lang.NoClassDefFoundError: org/jsoup/Jsoup
at p.eis.GetData1.startIt(GetData1.java:34)
at p.eis.GetData1.<init>(GetData1.java:28)
at p.eis.SampleController.initialize(SampleController.java:37)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2573)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
at p.eis.Start.loadFXML(Start.java:32)
at p.eis.Start.start(Start.java:19)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)
... 1 more Caused by: java.lang.ClassNotFoundException: org.jsoup.Jsoup
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 17 more
Hope I'll find solution for Maven projects in the near future.
Yeah I noticed you use maven but it's not fault of maven, I know why this happen and i have solution about it so in my solution there is magic and work fine because i use my solution to make jar and you know my jar file run without terminal(means double clicking on jar file)
Solution
you need winRar because i use it for info read my solution!
Just follow below step with images to run jar(both maven and gradle project)
solution of Error: Could not find or load main class mypackage. this line
you created main class at this location /src/main/java/YOUR_PACKAGE_NAME/Main.java so while creating jar file intellij couldn't care your main class if you create main class at above location and it doesn't add Main-Class: Main this line in Manifest File Solution is that create one more main class(don't delete Main.Java class we use this class in new one main class) at this location /src/main/java/EntryPoint.java see below image and code what i did
EntryPoint.java is new main class (IMAGE)
public class EntryPoint {
public static void main(String[] args) {
smartSeizeing.Main.main(args);
}
}
Main.java Image
Main.Java (IMAGE)
After creating EntryPoint.java(New Main Class) Manifest File For Jar File, clicking Cntr+Alt+Shift+S to create Manifest File | Jar File, during creating jar file(before build jar) Just select EntryPoint.Java As Main Class Below Image
Main Class : EntryPoint (IMAGE)
Before click Ok button change the location of manifest file create it at this location /src/META_INF/manifest.mf(Wrong location : /src/main/META_INF/menifest.mf) and click Apply button to save changes
Location Of Manifest File like below image
Just Manifest.MF File (IMAGE)
Build Jar file go to Option[Build->Build-Artifacts...] and take 3-5 min to create jar.
After Creating Jar file Please Read clearly this main step means
Means Solution Of This line of NOT FOUND FXML FILE this is tricky because all fxml file are stored at resource directory so while creating jar so intellij doesn't add the any file from resource directory again not include fxml file while creating jar
Solution Of How to include FXML FILE NOW WE HAVE TO USE WIN_RAR Software To Add This File And Believe Me Its work and not affect any file and work file Just Follow below step to add FXML FILE
Adding FXML FILE STEP
close Intellij
Go to your project Directory in my case C:\Users\ADMIN\IdeaProjects\YOUR_PROJECT_NAME and Go to YOUR_PROJECT_NAME\out\artifacts\YOUR_PROJECT_NAME\YOUR_PROJECT_NAME.Jar so u find jar file of your project
Just click right key of Mouse for option, select option of EXTRACT HERE(WinRar Option)
JUST I AM ExtractING MY JAR (IMAGE)
DELETE ONLY JAR FILE AFTER EXTRACTING Like my file name smartSeizeing.jar i delete it (IMAGE)
After extracting and deleting jar(only jar file) file so OPEN YOUR_PACKAGE_NAME File in My case C:\Users\ADMIN\IdeaProjects\SmartSeizeing\out\artifacts\SmartSeizeing_jar\smartSeizeing
Keep Open It And Open Your Project directory and copy all file(including all file like fxml, css, html, hibernet file if u have other file to with fxml) from resource directory and Paste all file(copied Files) in that previously open folder(extract jar folder like IdeaProjects\YOUR_PROJECT_NAME\out\artifacts\YOUR_PROJECT_NAME_jar\YOUR_PACKAGE_NAME) And after coping file so and just make jar file select all file(IdeaProjects\YOUR_PROJECT_NAME\out\artifacts\YOUR_PROJECT_NAME_jar) and click right key of mouse, select add to archive(WinRar) and after creating YOUR_PACKAGE_NAME.jar file just double click that file and see the magic
How to Add fxml and how to create again jar(without any curreption) i mentioned in below image so u can easily understand what i did and also image of my OUTPUT
i pasted all file of resource directory of my project (IMAGE)
Please see below answer too because i can't add more link for step of how to make jar using winRar and that jar work fine and also my output
Best Of Luck
and You wanna video just tell me i make video about it How to make runnable jar without any exception or error!
this is because i can't add more links that's why i again wrote this
WinRar to create Jar File
Continue From Previous Answer and image that is https://i.stack.imgur.com/fY1tw.png
this is what i copy from Resource folder of my project
just paste of all file of resource directory at (in my case) C:\Users\ADMIN\IdeaProjects\SmartSeizeing\out\artifacts\SmartSeizeing_jar\smartSeizeing
WinRar to make Jar follow bellow step (IMAGE)
Step 1
Step 2 select zip option then change extension of your file .zip to .jar
Step 3
This is what i am trying to explain to you and this is my Output
i hope you understand what i do for creating jar file

StackOverflowError during Liberty startup during ApplicationStateManager.fireStarting

BLUF: I'm getting a stackoverflow starting my Liberty server with a single war file before it reaches any of my code. I can't debug what is causing the problem. I tried adding trace statements to server.xml but never got files I could interpret (were binary) and trying to Open Log Files had no choices available (greyed out). If anyone has any ideas how to determine what is causing the stack overflow I'd appreciate the help. Thanks in advance. My code does use #Inject but I don't think this is the issue as all works fine if I move code from a separate project/jar into the war project.
Running wlp 17.0.0.1 when starting a single war using shared libraries to jar files in a single directory, I get a StackOverflowError before any of my code is reached (based on setting breakpoints in the RestServicesApplication and any static initializers).
This problem only occurs when some classes have been moved to a separate project and therefore into a separate jar (e.g., moving them back to the war project allows all to run fine).
I've checked that all classes and methods references are public. I'm calling public static methods in the new jar file.
I'm not sure how to figure out the problem as no references to my code are in the ffdc files in the stack traces.
I've verified the needed classes are in the jar file and there are no duplicate classes being referenced.
Essentially, the class in the war file has a call like:
public static JSONObject processFuzzyMatch(ID session,
ID userID, JSONObject request)
throws ILDException {
try {
return NLUFuzzyEntityMatcherFunction.processFuzzyMatch(request);
} catch (Exception e) {
throw new ILDException(e);
}
}
and NLUFuzzyEntityMatcherFunction is in the jar file declared as:
public static JSONObject processFuzzyMatch(JSONObject request)
throws Exception
Here is an example of the reported problem with the last line repeating (for the stack overflow...)
Stack Dump = com.ibm.ws.container.service.state.StateChangeException: java.lang.StackOverflowError
at com.ibm.ws.container.service.state.internal.ApplicationStateManager.fireStarting(ApplicationStateManager.java:33)
at com.ibm.ws.container.service.state.internal.StateChangeServiceImpl.fireApplicationStarting(StateChangeServiceImpl.java:51)
at com.ibm.ws.app.manager.module.internal.DeployedAppInfoBase.preDeployApp(DeployedAppInfoBase.java:376)
at com.ibm.ws.app.manager.module.internal.DeployedAppInfoBase.deployApp(DeployedAppInfoBase.java:403)
at com.ibm.ws.app.manager.war.internal.WARApplicationHandlerImpl.install(WARApplicationHandlerImpl.java:66)
at com.ibm.ws.app.manager.internal.statemachine.StartAction.execute(StartAction.java:141)
at com.ibm.ws.app.manager.internal.statemachine.ApplicationStateMachineImpl.enterState(ApplicationStateMachineImpl.java:1253)
at com.ibm.ws.app.manager.internal.statemachine.ApplicationStateMachineImpl.run(ApplicationStateMachineImpl.java:866)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.StackOverflowError
at java.io.UnixFileSystem.getBooleanAttributes0(Native Method)
at java.io.UnixFileSystem.getBooleanAttributes(UnixFileSystem.java:242)
at java.io.File.exists(File.java:819)
at com.ibm.wsspi.kernel.service.utils.FileUtils$3.run(FileUtils.java:88)
at com.ibm.wsspi.kernel.service.utils.FileUtils$3.run(FileUtils.java:85)
at java.security.AccessController.doPrivileged(Native Method)
at com.ibm.wsspi.kernel.service.utils.FileUtils.fileExists(FileUtils.java:85)
at com.ibm.ws.artifact.loose.internal.LooseArchive$DirEntryInfo.matches(LooseArchive.java:232)
at com.ibm.ws.artifact.loose.internal.LooseArchive$DirEntryInfo.matches(LooseArchive.java:207)
at com.ibm.ws.artifact.loose.internal.LooseArchive.getEntry(LooseArchive.java:782)
at com.ibm.ws.artifact.overlay.internal.DirectoryBasedOverlayContainerImpl.getEntry(DirectoryBasedOverlayContainerImpl.java:838)
at com.ibm.ws.adaptable.module.internal.AdaptableContainerImpl.getEntry(AdaptableContainerImpl.java:113)
at com.ibm.ws.jsp.taglib.TagLibraryCache.loadWebInfMap(TagLibraryCache.java:613)
at com.ibm.ws.jsp.taglib.TagLibraryCache.loadWebInfMap(TagLibraryCache.java:629)
at com.ibm.ws.jsp.taglib.TagLibraryCache.loadWebInfMap(TagLibraryCache.java:629)
(above line repeats due to stack overflow)
This is a known problem on Liberty. The fix to that problem will be available on Liberty 17.0.0.3.
You can use some workarounds:
I assume you have a folder named WEB-INF within a jar. Change the folder name to something else. That folder name causes the JSP engine to go to the web module's WEB-INF (scanning everything again!), instead of the jar's WEB-INF.
Try setting the JSP configuration parameter disableTldSearch to true; this may be troublesome if you are using custom tag libraries. With the property set, all your custom TLD files need to be declared in the web.xml.
Disable CDI; I know this may not be possible for you as you mentioned you are using injections.
Somehow I screwed up the project settings for the jar project (likely because I'd copied the pom.xml from the Web project and forgot to change it to jar...). This may have resulted in the screwed up xml file in the /apps folder with an embedded reference to a non-existent war file (see below):
<?xml version="1.0" encoding="UTF-8"?>
<archive>
<archive targetInArchive="/WEB-INF/lib/ildMicroServices-1.0.0-SNAPSHOT.jar">
<dir sourceOnDisk="/csnext/ild/ild_framework/ildMicroServices/WebContent" targetInArchive="/"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildMicroServices/target/classes" targetInArchive="/WEB-INF/classes"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildMicroServices/target/test-
classes" targetInArchive="/WEB-INF/classes"/>
</archive>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildRESTServices/target/m2e-wtp/web-resources" targetInArchive="/"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildRESTServices/WebContent" targetInArchive="/"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildRESTServices/target/classes" targetInArchive="/WEB-INF/classes"/>
<dir sourceOnDisk="/csnext/ild/ild_framework/ildRESTServices/target/test-classes" targetInArchive="/WEB-INF/classes"/>
</archive>
By deleting this embedded archive the problem went away.
I only found this after upgrading from Neon to Oxygen, and 17.0.0.1 to 17.0.0.2 and when setting up the new server using the old server's artifacts, I noticed the xml file in /apps didn't look correct.
I hope this helps somebody.

Setting Jetty resourcebase to static file embedded in the same jar file

I am trying to access static resource (eg. first.html) packed inside the same .jar file (testJetty.jar), which also has a class which starts the jetty (v.8) server (MainTest.java). I am unable to set the resource base correctly.
The structure of my jar file (testJetty.jar):
testJetty.jar
first.html
MainTest.java
==
Works fine on local machine, but when I wrap it in jar file and then run it, it doesn't work, giving "404: File not found" error.
I tried to set the resourcebase with the following values, all of which failed:
a) Tried setting it to .
resource_handler.setResourceBase("."); // Results in directory containing the jar file, D:\Work\eclipseworkspace\testJettyResult
b) Tried getting it from getResource
ClassLoader loader = this.getClass().getClassLoader();
File indexLoc = new File(loader.getResource("first.html").getFile());
String htmlLoc = indexLoc.getAbsolutePath();
resource_handler.setResourceBase(htmloc); // Results in D:\Work\eclipseworkspace\testJettyResult\file:\D:\Work\eclipseworkspace\testJettyResult\testJetty1.jar!\first.html
c) Tried getting the webdir
String webDir = this.getClass().getProtectionDomain()
.getCodeSource().getLocation().toExternalForm();
resource_handler.setResourceBase(webdir); // Results in D:/Work/eclipseworkspace/testJettyResult/testJetty1.jar
None of these 3 approaches worked.
Any help or alternative would be appreciated
Thanks
abbas
The solutions provided in this thread work but I think some clarity to the solution could be useful.
If you are building a fat jar and use the ProtectionDomain way you may hit some issues because you are loading the whole jar!
class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
So the better solution is the other provided solution
contextHandler.setResourceBase(
YourClass.class
.getClassLoader()
.getResource("WEB-INF")
.toExternalForm());
The problem here is if you are building a fat jar you are not really dumping your webapp resources into WEB-INF but are probably going into the root of the jar, so a simple workaround is to create a folder XXX and use the second approach as follows:
contextHandler.setResourceBase(
YourClass.class
.getClassLoader()
.getResource("XXX")
.toExternalForm());
Or change your build tool to export the webapp files into that given directory. Maybe Maven does this on a Jar for you but gradle does not.
Not unusually, I found a solution to my problem. The 3rd approach mentioned by Stephen in Embedded Jetty : how to use a .war that is included in the .jar from which Jetty starts? worked!
So, I changed from Resource_handler to WebAppContext, where WebAppContext is pointing to the same jar (testJetty.jar) and it worked!
String webDir = MainTest.class.getProtectionDomain()
.getCodeSource().getLocation().toExternalForm(); ; // Results in D:/Work/eclipseworkspace/testJettyResult/testJetty.jar
WebAppContext webappContext = new WebAppContext(webDir, "/");
It looks like ClassLoader.getResource does not understand an empty string or . or / as an argument. In my jar file I had to move all stuf to WEB-INF(any other wrapping dir will do). So the code looks like
contextHandler.setResourceBase(EmbeddedJetty.class.getClassLoader().getResource("WEB-INF").toExternalForm());
so the context looks like this then:
ContextHandler:744 - Started o.e.j.w.WebAppContext#48b3806{/,jar:file:/Users/xxx/projects/dropbox/ui/target/ui-1.0-SNAPSHOT.jar!/WEB-INF,AVAILABLE}

convert .WAR for auto deploy in karaf/servicemix

I've got very simple .WAR containing example servlet. I'm able to deploy it in servicemix using the following command:
osgi:install file:///home/seiho/apache-servicemix-4.4.2/deploy/TestServlet.war?Bundle-SymbolicName=TestServlet&Webapp-Context=/TestServlet
And then see it in my browser. But only with full path to a file, e.g.: localhost:8080/TestServlet/index.html or localhost:8080/TestServlet/TestServlet (my servlet is TestServlet class).
I'd like to launch the index.html page automatically after entering: localhost:8080/TestServlet
how to do it?
MORE IMPORTANT
I need a way to convert the .WAR file or servlet project (I've got the sources) so that new .WAR file can be auto-deployed by copying it to $SERVICEMIX_HOME/deploy directory.
I've tried editing the MANIFEST.MF file, but with no success. Probably I'm doing something wrong.
Thanks for any advice/help.
To be recognised as a wab, you need to add a context path header to your manifest:
Web-ContextPath: TestServlet
It's working now! I was doing my MANIFEST.MF according to this page: http://team.ops4j.org/wiki/display/ops4j/Pax+Web+Extender+-+War+-+OSGi-fy
The problem was that for some reason "Bundle-Version: 1.0" line was required as opposed to optional as stated on that page.
Honestly, just adding the Bundle-Version fix-it.
I knew it was something wrong with the MANIFEST.MF and after Holly Cummins' question I played with it a bit more. Thanks Holly.
I still can't do anything with the manual site launching (have to manually enter the index.html).
http://localhost:8080/TestServlet/ gives me this:
HTTP ERROR 404
Problem accessing /TestServlet/. Reason:
Not Found
Powered by Jetty://
http://localhost:8080/TestServlet/index.html gives me proper site.

NoClassDefFoundError: org/jbox2d/collision/shapes/Shape in netbeans

I am trying to add jbox2d as a dependency to my project in netbeans (playn-jbox2d-1.1-SNAPSHOT.jar), but at run time, I get:
Exception in thread "main" java.lang.NoClassDefFoundError: org/jbox2d/collision/shapes/Shape
All other classes can be accessed fine, just not Shape.
I simply right clicked dependencies in my core directory and did add dependency and searched for jbox2d.
Anyone know what could be wrong?
What version of jbox2d do you have, as a dependency? You can crosscheck in the dependency jar file, if that class (Shape.class) exists or not?
EDIT: Most of the times, 'NoClassDefFoundError' happens due to incorrect classpath settings or when there's more than one class (or jar file) in the classpath, with the same namespace.

Resources