Saturday, March 20, 2010

Quick test: GEF3D and e4 1.0 M4

Yesterday I posted my experiences of getting GEF3D running on e4 0.9. This is only a quick update for e4 1.0 M4. Remy Chi Jian Suen pointed me to e4 1.0 M4, and I followed the instruction on the Wiki page Remy linked to. Unfortunately, I did not succeed installing GMF with e4 1.0 M4 because there were always some unsatisfy dependencies errors. So I wasn't able to reproduce the NPE I described in the blog, and I wasn't able to test the Ecore Tools 3D example. I'm not personally using e4, so at the moment getting GEF3D running on e4 is not my first priority and I didn't investigate any further. Besides, I got a lot of exceptions in the e4 runtime, after restarting the runtime several times it didn't started at all. I get tons of "!MESSAGE unsupported:" messages, and when trying to create a new project with the context menu, the "new"-submenu is missing, finally I get another NPE:
java.lang.NullPointerException
 at org.eclipse.ui.internal.e4.compatibility.WorkbenchPage.getNewWizardShortcuts(WorkbenchPage.java:1172)
 at org.eclipse.ui.actions.BaseNewWizardMenu.addShortcuts(BaseNewWizardMenu.java:142)
 at org.eclipse.ui.actions.NewWizardMenu.addItems(NewWizardMenu.java:129)
 at org.eclipse.ui.actions.BaseNewWizardMenu.getContributionItems(BaseNewWizardMenu.java:205)
...
I don't know how but after switching the perspective I was able to create at least a simple project, and then the new-submenu was available enabling me to create a GEF3D graph example. So I got GEF3D to run with 1.0 M4 (proofed by screenshot ;-) ), however I found a severe problem with GEF 3.6 and I filed a bug report about that (# 306609). I had to fix that in order to get GEF3D running. Actually, this problem is a GEF3D blocker and I really hope the GEF team can solve that issue. As a matter of fact I'm glad to have found that bug now. I hope it's not too late for the final 3.6 version.
GEF3D on e4 1.0M4! Do you see the level-of-detail effect , i.e. labels on back planes are omitted! (Again kudos to Kristian ;-) )
Boris asked me to file a bug report, but frankly I don't know where to start... I could create a bug report about the NPE I described in my previous post, but I'd assume 0.9 is a little bit out-dated, isn't it?

Friday, March 19, 2010

Quick test: GEF3D and e4

Today I received an email from someone asking whether GEF3D will work with e4. Since GEF3D is "only" an extension of GEF (and GMF), I assumed it will work. In order to be sure, I tried it myself. This is my installation log: Step 1) Downloaded the e4 0.9 release (http://download.eclipse.org/e4/downloads/drops/R-0.9-200907291930/index.html#EclipseE4), in my case the Mac OS X Cocoa version Step 2) Installed the following features via the given update sites: Step 3) Imported GEF3D team project set found at http://eclipse.org/gef3d/resources/GEF3D.psf State: The 3D graph example is working, see screenshot.
GEF3D on e4! (Note the nice vector based fonts :-D Kudos to Kristian!)
Step 4) Now installed the missing features in order to test all examples: Restarted e4 after downloading these bundles. Ups, what's that? My toolbar has gone...? Where is it? However, I doubt GEF3D or GMF to be involved in that bug... Hmm... was there a toolbar before step 4)? Weird. UML2 Tools and Ecore Tools are working, at least the 2D versions. Unfortunately, the 3D versions are not working. There are not much error messages:
java.lang.NullPointerException
at org.eclipse.e4.extensions.LegacyPartRenderer.createEditor(LegacyPartRenderer.java:95)
at org.eclipse.e4.extensions.LegacyPartRenderer.createWidget(LegacyPartRenderer.java:357)
...
I didn't analyzed that error... without a toolbar, it's not very comfortable. Besides, I didn't found the code of LegacyPartRenderer and I didn't find a way to declare an exception breakpoint. Summary: Since the 3D graph example is working, I assume GEF3D and e4 should work in general (e4 does change the workbench, but not SWT or GEF). However, the 3D-fied UML2 and Ecore editors are not working, but I have no idea why they don't. Maybe it's not e4 but a problem with the latest GMF or ecore tools versions, I don't know. Frankly, I have ignored e4 for the time being (simply because I haven't had the time). IMHO you cannot simply install existing 3.x plugins and expect them to work with a 0.9 incubator framework. In so far I'm happy about the 3D graph example running! Besides, I assume my test only tested the legacy layer of e4, and not e4 itself. However, I'm still wondering why the 2D version of the ecore diagram editor is working and why the 3D version isn't. I'd assume there exist documents in the e4 project about how to solve problems like this.

Tuesday, January 19, 2010

Quick'n Dirty Tutorial on Modelling with Eclipse

A friend of mine asked me how to modelling with Eclipse. I gave him a quick tour, demonstrating how to create a model with EMF, how to create an instance of that model, how to query the model with OCL, and how to create a text editor for that model with Xtext. It's pure modelling, i.e. no Java programming at all! I thought that maybe other people would be interested in that topic as well, so I created this little tutorial showing how all these Eclipse modelling "ingredients" can work together.

Preparations

Install Eclipse 3.5 (Galileo) with all the modelling tools, that is the Galileo Eclipse Modeling Tools package. Additionally, we will need the OCL interpreter console, which can be installed using the MDT update site:
http://download.eclipse.org/modeling/mdt/updates/releases/
The OCL console actually is an example, so you will have to install that specific example.

