Locating fxml file from a different package - javafx

I am having "tare your hair out" type difficulties while trying to open an fxml file from a controller which is in a different package. the package structure is as follows:
Controller name = LocationController
Controller package = src/com/yas/prayertimeconfig/location/java
FXML file name = AvailableAddresses.fxml
FXML file package = src/com/yas/prayertimeconfig/availableaddresses/java
The code I am using to open up the fxml file from with in LocationController is as follows:
#FXML void btnFindAddress_Click(ActionEvent event) throws IOException {
try{
Parent root1 = FXMLLoader.load(getClass().getResource("/src/com/yas/prayertimeconfig/availableaddresses/java/AvailableAddresses.fxml"));
Stage stage = new Stage();
stage.setTitle("Available Addresses");
stage.setScene(new Scene(root1));
stage.show();
} catch (Exception e) {
System.out.println(e);
}
}
I keep getting:
java.lang.NullPointerException: Location is required.
I have tried every using:
getClass().getResource()
and
getClass().getClassLoader().getResource()
and no joy.
Please help!

Here's how I recreated that error, how I troubleshooted it, and how I ultimately fixed it, in that order.
Full Error Message: 
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:465)
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:364)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:901)
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NullPointerException: Location is required.
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3324)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3287)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3255)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3227)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3203)
at javafx.fxml#18.0.1/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3196)
at com.company.Main.start(Main.java:29)
at javafx.graphics#18.0.1/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:847)
at javafx.graphics#18.0.1/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
at javafx.graphics#18.0.1/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics#18.0.1/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
at javafx.graphics#18.0.1/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics#18.0.1/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics#18.0.1/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
... 1 more
Here's my Start function code that caused the error:
#Override
public void start(Stage stage) throws Exception {
System.out.println("Start()");
Parent root = FXMLLoader.load(getClass().getResource("login-form.fxml"));
stage.setTitle("Login");
Scene scene = new Scene(root, 200, 150);
stage.setScene(scene);
stage.show();
}
The code above basically is trying to load an fxml file on program entry and we can't load it for some reason. (stay tuned)
Basically what that error message is telling me is that it can't load login-form.fxml
For a quick and dirty test, Copy that fxml file that you are trying to load into the same project dir as the the file that has the function that is loading. Just put everything in the same folder. I use copy/paste in IntelliJ's project viewer to do this.
Just make sure that your project "sees" the file. You may have to import your fxml project into the file. 
It will load now for me and I can see my login form on program launch.
Now, let's fix this the "correct" ie. "less hacky" way. 
As another poster commented, relative paths are not a good idea since navigating "up" only works as long as the app is not deployed as jar. You need to start the path at the classpath root starting with /
You can see in my screencap that I have the fxml file I want to import in a different package called "view". In Java projects a "package" is basically a "folder", so I can use "/view/login-form.xml" as a path I can pass to
 
FXMLLoader.load(getClass().getResource("/view/login-form.fxml"))
Remember that "/" in this case is the root of your project, not the root directory of your entire hard drive.

Related

Write in an application jfx canvas from another Thread

