Xpand templates on XSDs

The screen definitions of our application are part of our model as well. They need to be exported to XML to be processed by our screen-interpreter at runtime. Our client is based on Eclipse RCP and we allow to apply hooks to certain steps within the interpretation process. This is required to let the developer implement behavior that differs from the standard behavior of the interpreter. Hooks are registered via an extensions using the name of a model element for identification.

The code within a hook references UI elements as it implements UI behavior. To access an element, it’s name has to be used as well, and that is quite error-prone. The name within the model might change but the code still references the old. So we decided to use Xpand to generate descriptors (it is only a list of String constants to be honest) for the modeled UI elements. The developer may use the constant, so the code will fail to compile if the name of the element changes in the model.

Generating these constants is a pretty easy thing as the XSD for the screen model can simply be used as meta-model.

...
<component class="org.eclipse.xtend.typesystem.xsd.XMLReader">
   <modelSlot value="model" />
   <uri value="${screen.model.project}/model/screen.xml" />
   <metaModel id="screenXMLModel">
      <schemaFile value="${screen.profile.project}/model/screen.xsd" />
      <registerPackagesGlobally value="true" />
   </metaModel>
</component>
...

When activating the XSD metamodel within the project preferences in the Eclipse IDE, the Xpand editor recognizes an XSD in the project’s classpath as metamodel and you may start creating the templates.
Pretty easy and very handy!

Executing commands programmatically

Executing commands (e.g. from a SWT listener) is a pretty handy thing. You don’t have to care about, where the handler is registered, you simply execute the command via the ICommandService, the delegation is provided by the framework.


...
ICommandService commandService = (ICommandService)getViewSite().getService(ICommandService.class);
try {
commandService.getCommand("com.foo.the.command").executeWithChecks(new ExecutionEvent());
}
catch (Exception exception) {
logger.error(exception.getMessage(), exception);
}
...

There is just one thing about the snippet above that is bad: The way the ExecutionEvent is created. Using the default constructor results in hard time for a handler, as the HandlerUtil class cannot be used due to the missing context information. A better way is to pass on some parameters to the ExecutionEvent to be created. The most important one is the last parameter, the application context object. It can be obtained via the IEvaluationService.


...
ICommandService commandService = (ICommandService)getViewSite().getService(ICommandService.class);
IEvaluationService evaluationService = (IEvaluationService)getViewSite().getService(IEvaluationService.class);
try {
Command theCommand = commandService.getCommand("com.foo.the.command");
theCommand.executeWithChecks(new ExecutionEvent(theCommand, new HashMap(), control, evaluationService.getCurrentState()));
}
catch (Exception exception) {
logger.error(exception.getMessage(), exception);
}
...

This command invokation can be processed by any handler using the HandlerUtil class.

Tuning Xpand Templates

Our current project is model driven, using MWE, Xpand & Xtend. Right at the beginning, our templates were really fast and the round trip time was fairly acceptable. By now, our model contains quite a lot of elements and a generator run takes far more time than before. So I had a look what can be done to tune our templates a little.
When studying the Xpand docs, I found something interesting: The cached keyword for Xtend functions. A return value of cached functions is stored for the given parameter(s) and this turns out to be very useful. We have a lot of typeSelect() operations to do something on specific model types, for example on all our Services, in both Xpand templates and Xtend functions.
... eRootContainer.eAllContents.typeSelect(Service) ...
This statement results in scanning the whole model for elements of the desired type. Usually you expect the result to be the same each time (at least you should hope). This piece of code is a perfect example for a cached Xtend function that replaces all occurrences of the upper statement.

cached List[Service] services(EObject eRootContainer):
eRootContainer.eAllContents.typeSelect(Service);

So the model is scanned only once, as the eRootContainer is always the same object. This saves a lot of time. If you provide such a function for each type you need, your templates will be processed much faster. I know, caching is a little dangerous, but well dosed it can be quite useful and reduces the required time for a round trip.

Eclipse RCP and language selection

Eclipse RCP Clients are usually shipped with language bundles providing the translations of the application’s labels. Depending on the locale (either the system’s default locale or the locale set with the -nl program argument), the client appears with the labels in the defined language. But what about letting the user choose his language, e.g. in a login dialog or during runtime?
Well, simply modifying the default locale using Locale.setDefault() has no effect as the underlaying workbench has been already configured with the startup language. You actually need to restart the client and reset the default locale. Eclipse provides a special exit code IApplication.EXIT_RELAUNCH in order to relaunch a client and use programmatically defined startup parameters. To do so, simply set the system property eclipse.exitdata with the required startup parameters with System.setProperty(). The prefix of the property’s value should be {eclipse.vm}\n, the rest is to be structured like the common .ini file, that is usually used to set the client’s startup configuration. In order to reset the locale, the property’s value needs to contain the -nl program argument set to the language selected by the user. When exiting the Workbench using the IApplication.EXIT_RELAUNCH exit code, the client will then be relaunched using the configuration defined with the eclipse.exitdata property’s value and appear in the requested language.

Building Source Features with the PDE Build

The PDE Build provides a pretty convenient way of automatically creating a source feature. The additional feature contains all source files and artefacts listed in the containing bundles’ build.properties files for a source build. There are only a few settings necessary.

