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.
Service with WaveType constants (.items(...).returnAction(...).returnItem(...)).doLoadEvents for LOAD_EVENTS).DefaultService; register in initService() with listen(DO_XXX) or use @OnWave on the interface.updateProgress / updateMessage when needed.returnData(MyService.class, MyService.DO_TASK, WBuilder.waveData(...)).initModel(), listen(MyService.DO_TASK.returnWaveType()) and add a handler method (e.g. doTaskCompleted(...)).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:
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:
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);
.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.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.returnAction (EVENTS_LOADED → doEventsLoaded).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().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;
}
}
updateProgress(wave, current, total) to keep UI responsive.Follow these steps end-to-end:
WaveType (entry + return items).initService() registration.returnData(...) to start the task.listen(entry.returnWaveType()) on the caller.doXxxCompleted(...) handler to apply the result on JAT.To call this Service Feature, you can use the returnData from any JRebirth's Component. It takes at least 2 mandatory arguments:
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.WaveType (DO_LOAD_EVENTS).WBuilder.waveData(...) — wraps the File input required by the wave contract.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:
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:
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.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.WaveItem on the return type (List<JRebirthEvent> here).Wave wave — always last; gives access to progress, chaining, or source context.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.
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.PriorityLevel.Low — service tasks yield to commands and other JTP work.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.
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.DO_CLEANUP.returnWaveType() and implements doCleanupDone(Wave).