Fork me on GitHub

Wave Area

Allow asynchronous communication between components

Wave Overview

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:

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

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.

67
68
69
70
71
72
73
/** 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>>() {
};

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

89
90
91
92
93
94
/** This wave item will be used only into a WaveData to pass the current Service task handled by the wave. */
WaveItem<ServiceTaskBase<?>> SERVICE_TASK = new WaveItemBase<ServiceTaskBase<?>>(false) {
};
  
/** This wave item will be used only into a WaveData to pass the right progress bar used by service task. */
WaveItem<ProgressBar> PROGRESS_BAR = new WaveItemBase<ProgressBar>(false) {
154
155
// Attach ServiceTask to the source wave
sourceWave.addDatas(WBuilder.waveData(JRebirthWaves.SERVICE_TASK, task));

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)
39
40
41
42
43
/** Trigger a Unload wave. */
WaveType DO_UNLOAD = WBuilder.waveType("UNLOAD");
  
/** Trigger a Play wave. */
WaveType DO_PLAY = WBuilder.waveType("PLAY");
  • Into a service class (here with on argument) :
41
42
43
44
45
46
47
48
/** 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.

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.

Each WaveItem will be passed to the method as an 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.

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

Chained Wave

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/**
 * Get more info at : www.jrebirth.org .
 * Copyright JRebirth.org ¬© 2011-2013
 * Contact : sebastien.bordes@jrebirth.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jrebirth.af.core.concurrent;
  
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
  
import javafx.scene.Scene;
  
import org.jrebirth.af.api.application.JRebirthApplication;
import org.jrebirth.af.api.concurrent.JRebirthRunnable;
import org.jrebirth.af.api.exception.CoreException;
import org.jrebirth.af.api.exception.JRebirthThreadException;
import org.jrebirth.af.api.facade.GlobalFacade;
import org.jrebirth.af.api.log.JRLogger;
import org.jrebirth.af.api.wave.Wave;
import org.jrebirth.af.core.command.basic.showmodel.DisplayModelWaveBean;
import org.jrebirth.af.core.command.basic.showmodel.ShowModelCommand;
import org.jrebirth.af.core.facade.GlobalFacadeBase;
import org.jrebirth.af.core.key.Key;
import org.jrebirth.af.core.log.JRLoggerFactory;
import org.jrebirth.af.core.resource.provided.parameter.CoreParameters;
import org.jrebirth.af.core.service.basic.StyleSheetTrackerService;
import org.jrebirth.af.core.wave.WBuilder;
  
/**
 * The class <strong>JRebirthThread</strong>.
 *
 * @author S√©bastien Bordes
 */
public final class JRebirthThread extends Thread implements ConcurrentMessages {
  
    /** The JRebirth Internal Thread name [JIT]. */
    public static final String JIT_NAME = "JIT";
  
    /** The class logger. */
    private static final JRLogger LOGGER = JRLoggerFactory.getLogger(JRebirthThread.class);
  
    /** The unique instance of the current class. */
    private static JRebirthThread internalThread;
  
    /** The Global Facade object that handle other sub facade. */
    private transient GlobalFacade facade;
  
    /** The javaFX application that launch this thread. */
    private transient JRebirthApplication<?> application;
  
    /** The list of tasks being processed, all access MUST BE synchronized. */
    private final PriorityBlockingQueue<JRebirthRunnable> processingTasks;
  
    /** Flag indicating that current thread has started and is ready to process events. */
    private final AtomicBoolean hasStarted = new AtomicBoolean(false);
  
    /** Flag to stop the infinite loop that process JRebirth Events. */
    private final AtomicBoolean infiniteLoop = new AtomicBoolean(true);
  
    /** Flag that indicate that the closure must be forced. */
    private final AtomicBoolean forceClose = new AtomicBoolean(false);
  
    /**
     * private final boolean readyToShutdown = false;
     *
     * /** Build the JRebirth Thread.
     */
    private JRebirthThread() {
        super(JIT_NAME);
  
        // Daemon-ize this thread, thus it will be killed with the main JavaFX Thread
        setDaemon(true);
  
        // Initialize the queue
        this.processingTasks = new PriorityBlockingQueue<JRebirthRunnable>(10, new JRebirthRunnableComparator());
    }
  
