2010-03-22

Preparing for big oil accidents - and how to avoid them

EclipseCon have just started and we - Frode Meling of Marintek in Norway and I - are preparing for our lightening talk "Modeling the World - If you want to move an oil rig, then model it first" that will take place Tuesday afternoon 16:45 in Lafayette.

Having just a lightening talk for the subject has turned out to be the big challenge, so we have looked at the old proverb "A picture tells a 1000 words", and found a very good video to illustrate the idea of the application in question.



You really don't want this is happen - it builds a compelling business case for the application. (I'm not saying this particular accident could have been avoided with SIMA, but...)

2010-02-14

Using Adapters in Handlers to control functionality

In my last blog post about the use of Dependency injection in e4, I used adapters in handlers with functional interfaces to control the enablement of functionality in an application. By request, here is an extended version of that with some additional explanations. [Incidentally, this was proposed as a talk for EclipseCon ´10, but unfortunately got rejected...]

Note that this is only for users in larger applications - if you have a command with a single handler and simple expressions, then this is not needed at all...

Why?

When you implement a larger Eclipse RCP based application, you can run into a number of problems with handlers and menus as you add more and more objects to the domain model of your application model and more and more commands for the objects in the UI.

In order to control the visibility of menu items in menus - most notable the popup menu - you have the visibleWhen construct for the commands in the menu. The used expression often is an or-ed together version of all the activeWhen expressions for the handlers for the command in question. E.g. if you have a command C with two handlers h1 and h2, each with the activeWhen expression aw1 and aw2, then you often want the command to use the visibleWhen expression (or aw1 aw2).

But... as new objects can be added by new plug-ins and the number of commands are enlarged for the existing objects over time, how do you maintain the visibleWhen expression?

Also, very often, you have a lot of common implementation for a specific command in the different handlers for the command - this is not so surprising as the command is an abstract description of some functionality - e.g. "cut", "print", "connect", etc - and some common code must be expected no matter which object that is operated on. E.g. consider the "print" command: a lot of the code for selection of printer and print options will be common no matter which object is printed.

Finally, very often, you really don't want to introduce all the different UI functionality in the domain model itself - maybe for principle reasons or maybe because you don't "own" the code of the model and cannot modify it. You might therefore want to use adapters to handle the functionality in the cases where you cannot change model and direct methods where you can change the model.

For these different reasons I often use a common design pattern in my applications that incorporate functional interfaces for the different commands, adapters for the implementations and some very simple handlers on top - and not least some very easy-to-maintain menu and handler expressions.

In the following, I have used a very simple RCP application as the example with just a single view that shows a table with a number of objects. The objects are Contacts - with name and address -, Customers - extends Contact with a segment - and Segment - with just a segment. [Yes, we could have used a set of model interfaces in this example as well, as we would if we had just used EMF for the model, but in many domain models, that is just not possible...] The table have a popup menu with just a single command "Show Segment" that should be shown for all Customers and Segments, but not for the Contacts. The command must show the segment of the selected object if relevant.

The complete test application can be found here.

How...

First, I use a functional interface for each of the domain model commands in the application. These interfaces have a number of methods used by the command handler to execute the wanted operation. Often this is just a single method, but there can be multiple methods for more complex scenarios.

In this case, the functional interface could be as follows:

public interface IDoShowSegment {
  void doShowSegment(Shell shell);
}

The doShowSegment method could also have been getSegmentName...

In my example, the Customer class implements the interface directly, whereas the Segment class does not, but have an adapter factory instead. The relevant part of the Command class looks as follows:

public class Customer extends Contact implements IDoShowSegment {
  // ...

  @Override
  public void doShowSegment(Shell shell) {
    MessageDialog.openInformation(shell, "The customer segment is...", getSegment());
  }
}

And the relevant part of the adapter factory looks as follows:

public class SegmentAdapterFactory implements IAdapterFactory {
  @Override
  public Object getAdapter(Object adaptableObject, Class adapterType) {
    if (!(adaptableObject instanceof Segment)) {
      return null;
    }
    final Segment s = (Segment) adaptableObject;
    if (adapterType == IDoShowSegment.class) {
      return new IDoShowSegment() {
        @Override
        public void doShowSegment(Shell shell) {
          MessageDialog.openInformation(shell, "The segment is...", s.getSegment());
        }
      };
    }
    return null;
  }

  // ...
}

The factory is installed using the adapters extension point