The Runtime Example

Let's assume a small IT company. The employees of that company develop software for other companies. Of course, they use models for that purpose! In order to better organize their work, they want to document who is working on what. That is, they want to assign certain task to developers. A task could be the implementation of a use case or writing a test case for a class. Let's see if we can use models for that...

Company Model with EMF

First of all, we have to create a model describing the company. Let's start from scratch:
  1. create a new project:
    File / New / Project... / Eclipse Modeling Framework /Empty EMF project
  2. create a new ecore diagram (we want to graphically design the model) in the newly created model folder: Right click on model folder and select
    New / Other... / Ecore Tools / Ecore Diagram
  3. enter the Domain file name:: company.ecore and press Finish.
Now, we can "draw" our model using the graphical editor. Create four classes (EClass), add a name attribute (EAttribute) to one of them, create references (EReference) between the classes, and set the properties (in the properties view, this view can be activated by right-clicking in the diagram and select Show Properties View. The result should look like Figure 1.
Figure 1: The domain model of a company
Some remarks:
  • The model is an instance of the ecore model, which is quite similar to class models in UML. All elements in ecore start with an "E", so it is EClass, EAttribute, or EString.
  • The EType of the attribute name is EString.
  • The upper bound of all references is "*" (you can enter "-1", which actually is the same as "*").
  • You will need a class containing all your elements later. In the example, the Company serves as a container. Make sure the Is Containment flag is set for the two references employees and skills (see Fig. 1)
Now that we have created a model of our company, we can create an instance of that model. Later, we will generate an editor, but right now we want to quickly create an instance to get a feeling for our model. An instance of our model actually is an instance of our container element, that is the Company class. There is a generic editor available, which can create an instance of a model (or its elements) directly without the need of code generation. All you need is the ecore model. This is how to activate it:
  1. Close the ecore diagram
  2. Open the ecore model, this time use the Sample Ecore Model Editor. Usually, this editor is used if you double-click the ecore-file, but to be sure use the Open With... context menu entry.
  3. Select the Company class (the class, not the package!), and select Create Dynamic Instance... from its context menu. This is shown in Figure 2.
    Figure 2: Create a dynamic instance.
  4. enter the File name: Company.xmi and press Finish. The instance will be created in the model folder.
  5. edit the model instance using the context menus New Child of the elements in the model.
  6. edit the elements properties in the properties section of the editor, see Figure 3.
    Figure 3: Edit properties with the Generic EMF Form Editor
Now that we have create a model and an instance of that model, we want to "work" with that model instance. E.g., we can use OCL to query the model:
  1. Activate the console view and open the Interactive OCL console with the button on the left of the console, see Figure 4.
    Figure 4: Open OCL interpreter console
  2. Select an element in the editor, This selected element is the context of the OCL query.
  3. Enter your OCL query in the console (in the lower section of the OCL interpreter console). E.g. query the name of the selected element with self.name. The result will be displayed in the upper section of the OCL console as shown in Figure 5. We will demonstrate other queries later on.
    Figure 5: Query the model instance with OCL

Task Model with Xtext

Now that we have a model of our company, we want to assign tasks to the employees. We could create a new ecore model just as demonstrated above, but we want to try something new. So, let's try to not only create a model, but a text editor as well. For that, we will use Xtext. Based on a grammar, Xtext can create an ecore model and a text editor with nice features. The grammar is an annotated EBNF grammar, I do not want to go into the details here (otherwise it wouldn't be a q'n d-tutorial ;-) ). So, we have to create a new project and enter a grammar:
  1. Create a new Xtext project:
    File / New / Project... / Xtext /Xtext Project
  2. SetMain project name, the Language name (to de.feu.Tasks), and the DSL-File extension (to tasks).
  3. Open Tasks.xtext (this is the EBNF-like grammar) and enter your grammar according to Figure 6.
    Figure 6: Xtext grammar defining our task model along with a concrete textual syntax
    Here is the grammer (for copy & paste):
    grammar de.feu.Tasks with org.eclipse.xtext.common.Terminals
    
    import "http://www.eclipse.org/emf/2002/Ecore" as ecore
    import "platform:/resource/de.feu.company/model/company.ecore" as company
    
    generate tasks "http://www.feu.de/Tasks"
    
    Tasks :
     (developers+=Developers)*
     (domainmodels+=DomainModels)*
     (tasks+=Task)*;
     
    Developers :
     'developer' importURI=STRING;
     
    DomainModels :
     'domainmodel' importURI=STRING;
    
    
    Task: 'task' element=[ecore::EObject] 
       'by' developer=[company::Developer] 
       ':' description=STRING;
    
    This grammar defines a container element Tasks. Inside, we can "load" a list of developers and domain models. Eventually, tasks can be defined by assigning an element from a domain model (see element=[ecore::EObject]) to a developer (developer=[company::Developer]) and add a description of that task.
  4. Save the gammar and generate the ecore model along with the text editor using the MWE-workflow. For that, select file GenerateTasks.mwe and run the workflow via its context menu Run As / MWE Workflow
Notes:
  • In Xtext, a model is called a DSL. Experts like to use different names for "model", sometimes it's cooler to call a model "meta-model" (or, even cooler, "meta-meta-model"), sometimes they call it "domain specific language", abbreviated with a nice TLA (three letter acronym): DSL. Of course, there are good (and sometimes not so good) reasons for doing so, but usually it's easier to simply call a model a model (and an "instance of a model" an "instance of a model") .
  • The grammar shown in Figure 6 actually uses a lot of nice Xtext features and you will have to read the Xtext documentation for details. I only want to explain one thing here, which is a little bit advanced. You can import existing models into the grammar (import ...). In the example, we import the ecore model and our previously created company model. We import these models in order to be able to define inter-model references later on. Our Task element will refer to an element, which can be any ecore::EObject, and the developer is to one developer defined in our company model (company::Developer). EMF supports inter-model-references, and Xtext generated editors support that feature as well! The import statements in our grammar only import the models, but later on we want to actually import existing model instances. For that, we need the importURI feature of Xtext to define what instance to import in our actual task model instance.
Although we haven't written a single line of Java code yet, a lot of code has been generated automatically. In order to "activate" that code, which actually defines a new Eclispe plugin, we have to start a new runtime instance of Eclipse, that is we start Eclipse from within Eclipse. In the long run, you will have to get used to Eclipse plugin development anyway... As we have to run a new instance anyway, we can generate an editor for our company model as well. Instead of using a dynamically created instance using the "Generic EMF Form Editor", EMF can generate a Java implementation of the model and an editor as well. We will do that now:
  1. Select the company.ecore file and choose New / Other... / Eclipse Modeling Framework / EMF Generator Model from its context menu. Use the suggested file name, select Ecore Model in the next wizard page. Then, press Load in the next page, and eventually Finish on the last wizard page. This creates a generator model, which basically adds some information to the original ecore model which is necessary in order to actually generate code (e.g., the name of the plugins and so on). We do not want to change anything here, but we still need that model.
  2. In that model, select the very first element (Company) and select Generate All from its context menu (see Figure 7).
    Figure 7 Generate the model and editor code

Work with Multiple Models

Now that we have generate a lot of code, we want to use the newly created tools. Start a new Eclipse runtime instance (e.g. by selecting Run As / Eclipse Application from a project context menu) and do the following:
  1. Create a new project (in the runtime instance):
    File / New / Project... / General /Project
  2. Select the project and choose from its context menu:
    New / Other... / Example EMF Model Creation Wizard / Company Model
    This activates our previously generated editor (and a wizard) for creating a company model instance. We can edit a company instance just as we did it with the generic editor. In the wizard, select the Model Object Company and then create a new company as shown in Figure 8. (Don't forget to save the model ;-) ).
    Figure 8: A company model, edited with the generated editor
  3. Now, create a new file (File / New / File) inside the project and call it project.tasks. The Xtext generated editor is opened automatically and we can now edit the task model instance.
  4. In order to "simulate" a project, we create a simple UML use case model. Simply create a new use case diagram via File / New / Other... / UML 2.1 Diagrams / Use Case Diagram, give it a name (e.g. project_usecase) and draw some use cases, a sample is shown in Figure 9.
    Figure 9: A sample use case diagram
  5. Switch back to project.tasks and "import" our company model and the sample use cases. Add a task using content assist (Ctrl-Space) just as shown in Figure 10. Just play around, add three or four tasks in order to be able to follow the next steps.
    Figure 10: Content assist, demonstrating access to imported models
  6. Just as at the beginning, we want to execute some OCL queries on our model, but this time on our project.task model instance. For OCL, we always need a context, but unfortunately we cannot select a context (or model element) in the text editor. So we have to reopen the project.task with the generic EMF editor: Choose from its context menu Open With / Other... / Generic EMF Form Editor. You will now see the very same model as in the text editor, but this time you see a tree-based version of the model.
  7. Open the OCL console just as above, select an element (here Tasks) and enter a query. For example, we want to know how much tasks are assigned to a specific developer: self.tasks->select(developer.name='Jens')->size(). You can see that in Figure 11
    Figure 11 A little more sensible OCL query

Conclusion

IMHO it is impressing what you can do with all these cool Eclipse modelling tools, without writing a single line of (Java) code. We saw how to
  • create an EMF ecore model with the Ecore Tools diagram editor
  • open the same ecore model with the Generic EMF Form Editor
  • create instances of a model without the need to generate code and without starting a new runtime instance, using the "Create Dynamic Instance" feature (and the generic EMF editor again)
  • generate a text editor and a model without a single line of Java code with Xtext
  • generate a tree based editor and a Java based model implementation with EMF
  • create a UML diagram with the UML Tools diagram editor
  • query your models with OCL from the OCL project
We didn't bothered about how to store our models or model intances (it's all XMI), we were using OMG standards like UML (the EMF based implementation is provided by the UML2 project, EMF's ecore is an EMOF-like model, we were using OCL, other implementations are available, too (e.g., BPMN2, SBVR, or SPEM used by EPF). And if you do not find an Eclipse project, you probably will find a third party project providing an EMF based implementation ;-) With tools like GEF or GMF you can create (or generate) diagram editors for your models, and (well, I couldn't resist) with GEF3D you can even create 3D diagram editors, e.g. for visualizing inter-model connections. And there are many more tools out there, partially for simplifying the use of existing tools, for model transformations and code generation and so on. And of course you can adapt and modify the code generated above to suit your need.

Warning: Thin Ice!

While it is very easy to do impressive things (with the help of a tutorial), it is very hard to get into all these frameworks and tools. There are a lot of traps hidden everywhere! Just two examples from the tutorial:
  • In the Xtext grammar we used here, the ecore model was imported (see Fig. 6). I tried the very same using the UML2 model, and I got a weird error when generating the code (actually I couldn't generate in that case).
  • A NullPointer-Exception is thrown (you can see that in the console of the original Eclipse instance) when opening the project.tasks file with the Generic EMF Form Editor. Fortunately it still is possible to select an element (for the OCL query), but it's a little bit weird.
Well, I probably should file a bug report at least for the first problem... So be warned: Even if the tutorial gives you the impression as if modelling with Eclipse tools is very easy, it sometimes isn't. In general, modifying generated code as well as using tools like GMF is not that simple. But at least there are the newgroups, tutorials, and even books (e.g. the EMF book (2nd edition!) or the GMF book).

Disclaimer

This is a quick and dirty tutorial article. I simply documented an example modelling session by taking some screenshots, and then wrote some explanations. So, there probably are some things I've missed to tell you or errors in my text. Please leave me a comment if you find a bug here ;-) (or if you like the tutorial). May the Model be with you!

Tuesday, November 24, 2009

Retrospect: DemoCamp in Berlin

Yesterday I attended the Eclipse DemoCamp in Berlin. It took place at Fraunhofer Fokus, and (as the last democamps) it was organized by Tom Ritter (thank you, Tom!). This time, there were ten (10!) presentations, seems as if we should organize a DemoDay next time. The camp started with a nice welcome talk by Ralph Müller, encouraging the audience to become Eclipse members (I will talk with my employer about that, promised ;-) ) and visit Eclipse Summit Europe (I won't miss it). Kristian Duske (committer on the GEF3D project) presented a "GEF3D Based Editor for the GMF Mapping Model", which was the subject of his diploma thesis. His editor enables the creation and editing of the GMF mapping model using simple drag-and-drop mouse operations. In contrast to the tree-based GMF editors, all involved models are visualized in a graphical manner, and since all models are visualized in a single 3D scene, inter-model-connections are visible, too. I really like the idea and his presentation, but since I was his tutor, I'm not really an impartial observer ;-)
Fig 1: Kristian's 3D GMF Mapping Editor
Martin Esser then demonstrated a small editor he has created with GMF (unfortunately without Kristian's 3D editor ;-) ) for variability models (aka feature diagrams). The challenge is to implement these arcs connecting edges of optional or alternative features. I usually draw these diagrams using OmniGraffle, and although there is a stencil for these diagrams available, it is painful to adjust these arcs -- a GMF based editor would be a great help. Maybe Kang et al designed these diagrams in order to test the abilities of programmers of graphical editors... (BTW, I just stumbled over this Eclipse project proposal, they want to provide a graphical editor as well) It seems as if there is an Xtext presentation at every democamp ;-), and of course there was a talk about it in Berlin, too. Peter Friese gave a short overview of this really nice tool for creating editors (and more) for textual DSLs. I have attend a couple of Xtext presentations (e.g. at ESE 2008 and 2009), and although all these presentations used different slides and were presented by different persons, the slides are always magnificent (with great photos and nicely illustrated). Maybe they have an Xtext based tool for generating these slides... hmm... Ralph Müller mentioned something about Ytext in his keynote, maybe this is a new tool for generating presentations? After a short break (with Eclipse sponsored sandwiches and soft drinks ;-)), Marcus Engelhardt demonstrated a tool called Metrino for measuring models. Metrics can be defined using OCL for UML or Ecore based DSLs, and the tool creates nice reports and radar charts. IMHO model metrics are an important tool for modelers, and I always have the plan to create tool with GEF3D in order to display the metrics on top of the diagrams (using the city metaphor) as illustrated in Figure 2... Marcus, if you'd like to combine that with Metrino, I would be happy to assist you!
Fig. 2: Visualization of metrics with GEF3D
Joachim Hänsel and Jaroslav Svacina introduced their tool EvoTest for creating tests automatically with evolutionary techniques. I know that tests are very important, but (shame on me) I'm neither an expert for testing nor for evolutionary techniques. However, their tool looks very interesting, and I was impressed by the ability of that tool to generate white box tests considering path coverage. Next, Martin Köster talked (slides are available here) about how he created an Eclipse based IDE for the Clojure language, a Lisp (that language driving you crazy with brakets) dialect for the JVM. It was very interesting to learn how he used the DLTK in combination with his own ANTLR parser. There seem to be a lot of issues addressed by Xtext and DLTK. I wonder if it would make sense to integrate these two tools. Stephan Herrmann then presented a new episode of the famous Object Teams series. After a short "previously on OT" flash back (summarizing OT as a great tool for reusing existing components in a flexible (via AOP techniques) yet controlled (via modules and a role-team-concept) manner), the story continued with a special and important problem: persistence. He explained how it is possible to use OT in combination with O/R-mappers -- with minimal effort by using OT techniques. Actually, this topic was subject of a diploma thesis (in german language) by Olaf Otto. OT is a proposed Eclipse project, and I hope it will become a real Eclipse project, soon. Igor Novakovic demonstrated a powerful tool called SMILA. It is an Eclipse project for setting up tool chains for querying, processing and extracting data. In his demo, he showed how to combine some cool Fraunhofer tools for image recognition with a search engine (Lucene) (probably other tools were involved as well). The nice thing about SMILA is that in the end all these tools are combined in a way that some data can be queried in a very simple manner (e.g. HTML formular). In the demo, some chemical structures could be searched in a collection of research papers. Simply querying the text content wouldn't be that thrilling, but in that case, a tool analyzed the figures in the papers and presented the molecules using Jmol. Some years ago I integrated a search engine (Verity Information Server) with a CMS based on StoryServer, and a tool like SMILA would have been a great help (I assume that with SMILA I would have spent days instead of months to accomplish that task...). Finally, Enrico Schnepel presented a small framework called emf.observables for simplifying EMF databinding. His cool (Prezi based) slides are available, too. Actually it is a small yet helpful tool, generating some plugins next to your EMF model implementation with some wrapper classes hiding the complexity of EMFObservables/IObservable. It was a really interesting and inspiring evening: A big thank you to all the presenters. See you all again at the next Berlin Eclipse DemoCamp (or Day ;-)).

Wednesday, September 30, 2009

String.format vs. MessageFormat.format vs. String.+ vs. StringBuilder.append

Usually I'm not a performance hacker, i.e. I seldom use the final keyword, and I dare to use List.size() in loop expressions. But I'm a little bit sensitive when it comes to string operations, as they can cause severe performance problems, and sometimes security issues as well, e.g., if an SQL query is to be created (ok, bad example, one can use PerparedStatement instead of hacking an SQL string). For logging I often have to concatenate strings, such as
if (log.isLoggable(Level.INFO)) {
    log.info("Command created - cmd=" + cmd); //$NON-NLS-1$
}
Actually I'm not writing lines like this myself, I let log4e do the job -- I really love that tool! But sometimes these string concatenations are hard to read, using a String.format or MessageFormat.format would make it much easier. Here are some examples:
foo(String.format("Iteration %d, result '%s'", i, value[i%2]));

foo(MessageFormat.format("Iteration {0}, result ''{1}''", i, value[i%2]));

// single line:
foo( "Iteration " + i + ", result '" + value[i%2] + "'");

// multi line:
String s;
s = "Iteration ";
foo(s); s+= i; foo(s); s+= ",\nresult '";
foo(s); s+= largeString(i); foo(s); s+= "', '"; 
foo(s); s+= largeString(i+1); foo(s); s+= "'";

foo(new StringBuilder("Iteration '")
    .append(i).append(", result '").append(value[i%2]).append("'")
    .toString());
(Update: the multi line test was added after daObi and Laurent commented the first version) Hmm... maybe the "+" isn't that bad ;-) I do not understand why String.format andMessageFormat.format have these different notations, and frankly I seldom get the format string right in the first run. So, besides the aesthetics, what about performance. What would you guess? My guess was StringBuilder would be the fastest, followed by the format methods, and the String operator "+" would be the slowest as new Strings are to be created all along. I run a little test (calling these methods 100000 times, foo() is doing nothing and was, besides other things, only added in order to avoid too much compiler optimizations, although I have no idea if that worked ;-) ). Note that in the test only a few strings are concatenated, but I think that's a typical example and it was the setting I was thinking about to use format methods instead of string concatenation (and it's quite similar to many toString methods). I was surprised by the result:
String.format:757 ms
MessageFormat.format:1078 ms
String +:61 ms
String + (multi line):162 ms
StringBuilder:74 ms
Gosh! The "+" operator clearly is the winner! It is 10 (ten!) times faster then the format methods. 10 times, can you believe that. I was really surprised, and frankly, I couldn't believe it. (Update: daObi and Laurent explain it, see their comments below). Thus I changed the test, assuming the compiler tricked me, but I always got more or less the same results. I figured it may be the size of the strings, so I also changed that. That is, I used large strings (with 70.000 characters, the method returns one of two strings in order to avoid compiler optimization) in the concatenation:
for (int i = 0; i < n; i++) {
    s = MessageFormat.format("Iteration {0,number,#},\nresult ''{1}'', ''{2}''", i,
   largeString(i), largeString(i+1));
}

for (int i = 0; i < n; i++) {
 s =  "Iteration " + i + ",\nresult '" + largeString(i) + "', '" + largeString(i+1) + "'";
}
Actually, the test is a little bit unfair, as in all cases at least the result string has to be created (i.e. also the format methods have to create strings), but at least the string is rather long. The result string s has a length of 140027 characters, so this is a pretty long string, isnt't? Here are the result of the long-string-test:
String.format:584 ms
MessageFormat.format:816 ms
String +:621 ms
String + (multi line):867 ms
StringBuilder:555 ms
Yeah! Now we have the order I expected in the first place: StringBuffer.append is the winner, followed by String.format. MessageFormat.format has a little problem and is even slower than the String concatenation. But compared to the result of the first test, all methods are at the same speed. So, what did I learn? First, I will use the plain and simple string concatenation in the future more often, as it is easier to write in many cases compared to some weird format strings. I will use String.format only if I probably need to translate my code, since this is easier to translate a format string than changing the code (if the order of the sentence components change in another language). And, of course, I will use StringBuilder if large strings have to be concatenated, but I think I use it less in toString-methods. And maybe I'm going to read a book about performance hacking -- do you have any recommendations? Anyway, this test also teaches me (again) that good performance is not (only) a question of single statements, but a question of good algorithms and good design in general. Note: Actually this is not the first time I was surprised by the result of a preformance test. I did a test once comparing the performance of different class library designs in case of a math library for matrices and vectors. I have documented the test in the LWJGL forum, and its results influenced the design of the GEF3D geometry package (see package documentation).

Wednesday, July 1, 2009

User Report: Migrate from oAW Xtext to TMF Xtext

With Eclipse 3.5 comes the new version of Xtext, called TMF Xtext. Since I had to switch to Eclipse 3.5 in order to keep GEF3D running on the latest Eclipse version, I decided to migrate from the old openArchitecture Xtext (oAW Xtext) to the new TMF version. Fortunately the Xtext documentation contains a section about migrating from oAW Xtext to TMF Xtext. Frankly, I was a little bit afraid (never change a running system). But at least I hadn't implemented any content assist or other editor extensions yet, so I hoped that it wouldn't be too hard. Before you read on, please note that I'm only an Xtext user. I don't know any internal details about Xtext. Maybe some of my problems can be solved more efficiently, if that is the case, I would be more then happy if you leave me a comment. My first intention was to migrate my already running grammar as fast as possible, with as few modifications as possible.

The Setting

I have written a model transformation language, and it consists of an Xtext grammar (with about 90 rules), an interpreter for executing the language, and other things which I didn't expected to be involved in the migration, as a debugger component or other user-interface stuff. An Xtend-based M2M transformation exists which modifies the generated ecore model in order to set some default values, add some workarounds for existing oAW bugs, and do other things. In order to migrate my application, I had to
  1. migrate the grammar
  2. adapt the M2M-transformation
  3. adapt client code which uses the model and the Xtext API
In the following old versions are highlighted with a light red back and the new ones with a light green background.

Migrating the Grammar

As described in the Xtext documentation, I had to replace "Enum" with "enum", and add two new lines at the beginning of the grammar. Since "with" has become a keyword. Thus I had to rename "with" in my grammar :
RuleXY: ... ( "with" with=Block)? ...
into
RuleXY: ... ( "with" _with=Block)? ...
This also caused some small changes in the model and the client code. Is there a way to use Xtext keywords as a reference names?

Backtracking

Apparently the parser generation (or some settings) has changed, too. E.g., the following rule worked with the oAW Xtext version:
ParameterReference: QualifiedParameterReference|SimpleParameterReference;
SimpleParameterReference: type=Type (name=ID)?;  
QualifiedParameterReference: type=Type name=ID;
The idea of these rules is to force the definition of a name in case of qualified parameter references and to make it optional in simple ones. Unfortunately these rules are not working with the new version. Since ANTLR is a LL-parser, there are some constraints on how to define the grammar. There is a document explaining how to remove backtracking from a grammar, unfortunately some of the described techniques cannot be used with Xtext. In some cases I was able to fix the problem by rewriting my grammar, as in this example: I simply had to reorder the first rule:
ParameterReference: SimpleParameterReference|QualifiedParameterReference;
SimpleParameterReference: type=Type (name=ID)?;  
QualifiedParameterReference: type=Type name=ID;
In some cases I couldn't find a solution (maybe it is possible, but I'm not an LL/LR-expert). Actually I'm not the first one with this problem, and there is a posting in the TMF newsgroup about this. If you cannot rewrite your grammar, you need backtracking (and lookahead). Thanks to this posting, I was able to fix the problem. I had to edit the MWE-file from
<fragment class="org.eclipse.xtext.generator.AntlrDelegatingFragment" />
to
<fragment class="de.itemis.xtext.antlr.XtextAntlrGeneratorFragment">
   <options k="2" backtrack="true" memoize="true"/>
</fragment>
Note that you have to install the itemis generator fragment from http://download.itemis.com/updates as described in the Xtext documentation (page 62). Maybe I'm going to "left factor" my grammar in a future version, but for now I only wanted to get my application running.

Lexer Rules

In the oAW version, lexer rules were defined with the keyword "native", which has been changed to "terminal". Not mentioned in the migration guide yet: INT was redefined in the new version. I had rewritten the definition in the old version in order to remove the optional sign (as my language is handling this itself). This is the old INT definition:
Native INT: ('-')?('0'..'9')+ 
And here's the new one:
terminal INT: ('0'..'9')+ 
In my case I could remove my own definition since the new one matches my requirements. In other cases, this might be a trap. According to the documentation, it should be possible to define the type of a terminal rule now. I tried this as follows:
terminal FLOAT returns ecore::EFloat: ('0'..'9')*'.'('0'..'9')+;
As a matter of fact, the code is generated as expected, but the parser still returns a String, which leads to a ClassCastException. So I removed the type definition and added a convenient method to my model, as described below. I assume this is a bug or something, I will file a report later on ;-). Since the old version always returned Strings, my code was prepared for that, anyway.