Launch an application and talk to it via other classes (not instanciated at the moment of launching) I want to build multi app with multiple windows and Thread interacting one by one.
I will explain my problem with not too general question. I have "ApplicationPane" Application 1 : how to instantiate the GUI with object arguments? That is the first part of the question. In general when I'm on a project, I have naturally a frontend (here the JavaFX GUI) and a backend (one or sevaral thread referenced by a Object "Backend".
public static void main(String... args) {
SampleDrawingProcessor sampleDrawingProcessor = new SampleDrawingProcessor();
Oscillator os1 = new Oscillator(440, SoundProductionSystem.Waveform.SIN);
os1.getOutProcessors().put("Drawing samples", sampleDrawingProcessor);
ApplicationPane applicationPane = new ApplicationPane(sampleDrawingProcessor);
os1.start();
sampleDrawingProcessor.start();
}
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at be.manudahmen.mylittlesynth.processor.AudioViewer.render(AudioViewer.java:71)
at be.manudahmen.mylittlesynth.processor.AudioViewer$CanvasRedrawTask.handle(AudioViewer.java:201)
at javafx.animation.AnimationTimer$AnimationTimerReceiver.lambda$handle$485(AnimationTimer.java:57)
at java.security.AccessController.doPrivileged(Native Method)
at javafx.animation.AnimationTimer$AnimationTimerReceiver.handle(AnimationTimer.java:56)
at com.sun.scenario.animation.AbstractMasterTimer.timePulseImpl(AbstractMasterTimer.java:357)
at com.sun.scenario.animation.AbstractMasterTimer$MainLoop.run(AbstractMasterTimer.java:267)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:514)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:498)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:491)
at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$403(QuantumToolkit.java:319)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$147(WinApplication.java:177)
at java.lang.Thread.run(Thread.java:748)
public static void testOscillator() {
ApplicationPane.main();
}
public static void main(String ... args)
{
ApplicationPane applicationPane = new ApplicationPane();
SampleDrawingProcessor sampleDrawingProcessor = new SampleDrawingProcessor(applicationPane);
Oscillator os1 = new Oscillator(440, SoundProductionSystem.Waveform.SIN);
os1.getOutProcessors().put("Drawing samples", sampleDrawingProcessor);
os1.start();
sampleDrawingProcessor.start();
}
The problem seems to be Application reference after new ApplicationPane() seems to be null or the canvas created in start is null.
if(app==null)
System.exit(-1);
Canvas drawingZone = app.
getDrawingZone();
if(drawingZone==null)
System.exit(-2);
GraphicsContext context2D = drawingZone.getGraphicsContext2D();
"C:\Program Files\Java\jdk1.8.0_171\bin\java" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.6\lib\idea_rt.jar=57668:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.6\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_171\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_171\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_171\lib\javafx-mx.jar;C:\Users\Win\IdeaProjects\MyLittleSynth\out\production\MyLittleSynth;C:\Users\Win\IdeaProjects\MyLittleSynth\lib\empty3-64.jar;C:\Users\Win\IdeaProjects\MyLittleSynth\lib\xuggler-3.4.jar" be.manudahmen.mylittlesynth.processor.apps.ApplicationPane
Process finished with exit code -2
GraphicsContext context2D = drawingZone.getGraphicsContext2D();
Well, what I understand now, is that an application can't be created with the new keyword. I put a task in start(Stage) method creating links to other threads.

JSoup randomly throws java.io.IOException: stream is closed when running from browser