<extension point="org.eclipse.core.runtime.adapters">
  <factory
      adaptableType="com.rcpcompany.ex.adapterhandlers.model.Segment"
      class="com.rcpcompany.ex.adapterhandlers.adapters.SegmentAdapterFactory">
    <adapter type="com.rcpcompany.ex.adapterhandlers.functionality.IDoShowSegment" />
  </factory>
</extension>

[The used functional interface isn't perfect, as it forces the adapter factory to construct a new object for each call to the getAdapter method. It can be helped by changing the method to doShowSegment(Object,Segment), but... for the sake of simplicity...]

To invoke the "Show Segment" functionality for a specify object, we when have to do the following:

final IDoShowSegment showSegment = (IDoShowSegment)Platform.getAdapterManager().getAdapter(element, IDoShowSegment.class);
if (showSegment != null) {
  final Shell shell = ...;
  showSegment.doShowSegment(shell);
}

Note that we here just ignore the case where the object cannot be adapted to our functional interface.... Also note that the getAdapter method of the adapter manager automatically checks if 1) the object directly implements the interface, 2) the object implements the IAdaptable interface - and then uses this, or 3) if an adapter factory is installed for the interface and object class.

In the context of the handler, this is as follows - with the obvious declarations for the handler.

public class ShowSegmentHandler extends AbstractHandler implements IHandler {
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    final ISelection selection = HandlerUtil.getCurrentSelectionChecked(event);
    if (!(selection instanceof IStructuredSelection)) {
      return null;
    }
    final IStructuredSelection ss = (IStructuredSelection) selection;
    final Object element = ss.getFirstElement();
    final IDoShowSegment showSegment = (IDoShowSegment) Platform.getAdapterManager().getAdapter(element,
        IDoShowSegment.class);
    if (showSegment == null) {
      return null;
    }
    final Shell shell = HandlerUtil.getActiveShellChecked(event);
    showSegment.doShowSegment(shell);
    return null;
  }
}

With the above code and a menus extension, the "Show Segment" command is shown as enabled in the popup menu for all items - even the Contact objects.

To make the handler only active when the selection is an object that supports the functional interface, use the following handlers declaration:

<extension point="org.eclipse.ui.handlers">
  <handler
        class="com.rcpcompany.ex.adapterhandlers.handlers.ShowSegmentHandler"
        commandId="com.rcpcompany.ex.adapterhandlers.commands.ShowSegment">
    <activeWhen>
      <iterate ifEmpty="false" operator="and">
        <adapt type="com.rcpcompany.ex.adapterhandlers.functionality.IDoShowSegment" />
      </iterate>
    </activeWhen>
  </handler>
</extension>

With this declaration the command is only enabled in the popup menu when relevant, though it is still shown for the Contact objects.

To show the command only when an active handler exists, use the following visibleWhen expression:

<extension point="org.eclipse.ui.menus">
  <menuContribution locationURI="popup:org.eclipse.ui.popup.any">
    <command commandId="com.rcpcompany.ex.adapterhandlers.commands.ShowSegment" style="push">
      <visibleWhen checkEnabled="false">
        <iterate ifEmpty="false" operator="and">
          <adapt type="com.rcpcompany.ex.adapterhandlers.functionality.IDoShowSegment" />
        </iterate>
      </visibleWhen>
    </command>
  </menuContribution>
</extension>

Note that this only use the activeWhen expression to control the visibility of the command in the menu. This is slightly different from the visibleWhen with checkEnabled=true, which is based on the enabledWhen expression.

The End Result

The end result is that if you want to implement the command for a new or existing object you must either extend the object with the functional interface or add an adapter for the object class to the functional interface - I usually prefer the later.

To find the objects that supports the command, just look for implementations of the interface - which by the way I normally name "IDo<command-id>" - here IDoShowSegment.

Useful? In larger applications, yes - in small applications, this is probably like shooting flies with canons. Is it worth the added code and the redirection in the handler? That can only be decided by you...

2010-02-12

Dependency Injection in e4 - just why do we want to do that?

Lately, I have been giving a number of presentations of Eclipse e4. The focus has been on the changes that we will see when we program for e4 rather than 3.x.

With all the presentations, there have been a very lively discussion on the pros and cons of the new technologies in e4, but one subject in particular have been discussed: the use of Dependency Injection (DI) and what it will mean for productivity, testing and the tooling in Eclipse we all have grown so used to.

The following examples are taken from the excellent e4 contact manager by Kai Tödter that shows off some of the interesting features of e4 including theming and DI. The manager is very e4'ish and use the e4 features as these are probably meant to be used - with other words, I don't fault Kai for the examples or the problems I find in the examples.

