Abstract/Requirements Definition

I'm trying to implement a fairly simple address book application on top of RCP using frameworks provided by Eclipse in 3.3. There's also focus on how to structure and design an RCP to be as extensible and as flexible as possible, including theming, internationalization, datastorage independency, ... .

This article is going to introduce you to some basic concepts but it will not provide a full featured introduction to every thing EMF, OSGi and RCP are providing. E.g. this example will not implement dynamic contributions who can get loaded/unloaded at runtime, it will not use the advanced EditingDomain and Undo/Redo features provide by EMF.

Since 3.4 there also a provisional EMF-Databinding intetgration available still this article is based on the offically available plugins nonetheless people having finished this tutorial should not have a problem to write applications with the EMF-Databinding plug-ins.

Application Design

Plugin-Design

At the beginning of every project is the package design or in RCP/OSGI Environment this breaks down to the design of the various plugins and their responsibilities. One of most important things when it comes to plugin design is to split all your plugins into UI and non-UI (with the business logic) parts. This makes automated testing of the business logic using JUnit tests easier.

at.bestsolution.addressbook

The main RCP-Application

at.bestsolution.addressbook.ui

This plugin provides the UI bits (ViewPart, ...) for the addressbook application.

at.bestsolution.addressbook.ui.theme

This plugin addresses the themeability of the application by providing a pluggable theme-API. It will by default provide a standard theme.

at.bestsolution.addressbook.core

This plugin provides the none GUI bits for the application like Command-Definitions, handlers, ...

at.bestsolution.addressbook.core.model

This plugin provides the model implementation created using EMF

at.bestsolution.addressbook.core.datasource

This plugin will provide the API to provide pluggable datasources

at.bestsolution.addressbook.core.datasource.xmi

This plugin provides a datasource implementation on top of XMI (directly supported by EMF)

at.bestsolution.addressbook.core.datasource.iBatis

This plugin provides a datasource implementation on top of iBatis

Plugin Overview

Domain Model

The domain model is fairly simple and can be represented by 2 classes as shown in the diagram below. The only interesting thing is that there's a bidirectional relationship between Person(Attribute: primaryAddress) and Address(Attribute: person).

Implementing at.bestsolution.addressbook.core.model

Create an EMF-Project

Open the "New Project Wizard"

Select Eclipse Modeling Framework

Name the project "at.bestsolution.addressbook.core.model"

The resulting workspace looks like this

Create the Ecore-Model

Create the Ecore file

Select Example EMF Model Creation Wizards > Ecore Model

Name the model "addressbook.ecore"

Open the Properties-View (Window > Show View > Others ...)

Select the root node currently shown in the editor as null

Editing the properties in the property view

Create the Classes and Attributes

Now we have to add our Domain-Objects Person and Address to the Ecore-Model:

Right click on the addressbook-package you have created above and select "New Child > EClass"

Set the following properties (in the Properties View)Name: Person

Right click the Person and select "New Child > EAttribute"

Set the following properties (in the Properties View)Name: surnameEType: EString

Right click the Person and select "New Child > EAttribute"

Set the following properties (in the Properties View)Name: givennameEType: EString

Right click the Person and select "New Child > EAttribute"

Set the following properties (in the Properties View)Name: birthdayEType: EDate

Right click on the addressbook-package you have created above and select "New Child > EClass"

Set the following properties (in the Properties View)Name: Address

Right click the Address and select "New Child > EAttribute"

Set the following properties (in the Properties View)Name: streetEType: EString

Right click the Address and select "New Child > EAttribute"

Set the following properties (in the Properties View)Name: zipEType: EString

Right click the Address and select "New Child > EAttribute"

Set the following properties (in the Properties View)Name: cityEType: EString

Right click the Address and select "New Child > EAttribute"

Set the following properties (in the Properties View)Name: countryEType: EString

You'll notice that the types used for the attributes are not the standard classes provided by the JDK but wrappers defined by EMF. EMF provides wrappers for the most import JDK classes.

After having done this your model should look like the following:

