Notice: This Wiki is now read only and edits are no longer possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.
Difference between revisions of "Efxclipse/Runtime/Recipes"
(→LoggerCreator) |
|||
Line 2: | Line 2: | ||
This page holds best practice recipes when writing JavaFX application using e(fx)clipse | This page holds best practice recipes when writing JavaFX application using e(fx)clipse | ||
+ | |||
+ | = Service retrieval = | ||
+ | |||
+ | Retrieving services from the OSGi-Registry is sometimes a bit cumbersome so <code>org.eclipse.fx.core.Util</code> provides helpers to look up services with the following APIs | ||
+ | * <code>public static <S> S lookupService(Class<?> requestor, Class<S> serviceClass)</code> | ||
+ | * <code>public static <S> S lookupService(Class<S> serviceClass)</code> | ||
+ | * <code>public static <S> List<S> lookupServiceList(Class<?> requestor,Class<S> serviceClass)</code> | ||
+ | * <code>public static <S> List<S> lookupServiceList(Class<S> serviceClass)</code> | ||
+ | |||
+ | An added benefit of this utilities is that they work also outside OSGi by using <code>ServiceLoader</code> instead to ensure a specific sort order services can implement the '''optional''' <code>org.eclipse.fx.core.RankedService</code>. | ||
= Logging = | = Logging = |
Revision as of 05:57, 20 January 2015
This page holds best practice recipes when writing JavaFX application using e(fx)clipse
Service retrieval
Retrieving services from the OSGi-Registry is sometimes a bit cumbersome so org.eclipse.fx.core.Util
provides helpers to look up services with the following APIs
-
public static
S lookupService(Class<?> requestor, Class<S> serviceClass)</code> - <code>public static <S> S lookupService(Class<S> serviceClass)</code>
- <code>public static <S> List<S> lookupServiceList(Class<?> requestor,Class<S> serviceClass)</code>
- <code>public static <S> List<S> lookupServiceList(Class<S> serviceClass)</code>
An added benefit of this utilities is that they work also outside OSGi by using <code>ServiceLoader</code> instead to ensure a specific sort order services can implement the optional <code>org.eclipse.fx.core.RankedService</code>.
Logging
e(fx)clipse has its own logging facade <code>org.eclipse.fx.core.log.Logger</code> which allows to plug-in different log frameworks.
Currently available are:
- <code>java.util.Logging</code> (default)
- log4j by adding <code>org.eclipse.fx.core.log4j</code> bundle to your OSGi-Runtime
Usage
There are different ways to use get a logger.
LoggerCreator
If you are running on OSGi or in a simple java application. You can retrieve a logger using <code>org.eclipse.fx.core.log.LoggerCreator</code>
import org.eclipse.fx.core.log.Logger; import org.eclipse.fx.core.log.LoggerCreator; public class MyClass { private static Logger LOGGER = LoggerCreator.createLogger(MyClass.class); // .... }
In an OSGi-Environment the OSGi-Service registry is searched to find a <code>LoggerFactory</code> and in none OSGi-Applications the <code>ServiceLoader</code> is consulted.
LoggerFactory Service
The different logger bundles contribute their <code>LoggerFactory</code> implementation into the OSGi-Registry. In case you are e.g. contributing a service via DS you can get simple add a service reference and you'll get the <code>LoggerFactory</code> with the highest rank injected.
import org.eclipse.fx.core.log.LoggerFactory; import org.eclipse.fx.core.log.Logger; public class MyServiceImpl implements MyService { private Logger logger; public void setLoggerFactory(LoggerFactory factory) { this.logger = factory.createLogger(MyService.class.getName()); } public void unsetLoggerFactory(LoggerFactory factory) { } }
<?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="myservice"> <implementation class="impl.MyServiceImpl"/> <service> <provide interface="service.MyService"/> </service> <reference bind="setLoggerFactory" cardinality="1..1" interface="org.eclipse.fx.core.log.LoggerFactory" name="LoggerFactory" policy="static" unbind="unsetLoggerFactory"/> </scr:component>
Eclipse DI & @Log annotation
If you make use of Eclipse DI in your code you can get a <code>Logger</code> instance injected with:
import org.eclipse.fx.core.log.Log; import org.eclipse.fx.core.log.Logger; import javax.inject.Inject; public class MyDIComponent { @Inject @Log Logger logger; }
Google Guice & @Log annotation
If you use Guice as the DI container you use the <code>org.eclipse.fx.core.guice</code> bundle to get a Logger injected in your component with:
import org.eclipse.fx.core.log.Log; import org.eclipse.fx.core.log.Logger; import javax.inject.Inject; public class MyDIComponent { @Log Logger logger; }
if you have configured your Guice-Module with:
import com.google.inject.Module; import com.google.inject.Binder; import org.eclipse.fx.core.log.LoggerFactory; import org.eclipse.fx.core.log4j.Log4JLoggerFactory; import org.eclipse.fx.core.guice.FXLoggerListener; public class MyModule implements Module { public void configure(Binder binder) { binder.bind(LoggerFactory.class).toProvider(Log4JLoggerFactory.class); // or JUtilLoggerFactory binder.bindListener(Matchers.any(), new FXLoggerListener()); } }
Instead of directly binding to a logger factory you can delegate to the OSGi-Service registry by using <code>OSGiLoggerFactoryProvider</code>:
import com.google.inject.Module; import com.google.inject.Binder; import org.eclipse.fx.core.log.LoggerFactory; import org.eclipse.fx.core.guice.FXLoggerListener; import org.eclipse.fx.core.guice.OSGiLoggerFactoryProvider; public class MyModule implements Module { public void configure(Binder binder) { binder.bind(LoggerFactory.class).toProvider(OSGiLoggerFactoryProvider.class); binder.bindListener(Matchers.any(), new FXLoggerListener()); } }
Extending
Like outlined above there are 2 logger implementations available from the e(fx)clipse p2 repository. If you want to use a different logging framework you are able to plug-in your own by implementing <code>LoggerFactory</code> and contributing it to the OSGi-Service-Registry.
import javax.inject.Provider; import org.eclipse.fx.core.log.LoggerFactory; import org.eclipse.fx.core.log.Logger; public class MyLoggerFactory implements LoggerFactory, Provider<LoggerFactory> { @Override public LoggerFactory get() { return this; } @Override public Logger createLogger(String name) { return new LoggerImpl(name); } static class LoggerImpl implements Logger { private String name; public LoggerImpl(String name) { this.name = name; } // .... } }
You contribute it to the OSGi-Service registry e.g. by using DS. You should give the service a higher ranking than 1 (which is the ranking of the log4j service) to ensure it is picked when a logger is requested.
<?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="my.logger.framework.factory"> <implementation class="my.logger.framework.MyLoggerFactory"/> <property name="service.ranking" type="Integer" value="2"/> <service> <provide interface="org.eclipse.fx.core.log.LoggerFactory"/> </service> </scr:component>
Eclipse DI
Publishing to the IEclipseContext
The <code>IEclipseContext</code> is the central component of the Eclipse DI container. Retrieving values from it is as easy as writing <code>@Inject</code> in your java class and the DI container will fill it with a value and keep it up-to-date if you used field or method injection.
The opposite - publishing a value into the context - is not as easy because your java component will get a dependency on the DI-Container because it needs to access the <code>IEclipseContext</code> directly. e(fx)clipse provides you the possibility to get around this architectual problem by defining an annotation named <code>@ContextValue</code> which marks a slot in <code>IEclipseContext</code> instance which can be used to observe the value and modified.
import org.eclipse.fx.core.di.ContextBoundValue; import org.eclipse.fx.core.di.ContextValue; import javax.inject.Inject; public static class SimpleInject { @Inject @ContextValue(contextKey="user") public ContextBoundValue<String> value; private void updateValue() { value.publish("tomschindl"); } }
To make use of this your bundle needs to have a dependency on <code>org.eclipse.fx.core.di</code> and your runtime has to include <code>org.eclipse.fx.core.di.context</code>.
Injected value as an observable
A reoccuring pattern when developing with Eclipse Databinding and Dependency Injection is that the injected value is used as the master in master-detail binding scenario.
import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.core.databinding.observable.value.WritableValue; import org.eclipse.fx.core.di.ContextBoundValue; import org.eclipse.fx.core.di.ContextValue; public class DetailView { private IObservableValue master = new WritableValue(); @Inject public void update(Person p) { master.getRealm().exec(new Runnable() { public void run() { master.setValue(p); } }); } }
The <code>@ContextValue</code> framework introduce in the recipe above is able to reduce the code to
import org.eclipse.core.databinding.observable.value.IObservableValue; import org.eclipse.fx.core.di.ContextBoundValue; import org.eclipse.fx.core.di.ContextValue; public class DetailView { @Inject @ContextValue("my.domain.Person") IObservableValue master; }
If you prefer the JavaFX observable system you get let the system inject you this type as well
import javafx.beans.property.Property; import org.eclipse.fx.core.di.ContextBoundValue; import org.eclipse.fx.core.di.ContextValue; public class DetailView { @Inject @ContextValue("my.domain.Person") Property<Person> property; }
Generally speaking you can use any type for the value injected by <code>@ContextValue</code> as long as there's an adapter registered which is able to convert from <code>ContextBoundValue</code> to it.
An observable value is not a one way street so it also allows publish through it:
public class ListView { @PostConstruct public void initUI(@ContextValue("my.domain.Person") Property<Person> property) { ListView<Person> v = new ListView<>(); // ... property.bind(v.getSelectionModel().selectedItemProperty()); } }
@FXMLLoader
If you want to use DI in the controller attached to an FXML-File you'd normally use an <code>org.eclipse.fx.ui.di.InjectingFXMLLoader</code> to free you from configuring the loader with information the DI container already knows you can make use of the <code>@org.eclipse.fx.ui.di.FXMLLoader</code> in your components which provides you an <code>org.eclipse.fx.ui.di.FXMLLoaderFactory</code> instance.
public class MyLoginView { @PostConstruct void init(BorderPane p, @FXMLLoader FXMLLoaderFactory factory) { GridPane gridPane = factory.loadRequestorRelative("myLoginView.fxml").load(); p.setCenter(gridPane); // ... } }
and now you can use <code>@Inject</code> in your controller:
public class MyLoginController { @Inject MyLoginService loginService; @FXML TextField username; @FXML TextField password; }
@Adapt
Sometimes a generic container objects like an <code>IStructuredSelection</code> are pushed into the context but in your application you want to get a concrete type. So generic type conversion can be implemented using the <code>AdapterService</code> introduced below. To make direct use of the adapters as part of the the DI-Process you can use the <code>@org.eclipse.fx.core.adapter.Adapt</code> annotation who will try to convert the value in the context using the the AdapterService.
For the example. Let's suppose there's an adapter who is able to convert from a <code>String</code> to an <code>Integer</code> you could use DI in the following way
import org.eclipse.fx.core.adapter.Adapt; @Inject @Adapt @Named("myValue") Integer myValueAsInteger;
Handling @Translation effeciently
If you mark an injected value with @Translation the DI container will inject you a Message-Object which translated Strings and reinject a new instance when ever you switch the locale. A very common task you have to do when deal with dynamic language switches is to update all UI-Elements. e(fx)clipse provide specialized classes helping you to deal with such a situation.
The first thing you should do is to create a class dealing with the registration and language flipping:
@Creatable public class MessageRegistry<Messages> extends org.eclipse.fx.core.di.AbstractMessageRegistry { @Inject public void updateMessages(@Translation Messages messages) { super.updateMessages(messages); } // Optional provide method to access current message public String MyString() { return getMessages().MyString; } }
And use it in your UI like this:
@Inject MessageRegistry r; @PostConstruct void init(BorderPane parent) { Label l = new Label(); // if you opted to NOT add the MyString() method r.register(l::setText, (m) -> m.MyString); // if you opted to have a MyString() method r.register(l::setText, r::MyString); }
Injection of OSGi-Services
By default the DI container of Eclipse will inject you a service found in the OSGi-Registry but this default comes with a few restrictions who might cause you troubles:
- you can only inject one instance (the one with the highest rank in the OSGi-Service-Registry)
- you won't get a new instance reinjected if a new service instance with a higher ranking is registered on the OSGi-Service-Registry
To fix both of those problems e(fx)clipse provides a new annotation <code>@Service</code> who fixes both of your problems.
import org.eclipse.fx.core.di.Service public class MyView { @Inject @Service private MyOSGiService instance; // inject the highest service and reinject a new higher ranked one is available @Inject @Service private List<MyOSGiService> allServiceInstances; // all instances available and reinject when services are added/removed }
FXML
FXML in OSGi
Loading FXML-Files in OSGi is a bit harder than doing it in a standard java application and one can not use the static <code>FXMLLoader.load()</code> so we provide an extra class named <code>org.eclipse.fx.osgi.utilOSGiFXMLLoader</code>
public class MyView { @PostConstruct public void init(BorderPane p) { Node n = OSGiFXMLLoader.load(getClass(), "myView.fxml", null, null); } }
DI in FXML controller
Eclipse DI
If you are running in OSGi and with Eclipse DI (e.g. when you are writing an Eclipse 4 Application) you can make use of <code>org.eclipse.fx.ui.di.InjectingFXMLLoader</code>.
public class MyView { @PostConstruct public void initUI(BorderPane p, IEclipseContext context) { InjectingFXMLLoader<Node> iFXMLLoader = InjectingFXMLLoader.create( context, getClass(), "myView.fxml" ); Node n = iFXMLLoader.load(); // ... } }
The above code is perfectly ok although you can get rid of the direct <code>IEclipseContext</code> dependency by using the @FXMLLoader annotation.
Google Guice
If you are not running on OSGi and Eclipse DI but develop a standard java application which uses Google Guice as the DI container you can make use of <code>org.eclipse.fx.core.guice.InjectingFXMLLoader</code>
public class MyGuiceComponent { public void init(Injector injector) { Node n = InjectingFXMLLoader.loadFXML(injector,getClass().getResource("myui.fxml")); // ... } }
Adapter System
The <code>@ContextValue</code> support introduce above makes use of the adapter system provided by e(fx)clipse core runtime bundle (<code>org.eclipse.fx.core</code>) which constits of the 3 main interfaces:
- <code>Adaptable</code>
- <code>AdapterService</code>
- <code>AdapterProvider</code>
Usage
The simplest usage is if the source-object implements the <code>Adaptable</code> interface
public class Sample { private void sellProduct(Person person) { Customer customer = person.adapt(Customer.class); // ... } }
If the source-object itself does not implement the <code>Adaptable</code> interface or you are the one who has to implement a class which implements <code>Adaptable</code> you have to use the <code>AdapterService</code> whicn is provided through the OSGi-Service-Registry if the object is managed by Eclipse DI it will look like this:
public class Sample { @Inject AdapterService adapterService; private void sellProduct(Person person) { Customer customer = adapterService.adapt(person,Customer.class); // ... } }
Otherwise you need to query the OSGi-Service-Registry to get access to the <code>AdapterService</code>.
Extending
To enhance the adapter system it is possible to register <code>AdapterProvider</code> as OSGi-Services. All you need to do is to implement the <code>AdapterProvider</code> likes this:
public class CustomerAdapterProvider implements AdapterProvider<Person, Customer> { @Override public Class<Person> getSourceType() { return Person.class; } @Override public Class<Customer> getTargetType() { return Customer.class; } @Override public boolean canAdapt(Person sourceObject, Class<Customer> targetType) { return true; } @Override public Customer adapt(final Person sourceObject, Class<Customer> targetType, ValueAccess... valueAccess) { // ... } }
and register it e.g. through DS with
<?xml version="1.0" encoding="UTF-8"?> <scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="my.adapter.sample.customer"> <implementation class="my.adapter.sample.CustomerAdapterProvider"/> <service> <provide interface="org.eclipse.fx.core.adapter.AdapterProvider"/> </service> </scr:component>
e4
Position a TrimBar element to the far right
Sometimes it is necessary to position an element in the TrimBar to the far right or bottom. This can be implemented by adding a spacer element to the trimbar
<trimBars elementId="my.sample.trim.bottom" side="Bottom"> <children xsi:type="menu:ToolControl" > <tags>fillspace</tags> </children> <children xsi:type="menu:ToolControl" elementId="my.sample.trim.progress" contributionURI="bundleclass://my.bundle/my.bundle.ProgressControl"/> </trimBars>
Restart Service
Sometimes it is necessary to restart your application with a cleared persisted state. This could be the case when you want to reset the user interface to its default or after an update to your <code>application.e4xmi</code> or a <code>fragment.e4xmi</code>.
To use the <code>RestartService</code>, you can inject it into your handler. To clean the persisted state on the next start of the application pass <code>true</code> to the <code>restart</code> method.
public class CleanRestartHandler { @Execute public void execute(RestartService restartService) { restartService.restart(true); } }
Extended @PostContextCreate Features
The life cycle hook <code>@PostContextCreate</code> is a good place to perform initial tasks, like making your user supply login credentials and setting up a connection. If this fails, there is no need to continue starting the application. With e(fx)clipse it is possible to return a <code>Boolean</code> to control whether to continue or not.
public class ApplicationLifecycle { @PostContextCreate Boolean connect() { if (connectToServer()) { return true; } return false; } private boolean connectToServer() { ... } }
Another scenario is that you are performing an automatic application update and you want to restart the application right away. For these and similar situations we have provided another extension to the <code>@PostContextCreate</code> API. With e(fx)clipse it is also possible to return an instance of the enum <code>LifecycleRV</code> from <code>@PostContextCreate</code> to tell the framework what to do next. You have the following options:
- LifecycleRV.CONTINUE - Continue starting the application
- LifecycleRV.SHUTDOWN - Shutdown the application
- LifecycleRV.RESTART - Restart the application
- LifecycleRV.RESTART_CLEAR_STATE - Restart the application with a cleared persisted state
public class ApplicationLifecycle { @PostContextCreate LifecycleRV showStartUp(UISynchronize sync) { BlockCondition<LifecycleRV> c = new BlockCondition<>(); Stage s = new Stage(); VBox box = new VBox(); { Button b = new Button("Continue"); b.setMaxWidth(Double.MAX_VALUE); b.setOnAction((e) -> c.release(LifecycleRV.CONTINUE)); box.getChildren().add(b); } { Button b = new Button("Shutdown"); b.setMaxWidth(Double.MAX_VALUE); b.setOnAction((e) -> c.release(LifecycleRV.SHUTDOWN)); box.getChildren().add(b); } { Button b = new Button("Restart"); b.setMaxWidth(Double.MAX_VALUE); b.setOnAction((e) -> c.release(LifecycleRV.RESTART)); box.getChildren().add(b); } { Button b = new Button("Restart with cleared State"); b.setMaxWidth(Double.MAX_VALUE); b.setOnAction((e) -> c.release(LifecycleRV.RESTART_CLEAR_STATE)); box.getChildren().add(b); } s.setScene(new Scene(box,200,200)); s.show(); LifecycleRV rv = sync.block(c); // Block until release s.close(); return rv; } }
Keybinding vs Native implementation
Images in e4xmi
Theme specific icons
=== FXML icons ===