I'm having some weird JSoup problem when running my JavaFX application from the browser (or as web-start).
When I run from inside the IDE (Eclipse or Netbeans) or as a standalone app, it runs normally. When I try to run as a web-start or from the browser (Chrome), JSoup randomly throws a "java.io.IOException: stream is closed".
The site I'm trying to parse is thepiratebay.sx. When I first run the application (from browser), I get this error. With the application running, if I try to parse again, than it works... sometimes.
The JSoup code:
try {
//TODO: Change to HttpFetcher. This method is reporting "stream is closed" when running on browser
Connection con = Jsoup.connect(url)
.timeout(HTTP_TIMEOUT)
.userAgent(UserAgentGenerator.getUserAgent())
.followRedirects(false);
doc = con.get();
System.out.println("Fetching... " + url);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Parser connect must have timed out, no results. " + url);
fetchFailed[i] = true;
continue;
}
finally {
i++;
if (CommonTFUtils.isAllTrue(fetchFailed)) {
throw new HttpException("Fetcher failed on every URL of " + response.getSite_name());
}
}
And the exception thrown:
CacheEntry[http://thepiratebay.sx/browse/207/0/7]: updateAvailable=true,lastModified=Tue May 14 14:28:16 BRT 2013,length=-1
java.io.IOException: stream is closed
at sun.net.www.http.ChunkedInputStream.ensureOpen(Unknown Source)
at sun.net.www.http.ChunkedInputStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.close(Unknown Source)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:468)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:410)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:164)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:153)
at com.package.torrent.parser.GenericParser.search(GenericParser.java:147)
at com.package.torrent.parser.GenericParser.browse(GenericParser.java:82)
at com.package.search.TrackerSearch.searchTracker(TrackerSearch.java:69)
at com.package.search.TrackerSearch.searchAllTrackers(TrackerSearch.java:40)
at com.package.search.TrackerSearch.searchAllTrackers(TrackerSearch.java:23)
at com.package.search.MovieBrowser.browseTrackers(MovieBrowser.java:49)
at com.package.ui.browse.BrowseController$MovieBrowserTask.call(BrowseController.java:237)
at com.package.ui.browse.BrowseController$MovieBrowserTask.call(BrowseController.java:213)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1259)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Does anyone have an idea of what might be causing this?
Thanks in advance.
I think I found a solution. Place this code before you ever call JSoup. Apparently, applets and web start set this value to true. Now, I wonder why Sun forces you to access a static variable non-statically.
new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
JSoup doesn't handle well when the URL is cached and treats it as an exception.

jpedal jpg2000 error

I convert pdfs to images using jpedal. This works fine for most of the pdfs but some containing jpeg2000 i continue receiving the following error:
java.lang.RuntimeException: JPeg 2000 Images needs the VM parameter -Dorg.jpedal.jai=true switch turned on
at org.jpedal.parser.PdfStreamDecoder.decodeStreamIntoObjects(Unknown Source)
at org.jpedal.parser.PdfStreamDecoder.decodePageContent(Unknown Source)
at org.jpedal.PDFtoImageConvertor.convert(Unknown Source)
at org.jpedal.PdfDecoder.getPageAsImage(Unknown Source)
at org.jpedal.PdfDecoder.getPageAsImage(Unknown Source)
at com.....
I already set the JVM Parameter in the JAVA_OPTS, the run configuration of my tomcat and also in program code using:
System.setProperty("org.jpedal.jai", "true");
PdfDecoder decode_pdf = new PdfDecoder(true);
FontMappings.setFontReplacements();
decode_pdf.openPdfArray(pdf_file);
also the 3 JAI libs are on my build path.
So I don't know what else I have to do?
My complete code for the conversion is:
List<BufferedImage> images = new LinkedList<BufferedImage>();
System.setProperty("org.jpedal.jai", "true");
PdfDecoder decode_pdf = new PdfDecoder(true);
FontMappings.setFontReplacements();
decode_pdf.openPdfArray(pdf_file);
decode_pdf.setExtractionMode(0, 1f); //do not save images
for (int i = 1; i<= decode_pdf.getPageCount(); i++)
{
images.add(decode_pdf.getPageAsImage(i));
}
decode_pdf.closePdfFile();
Any sugestions?
Activate jai for jpedal
System.setProperty("org.jpedal.jai", "true");
A better solution (than the article from Mark Stephens blog) is to re-register the
provider, because this only has to be done once:
IIORegistry registry = IIORegistry.getDefaultInstance();
registry.registerServiceProvider(new com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageWriterSpi());
registry.registerServiceProvider(new com.sun.media.imageioimpl.plugins.jpeg2000.J2KImageReaderSpi());
Of course JAI libs need to be in the classpath to work correctly.
I found the answer to this problem here.
When in a Tomcat environment you have to disable the JreLeakPreventionListener in server.xml then it works just fine.

how to save a base64 as image in java server faces project