EMF holds META-Informations about your model and that's why all classes part of an Ecore-model have to be known to EMF. Those META-Informations are used by EMF to do fancy things but can also be of use for you when you want to get informations about an your model (or the model of someone different).

There are different ways to get EMF to recognize classes:

You create a new EClass in your model

You define a new EData Type to wrap an existing class e.g. provided by the JDK

EMF in detail:

EClass: This represents a Class in EMF terminology TODO more information about EClass

EAttribute: This represents an Attribute in EMF terminology TODO more information about EAttribute You'll notice that the types used for the attributes are not the standard classes provided by the JDK but wrappers defined by EMF. EMF provides wrappers for the most import JDK classes and want to use another classes coming from the JDK you'll have to add an EData Type to your Ecore-model. We'll see this later on.

Model the (bidirectional) relation ship between Person and Address

Next thing we have to model is the bidirectional relation between Person and Address like we defined it in our UML-Class Diagramm. In EMF such a relation can be expressed as an EReference in conjunction with an EOpposite:

Right click the Person and select "New Child > EReference"

Set the following properties (in the Properties View)Name: primaryAddressEType: AddressContainment: true

Right click the Address and select "New Child > EReference"

Set the following properties (in the Properties View)Name: personEType: PersonEOpposite: primaryAddressTransient: true

The Ecore model should look like this now:

EMF in detail:

EReference: TODO explain EReference

Containment: TODO explain Containment

EOpposite: TODO explain EOpposite

Transient: Marking an attribute transient means that it is not persisted in the (e.g. in XMI). There are multiple reasons why an attribute might be marked transient. Here we mark the attribute transient because the person attribute is part of containment and the person-instance referenced here is already persisted (It is the container the Address-Instance is persisted into). Another reason could be that the intance value of the attribute is not serializable e.g. if you inherit from an already existing DataType you only wrap in EMF (see below for an example of this reason)

Model PropertyChangeSupport for Databinding

At this point we have implemented our original Domain-Model in Ecore but we are not finished because when we are working with JFace' Databinding Framework that ships with 3.3 we need to follow the JavaBean specification which means our domain objects have to implement java.bean.PropertyChangeSupport.
The best way to model this is that all our Domain-Model-Objects inherit from a super-class named BaseObject.
Because there are no wrapper for the Classes and Interfaces needed to implement PropertyChangeSupport and friends we need to create them our own by defining "EData Types":

Right click on the addressbook-package you have created above and select "New Child > EData Type"

Set the following properties (in the Properties View)Name: PropertyChangeSupportInstance Class Name: java.beans.PropertyChangeSupportSerializable: false

Right click on the addressbook-package you have created above and select „New Child > EData Type“

Set the following properties (in the Properties View)Name: PropertyChangeListenerInstance Class Name: java.beans.PropertyChangeListenerSerializable: false

Right click on the addressbook-package you have created above and select „New Child > EData Type“

Set the following properties (in the Properties View)Name: PropertyChangeEventInstance Class Name: java.beans.PropertyChangeEventSerializable: false

Now we are able to create our BaseObject:

Right click on the addressbook-package you have created above and select "New Child > EClass"

Set the following properties (in the Properties View)Name: BaseObject

Right click the BaseObject and select „New Child > EAttribute“

Set the following properties (in the Properties View)Name: idEtype: EInt

Right click the BaseObject and select „New Child > EAttribute“

Set the following properties (in the Properties View)Name: propertyChangeSupportEtype: PropertyChangeSupportChangeable: falseTransient: true

Right click the BaseObject and select „New Child > EOperation“

Set the following properties (in the Properties View)Name: addPropertyChangeListener

Right click the addPropertyChangeListener and select „New Child > EParameter“

Set the following properties (in the Properties View)Name: listenerEtype: PropertyChangeListener

Right click the BaseObject and select „New Child > EOperation“

Set the following properties (in the Properties View)Name: removePropertyChangeListener

Right click the removePropertyChangeListener and select „New Child > EParameter“

