Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
86 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).

public class ChartGenerator extends Application {

    private static Canvas canvas;

    private static volatile byte[] result;

    public static void initialize(TaskExecutor taskExecutor) {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                launch(ChartGenerator.class);
            }
        });
    }

    public static synchronized byte[] generateChart(final Object... params) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                ByteArrayOutputStream baos = null;
                try {
                    GraphicsContext gc = canvas.getGraphicsContext2D();
                    gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
                    /**
                     * Do the work with canvas
                     **/
                    final SnapshotParameters snapshotParameters = new SnapshotParameters();
                    snapshotParameters.setFill(Color.TRANSPARENT);
                    WritableImage image = canvas.snapshot(snapshotParameters, null);
                    BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
                    baos = new ByteArrayOutputStream();
                    ImageIO.write(bImage, chartType.outputFormat, baos);
                    result = baos.toByteArray();
                } catch (InstantiationException e) {
                    throw new ChartGenerationException(e);
                } catch (IllegalAccessException e) {
                    throw new ChartGenerationException(e);
                } catch (NoSuchMethodException e) {
                    throw new ChartGenerationException(e);
                } catch (InvocationTargetException e) {
                    throw new ChartGenerationException(e);
                } catch (IOException e) {
                    throw new ChartGenerationException(e);
                } finally {
                    IOUtils.closeQuietly(baos);
                }
            }
        });
        while (result == null) {
            //wait
        }
        byte[] ret = result;
        result = null;
        return ret;
    }


    @Override
    public void start(Stage stage) {
        canvas = new Canvas();
    }

    public static class ChartGenerationException extends RuntimeException {
        public ChartGenerationException(String message) {
            super(message);
        }
        public ChartGenerationException(Throwable cause) {
            super(cause);
        }
    }

}

Then I call the initialize() method when the Spring application is started:

@Autowired private TaskExecutor taskExecutor;

@PostConstruct private void initChartGenerator() {
    ChartGenerator.initialize(taskExecutor);
}

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:

  1. You cannot use JavaFX on OpenJDK (as of Aug 2013) - have to switch to Oracle JDK
  2. Java version must be no less than Java 7u6
  3. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...