OrmPackage missing

I don't know exactly why or when, but at some point in time my grammar file contains got an error marker:
- WrappedException: java.lang.ClassNotFoundException: com.sun.java.xml.ns.persistence.orm.OrmPackage"
This bug seems to be fixed already, fortunately it is possible to generate the model and code from the grammar, even with this error.

Unassigned Actions

In the oAW Xtext version, a model element was assigned whenever a non-abstract rule was hit. My grammar contained the following rule:
NullLiteral: "null";
This rule is not working with the new TMF Xtext version. As found in the documentation "by default the object to be returned by a parser rule is created lazily on the first assignment". Although I've read that passage, I was not aware of the consequences. In the new version, an element is not automatically created when the rule is hit, but only when an assignment is to be executed. That is, a rule which contains only terminals does not create a model element, as in the example above. While this first example is obvious, the problem is sometimes hidden. Here is another more tricky example:
Block: "{" (statements+=BlockStatement)* "}";
If no "BlockStatements" are specified, that is in case of an empty block ("{}"), no block element is created at all. I posted that problem to the newsgroup, and Sebastian Zarnekow immediately solved my problem (Thank you very much, Sebastian!). The solution is to use unassigned actions, which forces the creation of an element of the specified type. So I had to change the rules above as follows:
NullLiteral: {NullLiteral} "null";
Block: {Block} "{" (statements+=BlockStatement)* "}";
I figure this is a bitchy trap, especially if there is an optional assignment.