At first glance the use of DI seems to give some very understandable code and it has the potential to do away with some of the listener code that we see in many places in 3.x code.

E.g. to follow the current selection in a view - here just expecting a single selected object - you would do something like the following in 3.x (forget about removing the listener again...):

public class DetailsView extends ViewPart {
  @Override
  public void createPartControl(Composite parent) {
    // ...

    final ISelectionService ss = getSite().getWorkbenchWindow().getSelectionService();
    ss.addPostSelectionListener(myListener);
    myListener.selectionChanged(null, ss.getSelection());
  }

  protected void setSelection(Contact contact) {
    // ... do something with the selection
  }

  private final ISelectionListener myListener = new ISelectionListener() {
    @Override
    public void selectionChanged(IWorkbenchPart part, ISelection selection) {
      if (!(selection instanceof IStructuredSelection)) {
        setSelection(null);
        return;
      }

      final IStructuredSelection ss = (IStructuredSelection) selection;
      if (ss.isEmpty() || !(ss.getFirstElement() instanceof Contact)) {
        setSelection(null);
        return;
      }
      setSelection((Contact) ss.getFirstElement());
    }
  };

  // ...
}

whereas, you will just do something like this in e4:

public class DetailsView {
  @Inject
  public void setSelection(@Optional @Named(IServiceConstants.SELECTION) Contact contact) {
    // ... do something with the selection
    
  }

  // ...
}

So far, so good. A lot less code compared with the 3.x version and the intension is quite clear once you know the injection is persistent, so changes in the context is automatically propagated to the view.

The main difference between the two versions lies in the way that you find and access services: in 3.x you basically have a Java method chain - here getSite().getWorkbenchWindow().getSelectionService() - where the e4 version uses a magic class or string - here @Optional @Named(IServiceConstants.SELECTION). The general Java tooling helps us access the services in 3.x, but what type of tooling will help us in e4? And how will we get warned about accidental changed in the e4 string?

A much more problematic example - as far as I am concerned - can be found in the SaveHandler of the contact manager. This handler is used to save the current contact in the details view by delegating the save functionality to the doSave method of the view (Again, I have cut away some irrelevant stuff):

public class SaveHandler {
  public void execute(IEclipseContext context, @Optional IStylingEngine engine,
      @Named(IServiceConstants.ACTIVE_SHELL) Shell shell,
      @Named(IServiceConstants.ACTIVE_PART) final MContribution contribution) throws InvocationTargetException,
      InterruptedException {
    final IEclipseContext pmContext = EclipseContextFactory.create(context, null);

    final ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
    dialog.open();

    dialog.run(true, true, new IRunnableWithProgress() {
      public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
        pmContext.set(IProgressMonitor.class.getName(), monitor);
        Object clientObject = contribution.getObject();
        ContextInjectionFactory.invoke(clientObject, "doSave", pmContext, null);
      }
    });
    // ...
  }
}

Basically the handler creates a new context for the operation, opens a progress dialog, installs the progress monitor in the context, and then delegates to the doSave method with the new context.

The problem is found in the inner run methods: the name of the method of the view that is used to do the save operation itself is hard-coded as a string. How is this ever going to work with the Java tooling? How can we get quick assists or refactoring to work here? And how will we maintain this?

There are also some other problems with regards to testability. E.g. if a new doSave is ever created in the view, this will not provoke either a compile-time or a run-time error, but instead just execute both methods.

In the 3.x version, I would let the views that supports the doSave method implement a common Java interface - e.g. IDoSaveable and then test for this in the handler. An example of how this can be done is shown below:

The interface:

public interface IDoSaveable {
  void doSave(IProgressMonitor monitor);
}

The view:

public class DetailsView extends ViewPart implements IDoSaveable {
  @Override
  public void createPartControl(Composite parent) {
    // ...
  }

  @Override
  public void doSave(IProgressMonitor monitor) {
    // ... do save
  }
}

The handler - note that this version uses adaption, but you could use instanceof instead:

public class SaveHandler extends AbstractHandler {
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    final IWorkbenchPart part = HandlerUtil.getActivePartChecked(event);
    final IDoSaveable saveablePart = (IDoSaveable) Platform.getAdapterManager().getAdapter(part, IDoSaveable.class);
    if (saveablePart != null) {
      final Shell shell = HandlerUtil.getActiveShellChecked(event);
      final ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
      dialog.open();

      dialog.run(true, true, new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
          saveablePart.doSave(monitor);
        }
      });
    }
    return null;
  }
}