I am doing a project for school. Subject of project is tshirt design. I am using jsf and primefaces. But I don't know well jsf and primefaces. I wanted save a base64 from html as image in jsf project. But when I had tried to following functions, NullPointerException. This function is called in a Servlet. A base64 is grabbed by this Servlet.
public static void save(String dataURL){
line85: ExternalContext external = FacesContext.getCurrentInstance().getExternalContext();
ServletContext servletContext = (ServletContext) external.getContext();
String filename = servletContext.getRealPath("cloud.png");
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes;
try {
decodedBytes = decoder.decodeBuffer(dataURL.split("data:image/(png|jpg);base64,")[1]);
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(decodedBytes));
ImageIO.write(imag, "png", new File(filename));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
23.Ara.2012 17:48:20 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [org.soft.tshirt.servlets.DesignServlet] in context with path [/Tshirt] threw exception
java.lang.NullPointerException
at org.soft.tshirt.beans.ImageBean.save(ImageBean.java:85)
at org.soft.tshirt.servlets.DesignServlet.processRequest(DesignServlet.java:102)
at org.soft.tshirt.servlets.DesignServlet.doPost(DesignServlet.java:76)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
The current instance of the FacesContext is only available in the HTTP request thread which is been served through the FacesServlet who is the one responsible for creating the FacesContext. In other words, only when the request URL matches the URL pattern of the FacesServlet. In other words, only JSF pages, JSF managed beans (and thus not backing beans which you instantiate yourself like as is happening here!) and all other JSF artifacts like event/phase listeners, UI components, etc have the current instance of the FacesContext available to them.
In an arbitrary homegrown HTTP servlet, the FacesContext isn't available at all, for the simple reason that the FacesServlet is not been invoked beforehand. So the getCurrentInstance() method on it would return null. You know, trying to access/invoke any fields/method on null will cause NullPointerException. See also its javadoc.
In order to achieve the sole goal of obtaining the ServletContext, just invoke the inherited GenericServlet#getServletContext() method inside the servlet.
protected void doPost(...) {
String filename = getServletContext().getRealPath("cloud.png");
// ...
}
Pass that information instead to the method responsible for creating the file. You might want to extract that code into a different class which is reused between your servlet and backing bean.
Unrelated to the concrete problem, writing files to the expanded WAR folder is really a bad practice for the reasons mentioned in among others this answer: Uploaded image only available after refreshing the page.

How I can use Java Reflection API within EJB 3 entity?

I do the following steps with eclipse 3.5 ,JBoss 4.2 ,EJB3 but I face class not found exception
1.compiling this code to foo.jar file
package mypackage.foo;
import myejbpackage.ejb.fooInterface;
class foo implements fooInterface{
#override
void helloWorld(){System.out.print("HelloWorld");}
}
Note that fooInterface interface in is written inside the used EJB
2.using reflection , I take an instance from this class, also with the same ejb
package myejbpackage.ejb;
class fooCaller{
void call(){
Class foo= Class.forName("mypackage.foo.foo");
fooInterface iDataBackupWriter =(fooInterface) foo.newInstance();
fooInterface.helloWorld();
}
}
3.then calling it within stateless ejb3
package myejbpackage.ejb;
test(){
System.Out.Write("before calling");
new fooCaller().call();
}
4.then deploying to Jboss 4.2 and and puting foo.jar in default/lib
5.then calling the ejb 3 method.using simple client
it print :
"before calling"
and the following exception occurs in eclipse console
javax.ejb.EJBException: java.lang.RuntimeException: java.lang.NoClassDefFoundError: myejbpackage/ejb/fooInterface; nested exception is: java.lang.RuntimeException: java.lang.NoClassDefFoundError: myejbpackage/ejb/fooInterface
java.lang.RuntimeException: java.lang.NoClassDefFoundError:myejbpackage/ejb/fooInterface
Any suggestion ?
1.Is this exception from JBOOS, why ?
1.Where I should put the foo.jar to bee seen with the ejb3 jar ?
thanks in advance
there was a circular dependency which generate this problem

Resources