Model Changes

I'm already using an Xtend M2M-transformation to adjust the generated ecore model. TMF Xtext supports this mechanism, I simply had to rename my Xtend extension into MitraPostProcessor.ext (Mitra is the name of my language, by the way).

Enumeration NULL values

There are some adjustments necessary due to changed behaviour of Xtext. Most notable: There is no "NULL" value generated for enumerations. Also, it is not possible to define a hidden enumeration in the grammar, which might could have solved that problem. IMHO, this is a major drawback, as this makes a postprocessing of the created ecore file necessary. But they can be added to the M2M transformation. Unfortunately, I didn't got this problem solved with Xtend, I posted that to the TMF newsgroup. This is at least one solution using Java, although I would prefer a pure Xtend solution:
process(ecore::EPackage p):
 addNullValue(p, "VisibilityModifier") ->
 ... ;

Void addNullValue(ecore::EPackage p, String toEnum):
 doAddNullValue( (ecore::EEnum) p.getEClassifier(toEnum) );
 
Void doAddNullValue(ecore::EEnum e):
 JAVA de.feu.MitraPostProcessorHelper.addNullValue(org.eclipse.emf.ecore.EEnum);
And this is the Java extension:
public class MitraPostProcessorHelper {

 public static void addNullValue(org.eclipse.emf.ecore.EEnum e) {
  for (EEnumLiteral literal : e.getELiterals()) {
   literal.setValue(literal.getValue() + 1);
  }
  EEnumLiteral nullLiteral = EcoreFactory.eINSTANCE.createEEnumLiteral();
  nullLiteral.setName("NULL");
  nullLiteral.setLiteral("NULL");
  nullLiteral.setValue(0);
  e.getELiterals().add(0, nullLiteral);
 }
}
In order to make a literal the default value, it must be the first defined literal. This is why e.getELiterals().add(0, nullLiteral); is required, simply adding the literal with e.getELiterals().add(nullLiteral); doesn't work.