Set the following properties (in the Properties View)Name: listenerEtype: PropertyChangeListener

Select Person-Class and set the ESuperTypes-Attribute to BaseObject

Select Address-Class and set the ESuperTypes-Attribute to BaseObject

The final Ecore-Diagramm looks like this:

EMF in detail:

EData Type: TODO Explain EData Type

EOperation: TODO Explain EOperation

EParameter: TODO Explain EParameter

Create the Java-Code from the Ecore-model

Instead of writing the Java-Model-Objects our own we use EMFs codegeneration features do this boring task for us. EMF creates Stub-Objects for us which we are going to customize and implement the stub methods.

We have no created a so called genmodel which gives us control over how EMF generates Java-Code. E.g. we could define to use Java5 generics, ... . We will make some minor changes like e.g. the name of the base package and
suppressing of EMF Types in our public API.

Free public API from EMF Types

Select the 1st Addressbook in the Tree

Scroll in "Properties View" to the section "Model Feature Defaults"

Change "Suppress EMF Types" to true

Modify Base package name

Select the 2nd Addressbook in the Tree

Change the "Base Package" to "at.bestsolution.addressbook.core.model"

Time for code generation:

Select the 1st Addressbook in the Ǵenmodel-Editor

Right Click

Select „Generate Model Code“

In the end your project looks like this:

Analyze the generated Java-Code

General

Let's start at the top-level EMF has created 3 packages:

at.bestsolution.addressbook.core.model.addressbook: This package holds an interface for every class defined in our ecore-model. Outside of the model-plugin people should only use these interfaces and not the real implementations. We are going to hide them from the user using OSGI access restrictions

at.bestsolution.addressbook.core.model.addressbook.impl: This package holds the implemenation for all interfaces from the afore mentionned package.

at.bestsolution.addressbook.core.model.addressbook.util: This package holds utility classes useful when working with our model objects

EMF in detail:

You might have noticed that EMF has create 2 more classes we haven't defined in our ecore-Model. Theses classes are useful if you want to use find out informations about your model or interact with it e.g. creating instances of your interfaces.

When EMF generated the code for our project it also modified your MANIFEST.MF (added dependencies, ...). A thing we are going to fix now is that EMF added at.bestsolution.addressbook.core.model.addressbook.impl to the exported packages list. As we discovered before all Classes found in the impl-package have a corresponding Interfaces in at.bestsolution.addressbook.core.model.addressbook. As it is always in software and even more API development you start restrictive and open things if you have a use case. For us this means that we are removing at.bestsolution.addressbook.core.model.addressbook.impl from the list like this:

Open your META-INF/MANIFEST.MF

Navigate to the Runtime-Tab

Remove at.bestsolution.addressbook.core.model.addressbook.impl from the list

Having done this nobody from the outside can access the real implemention classes any more but has to work with their interface representation. Because the real implementations are not visible any more to the consumer of our plugin he/she won't be able to create instances of them directly but instead has to use our AddressbookFactory.

Person p = AddressbookFactory.eINSTANCE.createPerson()

Codepart Analyzation

Let's now take a closer look at the generated Model-Classes:

Fields generated by EMF have an accompanying static default value field

All Elements generated by EMF have an @generated in their JavaDoc. If you customize a method you need to remove this @generated else your modifications are overwritten the next time you generate your model code.

This is a problem because the Databinding-Framework shiped with Eclipse 3.3 can only deal with JavaBeans and not with EMF-Objects (Work is done by the EMF-Group to overcome this limitation in Bug 75625). The translation between the EMFs ChangeNotification-System and the standard PropertyChangeSupport is a task we are going to solve later. A big advantage of EMF generated code is that you can't forget about the notification code like it happened when you handcrafted your model-classes which was boring task.

PersonImpl#setPrimaryAddress(Address): Once more you'll find out that there's more code.

What you might have expected to find is the code in basicSetPrimaryAddress. The reason why setPrimaryAddress holds more code is that we modeled Person#primaryAddress and Address#person as EOpposite in our ecore model. Which means that when ever we set Person#primaryAddressAddress#person has to be synced (and the other way round). Once more you would have done the same your own when you handcrafted model classes in former days but there was a great likelyhood that you made a mistake which was very hard to track down.

