This could sound strange but I want to generate my chart images on server side using JavaFX. Because JavaFX has nice canvas API to perform image transformations joins and positioning.
In particular I have a spring MVC service to generate my charts as images. The main problem is how to invoke javaFX API from a convenient Spring bean. If I try to just run javafx code from java application (not extending javaFX Application class) I get
java.lang.IllegalStateException: Toolkit not initialized
Do you have any suggestions/ideas how to solve this issue?
So after some research I've implemented canvas draw with JavaFX and here is a simplified example:
First I made the JavaFX application which is being launched in a separate thread (I use Spring taskExecutor but a plain java thread can be used).
Then I call the initialize() method when the Spring application is started:
This solution of cource can be ported to a non-Spring application.
This is a single-threaded solution (in my case it's enough) but I think it could be adopted to multithreaded usage (maybe use RMI to invoke draw method).
Also this solution works "as is" on my windows workstation but on linux server environment some additional actions should be invoked:
The most complex - you have to use virtual display to make JavaFX run on headless environments:
apt-get install xvfb
// then on application server start:
export DISPLAY=":99"
start-stop-daemon --start --background --user jetty --exec "/usr/bin/sudo" -- -u jetty /usr/bin/Xvfb :99 -screen 0 1024x768x24
P.S. You can also use other JavaFX capabilities on server side (e.g. export html to image) with this solution.
Perhaps something similar to this solution would be helpful?
JavaFX 2.1: Toolkit not initialized
Otherwise, I would consider creating a service and pushing the image to a datastore and retrieving it in your spring application.
Hope that provides at least a little help!
In case other people are looking for this, this is a much simpler way. Using JavaFX 2.2 i was able to perform the following operations.
There is no need to add the node to a group. From there you can do any operation you want with the image.
The FxPlatformExecutor is from a JME3-JFX library I am using for my project. See: https://github.com/empirephoenix/JME3-JFX/blob/master/src/main/java/com/jme3x/jfx/FxPlatformExecutor.java
You can easily create the
runOnFxApplication()
method or create the FxPlatformExecutor class.Here is the code.
I did not write this code, the github link is above.