Java Body Annotation in the Ecore Model

In the old version, Xtext didn't create the genmodel and no code. I added this feature and I also edited the generated code after is was created using oAW extension. Since Xtext is doing the code generation now automatically, I didn't feel that comfortable with manually editing the generated model code anymore. So I decided to add Java annotations to the ecore model in order to add some tiny helper methods. This is how body annotations are added to an ecore model in Xtend:
Void addJavaBodies(ecore::EPackage p):
 let ecorePackage = p.getEcorePackage():
 p.getEClassifier("Bounds").addOperation("isMany",
     ecorePackage.getEClassifier("EBoolean"),
       'return upper==-1 || upper>1;') ->
   ...;
/*
This is a hack in order to retrieve the ecore package itself. This is usually
done with a Java extension, but I did not want to add a Java extension here.
The trick is to retrieve the package by navigating to the container of an ecore
type (here a String).
*/
cached ecore::EPackage getEcorePackage(ecore::EPackage p):
  (ecore::EPackage)
  ( ((ecore::EClass) (p.getEClassifier("MetamodelDeclaration")))
    .getEStructuralFeature("type").eType.eContainer
  );
 

create ecore::EOperation addOperation(ecore::EClassifier c, String strName, ecore::EClassifier type,  String strBody):
 setName(strName) ->
 setEType(type) ->
 eAnnotations.add(addBodyAnnotation(strBody)) ->
 ((ecore::EClass)c).eOperations.add(this);