    /**
     * Run into thread pool.
     *
     * If a slot is available the task will be run immediately.<br />
     * Otherwise it will run as soon as a slot will be available according to the existing task queue
     *
     * @param runnable the task to run
     */
    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());
        }
  
    }
  
    /**
     * Run this task as soon as possible. Enqueue the task to be run at the next event pulse. Run into the JRebirth Thread
     *
     * @param runnable the task to run
     */
    public void runLater(final JRebirthRunnable runnable) {
        this.processingTasks.add(runnable);
    }
  
    /**
     * Launch the JRebirth thread.
     *
     * @param application the javaFX application instance
     */
    public void prepare(final JRebirthApplication<?> application) {
  
        // Link the current application
        this.application = application;
        // Build the global facade at startup
        this.facade = new GlobalFacadeBase(application);
  
        // Start the thread (infinite loop)
        // start();
    }
  
    /**
     * Return true if JRebirth has been correctly started (boot action is done).
     *
     * @return true if JRebirth has been correctly started
     */
    public boolean hasStarted() {
        return this.hasStarted.get();
    }
  
    /**
     * {@inheritDoc}
     */
    @Override
    public void run() {
  
        manageStyleSheetReloading(this.application.scene());
  
        // Attach the first view and run pre and post command
        try {
            bootUp();
        } catch (final JRebirthThreadException e) {
            LOGGER.error(BOOT_UP_ERROR, e);
        }
  
        // JRebirth thread has boot up and is ready to process events
        this.hasStarted.set(true);
  
        while (this.infiniteLoop.get()) {
            try {
                if (!this.forceClose.get()) {
                    final JRebirthRunnable jrr = this.processingTasks.poll(100, TimeUnit.MILLISECONDS);
                    if (jrr != null) {
                        jrr.run();
                    }
                }
            } catch (final InterruptedException e) {
                LOGGER.error(JIT_ERROR, e);
            }
        }
        // Shutdown the application more properly
        shutdown();
    }
  
    /**
     * Manage style sheet reloading by using a custom service provide by JRebirth Core.
     *
     * @param scene the scene to reload in case of Style Sheet update
     */
    private void manageStyleSheetReloading(final Scene scene) {
        if (CoreParameters.DEVELOPER_MODE.get() && scene != null) {
  
            for (final String styleSheet : scene.getStylesheets()) {
  
                getFacade().serviceFacade().retrieve(StyleSheetTrackerService.class).listen(styleSheet, this.application.scene());
            }
            getFacade().serviceFacade().retrieve(StyleSheetTrackerService.class).start();
        }
    }
  
    /**
     * Attach the first view and run pre and post command.
     *
     * @throws JRebirthThreadException if a problem occurred while calling the command
     */
    public void bootUp() throws JRebirthThreadException {
  
        final List<Wave> chainedWaveList = new ArrayList<>();
  
        // Manage waves to run before the First node creation
        final List<Wave> preBootList = getApplication().preBootWaveList();
        if (preBootList != null && !preBootList.isEmpty()) {
            chainedWaveList.addAll(preBootList);
        }
  
        // Manage the creation of the first node and show it !
  
        final Wave firstViewWave = getLaunchFirstViewWave();
        if (firstViewWave != null) {
            chainedWaveList.add(firstViewWave);
        }
  
        // Manage waves to run after the First node creation
        final List<Wave> postBootList = getApplication().postBootWaveList();
        if (postBootList != null && !postBootList.isEmpty()) {
            chainedWaveList.addAll(postBootList);
        }
  
        if (!chainedWaveList.isEmpty()) {
            getFacade().notifier().sendWave(WBuilder.chainWaveCommand(chainedWaveList));
        }
    }
  
    /**
     * {@inheritDoc}
     */
    @Override
    public void interrupt() {
        super.interrupt();
  
        // Release all resources
        shutdown();
    }
  
    /**
     * This method can be called a lot of time while application is running.
     *
     * The first time to stop the infinite loop, then to purge all queues and let the thread terminate itself.
     */
    public void close() {
  
        // Infinite loop is still active
        if (this.infiniteLoop.get()) {
            // First attempt to close the application
            this.infiniteLoop.set(false);
        } else {
            // N-th attempt to close the application
            this.forceClose.set(true);
  
            // All Task Queues are cleared
            // this.queuedTasks.clear();
            this.processingTasks.clear();
        }
  
    }
  
    /**
     * Release all resources.
     */
    private void shutdown() {
        try {
            this.facade.stop();
            this.facade = null;
            // Destroy the static reference
            destroyInstance();
        } catch (final CoreException e) {
            LOGGER.log(SHUTDOWN_ERROR, e);
        }
    }
  
    /**
     * Destroy the singleton that hold the thread.
     */
    private static void destroyInstance() {
        internalThread = null;
    }
  
    /**
     * Launch the first view by adding it into the root node.
     *
     * @return the wave responsible of the creation of the first view
     */
    @SuppressWarnings("unchecked")
    protected Wave getLaunchFirstViewWave() {
        Wave firstWave = null;
        // Generates the command wave directly to win a Wave cycle
        if (this.application != null && this.application.rootNode() != null && this.application.firstModelClass() != null) {
  
            firstWave = WBuilder.callCommand(ShowModelCommand.class).waveBean(
                                                                              DisplayModelWaveBean.create()
                                                                                                  .childrenPlaceHolder(this.application.rootNode().getChildren())
                                                                                                  .showModelKey(Key.create(this.application.firstModelClass())));
            //
            //
            // ShowModelWaveBuilder.create()
            // .childrenPlaceHolder(this.application.getRootNode().getChildren())
            // .showModelKey(getFacade().getUiFacade().buildKey((Class<Model>) this.application.getFirstModelClass()))
            // .build();
        }
        return firstWave;
  
    }
  
    /**
     * @return Returns the application.
     */
    public JRebirthApplication<?> getApplication() {
        return this.application;
    }
  
    /**
     * @return Returns the facade.
     */
    public GlobalFacade getFacade() {
        return this.facade;
    }
  
    /**
     * Return the JRebirthThread used to manage facades and waves.
     *
     * @return the JRebirthThread
     */
    public static JRebirthThread getThread() {
        synchronized (JRebirthThread.class) {
            if (internalThread == null) {
                internalThread = new JRebirthThread();
            }
        }
        return internalThread;
    }
  
}