Writing JUnit-Test PropertyChangeSupport

Generate the JUnit-Test-Code

Open the .genmodel

Right click on the Addressbook and select "Generate Test Code"

In your workspace you find a new project called at.bestsolution.addressbook.core.model.addressbook.tests

Open "at.bestsolution.addressbook.core.model.addressbook.tests.BaseObjectTest"

As you see we are following the TestDrivenDevelopment idea which means that we are writing the TestCase before we implement the methods so the tests are supposed to fail at the moment. We'll implement the methods in next section.

Implement PropertyChangeSupport

As you have seen above EMF uses a different system for change-tracking and notification of interested parties. Before we can start to think about how to translate form EMF-Notification-System to PropertyChangeSupport we need to find out how the EMF-System works.

As you have seen above whenever you modify an attribute EMF is sending out a notification by calling eNotify(Notification)

You see that that the information passed by EMF holds all necessary informations about the change and to get one of parties who is informed about a change we need to register as a so called org.eclipse.emf.common.notify.Adapter.

We now have enough informations to implement the translation between EMF-Notification and PropertyChangeSupport:

Open BaseObjectImpl

Navigate to the constructor and remove @generated from the JavaDoc. This ensures that when we regenerate the class using EMF our changes are not lost

Create an anonymous instance of org.eclipse.emf.common.notify.Adapter and add it to the adapters of the object

The final result

Chapter Summary

In this chapter we learned step by step how to transform our UML model into real java-code using EMF and its source generating possibilities. We wrote a JUnit-Test to test the bits we implemented our own (from the rest we expect EMF is doing the correct thing e.g. automatic updating of parent-child relationships). EMF has much more to offer than simply creation of code and some of those possibilities we are going to explore late on.

Implementing at.bestsolution.addressbook.core.datasource

This plugin acts as the interface between our application and the datastorage implementations and hides them form the application code. This plugin provides a DatasourceManager who manages all Datasources who are contributed by specialized plugins using the Extension Point mechanism. If you don't want to depend on Eclipse but only on OSGI-Functions you could achieve the same using OSGI-Services (see Article for more informations)

In the above we created a so called "Extension Point" definition which allows others to contribute implementations and extend the functionality of the application. A possibile use case could be to add an implementation for a completely different datastorage system (e.g. one might use an LDAP-Server as the storage system). The advantage of extension points against programmatic contributions is the fact that the contributed bundle is only loaded (in OSGI terminology activated) when a class is accessed and not when the application is started.

Implementing the Java-Bits

The following UML diagram shows you all needed classes.

Initial implementation

class DatasourceException

We create our own specialized exception which wrapping the orginal exception thrown by the datasource. This gives us the possibility to add features later on if we want (e.g. passing an Error-Code, a serverity, ... ).

You'll notice that the above creates the datasource instance lazily this has the advantage that the plugin is only activated on demand and significantly improves startup performance. A general advice: Whenever possible you should load bundles only on demand and not by default.

class DatasourceManager

The job of this class is to manage all datasource implementations contributed and providing access to them.

class Activator

This class is generated automatically by PDE when the plugin is created. It is instantiated the first time a class from this bundle is loaded and afterwards the BundleActivator#start(BundleContext) is called. Currently this class is part of the public API of our plugin but this doesn't make much sense because nobody from the outside should access this class.

Finalizing

Let's create a new package named at.bestsolution.addressbook.core.datasource.internal and move the class there because the internal package is not part of the exported ones nobody from the outside can access this class.

Because ChangeDescription is part of our API all plugins who make use of our Datasource-API need to import the org.eclipse.emf.ecore.change-plugin and to make this more comfortable we can also tell this plugin to reexport this dependency this way all plugins importing this plugin will automatically import org.eclipse.emf.ecore.change.

Implementing JUnit-Tests

Setting up the plugin