create ecore::EOperation addOperation(ecore::EClassifier c, String strName, ecore::EClassifier type, 
 List parameters,
 String strBody):
 setName(strName) ->
 setEType(type) ->
 parameters.collect(e|((List)e).setParameter(this)) ->
 eAnnotations.add(addBodyAnnotation(strBody)) ->
 ((ecore::EClass)c).eOperations.add(this);

create ecore::EParameter setParameter(List parameter, ecore::EOperation op):
 setName((String)parameter.get(0)) ->
 setEType((ecore::EClassifier) parameter.get(1)) ->
 op.eParameters.add(this)
;

create ecore::EAnnotation addBodyAnnotation(ecore::EOperation op, String strBody):
 setSource("http://www.eclipse.org/emf/2002/GenModel") ->
 this.createBody(strBody) ->
 op.eAnnotations.add(this);

create ecore::EStringToStringMapEntry createBody(ecore::EAnnotation anno, String strBody):
 setKey("body") ->
 setValue(strBody) ->
 anno.details.add(this);

API Changes

So far I found three API changes which required changes in my code. These changes are rather simple and briefly explained in the following.

NodeUtil.getNode(..)

First of all, NodeUtil.getNode(EObject); has changed. There is no type Node anymore. I had to change my code from
Node node = NodeUtil.getNode(eobj);
to
NodeAdapter adapter = NodeUtil.getNodeAdapter(eobj);
AbstractNode node = null;
if (adapter != null) {
 node = adapter.getParserNode();
}