Assume we have a feature com.foo.feature containing some bundles with binaries only.

First, we need to configure a source feature include for the feature. Simply add a line to the com.foo.feature feature’s feature.xml:
<includes id="com.foo.feature.source" />

The linked feature com.foo.feature.source does not exist yet, it will be created by the PDE Build later on.

To get the PDE Build actually creating the source feature, we have to edit the com.foo.feature features’s build.properties by adding another line to it:
generate.feature@com.foo.feature.source = com.foo.feature

The PDE Build will now build the linked source feature com.foo.feature.source including a bundle containing all sources of all binary bundles included in the com.foo.feature feature. Since Eclipse 3.4, we can tell the PDE Build to create an individual source bundle for each bundle by setting a PDE Build property individualSourceBundles to true.

Fragments vs. Buddy Classloading

Classloading is a serious issue when creating OSGi based applications. As each bundle is bound to it’s own classpath, sometimes the reflection mechanism will not work as expected. So, there are basicly two ways of solving the problem of extending a bundle’s classpath (when using Equinox…), either create a feature or use Buddy Classloading. But which solutions fits best for what problem?

Fragments

A fragment is an OSGi mechanism to allow a dynamic extension of a bundle at runtime. The fragment itself is not a true component as other bundles may not define a dependency on the fragment. It is used for different purposes such as testing, internationalisation or logging configuration. You can add system dependent code or configuration files to a generic implementation. The good thing is, that the extended code has no dependency on the fragment i.e. does not necessarily require the fragment for running (for example testing fragments).

How to
A fragment is structured as a common bundle. It may be created using a wizard (in Eclipse) or by adding a line to the manifest.mf of a common bundle defining the so called fragment host:
Fragment-Host: bundleSymbolic-Name
This advises the runtime to merge the fragment’s content with it’s host at runtime.

What’s good
Fragments are pure OSGi and provide the flexibility of extending a component dynamicly at runtime without breaking the component architecture. Some third party classpath requirements can be solved this way, for example providing a logging configuration.

What’s bad
Some third party classpath requirements cannot be matched using fragments.

Buddy Classloading

Buddy Cassloading is somewhat a hack (in my opinion), as it adds a bundle’s classpath to another’s – you could call it ‘reverse-dependency’. In OSGi terms, this is explicitly not wanted as a bundle should be treated as a component. But since many Java libraries got used to a single classloader environment, they still expect an exclusive access to any class of the application using reflection. So, in some situations, you can’t really avoid using Buddy Classloading in an Equinox environment.

How to
The manifest.mf of the bundle to be extended receives an additional line to define a Buddy Policy:
Eclipse-BuddyPolicy: registered
This defines the bundle to be aware of registered bundles which entend the classpath.

The manifest.mf of the bundle to extend receives two additional lines:
Eclipse-RegisterBuddy: bundleSymbolic-Name
Require-Bundle: bundleSymbolic-Name

This defines the bundle to extend the classpath of the listed bundles. Additionally, the registered Buddy Policy requires the extending bundle to have a dependency on the extended bundle.

What’s good
Buddy Classloading easily enables using common reliable libraries without any problems. Additionally, the extending bundle can still be treated as a ‘normal’ bundle, other bundles may have a dependency on the bundle and use the exported packages as provided.

What’s bad
Buddy Classloading is not ‘the OSGi way’ as it corrupts the idea of having a component based application with clearly separated bundles defining an interface and dependencies. Buddy Classloading is an answer to a technical problem and should not be used for application design.

White Christmas

Unbelievably 3 days before Christmas Eve it is freezing cold outside (we had -11,7 °C) and everything is covered with snow. So there really is a chance for a white Christmas around here, which is pretty special.  I can’t really remember the last time we had snow for Christmas.

Programmatic command contributions

Have you ever faced the task of programmatically adding commands to a given menu? It is not that difficult – when you finally found out ;).
First of all, you need a target menu, whether it is declared or programmatically created does not matter. What you actually need is the menu’s location URI. You may the create an AbstractContributionFactory with the menu’s location URI:

...
AbstractContributionFactory contribFactory = new AbstractContributionFactory ("menu:com.foo.targetmenu?after=targetGroup", null) {
@Override
public void createContributionItems(IServiceLocator locator, IContributionRoot additions) {
// add the contribution using it's source
additions.addContributionItem(createContributionItem(contribSource), null);
}
IMenuService menuService = (IMenuService)getViewSite().getService(IMenuService.class);
menuService.addContributionFactory(locator, contribFactory);
...

The items are added to the IContributionRoot within the factory’s createContributionItems() method. The factory is then registered at the IMenuService and your contributions show up.
For creating an IContributionItem for a given command, you may use the CommandContributionItem class, which takes an CommandContributionItemParameter as constructor parameter. A CommandContributionItemParameter basicly contains all the required data for a command contribution known from the org.eclipse.ui.menus extension point.


private IContributionItem createContributionItem(IServiceLocator locator, Object contribSource) {
CommandContributionItemParameter contributionItemParameter = new CommandContributionItemParameter(locator, null, "com.foo.the.command.id", SWT.PUSH);
// pimp the item using the contribSource
...
return new CommandContributionItem(contributionItemParameter);
}

There you go.

A wicked blog about software architectur, Eclipse and Eclipse RCP