JRebirth Application Framework Documentation
Learn how to use JRebirth to help you building sophisticated application in minutes.

All In One Documentation Page

JRebirth Origins
The small story of JRebirth project.

Introduction

Origins

Just before the 2011's summer I was bored to work with some RIA toolkit that don't give me enought satisfaction.

Like many people I thought that web applications were the ultimate solution to build quickly beautiful and sophisticated applications. Before the advent of JQuery's like toolkit I built mine, a modularized javascript framework written with OOP spirit. Browser compatibility stops the projects because it requires too much time to manage their particularities. But the biggest pitfall is the Javascript language that is not enough powerful to build cleanly big application and not enough efficient than pre-compiled ones.

Then I was upset by the single thread used by Flash and Flex application, even if I really have pleasure to work with FlexBuilder with PureMVC framework. Making extension of Flex components was also sometimes pretty hard due to inheritance of Flash widgets (partially resolved with new spark components).

Unfortunately I also worked several month with Silverlight (C#) provided by Microsoft, the language itself has got some interesting feature but ecosystem is not as good as the Java one. The MVVM pattern (Model-View-ViewModel) is a fake that hide a MVVCVM (Model-View-ViewController-ViewModel) where VC is the .xaml.cs file…

Before working with RIA, I obviously worked with Swing and SWT/JFace toolkit. And finally Swing was not so bad !

It suffered from a lot drawback like graphical performance issues, concurrency problems and old layout and components. But it was possible to write nice application powered with a pleasant Look & Feel.

So JRebirth was first thought to be a rebirth of Java Swing Toolkit in order to create the missing Application Framework that Swing never had.

I posted on the ToulouseJUG mailing list a question about my Swing revival vision, and during the discussion I learned that Oracle had planned to rewrite the first JavaFX entirely in Java (and leave the awful fxscript language). So I spent the summer in reading beta documentation and during the autumn I began to play with it … and I decided to build my own Framework.

The name was readily found: JRebirth (for Java Rebirth) JavaFX Application Framework

Everything began on a local SVN and then was pushed on Github on Feb 22, 2012, few days after my first talk about JavaFX (2).

Since those early days, JRebirth has evolved significantly. It now supports Java 11+ with full JPMS modularization, runs on Java 25 and JavaFX 26, and ships a growing ecosystem of extension modules: REST client integration, Security, Form binding, UndoRedo, a reusable Component library (StackModel, TabbedPane, DockPane, Workbench), IconFont bridges (FontAwesome, Icomoon), and build-time tooling.

JRebirth Objectives

The main goal of building yet another application framework is to be the more convenient as possible for developers.

The major issue when building graphical application is to create unresponsive memory-hungry application, while dealing with ugly code hard to maintain.

To address the first point JRebirth offers a way to manage threads on your behalf, for the second JRebirth defines ‘layers’ to maintain a good Separation of Concern (SoC).

Why don't manage myself my application thread ?

Writing concurrent program is more complex than you can think, you should find a way to make it easier unless you will be probably struggle with incomprehensible problems so hard to debug. Moreover this kind of problems always occur when you are demo-ing your application to your client.

Layers sucks !

Are you sure ? Layer is the more basic way to organize and reuse smartly your code. It could seem to add some overhead to it but when you are working with a small or big team over years, you will enjoy to retrieve at the same place the same logic. It requires to respect some rules, within JRebirth Layers shall be seen as Area because there is no hierarchy between them, all Areas can communicate with others but they provide real concerns separation.

Moreover you will have the capability to customize your layer to fit your need by factorizing your code.

JRebirth Key features

Main features of JRebirth Application Framework are:

  1. Simplify Thread Management
  2. Avoid memory leak
  3. Maintain a good SoC
  4. Be the more convenient as possible for developers
  5. Be lightweight and modularizable — leveraging JPMS modules for strong encapsulation and an annotation processor for auto-wiring components
  6. Follow OSS spirit and Java Best Practices
  7. Provide reusable UI components (tabs, dock, workbench, stack navigation)
  8. Integrate with build tooling (Maven plugin for code generation)
How to use JRebirth Application Framework
This page will help you setting up your project to work with JRebirth.

Installation

Manual Download

JRebirth is composed by a set of jar files; add them to your application classpath to use them.

You can download the distribution archive from the home page or here: apps.jrebirth.org

You can also clone and build from source on GitHub.

Maven Way -------------

The easiest way to get JRebirth jars is Maven.

Add these dependencies to your project <dependencies> section (see also the sample application pom.xml):

<dependencies>

	<!-- Use logback logger -->
	<dependency>
		<groupId>ch.qos.logback</groupId>
		<artifactId>logback-classic</artifactId>
		<version>1.5.32</version>
	</dependency>

	<dependency>
		<groupId>org.jrebirth.af</groupId>
		<artifactId>core</artifactId>
		<version>${project.version}</version>
	</dependency>

	<dependency>
		<groupId>org.jrebirth.af</groupId>
		<artifactId>preloader</artifactId>
		<version>${project.version}</version>
	</dependency>
	
</dependencies>

Replace ${project.version} with the JRebirth release you target (for example 12.0.0), or inherit versions from the JRebirth parent POM as the sample project does.

Maven Repositories ============================

All stable JRebirth libraries are published to Maven Central. Snapshots are published to GitHub Packages.

  1. Maven Central — releases (default, no extra config)
  2. GitHub Packages — snapshots of the current development line
  3. Build from source on GitHub when you need a local install

Note: Bintray and JCenter were shut down in 2022. Do not configure them. The old repo.jrebirth.org Artifactory is no longer the recommended source.

Maven Central ----------------------

Maven Central is the default repository used by any Maven installation. You do not need extra repository configuration for stable JRebirth releases.

Browse artifacts: central.sonatype.com — org.jrebirth.af

GitHub Packages (snapshots) -------------------------------

Snapshot builds of the 12.x-dev line are published to GitHub Packages. Add a repository (and authentication for github) when you need snapshots:

<repositories>
	<repository>
		<id>github</id>
		<name>JRebirth GitHub Packages</name>
		<url>https://maven.pkg.github.com/JRebirth/JRebirth</url>
		<snapshots>
			<enabled>true</enabled>
		</snapshots>
		<releases>
			<enabled>true</enabled>
		</releases>
	</repository>
</repositories>

In ~/.m2/settings.xml, configure a server with id github and a GitHub personal access token that can read packages. See GitHub Packages documentation.

Alternatively, clone the repository and run mvn clean install under org.jrebirth.af.

JPMS Setup

For Java 11+ modular projects, your module-info.java should declare the required JRebirth modules and open your UI packages for reflection:

module com.example.myapp {
    requires org.jrebirth.af.core;
    requires org.jrebirth.af.component; // if using component library

    // opens your UI packages to jrebirth for reflection
    opens com.example.myapp.ui to org.jrebirth.af.core;
}

JRebirth uses reflection to instantiate Views and Controllers from Models. Without the opens directive, the framework will fail at runtime with IllegalAccessError. Open only the packages that contain your Model/View/Controller classes.

Overview of JRebirth Application Framework Core Architecture
JRebirth Application Framework offers a very efficient pattern to build real Professional JavaFX applications.

Overview

How does JRebirth work ?

JRebirth uses a wB-CS-Mvc pattern with 7 main layers of abstractions:

  • Wave
  • Behavior
  • Command
  • Service
  • Model
  • View
  • Controller

The illustration below shows 5 of them (Waves and Behaviors are not shown).

Behaviors are the fourth kind of component, providing pluggable cross-cutting logic that can be attached to any other component. Learn more about Behaviors

Components

3 of these elements are considered as JRebirth Components:

  • Command
  • Service
  • Model

Each Component can do generic things, like communicating with others Components synchronously or asynchronously. All these components are handled by 3 Facades (CF, CF, UF).

Learn more about Components

Application

The Application (App) is the starting class to extends to build a JavaFX 8 application that uses JRebirth Application Framework. Default implementation contains some convenient method to speed up development and to start the JRebirth engine.

Learn more about Application

GlobalFacade

The GlobalFacade (GF) is started by the Application and is just used to simplify access to all Components.

Learn more about GlobalFacade

Notifier and Wave

The Notifier (N) is the event bus that carry on small notifications called Waves (W). This notification engine is integrated into the core of JRebirth. Its role is to manage communication throught all JRebirth Components. A Wave is a quick and lightweight message that can be addressed to one or several other Components. There are a lot of convenient method available to create and launch Waves into the application.

Learn more about Notifier

CommandFacade and Commands

Command Components are used to manage complex group of actions: MultiCommand (MC) synchronously or asynchronously, or atomic reusable action :Command (C). They can be processed into one of the 3 kinds of thread managed by using annotation or class inheritance. All interactions between layers should be managed by Commands to keep control on thread involved.

Learn more about Commands

ServiceFacade and Services

Service (S) Components are used to communicate with others Applications (like a Server), to perform long tasks (computations). It can use Spring HttpRequests, Web Services, Restlets, files or whatever you want. Service's methods are called into a dedicated thread pool, and their results are sent to other Components that have declared they are interested in. It also manages the thread in which the receiver will process the result.

Learn more about Services

UiFacade and Models

Model (M) Components are used to manage the User Interface, it has control on the View element and shall provide data to display for example by calling a Service. A Model creates its attached View automatically by reflection. A Model manage the View logic.

Learn more about Models

Views

The View (V) elements are not Components, they are used to create user interface by using JavaFX visual components (with plain java code or by loading FXML files).

Each view has a Model used to load data and to be linked with other Components. Each view have a Controller used to manage JavaFX nodes events, the View creates its Controller automatically by reflection. Each JavaFX Node that need to be controlled by a Controller can declare a getter with package visibility to restrict access from other packages. It can also use an annotation to automatically call a dedicated method into the controller.

Controllers

Controller (C) elements are not Components, they are used to manage the View's Interactions logic. They intercept all JavaFX components' events. A controller can implements custom Adapters to manage events (like MouseAdapter) and link its built-in Handler to the View's nodes (like MouseHandler). Or it can simply implement custom methods if annotations are used. They also provide a set of convenient methods used to perform common event handling, ie: sending a wave when a button click is performed.

Extension Modules

JRebirth ships additional modules that extend the core framework:

  • Component Library — reusable UI components: StackModel, TabbedPane, DockPane, Workbench. Learn more
  • UndoRedo — command-based undo/redo stack. Learn more
  • Transitions — predefined JavaFX animations. Learn more
  • REST — declarative HTTP/REST client integration. Learn more
  • Security — authentication and authorization support. Learn more
  • Dialog — standard dialog management. Learn more
  • Form — form binding and validation. Learn more
  • IconFont — FontAwesome, Icomoon, and custom icon font bridges. Learn more
  • Tooling — Maven plugin for code generation and scaffolding. Learn more
Application Starter
How to create your first start class.

Application

In 30 seconds

Extend DefaultApplication, launch with preloadAndLaunch(args), and point firstModelClass() at your first screen Model. JRebirth boots the engine, preloader, scene, and attaches that Model on the JavaFX thread.

How to use

  1. Create a class extending DefaultApplication<YourRootPane> (root pane type = scene root, e.g. StackPane).
  2. Add public static void main(String... args) { preloadAndLaunch(args); } as the application entry point.
  3. Override firstModelClass() and return the Model class shown at startup (mandatory).
  4. Optionally override customizeStage, customizeScene (CSS via addCSS), and getResourceToPreload.
  5. Run your Application class as the JavaFX main class from the IDE or Maven javafx:run.

Overview

JRebirth Application Framework offers a custom class that extends the basic javafx.Application class. Its aim is to automatically start the JRebirth underlying Application Framework without doing complex stuff.

Short UML Diagram:

Application Class Diagram

Application Start-Up

To trigger the start-up of your JavaFX application you must add a static void main method in order to call one of the static protected method provided :

package org.jrebirth.af.core.application;

import java.lang.Thread.UncaughtExceptionHandler;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.stream.Collectors;

import javafx.application.Application;
import javafx.application.Preloader;
import javafx.application.Preloader.ProgressNotification;
import javafx.scene.Scene;
import javafx.scene.SceneAntialiasing;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import org.jrebirth.af.api.application.Configuration;
import org.jrebirth.af.api.application.JRebirthApplication;
import org.jrebirth.af.api.application.Localized;
import org.jrebirth.af.api.exception.CoreException;
import org.jrebirth.af.api.log.JRLogger;
import org.jrebirth.af.api.module.ModuleStarter;
import org.jrebirth.af.api.resource.ResourceItem;
import org.jrebirth.af.api.resource.style.StyleSheetItem;
import org.jrebirth.af.api.ui.ModuleModel;
import org.jrebirth.af.core.component.factory.RegistrationPointItemBase;
import org.jrebirth.af.core.concurrent.JRebirth;
import org.jrebirth.af.core.concurrent.JRebirthThread;
import org.jrebirth.af.core.exception.handler.DefaultUncaughtExceptionHandler;
import org.jrebirth.af.core.exception.handler.JatUncaughtExceptionHandler;
import org.jrebirth.af.core.exception.handler.JitUncaughtExceptionHandler;
import org.jrebirth.af.core.exception.handler.PoolUncaughtExceptionHandler;
import org.jrebirth.af.core.log.JRLoggerFactory;
import org.jrebirth.af.core.resource.ResourceBuilders;
import org.jrebirth.af.core.resource.Resources;
import org.jrebirth.af.core.resource.provided.JRebirthColors;
import org.jrebirth.af.core.resource.provided.JRebirthStyles;
import org.jrebirth.af.core.resource.provided.parameter.CoreParameters;
import org.jrebirth.af.core.resource.provided.parameter.ResourceParameters;
import org.jrebirth.af.core.resource.provided.parameter.StageParameters;
import org.jrebirth.af.core.util.ClassUtility;
import org.jrebirth.af.core.util.ModuleUtility;
import org.jrebirth.af.preloader.JRebirthPreloader;

//import com.sun.javafx.application.LauncherImpl;

/**
 *
 * The abstract class <strong>AbstractApplication</strong> is the base class of a JRebirth Application.
 *
 * This the class to extend if you want to build an application using JRebirth WCS-MVC (Wave-Command-Service-Model-View-Controller).
 *
 * @author Sébastien Bordes
 *
 * @param <P> The root node of the stage, must extends Pane to allow children management
 */
@Configuration(".*jrebirth")
@Localized(".*_rb")
public abstract class AbstractApplication<P extends Pane> extends Application implements JRebirthApplication<P>, ApplicationMessages {

    /** Default parameter replacement string. */
    private static final String PARAM = "{}";

    /** The default suffix for Application main class. */
    private static final String APP_SUFFIX_CLASSNAME = "Application";

    /** The class logger. */
    private static final JRLogger LOGGER = JRLoggerFactory.getLogger(AbstractApplication.class);

    /** The application primary stage. */
    private transient Stage stage;

    /** The application scene. */
    private transient Scene scene;

    /** The root node of the scene built by reflection. */
    // ...

In example, SampleApplication will be launched with default JRebirth preloader (Application and Preloader classes are omitted) like below:

    public static void main(final String... args) {
        preloadAndLaunch(args);
    }
  • main — standard Java entry point; delegates startup to JRebirth.
  • preloadAndLaunch(args) — boots JavaFX, runs the default or configured preloader, then starts your AbstractApplication subclass.

If you want to use the JRebirthPreloader, you must include the JRebirth preloader artifact to your pom.xml file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.jrebirth</groupId>
		<artifactId>af</artifactId>
		<version>12.0.0-SNAPSHOT</version>
		<relativePath>..</relativePath>
	</parent>

	<groupId>org.jrebirth.af</groupId>
	<artifactId>sample</artifactId>
	<packaging>jar</packaging>

	<name>Sample Application</name>
	<url>http://www.sample.org</url>
	<description>Built with JRebirth Framework</description>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<resources.base.path>org/jrebirth/af/sample</resources.base.path>
	</properties>

	<organization>
		<name>JRebirth</name>
		<url>https://www.jrebirth.org</url>
	</organization>

	<build>
		<resources>
			<resource>
				<filtering>false</filtering>
				<directory>${basedir}/src/main/java</directory>
				<includes>
					<include>**/*.fxml</include>
					<include>**/*.properties</include>
					<include>**/*.txt</include>
				</includes>
			</resource>
			<resource>
				<filtering>true</filtering>
				<directory>${basedir}/src/main/resources</directory>
				<includes>
					<include>**/*.*</include>
				</includes>
				<excludes>
					<exclude>**/*.ttf</exclude>
				</excludes>
			</resource>
			<resource>
				<filtering>false</filtering>
				<directory>${basedir}/src/main/resources</directory>
				<includes>
					<include>**/*.ttf</include>
				</includes>
			</resource>
		</resources>

		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>${maven.compiler.plugin.version}</version>
					<configuration>
						<source>${java.version}</source>
						<target>${java.version}</target>
						<release>${java.version}</release>
						<encoding>UTF-8</encoding>
					</configuration>
				</plugin>

				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-jar-plugin</artifactId>
					<version>${maven.jar.plugin.version}</version>

					<configuration>
    // ...

You can create your own Preloader class, JRebirth send only ProgressNotification with two kind of values:

  • With double value: 0.0 to 1.0 to update the progress bar
  • With integer value: > 1 to be translated into a message

Hereafter you have the default JRebirthPreloader implementation.

package org.jrebirth.af.preloader;

import javafx.animation.ScaleTransition;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * The class <strong>JRebirthPreloader</strong> is the default implementation that show a JRebirth logo with a progress bar.
 *
 * @author Sébastien Bordes
 */
public class JRebirthPreloader extends AbstractJRebirthPreloader {

    /**
     * {@inheritDoc}
     */
    @Override
    protected Scene createPreloaderScene() {

        final StackPane p = new StackPane();
        p.setStyle("-fx-background-color: transparent;");

        final ImageView logo = new ImageView(new Image("JRebirth_Title.png"));
        p.getChildren().add(logo);
        StackPane.setAlignment(logo, Pos.CENTER);

        this.progressBar = new ProgressBar(0.0);
        this.progressBar.setPrefSize(460, 20);
        p.getChildren().add(this.progressBar);
        StackPane.setAlignment(this.progressBar, Pos.BOTTOM_CENTER);
        StackPane.setMargin(this.progressBar, new Insets(30));

        this.messageText = new Text("Loading");
        p.getChildren().add(this.messageText);
        StackPane.setAlignment(this.messageText, Pos.BOTTOM_CENTER);
        StackPane.setMargin(this.messageText, new Insets(10));

        final Scene scene = new Scene(p, 600, 200, Color.TRANSPARENT);
        return scene;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void hideStage() {
        final Stage stage = this.preloaderStage;

        final ScaleTransition st = new ScaleTransition();
        st.setFromX(1.0);
        st.setToX(0.0);
        st.setDuration(Duration.millis(400));
        st.setNode(stage.getScene().getRoot());
        st.setOnFinished(actionEvent -> stage.hide());
        st.play();
    }

    public static void main(String... args) {
        launch(args);
    }

}
  • createPreloaderScene() — builds the splash UI (logo, progress bar, status text).
  • hideStage() — plays a scale-out animation before closing the preloader window.
  • ProgressNotification with a double (0.0–1.0) drives the bar; an int (> 1) selects a message id for messageText.

You can extends the AbstractJRebirthPreloader to just have to populate your scene within createPreloaderScene method, and to add a nice animation used to hide the preloader stage within hideStage method.

Minimal custom preloader:

public final class MyPreloader extends AbstractJRebirthPreloader {

    @Override
    protected Scene createPreloaderScene() {
        final StackPane root = new StackPane(new ProgressBar(0));
        return new Scene(root, 400, 120);
    }

    @Override
    protected void hideStage() {
        preloaderStage.hide();
    }
}
  • Extend AbstractJRebirthPreloader — only implement scene creation and hide animation.
  • Register the class in preloadAndLaunch(MyPreloader.class, args) or Maven javafx.preloader property when not using the default.

Application Customization

To define your own Application class you have 2 options:

The AbstractApplication class will do all extra stuff required to launch JRebirth engine. You don't have to bother about it.

This class skeleton provides some hooks to allow customization of the application start up.

Please note that one method is mandatory ! You must define a first Model Class to load the first Model that will initialize the first Node attached to the RootNode (automagically created) of your Scene.

If you have used the Maven archetype org.jrebirth.archetype you have obtained this source code (otherwise that you can copy-paste it):

package org.jrebirth.af.sample;

import java.util.Arrays;
import java.util.List;

import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import org.jrebirth.af.api.resource.ResourceItem;
import org.jrebirth.af.api.resource.font.FontItem;
import org.jrebirth.af.api.ui.Model;
import org.jrebirth.af.core.application.DefaultApplication;
import org.jrebirth.af.sample.resources.SampleFonts;
import org.jrebirth.af.sample.resources.SampleStyles;
import org.jrebirth.af.sample.ui.SampleModel;

/**
 * The class <strong>SampleApplication</strong>.
 *
 * @author
 */
public final class SampleApplication extends DefaultApplication<StackPane> {

    /**
     * Application launcher.
     *
     * @param args the command line arguments
     */
    public static void main(final String... args) {
        preloadAndLaunch(args);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Class<? extends Model> firstModelClass() {
        return SampleModel.class;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void customizeStage(final Stage stage) {
        stage.setFullScreen(false);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void customizeScene(final Scene scene) {
        addCSS(scene, SampleStyles.MAIN);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected List<? extends ResourceItem<?, ?, ?>> getResourceToPreload() {
        return Arrays.asList(new FontItem[] {
                SampleFonts.SPLASH,
        });
    }

}
  • extends DefaultApplication<StackPane> — root scene node type; framework instantiates this pane automatically.
  • preloadAndLaunch(args) — recommended launcher (preloader + JRebirth engine).
  • firstModelClass() — mandatory; first screen Model attached to the root pane after boot.
  • customizeStage / customizeScene — hook to resize, title, key bindings, and addCSS stylesheets.
  • getResourceToPreload() — fonts/images loaded before first paint (needed for CSS @font-face).

The SampleModel.class is shown and explained into the Ui page.

Root Node

AbstractApplication & DefaultApplication classes are using a generic type that represents the first JavaFX node hold by the scene. This node will be instantiated automatically by the framework and could be accessed by calling the protected method getRootNode(). You must define it in the class definition as generic type, this type must extend Pane class.

public final class MyApp extends DefaultApplication<StackPane> {
    // Framework instantiates StackPane as scene root — access via getRootNode()
}
  • Generic type parameter — root pane class (StackPane, BorderPane, …); must extend Pane.
  • getRootNode() — protected accessor to the auto-created root after startup.

First Model Class

The method Class<? extends Model> firstModelClass() is mandatory to define which UI model will be attached to the root node of the scene.

@Override
public Class<? extends Model> firstModelClass() {
    return MainWorkbenchModel.class;
}
  • Return type — any Model subclass; its View is built off-screen on JTP, then attached on JAT.

This first model will be created into the JRebirth Thread Pool (JTP), then it will be attached to the root node into the JavaFX Application Thread (JAT).

First Model Descriptor

As an alternative to firstModelClass(), you can override firstModelDescriptor() to provide a ModelDescriptor with additional configuration. This is useful when your first model needs configuration data (e.g., StackModel with a StackConfig):

@Override
public ModelDescriptor firstModelDescriptor() {
    return ModelDescriptor.of(MainWorkbenchModel.class)
        .withData(StackConfig.builder().initialTab("home").build());
}
  • firstModelDescriptor() — alternative to firstModelClass() when the first Model needs constructor/config data.
  • ModelDescriptor.of(Class) — names the Model class to instantiate at startup.
  • .withData(...) — passes configuration consumed by the Model during setup().

Application Title

The method String applicationTitle() is simply used to define the name of the application displayed by the stage (OS window) and used by OS task bar.

By default it will retrieve values from properties file (default is jrebirth.properties):

  • applicationName={} powered by JRebirth ({} is replaced by application class simple name)
  • applicationVersion=1.0
@Override
protected String applicationTitle() {
    return "My App — v1.2";
}
  • applicationTitle() — window title and OS task-bar label; override to skip property lookup.
  • Return a plain string; the framework sets it on the primary Stage during startup.

Stage customization

The first stage object is provided by the JavaFX launcher, the method void customizeStage(final Stage stage) allows doing some stage customizations.

@Override
protected void customizeStage(final Stage stage) {
    stage.setTitle(applicationTitle());
    stage.setMaximized(true);
    stage.centerOnScreen();
}
  • customizeStage(Stage) — hook after the primary stage exists, before it is shown.
  • Safe place for size, position, icons, and fullscreen policy — not for attaching Models.

Scene customization

The scene object automatically attached to the default stage stage is built by the protected method Scene buildScene() that could be overridden as needed. By defaut it creates a default scene with these attributes :

  • Width = 800 (applicationSceneWidth parameter)
  • Height = 600 (applicationSceneHeight parameter)
  • Background Color = Transparent (applicationSceneBgColor parameter)
  • Root = Automatically built according to the generic type used

Theses properties are customizable with a properties file, this is explained below into the Configuration section.

Another method let you customize the scene :

  • void customizeSscene(final Scene scene).

For example you can listen some key binding to perform a global action. The Presentation application uses it to listen <Ctrl> + <+> and <Ctrl> + <-> key combo to zoom in/out the whole scene.

This method is also useful to attach a stylesheet to the scene. The modern approach uses a StyleSheetItem resource:

  • addCSS(scene, MyStyles.MAIN);

This pattern delegates resource resolution to the JRebirth resource engine and is JPMS-compatible. The older scene.getStylesheets().add(loadCSS("style/sample.css")) still works but is discouraged in modular applications.

@Override
protected void customizeScene(final Scene scene) {
    addCSS(scene, SampleStyles.MAIN);
    scene.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
        if (e.isControlDown() && e.getCode() == KeyCode.PLUS) {
            zoomIn();
        }
    });
}
  • addCSS(scene, StyleSheetItem) — preferred way to load CSS via the resource engine (JPMS-safe).
  • customizeScene(Scene) — runs after buildScene(); use for global key bindings and scene-level styling.
  • Keep node mutations minimal here; attach Models through firstModelClass() / waves instead.

Resources preloading

The @Preload annotation can be used on resource enum classes to automatically register them for preloading. This replaces the need to manually list resources in getResourceToPreload(). Simply annotate your resource enum with @Preload and the framework will discover and load those resources during the pre-init phase.

Custom case for fonts: JavaFX applications are able to use fonts through programmatic declarations or with CSS declaration (in .css files. or inline).

If font used by CSS are not provided by the platform running the application, it must be provided and loaded by the application.

JRebirth provides a simple way to embed and declare font: this mechanism is explained in the custom topic: Managing Fonts.

The method List<ResourceEnum> getResourceToPreload() is used to preload resources to allow them to be used earlier (ie font in CSS declaration). They are loaded at boot in the same time than stylesheets.

@Override
protected List<? extends ResourceItem<?, ?, ?>> getResourceToPreload() {
    return Arrays.asList(SampleFonts.MAIN, SampleImages.LOGO);
}
  • getResourceToPreload() — fonts/images loaded during pre-init so CSS @font-face resolves on first paint.
  • Prefer @Preload on resource enums when every member of the enum should load at boot.

Running Waves

The JRebirth Application class allow running Waves before and after the creation of the first model class.

A Wave is a JRebirth Event that could be process by any JRebirth components, they are carrying throught JRebirth classes and threads.

You can add your own wave with the two following methods :

  • List<Wave>preBootWaveList()
  • List<Wave>postBootWaveList()

The waves returnes will be processed sequentially althought they could be processed by different threads.

In this method you are allowed to call visible methods from the javafx.application.Application class, in example the getParameter() will give you the arguments passed to command line.

Don't forget that you can chain your waves if you need to do more than one thing.

JRebirth Analyzer example :

package org.jrebirth.af.showcase.analyzer;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import org.jrebirth.af.api.resource.ResourceItem;
import org.jrebirth.af.api.ui.Model;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.api.wave.WaveGroup;
import org.jrebirth.af.core.application.DefaultApplication;
import org.jrebirth.af.core.wave.WBuilder;
import org.jrebirth.af.showcase.analyzer.service.LoadEdtFileService;
import org.jrebirth.af.showcase.analyzer.ui.editor.EditorWaves;
import org.jrebirth.af.showcase.analyzer.ui.workbench.WorkbenchModel;

/**
 * The class <strong>JRebirthAnalyzer</strong>.
 *
 * The application that demonstrate how to use JRebirth Framework.
 *
 * It also allows showing all JRebirth events.
 *
 * @author Sébastien Bordes
 */
public final class JRebirthAnalyzer extends DefaultApplication<StackPane> {

    /**
     * Application launcher.
     *
     * @param args the command line arguments
     */
    public static void main(final String... args) {
        Application.launch(JRebirthAnalyzer.class, args);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Class<? extends Model> firstModelClass() {
        return WorkbenchModel.class;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected String applicationTitle() {
        return "JavaFX 2.0 - JRebirth Event Analyzer";
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void customizeScene(final Scene scene) {
        scene.getStylesheets().add("css/analyzer.css");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void customizeStage(final Stage stage) {
        // Center the stage
        stage.centerOnScreen();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Wave> postBootWaveList() {
    // ...

Minimal boot waves (open a file passed on the command line):

@Override
protected List<Wave> postBootWaveList() {
    final String path = getParameters().getNamed().get("file");
    if (path == null) {
        return Collections.emptyList();
    }
    return Collections.singletonList(
        WBuilder.of(MyWaves.DO_OPEN)
            .data(WBuilder.waveData(MyWaves.FILE, new File(path)))
            .build());
}
  • postBootWaveList() — waves processed after the first Model is attached; safe to touch Application APIs.
  • getParameters().getNamed() — reads --file=... style CLI arguments from JavaFX.
  • WBuilder.of(...).data(...).build() — builds a wave you can chain with other boot tasks.

Default key shortcuts

The AbstractApplication class is using two defaults hotkey:

@Override
protected KeyCode fullScreenKeyCode() {
    return KeyCode.F11; // default is F10; return null to disable
}

@Override
protected KeyCode iconifiedKeyCode() {
    return null; // disable minimize shortcut
}
  • fullScreenKeyCode() — hotkey toggling fullscreen (default F10); return null to disable.
  • iconifiedKeyCode() — hotkey iconifying the stage (default F11); return null to disable.
  • Overrides apply globally to the primary stage created by the Application class.

Exception Manager

JRebirth creates its own uncaught exception handlers in order to log exceptions that were not caught by application code.

It's possible to customize them by overriding methods listed hereafter:

  • Exception handler of the JavaFX Application Thread
@Override
protected UncaughtExceptionHandler getJatUncaughtExceptionHandler() {
    return new JatUncaughtExceptionHandler(this);
}
  • getJatUncaughtExceptionHandler() — catches uncaught exceptions on the JavaFX Application Thread.

  • Exception handler of the JRebirth Internal Thread

@Override
protected UncaughtExceptionHandler getJitUncaughtExceptionHandler() {
    return new JitUncaughtExceptionHandler(this);
}
  • getJitUncaughtExceptionHandler() — catches uncaught exceptions on JIT (messaging thread).

  • Default Exception handler of all other threads

@Override
protected UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() {
    return new DefaultUncaughtExceptionHandler(this);
}
  • getDefaultUncaughtExceptionHandler() — fallback for JTP slots and other pooled threads.

Initialization Phases

  • [init] (#Init_Phase)
  • [start] (#Start_Phase)

Init Phase

The Initialization phase is composed by:

  • 00-10% - Begin Initialization (Loading Resources transition)
  • 10-30% - Customizable Pre-Init Steps
  • 30-40% - Loading Message Files
  • 40-50% - Loading Configuration Files
  • 50-60% - Attach Exception Handler and Prepare the JIT
  • 60-70% - Preload Fonts and attach CSS Files
  • 70-90% - Customizable Pre-Init Steps
  • 100% - trigger the start phase

Customizable steps are handled by 2 methods to override:

@Override
protected void preInit() {
    notifyPreloader(new ProgressNotification(0.15));
    // custom work between 10% and 30% of boot progress
    notifyPreloader(new ProgressNotification(200)); // custom message id
}
  • preInit() — runs during init phase (10–30% progress); use for early custom setup.
  • notifyPreloader(ProgressNotification(double)) — fine-grained bar update (0.11–0.29).
  • notifyPreloader(ProgressNotification(int)) — message id understood by your preloader (e.g. 200, 300).
@Override
protected void postInit() {
    notifyPreloader(new ProgressNotification(0.75));
    // custom work between 70% and 90% of boot progress
    notifyPreloader(new ProgressNotification(800)); // custom message id
}
  • postInit() — runs late in init (70–90% progress), after fonts/CSS preload.
  • Progress doubles use range 0.71–0.89; message ids 800 or 900 for custom preloader text.

Start Phase

The Start phase will build and attach the scene object. Then it will start the JRebirth Thread (JIT) and show the stage.

Manage Configuration

JRebirth provides a configuration engine that allow to parse configuration files and inject values into application.

@Configuration

Your application class can use the dedicated @Configuration annotation. The AbstractApplication class use a default one:

@Configuration(".*jrebirth")
  • Default on AbstractApplication — loads *-jrebirth.properties from the classpath.
  • Matched files inject parameters into the application at startup.

Hereafter you have a full annotation usage:

@Configuration(value = ".*-jrebirth", extension = "properties", schedule = 60)
  • value = ".*-jrebirth" — regex filter; matches files like myapp-jrebirth.properties.
  • extension = "properties" — file suffix without the dot.
  • schedule = 60 — optional reload check interval in seconds (0 = no hot reload).

This annotation has 3 properties:

  • value
  • extension
  • schedule

Value (default property)

Define the wildcard used to find configuration files.

The format is the same as Regex Pattern (ie: .-jrebirth => for abc-jrebirth.EXTENSION files, abc matches the . regex part)

The default value is empty, no search will be done.

Extension

Define the file extension to find configuration files.

The extension must not included the first dot (ie: properties => for abc-jrebirth.properties files)

The default value is “properties” to load properties files

Schedule

Define the delay used to check if the file has changed in order to reload configuration files.

This value is in seconds.

The default value is 0, no check will be done (this feature is still under development)

Avoid Configuration

It's possible to avoid configuration mechanism, for example if you want to use your own and don't need another process at start-up.

You can disable it by setting an empty @Configuration annotation.

@Configuration
  • Empty @Configuration — disables automatic configuration file scanning.

Manage Localization

JRebirth provides a Internationalization engine that allow to localize internal resources and also your resources. It parses properties files and inject values into application.

@Localized

Your application class can use the dedicated @Localized annotation. The AbstractApplication class use a default one:

@Localized(".*_rb")
  • @Localized(".*_rb") — loads MyMessages_rb.properties, MyMessages_fr_rb.properties, etc.
  • Place message bundles on the classpath; keys become available through the resource engine.

This annotation has 2 properties:

  • value
  • schedule

Value (default property)

Define the wildcard used to find configuration files.

The format is the same as Regex Pattern (ie: ._rb => for MyMessages_rb.properties files, MyMessages matches the . regex part).

The default value is empty, no search will be done.

Schedule

Define the delay used to check if the file has changed in order to reload properties files.

This value is in seconds.

The default value is 0, no check will be done (this feature is still under development)

Avoid Localization

It's possible to avoid localization mechanism, for example if you want to improve performance by avoiding any translation into logs.

You can disable it by setting an empty @Localized annotation.

@Localized
  • Empty @Localized — disables i18n bundle scanning (useful for headless or performance-sensitive apps).
Thread Management
Writing concurrent application could be painful ! Not with JRebirth

Thread Management

In 30 seconds

JAT = JavaFX UI thread (update displayed nodes). JIT = JRebirth messaging (waves, listen/send). JTP/HPTP = background pools (heavy work). Commands/Services pick threads via @RunInto or base classes. From non-component code use JRebirth.runIntoJAT(...), runIntoJIT(...), runIntoJTP(...).

How to use

  1. UI updates on nodes in the scene → JAT (DefaultUICommand, @RunInto(JAT)).
  2. Wave listen/send and notifier work → JIT (automatic for listen / sendWave).
  3. File I/O, parsing, remote calls → JTP (DefaultPoolCommand, @RunInto(JTP)).
  4. Service task methods run on JTP by default; return waves to Models are handled on JAT.
  5. Stuck on the wrong thread? Use JRebirth.runIntoJAT(() -> { ... }) — not raw Platform.runLater as a pattern.

Threading overview

JRebirth is multi-threaded, not only by using Task Worker provided by JavaFX APIs. JRebirth has got its own Thread to manage local events (called waves) allowing components to communicate with each others. It also allows to manage multiple threads in a very simple manner with its included thread pool.

Thus all inner JRebirth tasks are processed into a custom thread and don't infer with the JavaFX Application Thread which have to manage user events and some UI instantiation.

Lags, UI Freeze … are lost to history :D

What happens when you debug a JRebirth application ? You can observe a lot of threads, but don't be scared !! Everything is at the right isolated place doing the right thing.

The most important are :

  • JAT - JavaFX Application Thread
  • JIT - JRebirth Internal Thread
  • JTP - JRebirth Thread Pool (name pattern is JTP Slot ‘n’)
  • HPTP - High Priority Thread Pool (name pattern is HPTP Slot ‘n’)

Other threads are related to JavaFX platform, JRebirth only creates one thread and two Thread Pools.

JRebirth Thread Pool and High Priority Thread Pool have the same size, computed like this:

  • Number of available Core * threadPoolSizeRatio parameter

The default parameter value is 2, so each thread pool will have a size of 16 on Core i7 (Quad Core with HyperThreading). You can use a double value to divide this amount if you think that it can disturb your platform performances (0.250 value will only provide a thread pool size of 2 on a such platform).

Obviously a minimum size of 1 will be used if your thread pool ratio is too low or if the platform has not enought cpu cores.

Concurrent Class Diagram

Thread Usage

Each thread shall manage specific tasks, let's see their aims.

JAT

JavaFX Application Thread is the graphical thread of the toolkit, you shouldn't perform long task into it, but you must update all node attached to the displayed scene into it. It's the equivalent of the former EDT (Event Dispatch Thread) in Swing. If you try to update a node attached to the main JavaFX scene outside it you will obtain an ugly Exception.

// Wrong — may throw if label is in the scene
statusLabel.setText("Done");

// Right — marshal to JAT from JTP or JIT
JRebirth.runIntoJAT(() -> statusLabel.setText("Done"));
  • Any mutation on nodes attached to the displayed scene must run on JAT.

JIT

JRebirth Internal Thread is the internal thread of JRebirth Application Framework. It will be used to host the communication engine between all JRebirth Components. If you start a long task into it it will freeze all communication tasks because all runnable added will be executed synchronously according to FIFO rule (First-In First-Out).

// Safe on JIT — register listeners, send waves
listen(MyWaves.DO_REFRESH);
sendWave(MyWaves.DO_REFRESH);

// Risky on JIT — blocks all messaging until perform() returns
getCommand(HeavyCommand.class).run();
  • listen / sendWave belong on JIT — the Notifier rejects calls from other threads.
  • Never run long work directly on JIT; use JTP commands or services instead.

JTP

JRebirth Thread Pool is designed to perform all other long task your application require, you just have to remember that any graphical update still require to be done into JAT. Moreover any JRebirth internal configuration must be performed into JIT (ie: listen a WaveType).

@RunInto(RunType.JTP)
public class ParseFileCommand extends DefaultCommand {

    @Override
    protected void perform(final Wave wave) {
        final List<String> lines = readAllLines(pathFrom(wave));
        sendWave(MyWaves.DO_LINES_LOADED, WBuilder.waveData(MyWaves.LINES, lines));
    }
}
  • @RunInto(JTP) — file I/O and parsing off UI and JIT.
  • Return results via sendWave — Model listeners receive them on JAT automatically.

HPTP

High Priority Thread Pool has been added to be able to assign a priority to a long task. On small platform or when using very long task, the JTP can be overloaded and we should create an higher priority task to trigger an User interface refresh. The HPTP will be used to trigger higher priority task when JTP is full. It has same settings than JTP.

Quick Reference

Task Thread How
Update displayed node JAT @RunInto(JAT) or DefaultUICommand
Send/receive waves JIT automatic for listen/sendWave
Heavy computation JTP @RunInto(JTP) or DefaultPoolCommand
Priority task HPTP @Priority(PriorityLevel.Highest) on service
From non-component code any JRebirth.runIntoJAT(...), JRebirth.runIntoJIT(...), JRebirth.runIntoJTP(...)

Example — update a label from background work:

JRebirth.runIntoJAT(() -> statusLabel.setText("Done"));
  • runIntoJAT — marshals the runnable onto the JavaFX Application Thread (safe for scene nodes).
  • Use after JTP/IO completes; never touch attached nodes from JTP directly.

Thread Rules

JavaFX Application Thread (JAT)

JAT is the the graphical thread of the JavaFX toolkit (identical to Swing EDT), all UI tasks must be perform into it only if a direct link can be establish between the graphical component and the displayed scene. So if you call setText(“myText”) on a Text node:

  • You must call it into JAT if the node is displayed or linked to the displayed scene.
  • You can call in whatever thread you want if the node isn't linked to the displayed scene.

JavaFX toolkit let you prepare some tree of node into a separate thread and then attached it to the displayed scene. This is how JRebirth load and display any Model, the PrepareModelCommand will run into JTP to create the Model root Node with all its children. Then the AttachModelCommand will be run into JAT to attach the model root node into another node already displayed into the Scene.

JRebirth Internal Thread

JIT does same things than JAT but for managing communication between JRebirth Components. It mainly manage the JRebirth Notifier. So any call to Notifier outside JIT will raise a new Exception. For a standrad usage it will be totally transparent for you.

But sometimes you can want to trigger a command within JIT to be sure it will be executed before another wave is handled. This is a really risky task, do it on your own responsability.

JRebirth Thread Pool

JRebirth provides 2 thread pools to run long task asynchronously without freezing neither the User Interface (JAT) nor JRebirth Messaging (JIT).

All Wave processing tasks are automatically done into the JIT.

When the JRebirth Framework needs to update UI (thanks to Model area), it's done automatically done into the JAT. No matters to have !

But when you call a component directly (synchronous method: getCommand, getService, getModel), your call is processed into the current thread, so you must pay attention to what you are doing.

Examples

If you are into the JIT

  • getCommand => the code will be processed synchronously into JIT, but if you call the run method of the command it will be run into the thread defined by the command configuration.
  • getModel => all called methods of the model will be processed into the JIT ==> Can Break !!! Toolkit will raise an error if any node displayed within the current scene is updated.
  • getService => all methods called of the service will be processed into the JIT, can dramatically slow down messaging.

When you are into the JIT you can use JRebirth.runIntoJAT that call internally Platform.runLater to perform UI updates.

JRebirth.runIntoJAT(() -> view().statusLabel().setText("Ready"));
  • runIntoJAT(Runnable) — preferred over raw Platform.runLater in JRebirth apps.
  • Call from JIT/JTP after async work completes.

JRebirth Framework offers some default commands to do the trick (DefaultUiCommand). Moreover if you send a Wave with a WaveType listened by a model, it will be automatically processed into the JAT (Cool JRebirth Magic).

If you are into the JAT

  • getCommand, getService => this code will be processed into JAT: Don't perform long task or you will freeze the application !!!
  • getModel => actions will be done synchronously into JAT ==> tolerated for short UI actions

When you are in the JAT you must use JRebirth.runIntoJIT that call internally JRebirthThread.runLater to run tasks into the core thread. You can also use JRebirth.runIntoJTP to run task within a slot of available thread pool.

// From JAT — schedule messaging work on JIT
JRebirth.runIntoJIT(() -> sendWave(MyWaves.DO_BACKGROUND_START));

// From JAT — offload heavy work to JTP
JRebirth.runIntoJTP(() -> parseLargeFile(file));
  • runIntoJIT — wave registration and sendWave must not run on JAT directly.
  • runIntoJTP — background work without blocking the UI thread.

JRebirth Framework offers some default commands to force to run into JIT & JTP (DefaultCommand and DefaultPoolCommand). You can also send a wave that will trigger a command, or call a service into another thread that JAT.

Run Synchronously

Sometimes you want to run a task within another thread but synchronously. It's a bad idea but can be required in some particular cases. You can use custom methods:

  • JRebirth.runIntoJATSync
  • JRebirth.runIntoJITSync
  • JRebirth.runIntoJTPSync

Each will wait synchronously the end of the task run within the wanted thread.

JRebirth.runIntoJATSync(() -> {
    previewPane.getChildren().setAll(buildPreviewNodes());
});
// continues on calling thread only after JAT work completes
  • Sync variants block the caller until the target thread finishes — use sparingly.
  • Prefer async runIntoJAT + return wave for service-style flows.

Use Case

If you want to call a service which make an asynchronous call to a remote server. You can use a Service Task method to initiate the call (By default this call will be managed into JRebirth Thread Pool: JTP), but the return must be managed into the JAT:

  • Either use a wave to send data received from remote server, default service will generate a such wave (automatically processed into the JAT for models that listen it)
  • Either call the model from the JAT and access to service results (the first way way is the best to use)

Wave customization

When components communicate using Wave, any Wave handler method can be managed in a specific thread by using @RunInto annotation.

The default behavior is:

  • Into JAT for Model
  • Into JIT for Service
  • Into JIT for Command

3 kinds of Wave are managed differently (not customizable) because they trigger special Component interaction:

  • attachUI => always into JAT
  • returnData => always into JTP
  • callCommand => Depends on Command called

Use @RunInto(value = RunType.JAT) on your wave handler method to override the default thread. For example, a Service method that needs to update UI directly can be annotated with @RunInto(RunType.JAT) to force execution on the JavaFX Application Thread regardless of the component's default behavior.

@RunInto(RunType.JAT)
public void doUpdateLabel(final String text, final Wave wave) {
    view().statusLabel().setText(text);
}
  • Overrides default handler thread (Models → JAT by default; Services → JIT).
  • Still declare listen(...) or @OnWave — annotation only affects where the handler body runs.
To log or not to log !
Logging is so important to diagnose UI bugs.

Logging

My first idea about logging for JavaFX apps was to build myself a small lightweight and powerful module to add log capability to JRebirth Framework.

But after some hundred of lines of code written, I realized that using a real logging library could be interesting and not too heavy to embed.

Logging Facade

I choose to add dependency to slf4j-api : Simple Logging Facade 4 Java

This API is lightweight because the jar is near to 10 kb.

Add the SLF4J API to your pom.xml:

<dependency>
	<groupid>org.slf4j</groupid>
	<artifactid>slf4j-api</artifactid>
	<version>1.7.5</version>
</dependency>

The slf4j api allow to declare logger for JRebirth Framework but doesn't provide any logger implementation. So you need to add another dependency to choose the implementation you want to use.

By default all logs are rejected and you will have this message into the Java console at startup:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See https://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

There are 3 implementations available:

  • NOP
  • LOGback
  • SimpleLogger

NOP

To avoid this error message to appear you can add the No-OPeration dependency, it will log nothing but avoid the previous error message:

<dependency>
	<groupid>org.slf4j</groupid>
	<artifactid>slf4j-nop</artifactid>
	<version>1.7.5</version>
</dependency>

LOGback

Personally I choose LOGback implementation because it represents a good compromise between performances and customization. It was finely integrated because it was written by the same team as slf4j.

LOGBack jars are quite heavy and weight more than 800 kb so it could be a problem for tiny applications. To use it you must add this dependency into your pom.xml :

<dependency>
	<groupid>ch.qos.logback</groupid>
	<artifactid>logback-classic</artifactid>
	<version>1.0.13</version>
</dependency>

Then you must add a configuration file like this one into the application classpath (from the JRebirth Analyzer showcase):

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>

	<appender name="FILE" class="ch.qos.logback.core.FileAppender">
		<file>JRebirthAnalyzer.log</file>
		<encoder>
			<pattern>%date %level [%thread{6}] %logger{10} [%file:%line] %msg%n</pattern>
		</encoder>
	</appender>

	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
		<!-- %level %msg%n -->
			<pattern>%level [%thread] %file:%line - %msg%n</pattern>
		</encoder>
	</appender>


	<root level="trace">
		<appender-ref ref="STDOUT" />
		<appender-ref ref="FILE" />
	</root>

</configuration>

SimpleLogger

If you don't want to embed 800 kb of jar to provide logging feature you can use the simple logger provided by slf4j, it's only a 10 kb jar file.

You just have to add this dependency to your pom.xml:

<dependency>
	<groupid>org.slf4j</groupid>
	<artifactid>slf4j-simple</artifactid>
	<version>1.7.5</version>
</dependency>

JRebirth Logs

All JRebirth logs use an internationalized engine allowing us to provide extensible log messaging.

It could be seen as an overkill feature but it has some advantages:

  • Provide localized log message
  • Manage log level activation automatically
  • Parameterize log level, to increase or decrease it by customization
  • Disable Message resolution for high performance

Note that you can still use your logger basic features.

Short UML Diagram:

Logging Class Diagram

JRebirth provides its own LoggerFactory that you can initialize like this (from JRebirthThread, which also implements a message container interface):

public final class JRebirthThread extends Thread implements ConcurrentMessages {

    /** The class logger. */
    private static final JRLogger LOGGER = JRLoggerFactory.getLogger(JRebirthThread.class);

Then you can log your message like this, using a MessageItem constant declared on the message container interface:

public void runIntoJTP(final JRebirthRunnable runnable) {

    if (getFacade().executorService().checkAvailability(runnable.priority())) {
        getFacade().executorService().execute(runnable);
        LOGGER.log(JTP_QUEUED, runnable.toString());
    } else {
        getFacade().highPriorityExecutorService().execute(runnable);
        LOGGER.log(HPTP_QUEUED, runnable.toString());
    }

}

All these log messages are store into an interface implemented by the class to let them accessible

package org.jrebirth.af.core.concurrent;

import static org.jrebirth.af.core.resource.Resources.create;

import org.jrebirth.af.api.resource.i18n.JRLevel;
import org.jrebirth.af.api.resource.i18n.MessageItem;
import org.jrebirth.af.core.log.JRebirthMarkers;
import org.jrebirth.af.core.resource.i18n.LogMessage;
import org.jrebirth.af.core.resource.i18n.MessageContainer;

/**
 * The class <strong>ConcurrentMessages</strong>.
 *
 * Messages used by the Concurrent package.
 *
 * @author Sébastien Bordes
 */
public interface ConcurrentMessages extends MessageContainer {

    /** JRebirthThread. */

    /** "Runnable submitted to JTP with hashCode={0}" . */
    MessageItem JTP_QUEUED = create(new LogMessage("jrebirth.concurrent.jtpQueued", JRLevel.Trace, JRebirthMarkers.CONCURRENT));

    /** "Runnable submitted to HPTP with hashCode={0}" . */
    MessageItem HPTP_QUEUED = create(new LogMessage("jrebirth.concurrent.hptpQueued", JRLevel.Trace, JRebirthMarkers.CONCURRENT));

    /** "An exception occurred during JRebirth BootUp" . */
    MessageItem BOOT_UP_ERROR = create(new LogMessage("jrebirth.concurrent.bootUpError", JRLevel.Error, JRebirthMarkers.CONCURRENT));

    /** "An exception occurred into the JRebirth Thread". */
    MessageItem JIT_ERROR = create(new LogMessage("jrebirth.concurrent.jitError", JRLevel.Error, JRebirthMarkers.CONCURRENT));

    /** "An error occurred while shutting down the application ". */
    MessageItem SHUTDOWN_ERROR = create(new LogMessage("jrebirth.concurrent.shutdownError", JRLevel.Error, JRebirthMarkers.CONCURRENT));

    /** AbstractJrbRunnable. */

    /** "Run> {0}". */
    MessageItem RUN_IT = create(new LogMessage("jrebirth.concurrent.runIt", JRLevel.Trace, JRebirthMarkers.CONCURRENT));

    /** "Thread error : {0} ". */
    MessageItem THREAD_ERROR = create(new LogMessage("jrebirth.concurrent.threadError", JRLevel.Error, JRebirthMarkers.CONCURRENT));

    /** JRebirthThreadPoolExecutor. */

    /** "JTP returned an error" . */
    MessageItem JTP_ERROR = create(new LogMessage("jrebirth.concurrent.jtpError", JRLevel.Error, JRebirthMarkers.CONCURRENT));

    /** "JTP returned an error with rootCause =>". */
    MessageItem JTP_ERROR_EXPLANATION = create(new LogMessage("jrebirth.concurrent.jtpErrorExplanation", JRLevel.Error, JRebirthMarkers.CONCURRENT));

    /** "Future (hashcode={}) returned object : {0}". */
    MessageItem FUTURE_DONE = create(new LogMessage("jrebirth.concurrent.futureDone", JRLevel.Trace, JRebirthMarkers.CONCURRENT));

}

Event Tracking

JRebirth can log component lifecycle events (creation, access, destruction) and wave flows for analysis by the JRebirth Analyzer tool.

To enable, configure these loggers in your logback.xml:

<logger name="org.jrebirth.af.core.facade" level="TRACE"/>
<logger name="org.jrebirth.af.core.link" level="TRACE"/>

The output format matches the Analyzer's EDT file parser. Redirect to a file appender for post-mortem analysis.

Facades Area
Simplify component accessibility.

Facade(s)

In 30 seconds

The GlobalFacade (from your Application) owns UiFacade, CommandFacade, ServiceFacade, and BehaviorFacade. Each facade stores components by UniqueKey (class = singleton, extra key parts = multiton). Use getModel, getCommand, getService — never new top-level components yourself.

How to use

  1. From any FacadeReady component, call globalFacade() to reach the global facade.
  2. Retrieve UI: getModel(MyModel.class) or getModel(MyModel.class, keyPart).
  3. Run actions: getCommand(MyCommand.class).run().
  4. Async work: returnData(MyService.class, MyService.DO_TASK, waveData...).
  5. Behaviors: attach via the BehaviorFacade through BehavioredComponent APIs on Models/Commands/Services.

JRebirth provides 4+1 Facades used to manage its dedicated pattern wB-CS-Mvc.

Overview

Short UML Diagram:

Global Facade

One Facade to rule them all

JRebirth uses a global facade automatically created by JRebirth AbstractApplication class. Its main role is to manage all JRebirth components by using Facades.

Internal Communication

The global facade creates automatically the JRebirth notification engine. You should read the Notifier page to have more informations.

Linked with Application

The global facade also allows to communicate with the Application class and therefore with its stage and scene.

Manage Local Facades

It allows to manage the three main facades (+extra one):

  • CommandFacade
  • ServiceFacade
  • UiFacade
  • BehaviorFacade

The GlobaleFacadeBase allows to get each of these facades by calling appropriate getters:

    LocalFacade<Model> uiFacade();
  • uiFacade() — accessor on GlobalFacade for all UI Models (same pattern for commandFacade(), serviceFacade()).

Minimal retrieval from a Model:

// Same thread as caller — use only for quick synchronous access
final OtherModel other = getModel(OtherModel.class);
other.refresh();

getCommand(SaveCommand.class).run();
returnData(FileService.class, FileService.DO_SAVE, WBuilder.waveData(FileWaves.FILE, file));
  • getModel(Class) — UiFacade lookup; creates instance on first access if absent.
  • getCommand(Class).run() — CommandFacade; runs on the command's configured thread.
  • returnData(...) — ServiceFacade async task; result arrives as a return wave.

This link is bidirectionnal because global facade is accessible from the 3 main facades by calling :

  • getGlobalFacade() (each facade extends the AbstractGlobalReady abstract class which implement GlobalReady interface.
package org.jrebirth.af.api.facade;

@FunctionalInterface
public interface GlobalReady {

    GlobalFacade globalFacade();
}
  • GlobalReady — implemented by all facades and components with facade access.
  • globalFacade() — entry point to Ui/Command/Service/Behavior facades.

Local Facades

There are 4 LocalFacade, each one is responsible of an area storing same kind of components.

Basic Features

Each Facade can manage its components (also called readyObject) throught some public methods.

  • register : store a pre-built component
  • unregister : remove a component
  • exists : check if the component is already registered, it could be released
  • retrieve : used to get a component (build and register it if needed)
    <E extends R> void register(final UniqueKey<E> uniqueKey, final E readyObject);
  • register(key, instance) — store a pre-built component under an explicit key.
  • retrieve(key) / getModel / getCommand — fetch existing or create-and-register.
  • exists(key) — check registration without creating.
  • unregister(key) — drop from facade; component may be GC'd if nothing else holds it.

Component Key

Each Component (b-CSM) are registered into the facade using a UniqueKey, there are 2 options:

ClassKey

The simplest key is the ClassKey, it's only composed by the class object of the component, thus the can only be stored once into the facade (=singleton).

// Singleton — one CounterModel for the whole application
final CounterModel model = getModel(CounterModel.class);
  • getModel(Class) — uses ClassKey; second retrieve returns the same instance.
  • Same pattern for getCommand(MyCommand.class) and getService(MyService.class).

MultitonKey

The MultitonKey uses also the class of the component but add a variable part to be able to store several instances of a same Component.

// Multiton — one EditorModel per document id
final EditorModel doc1 = getModel(EditorModel.class, "doc-1");
final EditorModel doc2 = getModel(EditorModel.class, "doc-2");
  • Extra key parts distinguish instances of the same component class.
  • Key parts are concatenated via toString() — use stable, unique identifiers.

Convenient Builder

JRebirth API has got a lot of methods that take the Component Class with additional objects as key parts, but the API also provides a convenient class used to build key.

    static <C> UniqueKey<C> create(final Class<C> clazz, final Object... keyPart);
  • create(MyModel.class) — singleton key (class only).
  • create(MyModel.class, "tab-1") — multiton: several MyModel instances keyed by "tab-1".
  • Key parts are serialized via toString() — use stable, unique values.

Component Lifecycle

When a component is retrieved from its facade:

  1. retrieve() — if not cached, creates a new instance
  2. setup() — initializes the component (calls initCommand/initService/initModel)
  3. ready — component is active and can receive waves
  4. release() — component is deregistered and eligible for GC

Components with wave listeners are strongly referenced by the Notifier and won't be collected until unlisten() is called or the component is explicitly released.

// Typical lifecycle from a Model
final DetailModel detail = getModel(DetailModel.class, itemId);
detail.refresh(item);          // ready — can send/receive waves
// ...
globalFacade().uiFacade().release(detail.getModelKey());  // explicit cleanup
  • First getModel → retrieve + setup + ready.
  • release(key) — deregister from facade; Notifier drops listeners if component releases properly.

Provide Tracking

JRebirth allows to track all creation & finalization of each component (Command, Service, Model, Behavior) and also track the emission of waves and their path.

These events are logged using the JRebirth event tracking framework. The JRebirth Analyzer application can load and replay these log files to visualize component creation, access patterns, and wave flows. Enable tracking by configuring the org.jrebirth.af.core.facade logger at TRACE level.

Notifier & Components
Provide a communication means between top-level components

Messaging engine

In 30 seconds

The Notifier is JRebirth's event bus on JIT. Components listen to WaveTypes during initModel / initService / initCommand, then sendWave to notify others. No direct references between Models and Services are required.

How to use

  1. Define WaveType and WaveItem constants (see Wave page).
  2. In the listener, call listen(MyWaves.DO_SOMETHING) inside the right initXxx() method.
  3. Add a handler method (doSomething(...)) matching the wave contract, ending with Wave wave.
  4. From any component, dispatch with sendWave(MyWaves.DO_SOMETHING, WBuilder.waveData(MyWaves.ITEM, data)).
  5. Call unlisten(...) when the component no longer needs those events (Models are auto-unlistened on release).

JRebirth provides its own event bus to manage asynchronous communication between all components. Synchronous communication can be achieved by using direct method call.

Communication Engine - Class Diagram

Notifier Overview

JRebirth has got its own Notification Engine to allow each component to communicate with each other. All these communications are processed into a dedicated thread described before. The notification engine uses custom objects to transport data: Waves.

The Notifier is JRebirth's internal event bus, running on JIT (JRebirth Internal Thread). It dispatches Wave objects to any component that has registered interest in a particular WaveType. This decoupled messaging system ensures that Models, Services, and Commands can interact without holding direct references to one another.

The typical flow is:

  1. A component registers (listens) for one or more WaveTypes.
  2. Another component sends a Wave carrying a WaveType and optional data.
  3. The Notifier finds every component that listens for that WaveType and invokes the matching handler method.

Registering for Waves

To receive Waves, a component must call listen(WaveType...) during its initialization phase. For a Model this is typically done inside initModel(), for a Service inside initService(), and for a Command inside initCommand().

The listen method is defined in the Component interface:

package org.jrebirth.af.api.component.basic;

import java.lang.reflect.Method;

import org.jrebirth.af.api.facade.FacadeReady;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.api.wave.WaveBean;
import org.jrebirth.af.api.wave.checker.WaveChecker;
import org.jrebirth.af.api.wave.contract.WaveData;
import org.jrebirth.af.api.wave.contract.WaveType;

/**
 * The interface <strong>EnhancedComponent</strong>.
 *
 * Define the contract used to manage waves.
 *
 * @author Sébastien Bordes
 *
 * @param <R> A type that implements FacadeReady
 */
public interface Component<R extends FacadeReady<R>> extends FacadeReady<R> {

    /**
     * Begin to listen the type of wave for the current component.
     *
     * Wave Contract will be checked if {@link org.jrebirth.af.core.resource.provided.JRebirthParameters.DEVELOPER_MODE} parameter is true
     *
     * @param waveType the type(s) to listen
     */
    void listen(final WaveType... waveType);

    /**
     * Begin to listen the type of wave for the current component.
     *
     * Wave Contract will be checked if {@link org.jrebirth.af.core.resource.provided.JRebirthParameters.DEVELOPER_MODE} parameter is true
     *
     * The wave checker is used to filter the wave if the checker returns false
     *
     * @param waveChecker the wave checker used to forward the wave only if the checker return true
     * @param waveType the type(s) to listen
     */
    void listen(final WaveChecker waveChecker, final WaveType... waveType);

    /**
     * Begin to listen the type of wave for the current component.
     *
     * Wave Contract will be checked if {@link org.jrebirth.af.core.resource.provided.JRebirthParameters.DEVELOPER_MODE} parameter is true
     *
     * The wave checker is used to filter the wave if the checker returns false
     *
     * @param waveChecker the wave checker used to forward the wave only if the checker return true
     * @param method the annotated method concerned
     * @param waveType the type(s) to listen
     */
    void listen(final WaveChecker waveChecker, final Method method, final WaveType... waveType);

    /**
     * Stop to listen the type of wave for the current component.
     *
     * @param waveTypes the type(s) to stop to listen
     */
    void unlisten(final WaveType... waveTypes);

    /**
     * Send a wave to the notifier.
     *
     * The wave will automatically be sent from JRebirthThread.
     *
     * @param wave the wave to send
     */
    void sendWave(final Wave wave);

    /**
     * Send a wave to the notifier.
     *
     * The wave will automatically be sent from JRebirthThread.
     *
     * @param waveType the type of wave to send
     * @param waveBean the wave bean
     *
    // ...

You can listen for several WaveTypes at once:

@Override
protected void initModel() {
    listen(MyWaves.DO_ACTION_A, MyWaves.DO_ACTION_B);
}
  • initModel() — correct hook for Models; Services use initService(), Commands use initCommand().
  • listen(...) — registers this component with the Notifier (strong reference until unlisten).
  • Multiple WaveTypes — one registration call for all events this component handles.

When listen is called, the component registers itself with the Notifier for the given WaveType(s). The Notifier holds a strong reference to the component, so it will not be garbage-collected as long as it remains registered.

Here is a real-world example from the Analyzer showcase:

package org.jrebirth.af.showcase.analyzer.ui.controls;

import java.util.List;

import org.jrebirth.af.api.facade.JRebirthEvent;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.core.ui.DefaultModel;
import org.jrebirth.af.showcase.analyzer.service.LoadEdtFileService;
import org.jrebirth.af.showcase.analyzer.ui.editor.EditorWaves;

/**
 * The class <strong>ControlsModel</strong>.
 *
 * @author Sébastien Bordes
 */
public final class ControlsModel extends DefaultModel<ControlsModel, ControlsView> {

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initModel() {
        listen(LoadEdtFileService.DO_LOAD_EVENTS.returnWaveType());
        listen(EditorWaves.DO_UNLOAD);
    }

    /**
     * Call when event are loaded.
     *
     * @param eventList the list of events loaded
     *
     * @param wave the wave received
     */
    public void doEventsLoaded(final List<JRebirthEvent> eventList, final Wave wave) {
        view().activateButtons(!eventList.isEmpty());
    }

    /**
     * Call when event are loaded.
     *
     * @param wave the wave received
     */
    public void doUnload(final Wave wave) {
        view().activateButtons(false);
    }
}
  • listen(...returnWaveType()) — service return waves use .returnWaveType() on the entry WaveType.
  • doEventsLoaded(List, Wave) — name from return action EVENTS_LOADED; updates View via view().
  • doUnload(Wave) — parameterless action wave; only the trailing Wave argument is required.

The handler method name is derived from the WaveType action. For example, if the WaveType action is DO_LOAD_EVENTS, the handler method must be named doEventsLoaded (camelCase, matching the action string).

    public void doEventsLoaded(final List<JRebirthEvent> eventList, final Wave wave) {
        view().activateButtons(!eventList.isEmpty());
    }

Unregistering

To stop receiving Waves, call unlisten(WaveType...). This removes the component from the Notifier and releases the strong reference, preventing potential memory leaks.

    void unlisten(final WaveType... waveTypes);

    /**
     * Send a wave to the notifier.
     *
     * The wave will automatically be sent from JRebirthThread.
     *
     * @param wave the wave to send
     */
    void sendWave(final Wave wave);

    /**
     * Send a wave to the notifier.
     *
     * The wave will automatically be sent from JRebirthThread.
     *
     * @param waveType the type of wave to send
     * @param waveBean the wave bean
     *
     * @return the wave created and sent to JIT, be careful when you use a strong reference it can hold a lot of objects
     */
    <WB extends WaveBean> Wave sendWave(final WaveType waveType, final WB waveBean);

    /**
     * Send a wave to the notifier.
     *
     * The wave will automatically be sent from JRebirthThread.
     *
     * @param waveType the type of wave to send
     * @param waveData the data (key-value
     *
     * @return the wave created and sent to JIT, be careful when you use a strong reference it can hold a lot of objects
     */
    Wave sendWave(final WaveType waveType, final WaveData<?>... waveData);

    /**
     * Return the root component (for inner component).
     *
     * @return the root component of the inner component
     */
    Component<?> rootComponent();

    /**
     * Define the root component for an inner component.
     *
     * @param rootComponent The root component to set.
     */
    void rootComponent(final Component<?> rootComponent);

    // /**
    // * Add an inner component.
    // *
    // * It will instantiate the component from the right Facade and store it into the current component.
    // *
    // * Shall be called from {@link AbstractComponent}.initInnerComponent (protected API)
@Override
protected void unlistenOnDispose() {
    unlisten(MyWaves.DO_REFRESH);
}
  • unlisten(WaveType...) — removes this component from the Notifier for those types.
  • Models are auto-unlistened on release; call explicitly for long-lived components that change behavior.

Sending Waves

Any component can send a Wave via the sendWave methods defined on the Component interface:

package org.jrebirth.af.api.component.basic;

import java.lang.reflect.Method;

import org.jrebirth.af.api.facade.FacadeReady;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.api.wave.WaveBean;
import org.jrebirth.af.api.wave.checker.WaveChecker;
import org.jrebirth.af.api.wave.contract.WaveData;
import org.jrebirth.af.api.wave.contract.WaveType;

/**
 * The interface <strong>EnhancedComponent</strong>.
 *
 * Define the contract used to manage waves.
 *
 * @author Sébastien Bordes
 *
 * @param <R> A type that implements FacadeReady
 */
public interface Component<R extends FacadeReady<R>> extends FacadeReady<R> {

    /**
     * Begin to listen the type of wave for the current component.
     *
     * Wave Contract will be checked if {@link org.jrebirth.af.core.resource.provided.JRebirthParameters.DEVELOPER_MODE} parameter is true
     *
     * @param waveType the type(s) to listen
     */
    void listen(final WaveType... waveType);

    /**
     * Begin to listen the type of wave for the current component.
     *
     * Wave Contract will be checked if {@link org.jrebirth.af.core.resource.provided.JRebirthParameters.DEVELOPER_MODE} parameter is true
     *
     * The wave checker is used to filter the wave if the checker returns false
     *
     * @param waveChecker the wave checker used to forward the wave only if the checker return true
     * @param waveType the type(s) to listen
     */
    void listen(final WaveChecker waveChecker, final WaveType... waveType);

    /**
     * Begin to listen the type of wave for the current component.
     *
     * Wave Contract will be checked if {@link org.jrebirth.af.core.resource.provided.JRebirthParameters.DEVELOPER_MODE} parameter is true
     *
     * The wave checker is used to filter the wave if the checker returns false
     *
     * @param waveChecker the wave checker used to forward the wave only if the checker return true
     * @param method the annotated method concerned
     * @param waveType the type(s) to listen
     */
    void listen(final WaveChecker waveChecker, final Method method, final WaveType... waveType);

    /**
     * Stop to listen the type of wave for the current component.
     *
     * @param waveTypes the type(s) to stop to listen
     */
    void unlisten(final WaveType... waveTypes);

    /**
     * Send a wave to the notifier.
     *
     * The wave will automatically be sent from JRebirthThread.
     *
     * @param wave the wave to send
     */
    void sendWave(final Wave wave);

    /**
     * Send a wave to the notifier.
     *
     * The wave will automatically be sent from JRebirthThread.
     *
     * @param waveType the type of wave to send
     * @param waveBean the wave bean
     *
    // ...

There are several ways to send a Wave:

1. Using WaveType + WaveData

sendWave(MyWaves.DO_REFRESH, WBuilder.waveData(MyWaves.ITEM, selectedItem));
  • sendWave(waveType, waveData...) — builds the wave and posts it to JIT for dispatch.
  • WBuilder.waveData(item, value) — pairs a WaveItem key with the payload value.

2. Using WaveType + WaveBean

sendWave(MyWaves.DO_REFRESH, myWaveBean);
  • sendWave(waveType, waveBean) — typed bean instead of varargs WaveData; good for many fields.

3. Using a pre-built Wave with WBuilder

The WBuilder fluent API offers a convenient way to create and configure Waves before sending them:

sendWave(WBuilder.callCommand(MyCommand.class));
  • WBuilder.callCommand(Class) — builds a Call Command wave ready to send.
  • Equivalent to callCommand(MyCommand.class) but useful when chaining waves.

How to use — end-to-end

  1. Define WaveType + WaveItem constants in a shared interface.
  2. In the receiver: listen(waveType) inside initModel / initService / initCommand.
  3. Add handler method (doActionName(...)) matching items + trailing Wave.
  4. In the sender: sendWave(waveType, WBuilder.waveData(item, value)).
  5. Call unlisten when the receiver should stop reacting.

Wave Dispatching

When a Wave is sent, the following sequence occurs:

  1. The Wave is queued on JIT (JRebirth Internal Thread).
  2. The Notifier looks up all components registered for the Wave's WaveType.
  3. For each registered component, the Notifier resolves the handler method by convention:
    • The WaveType has an action name (e.g. "DO_MY_ACTION").
    • The action name is converted to camelCase: doMyAction.
    • The Notifier calls this method via reflection, passing the Wave and any typed data items.
  4. If a WaveChecker is registered for that component + WaveType pair, it is evaluated first — the handler is invoked only when the checker returns true.

This convention-over-configuration approach keeps handler wiring completely declarative.

@OnWave Annotation

As an alternative to calling listen() manually, you can annotate a method with @OnWave. The framework will auto-register the component for the specified WaveType at startup.

The annotation accepts a single value attribute matching the WaveType action string:

@OnWave("MY_ACTION")
protected void myMethod(Wave wave) {
    // handle wave
}
  • @OnWave("MY_ACTION") — auto-registers at startup; method name is free.
  • Value must match the WaveType action string exactly.

The method name is free — only the annotation value must match the WaveType action. @OnWave is repeatable, so a single method can listen for multiple WaveTypes.

Here is a real example from the Wave showcase:

@Register(value = ModuleModel.class)
public class MainModel extends DefaultFXMLModel<MainModel> implements ModuleModel {

    @OnWave(WWaves.CHANGE)
    protected void whatyouwant(Wave wave) {
        getFXMLController().txtMessage.setText("Wave received : " + wave.waveType().action());
    }

    @Override
    public String moduleName() {
        return "Wave";
    }

    @Override
    public MainController getFXMLController() {
        return (MainController) super.getFXMLController();
    }

}
  • @OnWave(WWaves.CHANGE) — listens without calling listen() in initModel().
  • Method name (whatyouwant) is arbitrary; only the annotation value matters.
  • wave.waveType().action() — inspect which action was received at runtime.

JRebirth itself uses @OnWave internally for built-in UI actions (see Built-in WaveTypes below):

@OnWave(WaveConstants.SHOW_VIEW)
void doShowView(final Wave wave);

@OnWave(WaveConstants.HIDE_VIEW)
void doHideView(final Wave wave);
  • Built into the Model interface — every Model handles show/hide automatically.
  • Trigger visibility from any component with WBuilder.showModel(...) / hide waves.

WaveChecker

A WaveChecker lets you filter incoming Waves for a specific component. Only Waves for which the checker returns true are dispatched to the handler method.

WaveChecker is a @FunctionalInterface extending Callback<Wave, Boolean>:

@FunctionalInterface
public interface WaveChecker extends Callback<Wave, Boolean> {

}
  • WaveChecker — functional interface: boolean call(Wave wave).
  • Return true to dispatch to the handler; false skips this listener for that wave.

You register a checker with the overloaded listen method:

package org.jrebirth.af.api.component.basic;

import java.lang.reflect.Method;

import org.jrebirth.af.api.facade.FacadeReady;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.api.wave.WaveBean;
import org.jrebirth.af.api.wave.checker.WaveChecker;
import org.jrebirth.af.api.wave.contract.WaveData;
import org.jrebirth.af.api.wave.contract.WaveType;

/**
 * The interface <strong>EnhancedComponent</strong>.
 *
 * Define the contract used to manage waves.
 *
 * @author Sébastien Bordes
 *
 * @param <R> A type that implements FacadeReady
 */
public interface Component<R extends FacadeReady<R>> extends FacadeReady<R> {

    /**
     * Begin to listen the type of wave for the current component.
     *
     * Wave Contract will be checked if {@link org.jrebirth.af.core.resource.provided.JRebirthParameters.DEVELOPER_MODE} parameter is true
     *
     * @param waveType the type(s) to listen
     */
    void listen(final WaveType... waveType);

    /**
     * Begin to listen the type of wave for the current component.
     *
     * Wave Contract will be checked if {@link org.jrebirth.af.core.resource.provided.JRebirthParameters.DEVELOPER_MODE} parameter is true
     *
     * The wave checker is used to filter the wave if the checker returns false
     *
     * @param waveChecker the wave checker used to forward the wave only if the checker return true
     * @param waveType the type(s) to listen
     */
    void listen(final WaveChecker waveChecker, final WaveType... waveType);

    /**
     * Begin to listen the type of wave for the current component.
     *
     * Wave Contract will be checked if {@link org.jrebirth.af.core.resource.provided.JRebirthParameters.DEVELOPER_MODE} parameter is true
     *
     * The wave checker is used to filter the wave if the checker returns false
     *
     * @param waveChecker the wave checker used to forward the wave only if the checker return true
     * @param method the annotated method concerned
     * @param waveType the type(s) to listen
     */
    void listen(final WaveChecker waveChecker, final Method method, final WaveType... waveType);

    /**
     * Stop to listen the type of wave for the current component.
     *
     * @param waveTypes the type(s) to stop to listen
     */
    void unlisten(final WaveType... waveTypes);

    /**
     * Send a wave to the notifier.
     *
     * The wave will automatically be sent from JRebirthThread.
     *
     * @param wave the wave to send
     */
    void sendWave(final Wave wave);

    /**
     * Send a wave to the notifier.
     *
     * The wave will automatically be sent from JRebirthThread.
     *
     * @param waveType the type of wave to send
     * @param waveBean the wave bean
     *
    // ...

Example — listen only if the Wave carries a non-null data item:

listen(wave -> wave.contains(MyWaves.ITEM), MyWaves.DO_REFRESH);

Threading

By default, wave handler methods run on the thread natural to the component type:

Component Type Default Thread
Model JAT (JavaFX Application Thread)
Service JTP (JRebirth Thread Pool)
Command Depends on command type (JIT, JAT, or JTP)

You can override the default thread for any handler method with the @RunInto annotation:

@RunInto(RunType.JTP)
public void doHeavyComputation(final Wave wave) {
    // runs in the thread pool instead of JAT
}
  • @RunInto(JTP) — override default handler thread for this method only.
  • Models default to JAT; Services default to JIT — use when work must move off that thread.

Available RunType values: JAT, JAT_SYNC, JIT, JIT_SYNC, JTP, JTP_SYNC, SAME.

You can also set a runnable priority:

@RunInto(value = RunType.JTP, priority = PriorityLevel.Highest)
public void doCriticalTask(final Wave wave) { ... }
  • priority = PriorityLevel.Highest — prefer HPTP slot when JTP is busy.
  • Combine with @RunInto(JTP) for time-sensitive background handlers.

Built-in WaveTypes

JRebirth ships with several built-in WaveTypes defined in WaveConstants and used across the framework:

Constant Purpose
WaveConstants.SHOW_VIEW Show a Model's root node in the scene graph
WaveConstants.HIDE_VIEW Hide a Model's root node from the scene graph
WaveConstants.RETURN_VOID Used internally for void-returning service tasks

Models automatically listen for SHOW_VIEW and HIDE_VIEW through the @OnWave annotations declared on the Model interface, so you can trigger view visibility from any component:

sendWave(WBuilder.showModel(TargetModel.class, myPlaceholder));
  • WBuilder.showModel(Class, Node) — shows the Model's root node inside myPlaceholder.
  • Uses built-in SHOW_VIEW wave; always processed on JAT.
Wave Area
Allow asynchronous communication between components

Wave Overview

In 30 seconds

A Wave is a message between JRebirth components. It carries a WaveType (contract: action name + WaveItems) and optional data. Components listen for types and handle them via doXxx(...) methods or processWave. Build types with WBuilder.waveType("ACTION").items(...) and send with sendWave.

How to use

  1. Create a waves interface (e.g. MyWaves) with WaveType and WaveItemBase<T> constants.
  2. In the emitter, call sendWave(MyWaves.DO_ACTION, WBuilder.waveData(MyWaves.ITEM, value)).
  3. In the receiver's initModel() / initService() / initCommand(), call listen(MyWaves.DO_ACTION).
  4. Add a handler method named from the action (DO_REFRESH → doRefresh(...)) with parameters matching WaveItems, plus a final Wave wave argument.
  5. For services, chain return waves with .returnAction(...).returnItem(...) on the entry WaveType.

What's a Wave

A Wave is a temporary object created to carry data througt CSM components. They allow JRebirth to handle application internal events asynchronously between each component, at the opposite you can use getModel, getCommand and getService method to perform synchronous operations.

Waves are handled by the notifier engine which are running within the JRebirthThread (JIT).

Short UML Diagram:

Wave Group

There are 4 main group of waves :

  1. Call Command : used to trigger a command action
  2. Call Service : used to call a service, later another wave will be used
  3. Attach Ui : used to link two JavaFX nodes
  4. Undefined : to handle all other waves, the wave type must be defined
// Call a command from any component
sendWave(WBuilder.callCommand(ShowModelCommand.class));

// Call a service task (async; result arrives as return wave)
returnData(LoadEdtFileService.class, LoadEdtFileService.DO_LOAD_EVENTS,
    WBuilder.waveData(EditorWaves.EVENTS_FILE, file));

// Attach another Model's node into a placeholder
sendWave(WBuilder.showModel(DetailModel.class, view().contentPane()));

// Custom application wave
sendWave(MyWaves.DO_REFRESH, WBuilder.waveData(MyWaves.ITEM, selection));
  • WBuilder.callCommand(...) — Call Command group; runs the command on its configured thread.
  • returnData(...) — Call Service group; task runs on JTP, completion wave follows.
  • WBuilder.showModel(...) — Attach Ui group; always processed on JAT.
  • Custom WaveType constants — Undefined group; your own contracts via listen / doXxx handlers.

Wave Item

A wave item designate a Java type (precisely a generic type that can be for example: List<String>). It could be used with a custom name or as a parameter.

Don't forget the opening and closing braces used { } to allow anonymous class to define the super generic type !

This is the only way to reference a generic type at compile time.

Wave items are used by Wave Type to describe an api contract.

package org.jrebirth.af.showcase.analyzer.ui.editor;

import java.io.File;
import java.util.List;

import org.jrebirth.af.api.facade.JRebirthEvent;
import org.jrebirth.af.api.wave.contract.WaveType;
import org.jrebirth.af.core.wave.WBuilder;
import org.jrebirth.af.core.wave.WaveItemBase;

/**
 * The class <strong>EditorWaves</strong>.
 *
 * @author Sébastien Bordes
 */
public interface EditorWaves {

    /*************************************************************************/
    /** Wave Types **/
    /*************************************************************************/

    /** Trigger a Unload wave. */
    WaveType DO_UNLOAD = WBuilder.waveType("UNLOAD");

    /** Trigger a Play wave. */
    WaveType DO_PLAY = WBuilder.waveType("PLAY");

    /** Trigger a Next wave. */
    WaveType DO_NEXT = WBuilder.waveType("NEXT");

    /** Trigger a Previous wave. */
    WaveType DO_PREVIOUS = WBuilder.waveType("PREVIOUS");

    /** Trigger a Stop wave. */
    WaveType DO_STOP = WBuilder.waveType("STOP");

    /** The WaveType key usabe by OnWave annotation. */
    String DO_SELECT_EVENT_ACTION = "EVENT_SELECTED";

    /** Wave used to display info into the properties view. */
    WaveType DO_SELECT_EVENT = WBuilder.waveType(DO_SELECT_EVENT_ACTION);

    /** Wave type used to return the event currently processed. */
    WaveType RE_EVENT_PROCESSED = WBuilder.waveType("EVENT_PROCESSED");

    /*************************************************************************/
    /** Wave Items **/
    /*************************************************************************/

    /** The file containing all events serialized. */
    WaveItemBase<File> EVENTS_FILE = new WaveItemBase<File>() {
    };

    /** The name of the events. */
    WaveItemBase<List<JRebirthEvent>> EVENTS = new WaveItemBase<List<JRebirthEvent>>() {
    };

    /** An event unserialized. */
    WaveItemBase<JRebirthEvent> EVENT = new WaveItemBase<JRebirthEvent>() {
    };

}
  • DO_UNLOAD = WBuilder.waveType("UNLOAD") — action-only wave (no payload items).
  • WaveItemBase<File> EVENTS_FILE — typed slot; anonymous subclass captures generic type at compile time.
  • Handler naming — DO_SELECT_EVENT → method doSelectEvent(...) (camelCase from action string).

Wave items can also be used to define the unique identifier of a value wrapped into a WaveData wrapper stored into a wave.

package org.jrebirth.af.core.wave;

import static org.jrebirth.af.core.wave.WBuilder.waveType;

import java.util.List;

import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.ProgressBar;

import org.jrebirth.af.api.annotation.Preload;
import org.jrebirth.af.api.command.Command;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.api.wave.WaveBean;
import org.jrebirth.af.api.wave.WaveConstants;
import org.jrebirth.af.api.wave.contract.WaveData;
import org.jrebirth.af.api.wave.contract.WaveItem;
import org.jrebirth.af.api.wave.contract.WaveType;
import org.jrebirth.af.core.command.basic.showmodel.ShowModelCommand;
import org.jrebirth.af.core.service.ServiceTaskBase;

/**
 * The class <strong>JRebirthWaves</strong> stores some predefined {@link WaveItem} and {@link WaveType}.
 *
 * This class will be preloaded to allow registration of {@link WaveType} into {@link WaveTypeRegistry}.
 *
 * @author Sébastien Bordes
 */
@Preload
public interface JRebirthWaves {

    /********************************/
    /** WaveItem related to UI */
    /********************************/

    /** The waveItem that hold the attached node. */
    WaveItem<ObjectProperty<Node>> ATTACH_UI_NODE_PLACEHOLDER = new WaveItemBase<ObjectProperty<Node>>() {
    };

    /** The waveItem that hold the children list of the parent node. */
    WaveItem<ObservableList<Node>> ADD_UI_CHILDREN_PLACEHOLDER = new WaveItemBase<ObservableList<Node>>() {
    };

    /** This item allow to use another Command to attach a model into another one, it replaces the default {@link ShowModelCommand}. */
    WaveItem<Class<? extends Command>> SHOW_MODEL_COMMAND = new WaveItemBase<Class<? extends Command>>() {
    };

    /** This item allow to define Key Parts. */
    WaveItem<List<?>> KEY_PARTS = new WaveItemBase<List<?>>() {
    };

    /** This item is used to store several {@link WaveBean} into a wave. */
    WaveItem<List<WaveBean>> EXTRA_WAVE_BEANS = new WaveItemBase<List<WaveBean>>() {
    };

    /********************************/
    /** WaveItem related to Command */
    /********************************/

    /** The waveItem that hold the list of wave to be executed back to back. */
    WaveItem<List<Wave>> CHAINED_WAVES = new WaveItemBase<List<Wave>>() {
    };

    /** The waveItem that indicates if command instance must be reused or if another must created. Default value is false. */
    WaveItem<Boolean> REUSE_COMMAND = new WaveItemBase<Boolean>() {
    };

    /** The waveItem that indicates if command instance must be run synchronously. Default value is false. */
    WaveItem<Boolean> FORCE_SYNC_COMMAND = new WaveItemBase<Boolean>() {
    };

    /********************************/
    /** WaveData related to Command */
    /********************************/

    /** This WaveData allows to reuse a command instead of creating another one using an unique key timestamp. */
    WaveData<Boolean> REUSE = WBuilder.waveData(REUSE_COMMAND, true);
    // ...
  • ATTACH_UI_NODE_PLACEHOLDER — target property where a child Model node is attached.
  • SHOW_MODEL_COMMAND — optional override of the default ShowModelCommand class.
  • REUSE — WaveData preset telling the engine to reuse an existing command instance.
sourceWave.addDatas(WBuilder.waveData(JRebirthWaves.SERVICE_TASK, task));
  • addDatas(...) — append extra WaveData entries to an existing wave before dispatch.
  • JRebirthWaves.SERVICE_TASK — framework slot linking a wave to its running service task.

Wave Type

The wave type is where black magic resides. It defines a contract between the emitter (the one who creates the wave) and the receiver (the one who handles the waves). This contract is dynamic because it relies on a String and WaveItem objects.

A WaveType has a unique name and a set of WaveItem objects. It must be created and stored like this:

  • Into an Interface to define wave contract (here without argument)
package org.jrebirth.af.showcase.analyzer.ui.editor;

import java.io.File;
import java.util.List;

import org.jrebirth.af.api.facade.JRebirthEvent;
import org.jrebirth.af.api.wave.contract.WaveType;
import org.jrebirth.af.core.wave.WBuilder;
import org.jrebirth.af.core.wave.WaveItemBase;

/**
 * The class <strong>EditorWaves</strong>.
 *
 * @author Sébastien Bordes
 */
public interface EditorWaves {

    /*************************************************************************/
    /** Wave Types **/
    /*************************************************************************/

    /** Trigger a Unload wave. */
    WaveType DO_UNLOAD = WBuilder.waveType("UNLOAD");

    /** Trigger a Play wave. */
    WaveType DO_PLAY = WBuilder.waveType("PLAY");

    /** Trigger a Next wave. */
    WaveType DO_NEXT = WBuilder.waveType("NEXT");

    /** Trigger a Previous wave. */
    WaveType DO_PREVIOUS = WBuilder.waveType("PREVIOUS");

    /** Trigger a Stop wave. */
    WaveType DO_STOP = WBuilder.waveType("STOP");

    /** The WaveType key usabe by OnWave annotation. */
    String DO_SELECT_EVENT_ACTION = "EVENT_SELECTED";

    /** Wave used to display info into the properties view. */
    WaveType DO_SELECT_EVENT = WBuilder.waveType(DO_SELECT_EVENT_ACTION);

    /** Wave type used to return the event currently processed. */
    WaveType RE_EVENT_PROCESSED = WBuilder.waveType("EVENT_PROCESSED");

    /*************************************************************************/
    /** Wave Items **/
    /*************************************************************************/

    /** The file containing all events serialized. */
    WaveItemBase<File> EVENTS_FILE = new WaveItemBase<File>() {
    };

    /** The name of the events. */
    WaveItemBase<List<JRebirthEvent>> EVENTS = new WaveItemBase<List<JRebirthEvent>>() {
    };

    /** An event unserialized. */
    WaveItemBase<JRebirthEvent> EVENT = new WaveItemBase<JRebirthEvent>() {
    };

}
  • Into a service class (here with on argument) :
package org.jrebirth.af.showcase.analyzer.service;

import java.io.File;
import java.util.List;

import org.jrebirth.af.api.annotation.PriorityLevel;
import org.jrebirth.af.api.concurrent.Priority;
import org.jrebirth.af.api.facade.JRebirthEvent;
import org.jrebirth.af.api.module.RegistrationPoint;
import org.jrebirth.af.api.service.Service;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.api.wave.contract.WaveType;
import org.jrebirth.af.core.wave.WBuilder;
import org.jrebirth.af.showcase.analyzer.ui.editor.EditorWaves;

/**
 * The class <strong>LoadEdtFileService</strong>.
 *
 * @author Sébastien Bordes
 */
@RegistrationPoint(exclusive = true)
public interface LoadEdtFileService extends Service {

    /** Wave type use to load events. */
    WaveType DO_LOAD_EVENTS = WBuilder.waveType("LOAD_EVENTS")
                                      .items(EditorWaves.EVENTS_FILE)
                                      .returnAction("EVENTS_LOADED")
                                      .returnItem(EditorWaves.EVENTS);

    /**
     * Parse the event file.
     *
     * @param selecteFile the event file selected
     * @param wave the wave that trigger the action
     *
     * @return the list of loaded events
     */
    @Priority(PriorityLevel.High)
    List<JRebirthEvent> doLoadEvents(final File selecteFile, final Wave wave);

}
  • DO_LOAD_EVENTS = waveType("LOAD_EVENTS").items(...).returnAction(...).returnItem(...) — full service contract in one constant.
  • .items(EditorWaves.EVENTS_FILE) — input File passed to doLoadEvents.
  • .returnAction("EVENTS_LOADED") — completion wave action; handler is doEventsLoaded(...).
  • @Priority(PriorityLevel.High) — optional; runs the task on HPTP when JTP is saturated.

WaveType name

This string is used to link to a component method, this call is made by reflection when the wave is processed.

A best practice is to store them within static final field or within an interface to avoid their replication (possible source of error) especially when used within @OnWave annotation.

WaveItem List

Each WaveItem will be passed to the method as an argument.

// Contract: DO_SAVE with FILE item → doSave(File file, Wave wave)
WaveType DO_SAVE = WBuilder.waveType("SAVE").items(MyWaves.FILE);

public void doSave(final File file, final Wave wave) {
    // file matches MyWaves.FILE; wave is always last
}
  • Method parameters follow WaveItem order declared on the WaveType.
  • Action SAVE maps to handler name doSave (prefix do + camelCase action).
  • Final parameter is always the source Wave.

Wave argument

Each wave procesing method must add a least argument : the source wave, thus it will be possible to know the handling context for this method call. The wave argument is useful to access to wave bean or other information like source wave.

public void doRefresh(final String filter, final Wave wave) {
    final Object source = wave.source();
    final Optional<String> extra = wave.get(MyWaves.FILTER);
}
  • wave.source() — component that sent the wave (useful for routing or logging).
  • wave.get(WaveItem) — read optional data not declared as method parameters.

Wave Lifecycle

Wave lifecycle are defined by the Status enumeration:

  1. Created : The Wave object has just been built by someone.
  2. Sent : The wave has been sent to the JRebirth Notifier Engine
  3. Processing : The wave is being dispatched
  4. Cancelled : The wave has been cancelled by an user action
  5. Consumed : All Wave Handlers have been called, or the Service Method or the Command has been called
  6. Handled : All Wave Handlers are terminated
  7. Failed : The wave process has generated an error
  8. Destroyed : the wave is available for garbage collection
// Typical path: build → send → handler runs → consumed
final Wave wave = sendWave(MyWaves.DO_GREET, WBuilder.waveData(MyWaves.NAME, "World"));
// wave.status() progresses: SENT → PROCESSING → CONSUMED → HANDLED → DESTROYED
  • sendWave(...) — transitions the wave to Sent and queues it on JIT.
  • Notifier dispatch moves it to Processing, then Consumed after handlers/commands run.
  • Failed waves surface exceptions; Destroyed means the wave can be garbage-collected.

Chained Wave

It's possible to chain command by using the ChainWaveCommand class. A sample is used into the JRebirthThread.bootUp() method.

sendWave(WBuilder.of(JRebirthWaves.CHAINED_WAVES)
    .data(WBuilder.waveData(JRebirthWaves.CHAINED_WAVES, Arrays.asList(
        WBuilder.callCommand(PrepareModelCommand.class),
        WBuilder.callCommand(AttachModelCommand.class))))
    .build());
  • CHAINED_WAVES — built-in item holding a List<Wave> executed sequentially.
  • ChainWaveCommand — runs each wave in order, respecting each command's thread.
  • Use when several commands must complete before the next step (show-model flow, boot tasks).

WBuilder API

JRebirth provides a fluent builder for constructing waves:

WaveType type = WBuilder.waveType("MY_ACTION")
    .items(MyWaves.ITEM_A, MyWaves.ITEM_B);

WaveData<String> data = WBuilder.waveData(MyWaves.ITEM_A, "value");
Wave wave = WBuilder.of(type).data(data).build();
sendWave(wave);
  • WBuilder.waveType(name) — start defining a WaveType contract.
  • .items(...) — attach typed slots to the contract.
  • WBuilder.of(type).data(...).build() — assemble a wave before sending.

Common usage patterns:

  • WBuilder.callCommand(CommandClass.class) — create a wave that triggers a command
  • WBuilder.waveType(name).items(waveItem1, waveItem2) — define a WaveType
  • WBuilder.waveData(waveItem, value) — create WaveData for a specific item

Minimal send/listen example:

// MyWaves.java
WaveType DO_GREET = WBuilder.waveType("GREET").items(MyWaves.NAME);
WaveItemBase<String> NAME = new WaveItemBase<String>() { };

// Model — initModel()
listen(MyWaves.DO_GREET);
sendWave(MyWaves.DO_GREET, WBuilder.waveData(MyWaves.NAME, "World"));

public void doGreet(final String name, final Wave wave) {
    LOGGER.info("Hello {}", name);
}
  • listen(DO_GREET) — registers this Model with the Notifier on JIT.
  • sendWave(..., waveData) — builds and dispatches the wave to all listeners.
  • doGreet(String, Wave) — name derived from action GREET; last arg is always the source wave.

@OnWave Annotation

Instead of manually calling listen(waveType), you can annotate handler methods with @OnWave. The annotation value must match the WaveType action name.

@OnWave("REFRESH")
public void doRefresh(final Wave wave) { /* ... */ }
  • @OnWave("REFRESH") — action string must match WaveType action name (alternative to listen()).
  • Can be placed on interface methods so all implementations inherit the contract.
// Interface — contract visible to all implementations
public interface RefreshWaves {
    String REFRESH = "REFRESH";
    WaveType DO_REFRESH = WBuilder.waveType(REFRESH);

    @OnWave(REFRESH)
    void doRefresh(Wave wave);
}
  • Declare @OnWave on the interface — implementations auto-register without listen().
  • Keep the action string in a String constant shared with WaveType definition.
Command Area
Reuse common code and don't be scared by threading issue

Command Overview

In 30 seconds

A Command is a one-shot action (load file, show model, attach UI). Get it from any component with getCommand(MyCommand.class).run(), or trigger it indirectly with callCommand / linkCommand / waves. Pick the thread with @RunInto or base classes (DefaultUICommand = JAT, DefaultPoolCommand = JTP).

How to use

  1. Create a class extending DefaultCommand, DefaultUICommand, or DefaultPoolCommand (or bean variants).
  2. Implement initCommand() for setup and perform(Wave) for the action body.
  3. Annotate with @RunInto(RunType.JAT|JIT|JTP) if you do not use a default base class.
  4. Trigger from a Model, Service, or another Command: getCommand(MyCommand.class).run().
  5. From a View Controller, wire UI events with linkCommand(node, eventType, MyCommand.class, waveData...).
  6. For multi-step flows, extend DefaultMultiBeanCommand and list sub-commands in defineSubCommand().

A command is an atomic reusable action that could be triggered from anywhere. There are two kinds of Commands:

  • Single Command
  • Multi Command (composed by a set of Single Command)
Command - Class Diagram

Single Command

Single Commands are atomic and are run independently. If you trigger several commands in-a-row you will trigger them in parallel according to their predefined running thread. JRebirth engine will serialize their instantiation and their startup but they will be processed into JAT, JIT or one of JTP slots. JAT and JIT will process command one after the other. JTP will act in the same manner but internal engine will dispatch all actions to its pooled threads (by default {2 x Number of CPU core} slots are available by Thread Pool).

Minimal single command:

@RunInto(RunType.JIT)
public class LogActionCommand extends DefaultCommand {

    @Override
    protected void perform(final Wave wave) {
        LOGGER.info("Action executed");
    }
}
  • DefaultCommand — runs on JIT by default (via class annotation).
  • perform(Wave) — only mandatory method; called once per run().
  • Trigger with getCommand(LogActionCommand.class).run() from any component.

MultiCommand

MultiCommand provides the ability to run some Single Commands sequentially (even across several threads) or in parallel.

Hereafter you will find an example of MultiCommand used to display a model UI:

package org.jrebirth.af.core.command.basic.showmodel;

import java.util.Arrays;
import java.util.List;

import org.jrebirth.af.api.command.Command;
import org.jrebirth.af.api.key.UniqueKey;
import org.jrebirth.af.core.command.multi.DefaultMultiBeanCommand;

/**
 * The class <strong>ShowModelCommand</strong>.
 *
 * Run into JIT and is sequential
 *
 * @author Sébastien Bordes
 */
public class ShowModelCommand extends DefaultMultiBeanCommand<DisplayModelWaveBean> {

    /**
     * {@inheritDoc}
     */
    @Override
    protected List<UniqueKey<? extends Command>> defineSubCommand() {
        return Arrays.asList(
                             getCommandKey(PrepareModelCommand.class),
                             getCommandKey(AttachModelCommand.class));
    }

}
  • extends DefaultMultiBeanCommand<DisplayModelWaveBean> — multi-step command sharing one wave bean type.
  • defineSubCommand() — ordered list of child commands; ShowModelCommand runs prepare then attach.
  • getCommandKey(PrepareModelCommand.class) — resolves each sub-command's registration key from the facade.
  • Sub-commands keep their own @RunInto / base-class thread (JTP for prepare, JAT for attach).

The multi command code will be run into JIT, but its sub-command will be run respectively into JTP and JAT (according to their own configuration).

Why are they using these threads ?

ShowModelCommand use the annotation defined into DefaultMultiCommand to run into JIT.

PrepareModelCommand use the annotation defined into DefaultPoolCommand to run into JTP.

ShowModelCommand use the annotation defined into DefaultUICommand to run into JAT (it's mandatory to update scene's nodes within JAT).

How to trigger a Command

Commands are designed to be disposable after usage, but they could be retained by strong references to be executed twice or more or store data. Each call will return a new instance of the command class, because each command was stored with a timestamp key-based. (Timestamp is added to the default key and also for custom key).

You can create a command using four different ways:

Please note that Commands are JRebirth top-level components (with Services and Models), they follow the component lifecycle as described in Facade Page.

Thus AbstractBaseCommand extends BehavioredComponent and Component and their descendants must provide initCommand(), processAction() and execute() methods.

Direct way

It's possible to call a command from any JRebirth component (Command, Service, Model).

You just need to call the getCommand method to build an instance. You can provide either the Command Class or its unique key (if required).

    <C extends Command> C getCommand(final Class<C> clazz, final Object... keyPart);
  • getCommand(Class, keyPart...) — retrieves or creates a command from CommandFacade.
  • Optional key parts distinguish multiple instances of the same command class.

Once you have retrieved your command, you can store it with a strong reference to avoid GC collecting it. Your command life will depend on the lifetime of your strong reference. Thus you will be able to configure directly your command properties. Finally to trigger it you must call its run() method. The perform method of the command will be executed into the Thread Type chosen (JAT, JIT, JTP) by the Command declaration.

Minimal direct trigger from a Model:

@Override
protected void initModel() {
    getCommand(OpenFileCommand.class).run();
}
  • getCommand(OpenFileCommand.class) — retrieves (or creates) the command instance from the CommandFacade.
  • .run() — schedules perform(Wave) on the thread declared for that command class.
    Wave run();
  • run() — returns the wave used for this execution (useful for chaining or debugging).

Be careful: As explained here each call to getCommand could retrieve the same OR another instance of the command class depending on key parts provided and instance's strong references. (in this case no timestamp is added to the command key)

Indirect way

You can trigger a command execution by calling callCommand from any component, it will use JIT to trigger the command then the command will be run using the thread declared.

You can provide some parameters into WaveData that will be hold by the wave and so available into the command.

    public final Wave callCommand(final Class<? extends CommandBean<? extends WaveBean>> commandClass, final WaveBean waveBean, final WaveBean... waveBeans) {
  • callCommand(Class, WaveBean, ...) — indirect trigger via JIT; command runs on its own thread.
  • Accepts a primary bean plus optional extra beans for chained command data.

You can also provide a WaveBean object to store all data.

callCommand(ShowModelCommand.class, displayModelWaveBean);
  • callCommand — schedules command creation/run via JIT; command then runs on its own thread.
  • WaveBean — typed bag of properties instead of raw WaveData varargs.

Convenient Link method

UI's controllers provide a convenient method named void linkCommand(Node, EventType<E>, Class<? extends Command>, WaveData<?>…)

This method is useful to declare with only one line of code the call of a command triggered when the chosen JavaFX event occurred on a node belonging to the View.

It's also possible to add a callback function, in example to manage double-click detection (see LinkedCallback).

        linkCommand(view().getOpenButton(), MouseEvent.MOUSE_CLICKED, OpenEventTrackerFileCommand.class, CHECK_MOUSE_SINGLE_CLICK);
  • view().getOpenButton() — JavaFX node in the View (Controller has view() accessor).
  • MouseEvent.MOUSE_CLICKED — JavaFX event type that fires the command.
  • OpenEventTrackerFileCommand.class — command class resolved from CommandFacade.
  • CHECK_MOUSE_SINGLE_CLICK — optional WaveData / callback to filter events (e.g. ignore double-click).

Messaging way

Any Command is a JRebirth component and can benefits of Observer features. It's possible to listen a WaveType (registration done into the initModel, initService and initCommand methods, or using @OnWave) in order to be notified when a such wave is sent. You can manage custom methods called by reflection to handle waves and can you catch all waves into the processAction(Wave) method.

More information is available in Notifier & Component page.

Be careful, commands can handle asynchronous wave only if they haven't been collected by the Garbage Collector! So you need to create a instance and to keep a strong references on it somewhere.

@Override
protected void initCommand() {
    listen(MyWaves.DO_SAVE);
    // keep this command instance alive while listening
}

@Override
protected void perform(final Wave wave) {
    // default path when no doXxx handler matches
}
  • listen(...) in initCommand() — command reacts to waves while the instance is retained.
  • Hold a strong reference (getCommand(...) stored in a Model field) or the listener is GC'd.
  • perform(Wave) — fallback when wave handling is not delegated to a doXxx method.

Command Properties

A command is an atomic action reusable or not that can be run into a predefined thread. A command provides specific features:

How to manage Threading issues

Each command will be launch by JRebirth Internal engine and run into a dedicated thread. Threads involved in a JRebirth application are explained into the Thread page.

The runner thread can be configured using two ways:

The priority rule is : Annotation > Constructor argument > Default value. The default value is : JIT (JRebirth Internal Thread). The top-level annotation will be systematically used overriding lower ones and also constructor arguments.

Annotation usage

To run a command into the JAT (JavaFX Application Thread), use this annotation :

@RunInto(RunType.JAT)
  • RunType.JAT — JavaFX Application Thread; required for direct scene/node updates.
  • RunType.JIT — JRebirth Internal Thread; messaging-safe, not for UI nodes in scene.
  • RunType.JTP — thread pool slot; long I/O or CPU work off UI and JIT.

To run a command into the JIT (JRebirth Internal Thread), use this annotation :

@RunInto(RunType.JIT)

To run a command into JTP (JRebirth Thread Pool, the command will be run into a slot), use this annotation :

@RunInto(RunType.JTP)

Class inheritance usage

To run a command into the JAT (JavaFX Application Thread), extends the DefaultUICommand class :

public class AttachModelCommand extends DefaultUIBeanCommand<DisplayModelWaveBean> {
  • DefaultUICommand / DefaultUIBeanCommand — @RunInto(JAT) baked in for scene updates.

To run a command into the JIT (JRebirth Internal Thread), extends the DefaultCommand class :

public class ChainWaveCommand extends DefaultCommand implements WaveListener {
  • DefaultCommand — runs on JIT; base for messaging-safe atomic commands.
  • WaveListener — optional; receive all waves in processWave in addition to doXxx handlers.

To run a command into JTP (JRebirth Thread Pool, the command will be run into a slot), extends the DefaultPoolCommand class :

public class PrepareModelCommand extends DefaultPoolBeanCommand<DisplayModelWaveBean> {
  • DefaultPoolCommand / DefaultPoolBeanCommand — runs on JTP for I/O or CPU-heavy work.

Constructor argument usage

It's also possible to define the runType (The thread which will handle the command) by passing RunType, each descendant classes of AbstractBaseCommand offer at least one constructor allowing this enum value to the command constructor.

    public AbstractBaseCommand(final RunType runType, final PriorityLevel priority) {
  • Constructor RunType — alternative to @RunInto when subclassing AbstractBaseCommand directly.
  • Annotation wins over constructor; constructor wins over the base-class default.

Component Key

The component key as described in the Facade page allow storing unique commands.

All objects provided as key part will be serialized (toString call) to build the key. Warning : When a command is built consequently to a wave reception, the wave UID will be concatenated to the class name instead of using key parts.

Execute Code

Command are run in a custom thread in 3 steps:

  • beforePerform
  • perform
  • afterPerform

Only the perform method must be implemented to execute your action.

Minimal custom command:

@RunInto(RunType.JTP)
public class LoadDataCommand extends DefaultCommand {

    @Override
    protected void initCommand() { /* optional setup */ }

    @Override
    protected void perform(final Wave wave) {
        // long work on JTP — send result via sendWave when done
    }
}
  • @RunInto(JTP) — runs perform on a thread-pool slot, not on the JavaFX thread.
  • initCommand() — called once when the command instance is prepared (register waves here if needed).
  • perform(Wave) — your action; may read wave data or an attached WaveBean.

Wave Bean

A WaveBean is a Java Bean that allow carrying a lot of named properties into a Wave.

Command Classes can declare a generic type that allow to cast the Wave Bean into the right one, it allows to use getWaveBean().getMyProperty() into source code which is more convenient than parsing WaveData (but it implies to create a dedicated Java Class).

public class OpenFileCommand extends DefaultPoolBeanCommand<OpenFileWaveBean> {

    @Override
    protected void perform(final Wave wave) {
        final File file = getWaveBean().getFile();
        // ...
    }
}

public class OpenFileWaveBean implements WaveBean {
    private File file;
    public File getFile() { return file; }
    public void setFile(final File file) { this.file = file; }
}
  • DefaultPoolBeanCommand<OpenFileWaveBean> — generic binds the bean type for typed access.
  • getWaveBean() — cast-free access inside perform; populated by callCommand or linkCommand.
  • Prefer beans when a command carries more than two or three parameters.

Custom properties

Each command is a simple Java Object, you can add fields or JavaFX Properties to help configuring your execution code. You must pay attention that these values will be kept until the command is disposed (after execution if no strong references exists).

For example you can attach a command to a Model and launch it several times while updating command's properties.

private final SaveCommand saveCommand = getCommand(SaveCommand.class);

void saveDraft() {
    saveCommand.setDraft(true);
    saveCommand.run();
}

void saveFinal() {
    saveCommand.setDraft(false);
    saveCommand.run();
}
  • Store getCommand(...) in a field — strong reference keeps the instance and its custom properties.
  • Configure fields/properties on the command before each run() for reusable commands.

Built-in Commands

JRebirth provides several ready-to-use commands:

Command Purpose Thread
ShowModelCommand Display a model's view (prepare + attach) JIT → JTP → JAT
ShowFadingModelCommand Show with fade transition JIT → JTP → JAT
FadeInOutCommand Fade a node in or out JAT
ChainWaveCommand Execute a list of waves sequentially JIT
AttachModelCommand Attach a model's node to a parent JAT
DetachModelCommand Remove a model's node from parent JAT
PrepareModelCommand Build model's view off-screen JTP
Service Area
Process configurable action

Services

In 30 seconds

A Service runs long or async work off the UI thread. Define entry/return WaveTypes on the service interface, implement the task method, register with listen(...) or @OnWave, then call returnData(Service.class, WAVE_TYPE, waveData...). Results arrive as a return wave your Model listens for.

How to use

  1. Create a service interface extending Service with WaveType constants (.items(...).returnAction(...).returnItem(...)).
  2. Declare the task method on the interface (name matches the wave action, e.g. doLoadEvents for LOAD_EVENTS).
  3. Implement the interface in a class extending DefaultService; register in initService() with listen(DO_XXX) or use @OnWave on the interface.
  4. Implement the task body; use updateProgress / updateMessage when needed.
  5. From a Model (or other component), call returnData(MyService.class, MyService.DO_TASK, WBuilder.waveData(...)).
  6. In the caller's initModel(), listen(MyService.DO_TASK.returnWaveType()) and add a handler method (e.g. doTaskCompleted(...)).

Overview

A Service Object is a JRebirth Component (part of CSM pattern, Command-Service-Model).

It can be retrieved from the ServiceFacade.

A Service can hold several Tasks defined by a WaveType.

Each Task requires:

  1. Define Call Wave Type (entry point)
  2. Define Return Wave Type (exit point)
  3. Register the Callback
  4. Define the Task process into the right method name.

That's all ! You don't have to bother about threading issues and asynchronous tasks.

Warning:

You must pay attention to the lifecycle of your service instance. As a JRebirth Component, each service object is eligible to garbage collection if it isn't retained by another object currently used.

So your data stored or processed into your service can be loss if you didn't manage correctly your Service life.

The most easy way is to hold your service with a strong reference into a long-living object like a top-levelModel.

Any service listening a WaveType will be retained by Notifier so it will not be elligible for garbage colelction.

Short UML Diagram:

Service Class Diagram

Defining Wave Types

Entry Point Wave Type

This is the WaveType used to process a Wave generated anywhere into the application.

WaveType DO_LOAD_EVENTS = WBuilder.waveType("LOAD_EVENTS")
    .items(EditorWaves.EVENTS_FILE)
    .returnAction("EVENTS_LOADED")
    .returnItem(EditorWaves.EVENTS);
  • Full entry contract on the service interface — one constant defines call + return waves.
  • .items(...) — input parameters; .returnAction / .returnItem — completion contract.

This WaveType uses only one WaveItem to store the file that must be loaded. WaveItem wrap the type of the object we want to use, thus it's possible to check that API contract isn't broken.

Minimal entry WaveType on a service interface:

WaveType DO_LOAD = WBuilder.waveType("LOAD")
    .items(MyWaves.INPUT_FILE)
    .returnAction("LOADED")
    .returnItem(MyWaves.RESULT_LIST);
  • waveType("LOAD") — action name; handler method will be doLoad(...).
  • .items(...) — input parameters carried by the call wave.
  • .returnAction("LOADED") — name of the completion wave (doLoaded(...) handler).
  • .returnItem(...) — typed slot for the value returned from the task method.

Exit Point Wave Type

The return Wave Type is automatically created with by the using the returnAction value with returnItem as WaveItem. The code above will generate a WaveType that uses only one WaveItem to store the list of events loaded from the given file.

// Generated return type — listen with:
listen(LoadEdtFileService.DO_LOAD_EVENTS.returnWaveType());

public void doEventsLoaded(final List<JRebirthEvent> events, final Wave wave) {
    // handler for return action EVENTS_LOADED
}
  • .returnWaveType() — accessor on the entry WaveType for the auto-generated completion wave.
  • Handler name comes from returnAction (EVENTS_LOADED → doEventsLoaded).

Task Registration

Each Task requires to be registered in order to generate the right WaveType that wrap the return value.

This registration must be done into the JRebirth's Component void initService() method like this:

package org.jrebirth.af.showcase.analyzer.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jrebirth.af.api.annotation.PriorityLevel;
import org.jrebirth.af.api.concurrent.Priority;
import org.jrebirth.af.api.facade.JRebirthEvent;
import org.jrebirth.af.api.module.Register;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.core.facade.JRebirthEventBase;
import org.jrebirth.af.core.log.JRebirthMarkers;
import org.jrebirth.af.core.service.DefaultService;
import org.jrebirth.af.core.service.ServiceUtility;
import org.jrebirth.af.showcase.analyzer.service.LoadEdtFileService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The class <strong>LoadEdtFileServiceImpl</strong> is the basic implementation used to load a log file.
 *
 * @author Sébastien Bordes
 */
@Register(value = LoadEdtFileService.class, priority = PriorityLevel.Low)
public class LoadEdtFileServiceImpl extends DefaultService implements LoadEdtFileService {

    /** The class logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoadEdtFileServiceImpl.class);

    /**
     * {@inheritDoc}
     */
    @Override
    public void initService() {

        listen(DO_LOAD_EVENTS);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Priority(PriorityLevel.High)
    public List<JRebirthEvent> doLoadEvents(final File selecteFile, final Wave wave) {

        final List<JRebirthEvent> eventList = new ArrayList<>();

        updateMessage(wave, "Parsing events");

        // Get number of line to calculate the task progression
        final int totalLines = ServiceUtility.countFileLines(selecteFile);

        try (BufferedReader br = new BufferedReader(new FileReader(selecteFile));) {
            int processedLines = 0;

            String strLine = br.readLine();

            // Read File Line By Line
            while (strLine != null) {
                processedLines++;

                updateProgress(wave, processedLines, totalLines);

                if (strLine.contains(JRebirthMarkers.JREVENT.getName())) {
                    // Convert the string to a JRebirth event and add it to the list
                    addEvent(eventList, strLine.substring(strLine.indexOf(">>") + 2));
                }

                // Read the next line to process
                strLine = br.readLine();
            }

        } catch (final IOException e) {
            LOGGER.error("Error while processing event file", e);
        }
        return eventList;
    }
}
  • listen(DO_LOAD_EVENTS) — registers the task with the Notifier (JIT during initService()).
  • doLoadEvents(File, Wave) — runs on JTP; return value is sent on the return wave automatically.
  • updateMessage / updateProgress — optional UI feedback linked to the source wave.

If you don't declare the return WaveType a exception will be thrown at runtime when trying to send back the Service Task output.

If your Service Task doesn't return anything (void return) you can dismiss this step except if you want to receive an empty notification when the Job is done; just use JRebirthItems.voidItem.

You can also register your service task by putting @OnWave annoation using the action name of the WaveType. A best practice is to add annoation within interface methods, thus all implementations can avoid to use listen methods.

Alternative: You can use the @OnWave annotation on the service interface method instead of manually calling listen(). This is the recommended approach as it keeps the contract visible in the interface definition.

public interface MyService extends Service {

    WaveType DO_COMPUTE = WBuilder.waveType("COMPUTE")
        .items(MyWaves.INPUT)
        .returnAction("COMPUTED")
        .returnItem(MyWaves.OUTPUT);

    @OnWave("COMPUTE")
    @Priority(PriorityLevel.Normal)
    String doCompute(String input, Wave wave);
}
  • @OnWave("COMPUTE") on the interface — impl skips listen() in initService().
  • Task method signature still defines parameters and return type for the contract checker.

Perform the Job!

package org.jrebirth.af.showcase.analyzer.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jrebirth.af.api.annotation.PriorityLevel;
import org.jrebirth.af.api.concurrent.Priority;
import org.jrebirth.af.api.facade.JRebirthEvent;
import org.jrebirth.af.api.module.Register;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.core.facade.JRebirthEventBase;
import org.jrebirth.af.core.log.JRebirthMarkers;
import org.jrebirth.af.core.service.DefaultService;
import org.jrebirth.af.core.service.ServiceUtility;
import org.jrebirth.af.showcase.analyzer.service.LoadEdtFileService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The class <strong>LoadEdtFileServiceImpl</strong> is the basic implementation used to load a log file.
 *
 * @author Sébastien Bordes
 */
@Register(value = LoadEdtFileService.class, priority = PriorityLevel.Low)
public class LoadEdtFileServiceImpl extends DefaultService implements LoadEdtFileService {

    /** The class logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoadEdtFileServiceImpl.class);

    /**
     * {@inheritDoc}
     */
    @Override
    public void initService() {

        listen(DO_LOAD_EVENTS);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Priority(PriorityLevel.High)
    public List<JRebirthEvent> doLoadEvents(final File selecteFile, final Wave wave) {

        final List<JRebirthEvent> eventList = new ArrayList<>();

        updateMessage(wave, "Parsing events");

        // Get number of line to calculate the task progression
        final int totalLines = ServiceUtility.countFileLines(selecteFile);

        try (BufferedReader br = new BufferedReader(new FileReader(selecteFile));) {
            int processedLines = 0;

            String strLine = br.readLine();

            // Read File Line By Line
            while (strLine != null) {
                processedLines++;

                updateProgress(wave, processedLines, totalLines);

                if (strLine.contains(JRebirthMarkers.JREVENT.getName())) {
                    // Convert the string to a JRebirth event and add it to the list
                    addEvent(eventList, strLine.substring(strLine.indexOf(">>") + 2));
                }

                // Read the next line to process
                strLine = br.readLine();
            }

        } catch (final IOException e) {
            LOGGER.error("Error while processing event file", e);
        }
        return eventList;
    }
}
  • Return the task result from the method — framework wraps it into the return wave.
  • Long loops should call updateProgress(wave, current, total) to keep UI responsive.

How to use the Service Feature

Follow these steps end-to-end:

  1. Define service interface + WaveType (entry + return items).
  2. Implement task method + initService() registration.
  3. From Model: returnData(...) to start the task.
  4. listen(entry.returnWaveType()) on the caller.
  5. Implement doXxxCompleted(...) handler to apply the result on JAT.

Call the Service

To call this Service Feature, you can use the returnData from any JRebirth's Component. It takes at least 2 mandatory arguments:

  1. The Service Class Object
  2. The WaveType that is related to the Service Feature
  3. An unordered list of WaveData objects that wrap values required by WaveType contract

Hereafter you will fin an example of service call with only one arguments passed:

            returnData(LoadEdtFileService.class,
                       LoadEdtFileService.DO_LOAD_EVENTS,
                       WBuilder.waveData(EditorWaves.EVENTS_FILE, selected));
  • returnData(...) — asynchronous service call; does not block the caller on JTP work.
  • First argument — service interface class (facade lookup).
  • Second argument — entry WaveType (DO_LOAD_EVENTS).
  • WBuilder.waveData(...) — wraps the File input required by the wave contract.

Process the Service Result

The Service Feature Result is sent as a Wave that wrap returned value. So to be informed when the result is available, there is two things to do:

  • Let your component listening this WaveType.
  • Add Wave handler code to process the result.

Each JRebirth's Component are able to listen some WaveType's waves by calling the listen method with one or several Wave Types.

This call must be done into one of the following method according to component used:

  • initCommand : for Command classes
  • initService : for Service classes
  • initModel : for Model classes

Each initXXX method is called into JRebirth Internal Thread by ready method.

    @Override
    protected void initModel() {
        listen(LoadEdtFileService.DO_LOAD_EVENTS.returnWaveType());
        listen(EditorWaves.DO_UNLOAD);
    }
  • .returnWaveType() — listen for the completion wave emitted when the service task finishes.
  • Register in initModel / initService / initCommand — must run on JIT during component ready.

Add a method that suits the WaveType convention.

The name must used the predefined prefix (in our case DO_ converted to do), then the WaveType's name converted in a camel cased format.

Method parameters must be compliant with Wave Items defined into the Wave Type.

A final parameter must be added, the Wave itself taht could be useful to get extra data, for example when chained waves are used.

    public void doEventsLoaded(final List<JRebirthEvent> eventList, final Wave wave) {
        view().activateButtons(!eventList.isEmpty());
    }
  • doEventsLoaded — derived from return action EVENTS_LOADED on the service WaveType.
  • First parameters — one per WaveItem on the return type (List<JRebirthEvent> here).
  • Wave wave — always last; gives access to progress, chaining, or source context.

Threading

Which Threads are involved ?

All communications with Service Component is done into JIT and all Service Tasks are performed into one slot of JTP or HPTP according to priority defined with annotation.

Threading Priority

Each Service feature call will be processed by the JTP (JRebirth Thread Pool) or by the HPTP (High Priority Thread Pool) according to their predefined priority. By default the Priority is set to PriorityLevel.Low (a level below Normal) to let other task to be performed into JTP before Service feature calls (like Command).

Its possible to increase or decrease this value by adding an annotation on the Service Feature method like this:

@Override
@Priority(PriorityLevel.High)
public List<JRebirthEvent> doLoadEvents(final File selectedFile, final Wave wave) {
    // High priority → prefer HPTP when JTP is saturated
}
  • @Priority(PriorityLevel.High) — task may run on HPTP instead of default JTP.
  • Default is PriorityLevel.Low — service tasks yield to commands and other JTP work.

TaskTrackerService

JRebirth provides a built-in TaskTrackerService that monitors all running service tasks. It can be used to display a global progress indicator or to track background operations. Connect a UI component to the TaskTrackerService to show real-time task status across the entire application.

Follow Task progression

Each Service Task are able to update a progress bar with integer value and message. In both cases you must provide the wave provided as a method argument, it will be used to link the associated ServiceTask and find the right ProgressBar and Text widgets to update.

You can update the message test by calling this method:

updateMessage(wave, "Parsing events");
  • updateMessage(wave, text) — updates linked status text for this task (if UI is wired).

You can update progress bar indicator by calling this method:

updateProgress(wave, processedLines, totalLines);
  • updateProgress(wave, workDone, totalWork) — drives an associated progress bar (0–1 internally).

If your Service Task returns void (no result to send back), use JRebirthItems.voidItem as the returnItem. This still generates a completion wave so listeners know the task finished.

WaveType DO_CLEANUP = WBuilder.waveType("CLEANUP")
    .returnAction("CLEANUP_DONE")
    .returnItem(JRebirthItems.voidItem);

public void doCleanup(final Wave wave) { /* no return value */ }

public void doCleanupDone(final Wave wave) { /* task finished */ }
  • JRebirthItems.voidItem — void return still emits a completion wave.
  • Caller listens with DO_CLEANUP.returnWaveType() and implements doCleanupDone(Wave).
User Interface Area
Use a custom MVC pattern with a lot of convenient tricks

UI Roles

In 30 seconds

Model owns UI state, waves, and bindings. View builds JavaFX nodes. Controller wires events (often via linkCommand). Extend DefaultModel<Model, View> — the framework creates View and Controller from generics. Put logic in the Model, nodes in the View, clicks in the Controller.

How to use

  1. Create MyModel extends DefaultModel<MyModel, MyView> and implement initModel(), bind(), optional processWave.
  2. Create MyView extends AbstractView<MyModel, RootPane, MyController> and build nodes in initView() / bootView().
  3. Create MyController extends AbstractController<MyModel, MyView> and attach handlers with linkCommand / linkWave.
  4. Register the Model key when showing it: getModel(MyModel.class) or ShowModelCommand with a parent placeholder.
  5. Keep business rules and service calls in the Model; avoid heavy logic in View or Controller.

The User Interface layer is composed by three main parts :

  • Model
  • View
  • Controller

Each of these must do predefined tasks to maintain a good Separation of Concerns (SoC).

Models are JRebirth Components like Commands and Services, they are mandatory whereas Views and Controllers are optionals.

Short UML Diagram:

Models

Model are JRebirth Components, they are retrievable from UiFacade and they can be dynamically attached to any placeholder. They are able to listen Wave and to communicate with other components.

public final class CounterModel extends DefaultModel<CounterModel, CounterView> {

    private final IntegerProperty count = new SimpleIntegerProperty(0);

    @Override
    protected void initModel() {
        listen(CounterWaves.DO_INCREMENT);
    }

    public void doIncrement(final Wave wave) {
        count.set(count.get() + 1);
    }

    public IntegerProperty countProperty() { return count; }
}
  • Model holds state (countProperty) and wave handlers — not the View.
  • listen(...) in initModel() — registers for incoming waves on JIT, handlers run on JAT.

Models store business objects with custom method that allow to bound an object to a model and then to use its internal properties to bound them to UI widget.

Models' aim is to manage UI lifecycle and communication, you can place into some part of your business logic.

Views

Views are automatically created by Models according to generic type used, their main objectives is to build and wrap the graphical root Node.

public final class CounterView extends AbstractView<CounterModel, BorderPane, CounterController> {

    private Label counterLabel;

    public CounterView(final CounterModel model) throws CoreException {
        super(model);
    }

    @Override
    protected void initView() {
        counterLabel = new Label();
        node().setCenter(counterLabel);
    }

    Label counterLabel() { return counterLabel; }
}
  • View builds nodes only — expose package getters (counterLabel()) for Model bindings.
  • node() — typed root pane (BorderPane here) created from the generic type parameter.

You can manage Model-View interaction in both direction: Model-to-View by adding some ‘package’ Node getters into the view (preferred way for binding declarations), or View-to-Model by adding some ‘package’ methods into Model (only for some call).

Controllers

Controllers are dedicated to manage event handling by providing several ways to facilitate developers' life. They are automatically created by the view according to generic type used.

public final class CounterController extends DefaultController<CounterModel, CounterView> {

    public CounterController(final CounterView view) throws CoreException {
        super(view);
    }

    @Override
    protected void initEventHandlers() throws CoreException {
        linkCommand(view().incrementButton(), MouseEvent.MOUSE_CLICKED, IncrementCommand.class);
    }
}
  • Controller wires UI events — delegates actions to Commands/Services/Waves via link* methods.
  • No business rules here; call model() only for simple coordination, not heavy logic.

Event Handler can be attached from View-to-Controller, or from Controller-to-View (preferred way, to centralize event handlers declarations).

About Generics

You can ask why do MVC objects use so much generics type that hurt eyes !! The reason is really simple: To avoid lot of cast !

When you want to call a method from another part you will have a method to grab the part with the right type, so no cast are needed.

An alternative would be to write ourselves getter method with right cast but it's really painful and doesn't have any value.

So you will write once this quite complex (especially when you use intermediate classes) class declaration with its generic type and you will enjoy coding without having to cast them.

Main Usage

User Interface layer is versatile and will adapt itself to your use case to avoid boiler plate code. Hereafter you will find a list of all possible ways to use a Model:

  • M - Only Model: rely on SimpleModel implementation
  • MV - Model with a View: Controller is omitted
  • MVC - Model, View, Controller: Basic Implementation
  • FMFFC - FxmlModel , Fxml, FxmlController: View and Controller are respectively replaced by Fxml and FxmlController
  • MVCFFC - FxmlModel, View, Controller, Fxml, FxmlController: Basic + Fxml files

Model Overview

Models are directly synchronized with the UIFacade and can send & receive Waves, they can also use any other components.

The goal of Models is to retrieve data from other layers, and to define Business Logic (business rules, authorizations …).

The Model automatically build its attached view (except SimpleModel).

@Override
protected void bind() {
    view().counterLabel().textProperty().bind(countProperty().asString());
}
  • bind() — JavaFX property bindings between Model state and View widgets.
  • Call view().counterLabel() — package-visible getter on the View.
package org.jrebirth.af.sample.ui;

import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.core.ui.DefaultModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The class <strong>SampleModel</strong>.
 *
 * @author
 */
public final class SampleModel extends DefaultModel<SampleModel, SampleView> {

    /** The class logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(SampleModel.class);

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initModel() {
        LOGGER.debug("Init Sample Model");
        // Put the code to initialize your model here
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initInnerComponents() {
        // Put the code to initialize inner models here (if any)
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void bind() {
        // Put the code to manage model object binding (if any)
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void processWave(final Wave wave) {
        // Process a wave action, you must listen the wave type before
    }

}
  • DefaultModel<SampleModel, SampleView> — self-type + View type; framework wires View/Controller from generics.
  • initModel() — register listen(...), initial state, non-UI setup.
  • initInnerComponents() — attach child Models (tabs, panels).
  • bind() — JavaFX property bindings between model state and view() widgets.
  • processWave(Wave) — fallback handler when you prefer one method over many doXxx methods.

Views Overview

As explained before, the main goal of a View is to create the rootNode attached to the Model.

Fortunately the rootNode is automatically created according to the generic type used in the View header.

View's initialization

The View's initialization code perform several operations:

  1. Link the model (strong reference)
  2. Create the root Node object according to the first generic type that extends Node.class
  3. Create the Controller according to the first generic type that extends Controller.class

If the construction fails, mainly due to Controller error, a custom error Node is created in order to display the stack trace of the exception.

package org.jrebirth.af.sample.ui;

import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;

import org.jrebirth.af.api.exception.CoreException;
import org.jrebirth.af.api.ui.annotation.OnMouse;
import org.jrebirth.af.api.ui.annotation.type.Mouse;
import org.jrebirth.af.core.ui.AbstractView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The class <strong>SampleView</strong>.
 *
 * @author
 */
public final class SampleView extends AbstractView<SampleModel, BorderPane, SampleController> {

    /** The class logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(SampleView.class);

    /** Button used to trigger the SampleCommand. */
    @OnMouse(Mouse.Clicked)
    public Button defaultCommand;

    /** Button used to trigger the SampleUICommand. */
    private Button uiCommand;

    /** Button used to trigger the SamplePoolCommand. */
    private Button pooledCommand;

    /**
     * Default Constructor.
     *
     * @param model the controls view model
     *
     * @throws CoreException if build fails
     */
    public SampleView(final SampleModel model) throws CoreException {
        super(model);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initView() {

        this.defaultCommand = new Button("Trigger a default Command into JIT");
        this.uiCommand = new Button("Trigger an UI Command into JAT");
        this.pooledCommand = new Button("Trigger a pooled Command into JTP");
        
        node().setCenter(new Label("JRebirth Sample"));

        final FlowPane fp = new FlowPane();
        fp.getChildren().addAll(this.defaultCommand,
                                this.uiCommand,
                                this.pooledCommand);
        node().setBottom(fp);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void bootView() {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void start() {
        LOGGER.debug("Start the Sample View");
        // Custom code to process when the view is displayed the first time
    }
    // ...
  • AbstractView<SampleModel, BorderPane, SampleController> — Model type, root pane type, Controller type.
  • initView() — construct widgets and add them to node() (the root BorderPane).
  • @OnMouse(Mouse.Clicked) — declarative wiring; Controller can also use linkCommand.
  • node().setCenter(...) — layout API on the typed root node returned by node().

Annotation Event Handler

Views can use annotations on Node fields to automatically wire JavaFX event handlers to the Controller. This removes the need for boilerplate addEventHandler calls.

The available annotations include @OnMouse, @OnKey, @OnAction, @OnSwipe, @OnDrag, @OnRotate, and @OnTouch. Each annotation specifies the event sub-type to listen for.

For example, annotating a Button field with @OnMouse(Mouse.Clicked):

@OnMouse(Mouse.Clicked)
public Button defaultCommand;
  • Field annotation — framework wires the node to a Controller handler at View init.
  • @OnMouse(Mouse.Clicked) — fires on single click; see @OnKey, @OnAction, etc.

When the View is initialized, the framework scans all annotated fields, resolves the matching Controller handler method, and attaches the JavaFX event handler automatically.

The Controller method name is derived by convention: on + fieldName + EventType. For instance, a field named myButton with @OnMouse(Mouse.Clicked) will call controller().onMyButtonMouseClicked(MouseEvent).

If no field-specific name is needed, the annotation uses a default handler. In the example above with defaultCommand, the handler is onMouseClicked(MouseEvent) in the Controller.

Here is the annotation used in the sample View:

package org.jrebirth.af.sample.ui;

import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;

import org.jrebirth.af.api.exception.CoreException;
import org.jrebirth.af.api.ui.annotation.OnMouse;
import org.jrebirth.af.api.ui.annotation.type.Mouse;
import org.jrebirth.af.core.ui.AbstractView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The class <strong>SampleView</strong>.
 *
 * @author
 */
public final class SampleView extends AbstractView<SampleModel, BorderPane, SampleController> {

    /** The class logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(SampleView.class);

    /** Button used to trigger the SampleCommand. */
    @OnMouse(Mouse.Clicked)
    public Button defaultCommand;

    /** Button used to trigger the SampleUICommand. */
    private Button uiCommand;

    /** Button used to trigger the SamplePoolCommand. */
    private Button pooledCommand;

    /**
     * Default Constructor.
     *
     * @param model the controls view model
     *
     * @throws CoreException if build fails
     */
    public SampleView(final SampleModel model) throws CoreException {
        super(model);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initView() {

        this.defaultCommand = new Button("Trigger a default Command into JIT");
        this.uiCommand = new Button("Trigger an UI Command into JAT");
        this.pooledCommand = new Button("Trigger a pooled Command into JTP");
        
        node().setCenter(new Label("JRebirth Sample"));

        final FlowPane fp = new FlowPane();
        fp.getChildren().addAll(this.defaultCommand,
                                this.uiCommand,
                                this.pooledCommand);
        node().setBottom(fp);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void bootView() {
        // Nothing to do yet
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void start() {
        LOGGER.debug("Start the Sample View");
        // Custom code to process when the view is displayed the first time
    }
    // ...

And the corresponding handler in the Controller:

    void onMouseClicked(final MouseEvent event) {

        LOGGER.debug("MouseClicked => Call Sample Command");

        // Manage Default Command Button
        model().getCommand(SampleCommand.class).run();

    }
  • onMouseClicked — default handler for @OnMouse(Mouse.Clicked) on defaultCommand.
  • model().getCommand(...).run() — Controller delegates to Command via the Model facade.

Controllers

Controllers are dedicated to managing event handling for a View. They centralize all user-interaction wiring and delegate business actions to the Model (or to Commands and Services through the Model).

A Controller is automatically created by the View, resolved through the generic type declared in the View class header.

public interface Controller<M extends Model, V extends View<M, ?, ?>> {

    /**
     * @return Returns the view.
     */
    V view();

    /**
     * @return Returns the root node.
     */
    Node node();

    /**
     * @return Returns the model.
     */
    M model();

    /**
     * Activate the controller by initializing all event handler.
     *
     * Must be called after children initialization.
     *
     * @throws CoreException if activation fails
     */
    void activate() throws CoreException;

}
  • view() — access the typed View to read nodes and package getters.
  • model() — access the Model for commands, services, and waves.
  • activate() — called after View build; runs initEventAdapters() then initEventHandlers().

Controller Lifecycle

The Controller lifecycle follows these steps:

  1. Construction — The View instantiates the Controller, passing itself as constructor argument.
  2. initEventAdapters() — Called to set up adapter-based event wiring (link methods).
  3. initEventHandlers() — Called to set up handler-based or direct event wiring.
  4. activate() — Called after the View's nodes are fully built and ready. This is the entry point where all event handler declarations take effect.

The activate() method orchestrates the two initialization phases and must be called after children nodes are created.

Event Handler Wiring

The preferred approach is Controller-to-View wiring: the Controller reads View nodes through package-visible getters and attaches event handlers declaratively. JRebirth provides several link* methods for this purpose.

linkCommand

linkCommand wires a JavaFX event on a node directly to a Command class. When the event fires, the Command is called via the Model:

package org.jrebirth.af.core.ui;

import java.util.Optional;
import java.util.function.Supplier;

import javafx.event.Event;
import javafx.scene.Node;
import javafx.util.Callback;

import org.jrebirth.af.api.command.Command;
import org.jrebirth.af.api.command.CommandBean;
import org.jrebirth.af.api.exception.CoreException;
import org.jrebirth.af.api.exception.CoreRuntimeException;
import org.jrebirth.af.api.service.Service;
import org.jrebirth.af.api.ui.Model;
import org.jrebirth.af.api.ui.View;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.api.wave.WaveBean;
import org.jrebirth.af.api.wave.contract.WaveData;
import org.jrebirth.af.api.wave.contract.WaveItem;
import org.jrebirth.af.api.wave.contract.WaveType;
import org.jrebirth.af.core.resource.provided.parameter.CoreParameters;
import org.jrebirth.af.core.ui.adapter.EventAdapter;
import org.jrebirth.af.core.ui.handler.AbstractNamedEventHandler;
import org.jrebirth.af.core.util.ClassUtility;
import org.jrebirth.af.core.wave.JRebirthWaves;

// TODO: Auto-generated Javadoc
/**
 * The abstract class <strong>AbstractController</strong>.
 *
 * Base implementation of the controller.
 *
 * @author Sébastien Bordes
 *
 * @param <M> the class type of the model of the view controlled
 * @param <V> the class type of the view controlled
 */
public abstract class AbstractController<M extends Model, V extends View<M, ?, ?>> extends AbstractBaseController<M, V> {

    /**
     * Default Constructor.
     *
     * @param view the controlled view
     *
     * @throws CoreException if an error occurred while creating event handlers
     */
    public AbstractController(final V view) throws CoreException {
        super(view);
    }

    /**
     * Link the creation of a wave to an event triggered on a node.
     *
     * This method doesn't use any callback function to trigger the launch the wave.
     *
     * @param node the node to follow
     * @param eventType the type of the event to follow
     * @param waveType the type of the wave to create
     * @param waveData additional Wave data
     *
     * @param <E> The type of JavaFX Event to track
     */
    protected <E extends Event> void linkWave(final Node node, final javafx.event.EventType<E> eventType, final WaveType waveType,
            final WaveData<?>... waveData) {

        linkWave(node, eventType, waveType, null, waveData);
    }

    /**
     * Link the creation of a wave to an event triggered on a node.
     *
     * @param node the node to follow
     * @param eventType the type of the event to follow
     * @param waveType the type of the wave to create
     * @param callback the call back to use to check if the wave can be sent
     * @param waveData additional Wave data
     *
     * @param <E> The type of JavaFX Event to track
     */
    // ...

Example from the Analyzer showcase — a mouse click on the Open button triggers OpenEventTrackerFileCommand:

package org.jrebirth.af.showcase.analyzer.ui.controls;

import javafx.scene.input.MouseEvent;

import org.jrebirth.af.api.exception.CoreException;
import org.jrebirth.af.core.ui.DefaultController;
import org.jrebirth.af.core.ui.EventFilter;
import org.jrebirth.af.showcase.analyzer.command.OpenEventTrackerFileCommand;
import org.jrebirth.af.showcase.analyzer.ui.editor.EditorWaves;

/**
 * The class <strong>ControlsController</strong>.
 *
 * @author Sébastien Bordes
 */
public final class ControlsController extends DefaultController<ControlsModel, ControlsView> implements EventFilter {

    /* implements MouseAdapter */

    /**
     * Default Constructor.
     *
     * @param view the view to control
     *
     * @throws CoreException if an error occurred while creating event handlers
     */
    public ControlsController(final ControlsView view) throws CoreException {
        super(view);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initEventHandlers() throws CoreException {

        linkCommand(view().getOpenButton(), MouseEvent.MOUSE_CLICKED, OpenEventTrackerFileCommand.class, CHECK_MOUSE_SINGLE_CLICK);

        linkWave(view().getUnloadButton(), MouseEvent.MOUSE_CLICKED, EditorWaves.DO_UNLOAD);
        linkWave(view().getPlayPauseButton(), MouseEvent.MOUSE_CLICKED, EditorWaves.DO_PLAY);
        linkWave(view().getBackwardButton(), MouseEvent.MOUSE_CLICKED, EditorWaves.DO_PREVIOUS);
        linkWave(view().getForwardButton(), MouseEvent.MOUSE_CLICKED, EditorWaves.DO_NEXT);
        linkWave(view().getStopButton(), MouseEvent.MOUSE_CLICKED, EditorWaves.DO_STOP);

        // Register mouse clicked handler
        // getView().getOpenButton().setOnMouseClicked(getMouseHandler());
        // getView().getUnloadButton().setOnMouseClicked(getMouseHandler());
        // getView().getPlayPauseButton().setOnMouseClicked(getMouseHandler());
        // getView().getForwardButton().setOnMouseClicked(getMouseHandler());
        // getView().getBackwardButton().setOnMouseClicked(getMouseHandler());
        // getView().getStopButton().setOnMouseClicked(getMouseHandler());
    }

    // /**
    // * {@inheritDoc}
    // */
    // @Override
    // public void mouseClicked(final MouseEvent mouseEvent) {
    // if (mouseEvent.getSource().equals(getView().getOpenButton())) {
    //
    // // Call the command synchronously
    // getModel().callCommand(OpenEventTrackerFileCommand.class);
    //
    // } else if (mouseEvent.getSource().equals(getView().getUnloadButton())) {
    //
    // getModel().send(EditorWaves.DO_UNLOAD);
    //
    // } else if (mouseEvent.getSource().equals(getView().getPlayPauseButton())) {
    //
    // getModel().send(EditorWaves.DO_PLAY);
    //
    // } else if (mouseEvent.getSource().equals(getView().getForwardButton())) {
    //
    // getModel().send(EditorWaves.DO_NEXT);
    //
    // } else if (mouseEvent.getSource().equals(getView().getBackwardButton())) {
    //
    // getModel().send(EditorWaves.DO_PREVIOUS);
    //
    // } else if (mouseEvent.getSource().equals(getView().getStopButton())) {
    // ...

linkWave

linkWave wires a JavaFX event on a node to send a Wave with a given WaveType. Any component that listens for that WaveType will receive the Wave:

package org.jrebirth.af.core.ui;

import java.util.Optional;
import java.util.function.Supplier;

import javafx.event.Event;
import javafx.scene.Node;
import javafx.util.Callback;

import org.jrebirth.af.api.command.Command;
import org.jrebirth.af.api.command.CommandBean;
import org.jrebirth.af.api.exception.CoreException;
import org.jrebirth.af.api.exception.CoreRuntimeException;
import org.jrebirth.af.api.service.Service;
import org.jrebirth.af.api.ui.Model;
import org.jrebirth.af.api.ui.View;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.api.wave.WaveBean;
import org.jrebirth.af.api.wave.contract.WaveData;
import org.jrebirth.af.api.wave.contract.WaveItem;
import org.jrebirth.af.api.wave.contract.WaveType;
import org.jrebirth.af.core.resource.provided.parameter.CoreParameters;
import org.jrebirth.af.core.ui.adapter.EventAdapter;
import org.jrebirth.af.core.ui.handler.AbstractNamedEventHandler;
import org.jrebirth.af.core.util.ClassUtility;
import org.jrebirth.af.core.wave.JRebirthWaves;

// TODO: Auto-generated Javadoc
/**
 * The abstract class <strong>AbstractController</strong>.
 *
 * Base implementation of the controller.
 *
 * @author Sébastien Bordes
 *
 * @param <M> the class type of the model of the view controlled
 * @param <V> the class type of the view controlled
 */
public abstract class AbstractController<M extends Model, V extends View<M, ?, ?>> extends AbstractBaseController<M, V> {

    /**
     * Default Constructor.
     *
     * @param view the controlled view
     *
     * @throws CoreException if an error occurred while creating event handlers
     */
    public AbstractController(final V view) throws CoreException {
        super(view);
    }

    /**
     * Link the creation of a wave to an event triggered on a node.
     *
     * This method doesn't use any callback function to trigger the launch the wave.
     *
     * @param node the node to follow
     * @param eventType the type of the event to follow
     * @param waveType the type of the wave to create
     * @param waveData additional Wave data
     *
     * @param <E> The type of JavaFX Event to track
     */
    protected <E extends Event> void linkWave(final Node node, final javafx.event.EventType<E> eventType, final WaveType waveType,
            final WaveData<?>... waveData) {

        linkWave(node, eventType, waveType, null, waveData);
    }

    /**
     * Link the creation of a wave to an event triggered on a node.
     *
     * @param node the node to follow
     * @param eventType the type of the event to follow
     * @param waveType the type of the wave to create
     * @param callback the call back to use to check if the wave can be sent
     * @param waveData additional Wave data
     *
     * @param <E> The type of JavaFX Event to track
     */
    // ...

linkUi

linkUi wires a JavaFX event to attach another Model's node into a placeholder in the current View:

linkUi(view().getContentPane(), MouseEvent.MOUSE_CLICKED, DetailModel.class,
    WBuilder.waveData(JRebirthWaves.ATTACH_UI_NODE_PLACEHOLDER, view().getDetailHolder()));
  • linkUi(node, event, ModelClass, waveData...) — on event, attaches target Model's node into the placeholder.
  • Uses built-in Attach Ui wave group; always processed on JAT.

linkService

linkService wires a JavaFX event to call a Service method:

linkService(view().getRefreshButton(), MouseEvent.MOUSE_CLICKED,
    DataService.class, DataService.DO_LOAD_DATA);
  • linkService(node, event, ServiceClass, WaveType) — fires returnData when the event occurs.
  • Equivalent to calling the service from the Model, but wired declaratively from the Controller.

All link* methods accept an optional Callback<E, Boolean> parameter that acts as a gate — the action is performed only when the callback returns true.

Adapters & Handlers

Controllers can implement adapter interfaces that provide a full set of event-handling methods for a given event family. Each adapter interface has a corresponding handler class that delegates events to the adapter methods.

Available adapter / handler pairs:

Adapter Interface Handler Class Event Family
MouseAdapter MouseHandler Mouse events (clicked, pressed, released, moved, dragged…)
KeyAdapter KeyHandler Key events (pressed, released, typed)
ActionAdapter ActionHandler ActionEvent
DragAdapter DragHandler Drag events (detected, over, dropped, entered, exited…)
RotateAdapter RotateHandler Rotate gesture events
SwipeAdapter SwipeHandler Swipe gesture events
TouchAdapter TouchHandler Touch events

To use an adapter, have the Controller implement the interface (or extend a Default*Adapter) and override only the methods you need. Then register the adapter with addAdapter():

package org.jrebirth.af.sample.ui;

import javafx.scene.input.MouseEvent;

import org.jrebirth.af.api.exception.CoreException;
import org.jrebirth.af.core.ui.AbstractController;
import org.jrebirth.af.core.ui.adapter.DefaultMouseAdapter;
import org.jrebirth.af.core.wave.WBuilder;
import org.jrebirth.af.sample.command.SampleCommand;
import org.jrebirth.af.sample.command.SamplePoolCommand;
import org.jrebirth.af.sample.command.SampleUICommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The class <strong>SampleController</strong>.
 *
 * @author
 */
public final class SampleController extends AbstractController<SampleModel, SampleView> {

    /** The class logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(SampleController.class);

    /**
     * Default Constructor.
     *
     * @param view the view to control
     *
     * @throws CoreException if an error occurred while creating event handlers
     */
    public SampleController(final SampleView view) throws CoreException {
        super(view);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initEventAdapters() throws CoreException {

        // Manage Ui Command Button
        linkCommand(view().getUiCommand(), MouseEvent.MOUSE_CLICKED, SampleUICommand.class);

        // Use the inner class
        addAdapter(new SampleMouseAdapter());

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initEventHandlers() throws CoreException {
        // Listen events

        // Manage Pooled Command Button
        view().getPooledCommand().setOnMouseClicked(getHandler(MouseEvent.MOUSE_CLICKED));
    }

    /**
     * Manage Mouse click of widget that have annotation.
     *
     * @param event the mouse event
     */
    void onMouseClicked(final MouseEvent event) {

        LOGGER.debug("MouseClicked => Call Sample Command");

        // Manage Default Command Button
        model().getCommand(SampleCommand.class).run();

    }

    /**
     * The class <strong>SampleMouseAdapter</strong>.
     */
    private class SampleMouseAdapter extends DefaultMouseAdapter<SampleController> {

        @Override
    // ...

The inner class SampleMouseAdapter demonstrates a custom adapter that overrides mouseClicked:

    private class SampleMouseAdapter extends DefaultMouseAdapter<SampleController> {

        @Override
        public void mouseClicked(final MouseEvent mouseEvent) {
            super.mouseClicked(mouseEvent);

            LOGGER.debug("MouseClicked => Call Sample Pool Command");

            model().sendWave(WBuilder.callCommand(SamplePoolCommand.class));
        }

    }

The handler is then attached to the node. For example, to get the MouseHandler for MOUSE_CLICKED:

view().getPooledCommand().setOnMouseClicked(getHandler(MouseEvent.MOUSE_CLICKED));
  • getHandler(EventType) — returns the shared handler that delegates to registered adapters.
  • Attach after nodes exist — typically in initEventHandlers().

Controller Annotations

As an alternative to adapters or manual wiring, Controller methods can be annotated with @OnAction, @OnMouse, @OnKey, etc. to receive specific events by convention.

This is the Controller-side counterpart to the View field annotations described earlier. The framework scans annotated methods and wires them to the appropriate View nodes.

Direct Event Handling

For complete control, you can use addHandler(node, EventType, handler) to attach any custom JavaFX EventHandler to a node. This is useful for one-off event handling that doesn't fit the adapter or annotation patterns.

Full sample Controller

Here is the complete sample Controller showing all three approaches — linkCommand, adapters, and direct handlers:

public final class SampleController extends AbstractController<SampleModel, SampleView> {

    /** The class logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(SampleController.class);

    /**
     * Default Constructor.
     *
     * @param view the view to control
     *
     * @throws CoreException if an error occurred while creating event handlers
     */
    public SampleController(final SampleView view) throws CoreException {
        super(view);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initEventAdapters() throws CoreException {

        // Manage Ui Command Button
        linkCommand(view().getUiCommand(), MouseEvent.MOUSE_CLICKED, SampleUICommand.class);

        // Use the inner class
        addAdapter(new SampleMouseAdapter());

    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initEventHandlers() throws CoreException {
        // Listen events

        // Manage Pooled Command Button
        view().getPooledCommand().setOnMouseClicked(getHandler(MouseEvent.MOUSE_CLICKED));
    }

    /**
     * Manage Mouse click of widget that have annotation.
     *
     * @param event the mouse event
     */
    void onMouseClicked(final MouseEvent event) {

        LOGGER.debug("MouseClicked => Call Sample Command");

        // Manage Default Command Button
        model().getCommand(SampleCommand.class).run();

    }

    /**
     * The class <strong>SampleMouseAdapter</strong>.
     */
    private class SampleMouseAdapter extends DefaultMouseAdapter<SampleController> {

        @Override
        public void mouseClicked(final MouseEvent mouseEvent) {
            super.mouseClicked(mouseEvent);

            LOGGER.debug("MouseClicked => Call Sample Pool Command");

            model().sendWave(WBuilder.callCommand(SamplePoolCommand.class));
        }

    }

}

Another example from the Undo/Redo showcase, demonstrating linkCommand with additional WaveData:

public final class UndoController extends DefaultController<UndoModel, UndoView> {

    /** The class logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(UndoController.class);

    /**
     * Default Constructor.
     *
     * @param view the view to control
     *
     * @throws CoreException if an error occurred while creating event handlers
     */
    public UndoController(final UndoView view) throws CoreException {
        super(view);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void initEventAdapters() throws CoreException {

        // Manage Ui Command Button
        linkCommand(view().getUndoButton(), MouseEvent.MOUSE_CLICKED, UndoCommand.class, UndoModel.stackName);
        linkCommand(view().getRedoButton(), MouseEvent.MOUSE_CLICKED, RedoCommand.class, UndoModel.stackName);

        linkCommand(view().getAddCircleButton(), MouseEvent.MOUSE_CLICKED, CreateShapeCommand.class, WBuilder.waveData(UndoAppWaves.SHAPE_TYPE, ShapeType.Circle), UndoModel.stackName);
        linkCommand(view().getAddSquareButton(), MouseEvent.MOUSE_CLICKED, CreateShapeCommand.class, WBuilder.waveData(UndoAppWaves.SHAPE_TYPE, ShapeType.Square), UndoModel.stackName);
        linkCommand(view().getAddRectangleButton(), MouseEvent.MOUSE_CLICKED, CreateShapeCommand.class, WBuilder.waveData(UndoAppWaves.SHAPE_TYPE, ShapeType.Rectangle), UndoModel.stackName);

    }

}

SimpleModel

When the UI is simple or generated entirely in code, creating separate View and Controller classes is unnecessary boilerplate. JRebirth provides DefaultSimpleModel (and DefaultSimpleObjectModel<N, O>) for this use case.

With a SimpleModel:

  • There is no separate View or Controller class.
  • The root node is created directly according to the generic type.
  • UI initialization happens in initSimpleView() instead of a View's initView().
  • Event handling can be done directly inside the model or with inline JavaFX handlers.

This pattern is ideal for leaf UI components, tab content, generated layouts, or quick prototypes.

public class SimpleModel extends DefaultSimpleObjectModel<Text, String> {

    @Override
    protected void initSimpleView() {

        node().setText(object());

    }

}
  • DefaultSimpleObjectModel<Text, String> — node type Text, bound object type String.
  • initSimpleView() — replaces separate View class; node() is the auto-created root.

In this example, DefaultSimpleObjectModel<Text, String> creates a Text node automatically. The initSimpleView() method sets the text value from the bound object — no View or Controller needed.

To use a SimpleModel, declare it with its node type:

public class MySimpleModel extends DefaultSimpleModel<VBox> {

    @Override
    protected void initSimpleView() {
        node().getChildren().addAll(
            new Label("Hello"),
            new Button("Click me")
        );
    }
}
  • DefaultSimpleModel<VBox> — root node type only; no bound business object.
  • Ideal for leaf panels, tabs, or prototypes without full MVC boilerplate.

Or with a bound business object:

public class ItemModel extends DefaultSimpleObjectModel<Label, Item> {

    @Override
    protected void initSimpleView() {
        node().setText(object().getName());
    }
}
  • object() — current bound Item; refresh UI when the model object changes.
  • Combine with bind() overrides on DefaultSimpleObjectModel for property-driven updates.
Behavior Area
Extend your Components.

Behavior

In 30 seconds

A Behavior adds cross-cutting logic (docking, gestures, security) to any BehavioredComponent without subclassing. Define a Behavior interface, a BehaviorData class (@BehaviorDataFor), attach data to the component — the BehaviorFacade creates and wires behaviors at runtime.

How to use

  1. Create MyBehavior extends Behavior<MyData, MyModel> (interface + @RegistrationPoint).
  2. Create MyData extends BehaviorDataBase with @BehaviorDataFor(MyBehavior.class).
  3. Implement MyBehaviorImpl extends AbstractBehavior<MyData, MyModel>.
  4. Attach from the Model: addBehavior(MyData.class) or add data in initModel().
  5. Behaviors listen/send waves like any component; detach when the host component is released.

Overview

Behaviors are pluggable, cross-cutting logic units that can be attached to and detached from any BehavioredComponent at runtime. They extend a component's capabilities through composition rather than inheritance, keeping your Models, Services, and Commands focused on their primary role while behaviors handle orthogonal concerns like docking, security, or gesture handling.

A Behavior is itself a JRebirth Component: it is managed by the BehaviorFacade, participates in the Wave messaging system, and follows the standard component lifecycle.

Short UML Diagram:

Behavior Interface

The Behavior interface defines the contract that every behavior must fulfil. It is parameterized by:

  • D — the BehaviorData type that carries configuration and state for this behavior.
  • C — the BehavioredComponent type to which this behavior can be attached.

The interface exposes two accessors:

  • data() — returns the BehaviorData instance bound to this behavior.
  • component() — returns the owning component.
public interface Behavior<D extends BehaviorData, C extends BehavioredComponent<C>> extends Component<Behavior<?, ?>> {

    /**
     * Gets the {@link BehaviorData} used by this Behavior.
     *
     * @return the behavior data
     */
    D data();

    /**
     * Gets the {@link EnhancedComponent} concerned by this Behavior.
     *
     * @return the component
     */
    C component();

}
  • Behavior<D, C> — D = configuration data, C = host component type (Model, Command, …).
  • data() — read/write behavior configuration supplied at attach time.
  • component() — the owning BehavioredComponent this behavior augments.

Behavior Data

BehaviorData is the data holder associated with a behavior. It carries configuration and runtime state that the behavior needs to operate.

A single BehaviorData can reference one or more Behavior classes via the getBehaviors() method. This means that adding a BehaviorData to a component can trigger the creation of several related behaviors at once.

@FunctionalInterface
public interface BehaviorData {

    List<Class<? extends Behavior<?, ?>>> getBehaviors();

}
  • getBehaviors() — lists behavior interfaces to create when this data is attached.
  • Override getCustomBehaviors() on AbstractBehaviorData for programmatic additions.

The framework provides AbstractBehaviorData (in the core module) as a convenient base class. It automatically collects behavior references declared via:

  1. The getCustomBehaviors() template method (override to add programmatic references).
  2. The @BehaviorDataFor annotation placed on the data class itself.

BehaviorDataBase extends AbstractBehaviorData with an empty getCustomBehaviors() list, making it the simplest starting point for custom data classes.

@BehaviorDataFor Annotation

This annotation links a BehaviorData class to its Behavior interface at the type level:

@BehaviorDataFor(DockableBehavior.class)
public class Dockable extends BehaviorDataBase { /* ... */ }
  • @BehaviorDataFor(DockableBehavior.class) — one data class maps to one behavior interface.
  • At addBehavior(data) the framework reads this annotation to instantiate behaviors.

Creating a Custom Behavior

Creating a behavior requires three artifacts: an interface, an implementation, and a data class.

1. Define the Behavior Interface

Create an interface extending Behavior<YourData, TargetComponent>. Mark it with @RegistrationPoint so it can participate in the modular registration system:

@RegistrationPoint(exclusive = true)
public interface DockableBehavior extends Behavior<Dockable, Model> {

    default String modelName() {
        return getClass().getSimpleName().replaceAll("Model", "");
    }

    default Image modelIcon() {
        return ComponentImages.DefaultDockableIcon.get();
    }
}
  • @RegistrationPoint — exposes the behavior to the modular registration / facade system.
  • Behavior<Dockable, Model> — this behavior only attaches to Model hosts.
  • Default methods — optional API on the behavior interface (icons, labels, etc.).

2. Define the BehaviorData

Create a data class extending BehaviorDataBase and annotate it with @BehaviorDataFor to bind it to the behavior interface:

@BehaviorDataFor(DockableBehavior.class)
public class Dockable extends BehaviorDataBase implements Serializable {

    /** The generated serial version uid. */
    private static final long serialVersionUID = 8137109665415403740L;

    private String name;

    private UniqueKey<? extends Model> modelKey;

    public static Dockable create() {
        return new Dockable();
    }

    public String name() {
        return this.name;
    }

    public Dockable name(final String name) {
        this.name = name;
        return this;
    }

    public UniqueKey<? extends Model> modelKey() {
        return this.modelKey;
    }

    public Dockable modelKey(final UniqueKey<? extends Model> modelKey) {
        this.modelKey = modelKey;
        if (!this.modelKey.optionalData().contains(this)) {
            this.modelKey.optionalData().add(this);
        }
        return this;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName()).append(" [");
        sb.append(this.name).append(" ").append(this.modelKey.key()).append("]");
        return sb.toString();
    }

}
  • @BehaviorDataFor(DockableBehavior.class) — links data class to behavior implementation.
  • BehaviorDataBase — collects behavior classes from annotation + getCustomBehaviors().
  • Fluent setters (name(), modelKey()) — configuration passed when attaching to a Model.

3. Implement the Behavior

Extend AbstractBehavior (or AbstractModelBehavior for Model-aware behaviors) and annotate with @Register to wire the implementation to its interface:

@Register(value = DockableBehavior.class, priority = PriorityLevel.Normal)
public class DockableBehaviorImpl extends AbstractModelBehavior<Dockable> implements DockableBehavior {

    /**
     * {@inheritDoc}
     */
    @Override
    public String modelName() {
        return data().name();
    }

    @Override
    public void initBehavior() {
        // Nothing to init
    }

    @Override
    protected void initInnerComponents() {
    }

}
  • @Register(DockableBehavior.class) — binds implementation to interface for facade lookup.
  • AbstractModelBehavior<Dockable> — Model-specific base; provides model() helpers.
  • initBehavior() — startup hook once data() and component() are wired.
  • data().name() — read configuration supplied when the behavior was attached.

The initBehavior() method is called once the behavior is fully initialized (data and component references are resolved). Use it to set up listeners, bindings, or any startup logic.

Attaching Behaviors to Components

Behaviors are attached to any component implementing the BehavioredComponent interface (all standard Models, Services, and Commands qualify).

Programmatic Attachment

You can attach a behavior at any point during a component's lifecycle:

  • By Behavior class — addBehavior(MyBehavior.class) creates the behavior with default data.
  • By BehaviorData — addBehavior(myDataInstance) creates all behaviors referenced by the data.
@Override
protected void initModel() {
    addBehavior(Dockable.create().name("Tools").modelKey(getModelKey()));
    final DockableBehavior dock = getBehavior(DockableBehavior.class);
}
  • addBehavior(data) — creates every behavior listed on the BehaviorData instance.
  • getBehavior(DockableBehavior.class) — typed access after attach; same lifecycle as host Model.

Once attached, you can query and access behaviors:

  • hasBehavior(MyBehavior.class) — checks if the behavior is present.
  • getBehavior(MyBehavior.class) — retrieves the behavior instance.
  • getBehaviorData(MyBehavior.class) — retrieves the data bound to a behavior.
  • getBehaviorsAware(MyAwareInterface.class) — retrieves all behaviors implementing a given aware interface.
public interface BehavioredComponent<C extends Component<C>> extends Component<C> {

    /**
     * Return true if the component contains the {@link Behavior} class provided.
     *
     * @param behaviorClass the class of the {@link Behavior} to check
     *
     * @return true if the component has got this behavior
     */
    boolean hasBehavior(final Class<? extends Behavior<?, ?>> behaviorClass);

    /**
     * Add a behavior to the component by providing the {@link Behavior} class.
     *
     * @param behaviorClass the class of the behavior to add
     *
     * @return the current component to chain method call
     */
    <BD extends BehaviorData, B extends Behavior<BD, ?>> C addBehavior(final Class<B> behaviorClass);

    /**
     * Add a behavior to the component by providing a {@link BehaviorData}.
     *
     * The BehaviorData allow to add several {@link Behavior} if many of them rare reference by the BehaviorData.
     *
     * @param data the Behavior Data that references Behavior classes to add
     *
     * @return the current component to chain method call
     */
    <BD extends BehaviorData> C addBehavior(final BD data);

    /**
     * Return the {@link Behavior} instance created for the given Behavior type.
     *
     * @param behaviorClass the Behavior type to get
     *
     * @return the Behavior instance attached to the component
     */
    <BD extends BehaviorData, B extends Behavior<BD, ?>> B getBehavior(final Class<B> behaviorClass);

    /**
     * Return the list of {@link BehaviorAware} filtered using given parameter.
     * 
     * @param awareClass the class that shall be implemented by behaviors returned
     * 
     * @return the list of {@link BehaviorAware}
     */
    <BA extends BehaviorAware> List<BA> getBehaviorsAware(final Class<BA> awareClass);

    /**
     * Return the {@link BehaviorData} used by the given Behavior type.
     *
     * @param behaviorClass the Behavior type that use the searched data
     *
     * @return the Behavior Data used by the given Behavior
     */
    <BD extends BehaviorData, B extends Behavior<BD, ?>> BD getBehaviorData(final Class<B> behaviorClass);

}

Built-in Behaviors

JRebirth ships several ready-to-use behaviors in the component and security modules.

DockableBehavior

The DockableBehavior (in the component module) makes a Model dockable within a tabbed or panel-based layout. Each dockable component exposes a modelName() and modelIcon() used by the docking container.

Its data class, Dockable, carries the panel name and a UniqueKey pointing to the Model to display.

@RegistrationPoint(exclusive = true)
public interface DockableBehavior extends Behavior<Dockable, Model> {

    default String modelName() {
        return getClass().getSimpleName().replaceAll("Model", "");
    }

    default Image modelIcon() {
        return ComponentImages.DefaultDockableIcon.get();
    }
}
@BehaviorDataFor(DockableBehavior.class)
public class Dockable extends BehaviorDataBase implements Serializable {

    /** The generated serial version uid. */
    private static final long serialVersionUID = 8137109665415403740L;

    private String name;

    private UniqueKey<? extends Model> modelKey;

    public static Dockable create() {
        return new Dockable();
    }

    public String name() {
        return this.name;
    }

    public Dockable name(final String name) {
        this.name = name;
        return this;
    }

    public UniqueKey<? extends Model> modelKey() {
        return this.modelKey;
    }

    public Dockable modelKey(final UniqueKey<? extends Model> modelKey) {
        this.modelKey = modelKey;
        if (!this.modelKey.optionalData().contains(this)) {
            this.modelKey.optionalData().add(this);
        }
        return this;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName()).append(" [");
        sb.append(this.name).append(" ").append(this.modelKey.key()).append("]");
        return sb.toString();
    }

}

SecurityBehavior

The SecurityBehavior (in the security module) adds access-control capabilities to a Model. It relies on a Securable data class to store security metadata such as permission names.

@RegistrationPoint(exclusive = true)
public interface SecurityBehavior extends Behavior<Securable, Model> {

}
@Register(value = SecurityBehavior.class, priority = PriorityLevel.Normal)
public class SecurityBehaviorImpl extends AbstractBehavior<Securable, Model> implements SecurityBehavior {

    @Override
    public void initBehavior() {
        // check permissions, listen security waves, etc.
    }

    @Override
    protected void initInnerComponents() {
    }
}
  • Securable data carries permission metadata attached to the host Model.
  • initBehavior() — enforce access rules or register security-related wave listeners.
Using Resources
Decrease your memory footprint by using resource wrapper

In 30 seconds

Declare static ResourceItem fields with Resources.create(ResourceParam) (images, fonts, CSS, FXML). Call .get() for cached heavyweight objects stored weakly. Prefer interface “enum” groupings and @Preload for fonts referenced from CSS.

Quick Start

Resources are part of core. Declare typed ResourceItem constants and call .get() to obtain cached heavyweight objects (images, fonts, CSS, FXML).

<dependency>
    <groupId>org.jrebirth.af</groupId>
    <artifactId>core</artifactId>
    <version>${jrebirth.version}</version>
</dependency>

Minimal example — load an image and a stylesheet:

import static org.jrebirth.af.core.resource.Resources.create;

public interface AppResources {
    ImageItem LOGO = create(new RelImage("images/logo.png"));
    StyleSheetItem MAIN = create(new StyleSheet("application"));
}

// In Application.preInit() or View.initView():
Image logo = AppResources.LOGO.get();
addCSS(scene, AppResources.MAIN);

Resources are stored weakly and rebuilt on demand when memory is reclaimed.

Resources

The JRebirth Framework provides an useful way to deal with your local resources, we currently support :

  • Colors
  • Fonts
  • Images
  • Parameters
  • CSS
  • FXML
  • AudioClip (planned)
  • Media (planned)

These resources can consume a lot of memory if you don't dispose them (especially big images and fonts) when you stop using them. JRebirth provides a mechanism to store them weakly and to rebuild them if necessary in order to use the less memory as required. To do this JRebirth stores a ResourceParam lightweight object that contains all information to create the heavyweight resource. This one is linked by a ResourceItem to facilitate its usage.

UML Diagram Overview:

Resource loading

Heavyweight resource objects are retrieved by calling the get() method of ResourceItem. If the resource was already loaded it is retrieved from cache; otherwise it is loaded and stored weakly. When the system is low on memory, resources not retained by a Component or a Scene node become eligible for garbage collection.

// Declarative — preferred for static assets
ColorItem accent = Resources.create(new WebColor("0088D3"));
Color c = accent.get();

// Dynamic — anonymous ResourceItem, still cached by path
Image dynamic = Resources.create(new RelImage(item.getImagePath())).get();

ResourceItem

There are 3 ways to declare resources, each one is available for all kind of resources with special feature for parameters.

With Resources.create(ResourceParam)

The first way is to hold static field declaration instantiated with custom ‘factory’ Resources (not named, with an overloaded create method to avoid later cast). This static fields can be hold in any class you want but we recommend to store them into an Interface used ‘as’ an enum. It's better to have an interface per resource type to avoid big file that blends all resources. Another interesting trick, is to add a static import on related static Resource.create method to shorten the resource declaration (Ctrl+Shift+M with Eclipse).

Static import declaration:


import static org.jrebirth.af.core.resource.Resources.create;

Example of Web color declaration:


    ColorItem TEST_COLOR_WEB_1 = create(new WebColor("0088D3"));

With Enumeration

The other way to declare is a little bit complex, it implies to create an enum that implements a ResourceItem interface. But it requires to add use a custom syntax to use default method.

public enum EnumColors implements ColorEnum {

    // @formatter:off

    /** Color for slide title, white. */
    SLIDE_TITLE {{ web("FFFFFF", 1.0); }},

    /** Color for blue shape, xxx. */
    SHAPE_BLUE{{ web("3495CE", 1.0); }},

    /** Color for drop shadow, black. */
    DROP_SHADOW{{ web("000000", 0.8); }},

    /** Color for inner shadow, white. */
    INNER_SHADOW{{ web("FFFFFE", 0.3); }};

}

Severals default methods exist, at least one per ResourceParams to create.

Dynamically

We can load dynamicalli resource by creating “anonymous” ResourceItem, the resource will be kept within cache if memory is not constrained otherwise it will be deleted. Another call with the same path will hit the cache and the image will be only stored once, but created as many times as deleted and retrieved again.

            final Image image = Resources.create(new RelImage(item.getImage())).get();

In this sample item.getImage() return the relative srtring path of the image.

With @Preload

Resource enums annotated with @Preload are automatically loaded during application startup (in the preInit phase). This is useful for fonts that CSS references — they must be available before stylesheets are applied.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Preload {

}

Samples

Color

For example to manage web color, (basic hexadecimal string #00CC00), you have to use this declaration:


    ColorItem TEST_COLOR_WEB_1 = create(new WebColor("0088D3"));

Font

For example to manage the Turtles font, you have to use this declaration:


    FontItem TEST_REAL_FONT_1 = create(new RealFont(TestFontNames.Turtles, 10.0));

Hereafter the enumeration that stores font names.

public enum TestFontNames implements FontName {

    /** Turtles. */
    Turtles,

    /** Report 1942. */
    Report_1942,
}

StyleSheet

Stylesheets are declared as StyleSheetItem and loaded via addCSS():

public interface SampleStyles {

    /** The application main style sheet. */
    StyleSheetItem MAIN = create(new StyleSheet("sample"));

}

Apply to the scene from your Application class:

@Override
protected void preInit() {
    addCSS(getScene(), SampleStyles.MAIN);
}

Or apply locally from a View:

@Override
protected void initView() {
    addCSS(SampleStyles.LOCAL);
}

Image

import static org.jrebirth.af.core.resource.Resources.create;

ImageItem BANNER = create(new RelImage("images/banner.png"));

// Usage:
Image img = BANNER.get();
myImageView.setImage(img);

Relative paths resolve from the declaring class's package on the classpath.

AudioClip & Media

These resource types (AudioClipItem, MediaItem) are defined in the JRebirth API but not yet implemented in core. They are planned for a future release and will follow the same ResourceItem/ResourceParam pattern as other resources.

Component Library
Ready-made UI containers: Stack, Tabs, Dock, and Workbench

Component Library

In 30 seconds

The component module ships layout Models: StackModel (fading page stack), TabbedPaneModel, DockPaneModel, WorkbenchModel. Configure with fluent *Config beans and navigate via waves (StackWaves, TabbedPaneModel.ADD, etc.).

Quick Start

Add the component module and attach a StackModel with a PageEnum for animated page navigation.

<dependency>
    <groupId>org.jrebirth.af</groupId>
    <artifactId>component</artifactId>
    <version>${jrebirth.version}</version>
</dependency>

Minimal example — stack with enum-driven pages (FXML showcase pattern):

@Override
protected void initModel() {
    InnerComponent<StackModel> stack = CBuilder.innerComponent(StackModel.class, FXMLPage.class);
    this.stackModel = findInnerComponent(stack);
}

@Override
protected void showView() {
    view().node().setCenter(this.stackModel.node());
}

// Navigate to another page:
sendWave(WBuilder.wave()
    .waveType(StackWaves.SHOW_PAGE_ENUM)
    .addDatas(WBuilder.waveData(StackWaves.PAGE_ENUM, FXMLPage.HybridFxml)));

StackModel uses ShowFadingModelCommand internally — page switches fade automatically.

Component Library Overview

The component module provides reusable, configurable UI container models that cover common application layout patterns:

  • StackModel — Page-based navigation with animated transitions.
  • TabbedPaneModel — Tabbed container with drag-and-drop tab reordering.
  • DockPaneModel — Dockable panel layout with configurable orientation.
  • WorkbenchModel — IDE-style workbench combining dock panes and tabs.

Each container is configured via a dedicated configuration bean and communicates through JRebirth waves.

StackModel

StackModel manages a StackPane that shows one child Model at a time. It uses ShowFadingModelCommand for animated transitions between pages.

@Override
protected void initModel() {
    listen(new DefaultWaveChecker<>(StackWaves.STACK_NAME, getStackName()), StackWaves.SHOW_PAGE_MODEL);
    listen(new ClassWaveChecker<>(StackWaves.PAGE_ENUM, getPageEnumClass()), StackWaves.SHOW_PAGE_ENUM);
}

public void doShowPageEnum(final PageEnum pageEnum, final Wave wave) {
    if (getPageEnumClass() != null && getPageEnumClass().equals(pageEnum.getClass())) {
        showPage(pageEnum.getModelKey(), wave);
    }
}

private void showPage(final UniqueKey<? extends Model> pageModelKey, final Wave wave) {
    if (pageModelKey != null && !pageModelKey.equals(this.currentModelKey)) {
        final DisplayModelWaveBean waveBean = DisplayModelWaveBean.create()
            .childrenPlaceHolder(view().node().getChildren())
            .appendChild(false)
            .showModelKey(pageModelKey)
            .hideModelKey(this.currentModelKey);
        this.currentModelKey = waveBean.showModelKey();
        sendWave(WBuilder.callCommand(ShowFadingModelCommand.class).waveBean(waveBean).relatedWave(wave));
    }
}

showPage builds the wave bean with appendChild(false) and fires ShowFadingModelCommand — this is where cross-fade transitions run.

PageEnum

Pages are mapped via a PageEnum that associates enum constants with Model keys:

public enum MyPages implements PageEnum {
    Home, Settings, Profile;

    @Override
    public UniqueKey<? extends Model> getModelKey() {
        switch (this) {
            case Home:     return Key.create(HomeModel.class);
            case Settings: return Key.create(SettingsModel.class);
            case Profile:  return Key.create(ProfileModel.class);
            default:       return Key.create(HomeModel.class);
        }
    }
}

StackWaves

Navigation is triggered by sending waves defined in StackWaves:

public interface StackWaves {

    /*****************************************************************************************************/
    /** _________________________________________Wave Items.____________________________________________ */
    /*****************************************************************************************************/

    /** The name of the stack concerned. */
    WaveItemBase<String> STACK_NAME = new WaveItemBase<String>() {
    };

    /** The Enum class that list all pages displayable into the stack. */
    // WaveItem<Class<? extends PageEnum>> STACK_PAGES = new WaveItem<Class<? extends PageEnum>>() {
    // };

    /** The page to display (model class descriptor). */
    WaveItemBase<UniqueKey<? extends Model>> PAGE_MODEL_KEY = new WaveItemBase<UniqueKey<? extends Model>>() {
    };

    /** The page to display (enum descriptor). */
    WaveItemBase<PageEnum> PAGE_ENUM = new WaveItemBase<PageEnum>() {
    };

    /*****************************************************************************************************/
    /** _________________________________________Wave Types.____________________________________________ */
    /*****************************************************************************************************/

    /** Show Page (with Model) action. */
    WaveType SHOW_PAGE_MODEL = WBuilder.waveType("SHOW_PAGE_MODEL").items(PAGE_MODEL_KEY, STACK_NAME);

    /** Show Page (with Enum) action. */
    WaveType SHOW_PAGE_ENUM = WBuilder.waveType("SHOW_PAGE_ENUM").items(PAGE_ENUM/* , STACK_PAGES */);

}

Available wave types:

WaveType Parameters Description
SHOW_PAGE_MODEL PAGE_MODEL_KEY, STACK_NAME Show a page by its model key
SHOW_PAGE_ENUM PAGE_ENUM Show a page by its enum constant

Using StackModel

To create and configure a StackModel:

InnerComponent<StackModel> stack = CBuilder.innerComponent(StackModel.class, MyPages.class);
StackModel stackModel = findInnerComponent(stack);

To navigate programmatically:

sendWave(WBuilder.wave()
    .waveType(StackWaves.SHOW_PAGE_ENUM)
    .addDatas(WBuilder.waveData(StackWaves.PAGE_ENUM, MyPages.Settings)));

The first enum constant is automatically shown when the stack is first displayed.

Configuration

StackConfig allows you to set:

  • stackName() — Unique identifier for the stack (enables multiple stacks in the same app).
  • pageEnumClass() — The PageEnum class that maps page IDs to model keys.

TabbedPaneModel

TabbedPaneModel provides a tabbed container with support for drag-and-drop tab reordering and animated tab insertion/removal.

public static WaveType ADD = WBuilder.waveType("ADD_TAB").items(TAB);
public static WaveType REMOVE = WBuilder.waveType("REMOVE_TAB").items(TAB);

@Override
protected void initModel() {
    final WaveChecker waveChecker = wave ->
        ObjectUtility.equalsOrBothNull(wave.get(TAB_KEY), object().id());
    listen(waveChecker, ADD);
    listen(waveChecker, REMOVE);
}

@Override
protected void bind() {
    object().tabs().addListener(this::onTabsChanged);
}

Tab insertions and removals run through SequentialTransition on the JAT. Filter waves with TabbedPaneModel.TAB_KEY matching TabbedPaneConfig.id().

Adding Tabs

Tabs are added via waves or programmatically using Dockable instances:

Dockable tab = Dockable.create()
    .modelKey(Key.create(MyContentModel.class))
    .name("My Tab");

sendWave(WBuilder.wave()
    .waveType(TabbedPaneModel.ADD)
    .addDatas(
        WBuilder.waveData(TabbedPaneModel.TAB, tab),
        WBuilder.waveData(TabbedPaneModel.TAB_KEY, "myTabbedPane")));

Configuration

TabbedPaneConfig allows you to set:

  • id() — Unique identifier for this tabbed pane.
  • orientation() — Tab bar position: TabbedPaneOrientation.top, bottom, left, or right.
  • tabs() — Initial list of Dockable tabs.
  • styleClass() — CSS style class applied to the container.

DockPaneModel

DockPaneModel provides a dockable panel layout that splits space between child panes. Child panes can be other DockPaneModel instances (for nesting) or TabbedPaneModel instances.

public static WaveType ADD = WBuilder.waveType("ADD_PART").items(MODEL);

@Override
protected void initModel() {
    listen(wave -> ObjectUtility.equalsOrBothNull(wave.get(DOCK_KEY), object().id()), ADD, REMOVE);
    for (final PartConfig<?, ?> pc : object().panes()) {
        callCommand(AddDockCommand.class,
            DockWaveBean.create().dockConfig(object()).parts(pc));
    }
}

private void onPanesChanged(final ListChangeListener.Change<? extends PartConfig<?, ?>> change) {
    while (change.next()) {
        if (change.wasRemoved()) {
            callCommand(RemoveDockCommand.class, DockWaveBean.create().dockConfig(object())
                .parts(change.getRemoved().toArray(new PartConfig[0])));
        }
        if (change.wasAdded()) {
            callCommand(AddDockCommand.class, DockWaveBean.create().dockConfig(object())
                .parts(change.getList().get(change.getFrom())));
        }
    }
}

Pane list changes dispatch AddDockCommand / RemoveDockCommand. Nest DockPaneConfig entries inside panes() for multi-level splits.

Configuration

DockPaneConfig allows you to set:

  • id() — Unique identifier for this dock pane.
  • orientation() — DockPaneOrientation.horizontal or vertical (split direction).
  • panes() — Child PartConfig instances (can be nested DockPaneConfig or TabbedPaneConfig).

Adding/Removing Parts

Parts are managed via AddDockCommand / RemoveDockCommand or through the wave system:

sendWave(WBuilder.wave()
    .waveType(DockPaneModel.ADD)
    .addDatas(
        WBuilder.waveData(DockPaneModel.MODEL, myModel),
        WBuilder.waveData(DockPaneModel.DOCK_KEY, "myDock")));

WorkbenchModel

WorkbenchModel provides an IDE-style workbench layout. It combines DockPaneModel and TabbedPaneModel into a configurable multi-panel workspace.

WorkbenchModel is a thin wrapper; real workbench layouts are composed from nested DockPaneModel and TabbedPaneModel instances. The workbench showcase TabDemoModel builds a 2×2 grid by nesting DockPaneConfig and TabbedPaneConfig:

final DockPaneModel rootDock = getModel(DockPaneModel.class,
    DockPaneConfig.create()
        .id("RootDock")
        .orientation(DockPaneOrientation.vertical)
        .panes(topDockConfig, bottomDockConfig));
node().setCenter(rootDock.node());

Each quadrant wraps a TabbedPaneConfig with its own tab orientation (top, right, bottom, left). See the full listing below.

Example: Building a Workbench

The showcase demonstrates how to compose a complex workbench layout using nested dock panes and tabbed panes:

@Register(value = ModuleModel.class)
public class TabDemoModel extends DefaultSimpleModel<BorderPane> implements ModuleModel {

	private boolean done = false;

	@Override
	protected void initSimpleView() {
		super.initSimpleView();

		final String topLeft = "TopLeft";
		final String topRight = "TopRight";
		final String bottomLeft = "BottomLeft";
		final String bottomRight = "BottomRight";
		final DockPaneModel rootDock = getModel(DockPaneModel.class,
				DockPaneConfig.create()
						.id("RootDock")
						.orientation(DockPaneOrientation.vertical)
						.panes(
								DockPaneConfig.create()
										.id("TopDock")
										.orientation(DockPaneOrientation.horizontal)
										.panes(
												DockPaneConfig.create()
														.id(topLeft+"Dock")
														.orientation(DockPaneOrientation.horizontal)
														.panes(TabbedPaneConfig.create()
																.id(topLeft)
																.styleClass("Top Left")
																.orientation(TabbedPaneOrientation.top)
																.tabs(
																		dockable("1"),
																		dockable("2"),
																		dockable("3"),
																		dockable("4"),
																		dockable("5"),
																		dockable("6")
																		)),
												DockPaneConfig.create()
														.id(topRight+"Dock")
														.orientation(DockPaneOrientation.horizontal)
														.panes(TabbedPaneConfig.create()
																.id(topRight)
																.styleClass("Top Right")
																.orientation(TabbedPaneOrientation.right)
																.tabs(
																		dockable("7"),
																		dockable("8"),
																		dockable("9")
																		))),
								DockPaneConfig.create()
										.id("BottomDock")
										.orientation(DockPaneOrientation.horizontal)
										.panes(
												DockPaneConfig.create()
														.id(bottomLeft+"Dock")
														.orientation(DockPaneOrientation.horizontal)
														.panes(TabbedPaneConfig.create()
																.id(bottomLeft)
																.styleClass("Bottom Left")
																.orientation(TabbedPaneOrientation.bottom)
																.tabs(
																		dockable("15"),
																		dockable("16")
																		)),
												DockPaneConfig.create()
														.id(bottomRight+"Dock")
														.orientation(DockPaneOrientation.horizontal)
														.panes(TabbedPaneConfig.create()
																.id(bottomRight)
																.styleClass("Bottom Right")
																.orientation(TabbedPaneOrientation.left)
																.tabs(
																		dockable("10"),
																		dockable("11"),
																		dockable("12"),
																		dockable("13"),
																		dockable("14")
																		)
																))));
		node().setCenter(rootDock.node());
	}
}

This example creates a 2x2 grid layout:

  • Top-left: Tabbed pane with tabs on top
  • Top-right: Tabbed pane with tabs on the right
  • Bottom-left: Tabbed pane with tabs on the bottom
  • Bottom-right: Tabbed pane with tabs on the left

Each section is wrapped in nested DockPaneConfig instances to control the split directions.

Configuration Beans

All component containers use configuration beans that follow a fluent builder pattern:

StackConfig

StackConfig.create()
    .stackName("main")
    .pageEnumClass(MyPages.class)

TabbedPaneConfig

TabbedPaneConfig.create()
    .id("editor")
    .orientation(TabbedPaneOrientation.top)
    .styleClass("editor-tabs")
    .tabs(dockable1, dockable2)

DockPaneConfig

DockPaneConfig.create()
    .id("rootDock")
    .orientation(DockPaneOrientation.vertical)
    .panes(topConfig, bottomConfig)

PartConfig

PartConfig is the common supertype for all pane configurations (TabbedPaneConfig, DockPaneConfig). It allows heterogeneous nesting of container types within a dock layout.