Resources and Setup

For (JUnit) tests, I have to call a setup method in order to register Xtext's resource implementations and my model. This is now simply achieved via a generated setup method. This is the setup method I'm using now in JUnit tests:
public static void setup() {
   System.setProperty("org.eclipse.emf.ecore.EPackage.Registry.INSTANCE",
   "org.eclipse.emf.ecore.impl.EPackageRegistryImpl");
   MitraStandaloneSetup.doSetup();

No DSL-specific Editor Class

A little bit surprising at first is the absence of a DSL specific editor class, in my case MitraEditor. Instead, the general Xtext editor class is used, DSL specifics are injected using Google Guice as described in the Xtext manual. Most surprising is the new syntax found in the plugin.xml which is used to inject things. Here is the declaration of my editor using the new notation (the plugin.xml is generated):
<extension point="org.eclipse.ui.editors">
   <editor
       class="de.feu.MitraExecutableExtensionFactory:org.eclipse.xtext.ui.core.editor.XtextEditor"
       contributorClass="org.eclipse.ui.editors.text.TextEditorActionContributor"
       default="true"
       extensions="mitra"
       id="de.feu.Mitra"
       name="Mitra Editor">
   </editor>
</extension>
The attribute "class" defines the Guice module to be created and the editor class. Unfortunately I need the editor class in order to add breakpoint markers (for my debugger plugin). The old version looks like this:
public class MitraBreakpointAdapterFactory implements IAdapterFactory {
 public Object getAdapter(Object adaptableObject, Class adapterType) {
  if (adaptableObject instanceof MitraEditor) {
    ...
How do I identify the mitra editor in the new version? First of all, instead of a generated DSL specific editor, an XtextEditor is used (this class is found in plugin org.eclipse.xtext.ui.core). Then the current language can be retrieved via getLanguageName(). This is the new version:
public Object getAdapter(Object adaptableObject, Class adapterType) {
 if (adaptableObject instanceof XtextEditor) {
  XtextEditor xtextEditor = (XtextEditor) adaptableObject;
  if ("de.feu.Mitra".equals(xtextEditor.getLanguageName())) {
  ...
Note that the name of the editor class has to be changed in the plugin.xml of the debug plugin accordingly.

Summary

After applying the changes described above, my language worked as expected (at least all the tests are green and my application is running). Since I haven't written any extensions for content assist or other UI things, I only had to adjust the grammar, my M2M-transformation and the code a little bit. If you do not have an M2M-transformation, you may have to add it in order to add the missing NULL values for enumerations -- I assume this is the case quite often. TMF Xtext adds some very nice features (grammar mixings, improved linking/cross references feature with ILinkingService, serialization with formatter, return types, and tree rewrite actions). These features will simplify my hand written code immensely, and I'm looking forward using them. Last but not least, since Xtext is now part of the Eclipse modeling package, it is much easier to install an Xtext based DSL and editor. Last but not least: Kudos to the Xtext team! The new version looks really nice! And many thanks for the great and fast (newsgroup) support!

Friday, April 17, 2009

First Steps Towards a Multi Editor 3D

Some days ago I 3d-fied the UML 2 Tools Diagram Editors. Well, a single 2D editor in 3D is funny but not really thrilling. You may ask: "Why should I use a 2D editor in 3D?" And I agree with you. The idea behind GEF3D is to enable multi model or multi diagram editing (this is why I started the GEF3D project). I strongly believe that "raising the level of abstraction" as promoted by all these model-driven approaches requires good tools. What does "good" mean in that context? Many models are edited graphically*, and using different levels of abstraction means using different models, that is diagrams. Also, using different (architectural) view points means using different models or diagrams. And all these models are somehow related! But these relationships usually aren't visualized. Too often, the best thing you get is a (EMF generated) tree editor. The GMF mapping editor is a typical example. IMHO a good tool would be a tool enabling graphical notations throughout the development process. And this is what GEF3D is all about. By 3d-fying existing GEF or GMF based editors, it is possible to reuse existing code and, from the user's perspective, existing and well-known graphical notations. This is also a principle of GEF3D: Enable exiting editors to be reused in 3D. Nobody wants to write new 3D-enabled editors when there are 2D editors already available, and no user wants to learn a new 3D-like notion of the UML. The next step is to open several 2D diagrams in a single 3D scene. Actually this is working for quite some time, an example application is published in [1]. This application was more a design study or proof of concept, I 3d-fied an elder version of the TOPCASED UML editor (which is GEF based). With the 3d-fied UML2 Tools editors, I was optimistic to create a UML Tools multi editor as well. Frankly, I was very much surprised how easy that was! The example code is part of the UML2 tools example found in the GEF3D SVN. I created a video demonstrating the multi editor. Have fun! (Sorry for the bad quality, it's my first video I uploaded to YouTube) Watch the video at YouTube A multi editor certainly is only the foundation for real-world (MDD) applications. Opening multiple editors in a single 3D scene enables the visualization of inter-model (or inter-diagram) relations such as transformation traces [1], inter-package dependencies, model-differences, manual mappings and so on. While the demo sounds promising, there are a lot of problems and known bugs I don't want to keep secret. There are some problems with feedback figures, text editing is not working as expected, there are problems with rotated planes (yes, actually the planes can be positioned every where in the 3D scene), currently it isn't possible to simply move an element from one diagram to another and so on. The example is only the first step, and we are working for solving the known issues.
[1]
J. v. Pilgrim and B. Vanhooff and I. Schulz-Gerlach and Y. Berbers: Constructing and Visualizing Transformation Chains. In: ECMDA-FA 2008, Berlin, Germany, June 9-13, Proceedings, LNCS 5095, pp 17--32, Springer-Verlag, 2008. URL: http://dx.doi.org/10.1007/978-3-540-69100-6_2

*For non-graphical models, XText is a wonderful tool. Combining text and graphical models certainly is a challenge for future research ;-)