As we did before we are writing plain JUnit-Testcases. Another possibility which is build above JUnit would be to use TPTP which is really cool project but has the big shortcoming that it doesn't work on OS-X until they solved this Bug and because we'd like to stay as cross-platform as possible this is not a possibility for us which is a sad thing because TPTP provide so many cool features.

The only important thing is that we add a public static Test suite() method which is needed to run the suite as a "JUnit Plug-in Test".

Running the JUnit-Tests

Running the JUnit-Tests is trickier than a simple JUnit-Test because to take the extension point mechanism we are using to contribute our DummyDatasources the whole TestSuite has to run as an OSGI (or better Equinox) application. Nonetheless it's not fairly though to make this work because PDE provides the possibility to run the Suite in plugin-mode. The only thing is that the TestSuite-class has to have a method named: suite().

Open context menu of DatasourceAllTests in Package Explorer

Run As > JUnit Plug-in Test

Running the suite we'll see all Tests are failing. So the logical next step is to fix the tests step by step.

Implementation of Java-Classes or let's get all tests succeed

DatasourceManager#getInstance()

The manager is implemented as a Singleton so the implementation should be fairly straight forward for you.

DatasourceManager#getDatasourceDescriptors()

Here we see how we get access to the datasources contributed to us using our well defined extension point. In the end we ensure that noone from external can programmatically add a datasources by modifing the returned collection by create an unmodifiable one which is good programming praxis.

Running the TestSuite you should see all tests succeeding else go back and see what is causing the problems.

Chapter Summary

In this chapter we learned how to make our application extensible by the using Eclipse Extension Point mechanism. The PDE-Tools help us to easily create the extension point definition and along the way we also got to know more EMF classes which are of use for us (more in depth info will be provided as we proceed).

In case the code you have is not working you can proceed by fetching it from SVN-Freeze_02.

Implementing at.bestsolution.addressbook.core.datasource.xmi

Create a NONE-UI Project

Create the xmi-plugin

This is fairly the same steps you are already familiar with from the at.bestsolution.addressbook.core.datasource chapter:

Open the "New Project Wizard"

Select the "Plug-in Project"

Name the project: "at.bestsolution.addressbook.core.datasource.xmi"

Uncheck "This plug-in will make contributions to the UI"

Click Finish

Open the MANIFEST.MF

Open Dependencies-Tab

Click "Add ..." in the "Required Plug-ins"-Section

Select "at.bestsolution.addressbook.core.datasource"

Click OK

Click "Properties..."

Select "Reexport this dependency"

Repeat the these steps for: org.eclipse.emf.ecore.xmi and at.bestsolution.addressbook.core.model

Create the xmi-test-plugin

Open the "New Project Wizard"

Select the "Plug-in Project"

Name the project: "at.bestsolution.addressbook.core.datasource.xmi.tests"

Uncheck "This plug-in will make contributions to the UI"

Click Finish

Open the MANIFEST.MF

Open Dependencies-Tab

Click "Add ..." in the "Required Plug-ins"-Section

Select "org.junit" (We are once more NOT using JUnit4)

Click "Add ..." in the "Required Plug-ins"-Section

Select "at.bestsolution.addressbook.core.datasource.xmi"

Fix up the xmi-plugin

Before we proceed with the implementation let's as a first action ensure that nobody can't easily access the classes from our at.bestsolution.addressbook.core.datasource.xmi-plugin.

Create a new package at.bestsolution.addressbook.core.datasource.xmi.internal

Move the Activator to this package

Open the MANIFEST.MF

Open the Runtime-Tab

Click "Add.." in the "Exported Package"-Section

Select "at.bestsolution.addressbook.core.datasource.xmi.internal"

Click OK

Click "Add..." in "Package Visibility"-action

Select "at.bestsolution.addressbook.core.datasource.xmi.tests"

Click OK

OSGi in detail:

We are using a special feature of the OSGi-Framework which allows us to make packages visible only the plugins we control. In our case this is the test-plugin which will have access to all classes of the internal package others won't be able to access them.