Personally I see many advantages with this version:
  • It is actually more readable, as it has very little magic - aprt from the use of the adaption
  • It is easy to find all the views that supports the save operation.
  • Everything is based on the Java tooling and we have a no magic constants of any sorts
  • Refactoring works!
  • The activeWhen expression for the handler can simply test whether the activePart adapts to IDoSaveaeble.
What do you think? Is the new magic DI code worth the lost functionality in the Java tooling? Can we invent some new tooling to make up for the lost functionality? 

    Javagruppen - the Java user group in Denmark - yearly conference

    Javagruppen - the Java user group in Denmark - have had very interesting two-day conference at Hindsgavl Slot on Fyn.

    On the first day, I first talked about Eclipse e4 and what you should expect compared with the current 3.x versions. The presentation was well received and there was a very lively discussion about the pros and cons of the different changes that are made in e4. I almost didn't have the time for the look at the code... You can find the slides here.

    I then heard Heiko Seeberger talk about Scale and Lift. Scala is cool - very cool - for an old Lisp developer like me. If only I could find the time to integrate this with PDE, then it would be extremely cool. Heiko? Lift? I don't know... I'm not into web design so to me there are just too much magic involved in this...

    Then Agata Przybyszewska talked about RSpec and Cucumber for UI and functional testing. I'm not sure I understood all, but then I have never been looking into Ruby or RSpec.

    Next day, Jeppe Cramon first talked about how they have generated code from models in a number of projects using TigetMDSD. Very smart and definitely something that scales way better than JET from EMF.

    Last I heard Tommy Dejbjerg Pedersen talk about Google Android & Wave. Rather interesting - now I see a reason to get involved in Wave. And Tommy gave me not reasons to regret my

    I look forward to next year. If just it wasn't cold outside...

    2010-01-22

    Preparing for Exams...


    I have previously talked about my position as extern lecturer at the IT University in Copenhagen teaching model driven development and domain specific languages (course description and the course blog).

    Now it is pay back time... The next three days, we will have 35 student up for oral exams based on a written report around the modernization of a fictious bike shop "Noware Bike Shop".

    As part of the report, the student had to
    • construct an EMF model (mandatory)
    • a number of OCL constraints (mandatory)
    • design a (E)BNF grammar
    • create an XText editor
    • create an GMF editor
    • do a model-to-model transformation using QVT/O
    • do a model-to-text transformation using Xpand
    ... and talk about some of the theoretical properties of the MDD/DSL area - it is a university study after all. The first two assignments have been mandatory and the students then had to choose 3 additional assignments.

    Based on the turned-in reports, we have noticed a clear trend in the optional assignments they opted to solve:

    • EBNF: 13
    • Xtext: 13
    • GMF: 11
    • Xpand: 6
    • QVT: 0
    Some of these numbers are quite obvious - e.g. QVT/O is a rather difficult subject - but other numbers have surprised us a little - e.g. the number of people that opted for GMF.

    From the course evaluation, we know that many of the student have considered the Eclipse platform a little too fragile or unstable for the work. A common scenario has been that two or more student had the same installation and workspace... but yet only oner of them could get the tools to work properly.

    Will they want Eclipse and/or Modeling in their first real job? We don't know yet, but we do hope that we have showed them all how useful modeling can be in the "real world"... and that Eclipse is a good tool for the job - even it is a little fragile...

    2009-12-15

    Eclipse Democamp in Copenhagen - Done

    Last Thursday we had our edition of the Eclipse Democamp in Copenhagen. With 70+ participants it can only be considered a big success - given the COP15 conference going on right now in Copenhagen, it is not always easy to get around in Copenhagen these days.

    We were very lucky that IBM had both room and food to spare for the event - thanks for that.

    You can find the slides from the demo camp on eclipse.dk as I get them from the presenters.

    I started the camp with a presentation of the ideas behind e4 with focus on the differences you will see as a developer in the future. We will be talking about this a lot more in the future.

    Jesper Steen Møller talked about the state-of-the-art of the XPath2, XML Catalog and XSLT tooling in the WTP project. Among other things, Jesper showed a very cool debug session of XSLT.

    Bent Agervold Jensen - from ReportSoft - showed some very pretty graphics based on BIRT. I was rather impressed. I will have to look at BIRT again in some near future. Bent showed two real-life examples from the web based om some work they had done for customers - quite impressive.

    Mikkel Heisterberg - from Intravision - showed how Lotus Notes in an extension of Eclipse and illustrated how your "plain" Eclipse plug-ins can be used in Lotus Notes with a little extra work. He rightly stated that many of the things we will see in e4, already is present in Lotus Expeditor, but with e4 we will hopefully get something everybody will use...

    Jakob Lyng Petersen - from Maconomy - showed some of the work they have done with a commercial application based on Eclipse RCP. Among the more interesting things - for me at least - was their good looking presentation API and the way they have implemented searching just about everywhere. I bet that some of the new e4 technologies would have helped them a loot in their implementation...

    Ekkart Kindler - from DTU - showed how the modeling framework in Eclipse can be used together with Petri nets.

    Steen Brahe - from Danske Bank - talked about how he has used GMF in his bank. He first outlined the different models that makes up the GMF framework and then showed how they had enhanced their UML editor via a new model that described some of the constraints they have in the domain models. Not that I understood it all, but it was quite obvious that they can save a lot of work in their UML modeling this way.

    Jan Schoubo - from Oracle - talked about the LEJLN platform - Linux-Eclipse-Java-LEGO NXT - for absolute beginners. This was by far the most fun presentation where Jan showed how you can program LEGO NXT via Eclipse with a impressive demo where he got a LEGO to to find the colors of small LEGO bricks and showed these on the attached computer.

    The next eclipse.dk event will be our general assembly in January.

    2009-11-23

    Eclipse Democamp in Copenhagen

    eclipse.dk will have our first ever DemoCamp in Copenhagen on 10. December.

    IBM (at Lyngbyvej 2, 2100 KBH Ø by the Chokolade Frog) has provided the space for the event so we still have room for more people.

    The current presentations for the DemoCamp are very diverse:
    1. Tonny Madsen, The RCP Company, What exactly is the new e4
    2. Jesper Steen Møller, XPath2, XML Catalog and XSLT tooling
    3. Bent Agervold Jensen, ReportSoft, BIRT
    4. Mikkel Heisterberg, Intravision, Signed plugins and how these works end-to-end in Lotus Notes
    5. Jakob Lyng Petersen, Maconomy, Building a Generic Client for Business Professionals using Eclipse RCP
    6. Ekkart Kindler, DTU, Model-based Software Engineering with the Eclipse Modeling Framework
    7. Steen Brahe, Danske Bank, Use of the Graphical Modeling Framework in Danske Bank
    8. Jan Schoubo, LEJLN platformen - Linux-Eclipse-Java-LEGO NXT - For absolute beginners 
    If you want to participate, update the wiki page at eclipse.org or mail me on formand@eclipse.dk.
      And yes, we do have space for one or two presentations more...

      2009-11-02

      Learning more about Eclipse plug-in development...


      As part of the Eclipse Foundation Training series, there are scheduled 5 classes on "Advanced Eclipse RCP".

      This is the perfect class for people, who have developed Eclipse plug-ins for the last year or so and now wants to know more about some of the more advanced subjects in Eclipse plug-in development.

      The title of the classes is "Advanced RCP Eclipse", but with the exception of one subject, all the subjects of the class are just as relevant if you're developing Eclipse plug-ins for the IDE.


      Amoung the subjects we will teach in the classes are:
      • Wizards - which is basically here because we don't have time for this subject during "Development in Eclipse RCP".
      • Long-Running operations and Jobs and how to make the interaction between these and the UI as painless as possible.
      • How to use Eclipse Adapters. While the Adapter framework arguably is one of the more difficult to understand and use properly, the is also a framework that will solve many of the problems you might face is larger non-trivial applications especially when used in conjunction with the menus extension point and handlers.
      • The Data Binding framework and how to use this to cut down on the boilerplate code in the application.
      • How to handle virtual trees and tables when either the amount of data is large or the retrieval time is long for items in the tree or table.
      • How to declare and implement your own extension points. Not that this is especially difficult, but there are a number of god design patterns around this that can help reduce the code involved and also make your application react properly when plug-ins are either added or removed from the running aplication.
      • How to do head less builds using PDEBuild, which probably is not of the most troublesome subjects in Eclipse. One day it works, then next it don't...
      You can see the complete list of subjects in these classes and where to attend of the classes on the training page.

      Although the page on the training says "Prerequisites: Solid Java experience, experience with Eclipse SDK as a Java development environment and notions of Eclipse RCP", I know from past experience that mere notions will make for very hard three days. In the classes we assume you know about commands, views, perspectives, etc - basically the subjects from the "Development in Eclipse RCP".

      If you have been developing Eclipse plug-ins for some time, this just might be the next class for you...