* The Property Editor Factory property of a GenDataType or GenFeature (of an attribute), can use a URI of the form following form:<pre>editor://org.eclipse.nebula.widgets.cdatetime/<simple-date-format-pattern>/<cdt-style1>|<cdt-style2></pre>The CDT style constants are optional.

+

* The example below shows data types that use each of the supported instance types and are annotated directly in the Ecore model with GenModel annotations. The DateExample class has a corresponding attribute for each of the data types. Because each property editor factory is specified directly as an annotation in the Ecore model, they work even in the reflective editor. The example below shows a dynamic instance of DateExample selected to display its properties, and the cell editor activated for one of the properties.

Code generation recipes

You want make use of substitution groups as syntactic sugar for your serialization to avoid the use of xsi:type
without the resulting semantic rat poison in your generated APIs, i.e., difficult-to-use feature maps for the substitution groups.
The substitution group of a global element declaration is all the other element declaration that directly or indirectly refer to it via the substitutionGroup attribute on them. E.g., in the schema below, "member" is the head of a substitution group with "file" and "folder" as its members.
This allows "file" or "folder" to be used anywhere a "member" element may appear.
In fact, because the element is abstract, a substitute must be used.
Type of an element in the substitution group must be the same as the head element's type or a subtype thereof.
Because it can be a subtype, the type of the content for such a substitution element will be expected to be of that subtype and for this reason,
an xsi:type can be omitted from the serialization.
This is why I refer to it as syntactic sugar.
Unfortunately,
in the generated API,
you'll also end up with a read-only getMembers() list for "Folder",
and a getMembersGroup() feature map.
You'll need to do things like

Deducing elements works even for the root element, so we can save without using a document root. And because we've used XMLResource.OPTION_SUPPRESS_DOCUMENT_ROOT, we can load without there being a document root in the resource we've read. It reads and writes results like this:

Recipe: Generating Pure API With No Visible EMF Dependencies

Problem

You want to generate code for an EMF model but you don't want any references to EMF types in your API or anything else that reveals that the API is implemented by EMF.

Solution

In your genmodel:

Set the 'Suppress EMF Types' property to 'true'; standard Java types will be used rather than EMF types for all accessors and operations. Features of type 'EObject' will be surfaced as 'java.lang.Object' instead. If the model includes feature maps, you will need to use the properties 'Feature Map Wrapper Class', 'Feature Map Wrapper Interface', and 'Feature Map Wrapper Internal Interface' to provide an alternative API. You can look as the support for SDO's Sequence API as the example.

Clear or set the value of the 'Root Extends Interface' generator model property. If cleared, the generated domain API will not depend on anything, or it can be set to an interface of your choosing so that root interfaces will extend this specified interface.

Set 'Suppress EMF Metadata' to 'true' so that only a package implementation class is generated, but no interface, and so that the generated factory interface will not extend EFactory and will have an INSTANCE instead of an eINSTANCE field. Alternatively, set the generator package's 'Metadata' property to redirect the package and factory interfaces to a different Java subpackage.

Set the 'Suppress EMF Model Tags' property to 'false' to eliminate the generation of the @model tags in the Javadoc.

Set the 'Root Extends Class' and 'Root Implements Interface' properties to control the generation of the implementation, but if you clear the first one or set it so the generated implementation is not a subclass of EObjectImpl, the generated code will be invalid as it will have unresolved references to inherited methods that will not be available, e.g., eGet, eSet, eUnset, eIsSet and eIsProxy. Generating an implementation that is pure Java is not possible with the default templates but can be achieved with dynamic templates.

Recipe: Using Multiple Namespaces in the Generated EMF Editor

Problem

You want to use multiple namespaces in your generated EMF editor: say you have metamodel A with namespace mm.A which is a superset of legacy metamodel B with namespace mm.B .

If you generate an EMF editor using namespace mm.A, it can by default not read files which were serialized using namespace mm.B, unless you manually edit the files to point to namespace mm.A. But all files using metamodel B must be compatible with some legacy tool so they cannot be changed.

Now you could rename namespace mm.A to mm.B and regenerate the editor, but that forces you to adapt all your manual code and all your new files using metamodel A.

Solution

You can change your plugin.xml to let the editor recognize both namespaces:

If you save a model in your generated EMF editor, it will by default use namespace mm.A. You can change it to save using namespace mm.B by changing the String eNS_URI in src/mm.APackage (and changing the @generated tag).

Recipe: Generating Your Own Ecore Model using a stand-alone Java App

Problem

You want to generate your own ecore model files programmatically using a stand-alone command-line tool. Optionally, you also want your new model to be able to reference ecore entities in other ecore models.

Example

Let's say you want to write a tool that reads DDL information from a database and generates an EClass for each table that holds a collection of row objects with an EStructuralFeature for each column. Let's say you also have a separate ecore model that you have created by hand that contains two EClasses called "AbstractTable" and "AbstractRow" that you want your generated EClass to reference as an eSuperType.

So if you have a table called "Customers" that has columns "id", "firstName" and "lastName", you want to create an ecore model like this:

If you created the model by hand in the Ecore editor, it would look like this:

So how would we generate this file?

Solution

The code is below. Here are important notes:

In the initStandalone() we initialize the registry that will be relied on internally by EMF. See the EMF FAQ for more information on this. This will also give you other important setup steps like what's needed on the classpath.

In generate() it is tempting to use DDLPackage.eINSTANCE to get the ddl package instead of createAndLoadDDLResource, but DON'T DO IT. If you do, then when you save the new package, references to AbstractTable and AbstractRow will be serialized using the nsUri of DDLPackage instead of a path to the ecore file relative to your new file. This will cause the Ecore editor to not be able to load your new ecore file unless DDLPackage is already available in plugin form installed in Eclipse. Notice that it is safe to use EcorePackage.eINSTANCE since it always available via plugin registration in Eclipse (you could load it into the package manually if you need to use the model from a stand-alone program).

Also, very important are the two paths that you pass as arguments to main. Note that these get passed to URI.createFileURI to set the uri on the appropriate resources. This is important because when you save your new package, these two uri's will be used to figure how to reference your external ddl.ecore file (the one that declares AbstractTable and AbstractRow). So, for example, if you pass in the arguments:

C:\folder\ddl.ecore C:\folder\newmodels\customers.ecore

When the eSuperTypes reference is serialized in your customers.ecore file, it will reference it like this:

eSuperTypes="../ddl.ecore#//AbstractRow"

Note that this means that if you open customers.ecore in the Eclipse Ecore editor, then ddl.ecore must be in the directory above where you put customers.ecore.

Finally, notice that the save executes to System.out rather than to the outputPath passed in. You could change this if you want. Leaving it like it is allows you to inspect the output before overwriting your file. As implemented, you can simply create a new empty text file in the location you specified for pathToOutputFile and paste the output into it.

Here's the original discussion thread with Ed Merks that spurred this recipe: [1].

Recipe: Generating enumeration-based attributes that support null

Problem

You want an attribute whose type is an enumeration and you want it to support null, but EMF treats enumerations like primitives that always take on a default value, i.e., the first enumerator of the enumeration.

Solution

In your Ecore model:

Create a new EDataType and name it <Name>Object, where <Name> is the name of the EEnum for which you want to support null values.

Set the instance type name to "org.eclipse.emf.common.util.Enumerator"; the generator will replace that with the fully qualified name of the Java enum generated from the EEnum.

Use the Properties view (accessible from the context menu or by double-clicking the annotation) to change the "Source" property of the annotation, using the drop-down selector for that property in the properties view, to the value "http://www.eclipse.org/emf/2002/Ecore".

The Properties view will now show the specialized properties available for Ecore annotations of an EPackage; use that to modify the Conversion Delegates property to include the value "http:///org/eclipse/emf/ecore/util/DateConversionDelegate" (available as a choice in the feature dialog editor).

You can now use this annotation source for specify date conversion delegates for data types in your package.

Create a new EDataType:

Set the name to whatever you like.

Set the instance type name to long, java.lang.Long, java.util.Date, java.sql.Date, java.util.Calendar, java.util.GregorianCalendar, or javax.xml.datatype.XMLGregorianCalendar; this is the Java representation used for your date type.

and use the Format property to define your serialization format, choosing in the combo from among the proposed sample formatting URIs that are illustrative of what you can specify.

Use this new EDataType as the eType of any EAttribute.

You can use //LONG to serialize the value represented as an instant-in time, i.e., the numerical representation of the equivalent long value.

You can use //SimpleDateFormat/<simple-date-form-pattern> to specify any java.text.SimpleDateFormat pattern. If the representation you choose is locale-specific, you should specify the local, e.g., //SimpleDateFormat/<simple-date-format-pattern/<language>/<country>/<variant>.

You can use //DateFormat/<date-style>, //DateTimeFormat/<date-style>/<time-style>, //TimeFormat/<time-style> to choose the locale-specific java.util.DateFormat. In this case you must specify a locale, e.g., //DateTimeFormat/<date-style>/<time-style>/<language>/<country>/<variant> because these formats are always locale-specific.

Finally, if you specify the type java.util.Calendar, you may specify the calendar type in the query string, e.g., //DateFormat/LONG/ja/JP/JP?japanese.

The <date-style> and <time-style> may each be either FULL, LONG, MEDIUM, or SHORT.

The <language> is a two letter ISO language code, e.g., en. The <country> is a two letter ISO country code, e.g., US. The <variant> is optional because the locale for a /<language>/<country> may not provide variants. It is important that you specify the locale for locale-specific serializations to ensure that no matter in which locale a value is formatted, it will be parsed using the locale with which it was originally formatted.

This recipe works even on dynamic models because conversion delegates are supported directly in the core runtime, i.e., no specialized code will be generated for this recipe because EFactoryImpl provides the support direclty.

Notification Framework Recipes

Recipe: Use EContentAdapter to receive notifications from a whole containment tree

Problem

You want to observe changes in a whole containment tree.

Solution

Extend org.eclipse.emf.ecore.util.EContentAdapter (MyContentAdapter) and add that extension as an Adapter to the Root EObject of the containment hierarchy that you want to observe.

Override the method 'notifyChanged(Notification n)'. Inside the method´s body your first call must be super.notifyChanged(n) which adds MyContentAdapter to any new elements in the hierarchy and removes MyContentAdapter from any removed EObjects in the hierarchy. After finding out the type of the notifier Object (Remember: this might now be any EObject in the containment hierarchy, not just the EObject you initially added MyContentAdapter to - so it could be of any type that occurs in the containment hierarchy) you can go on by writing the usual notification code to find out about what feature changed, the type of the notification, etc.

Example

A simple example model org.example.library consists of an EClass 'Library' which has a containment reference 'books' of type 'Book'. The EClass 'Book' has a String attribute 'title' and a boolean attribute 'available'. Now you want to be notified about a) new Books in the Library and b) about changes of any book´s availability (the title of a book usually won´t change so we exclude this feature). Using the Solution described above we will do the following:

Recipe: Derived Attribute Notifier

Problem

If you have a derived attribute in EMF and change one of the attributes that the derived value depends on, then no notification will be sent for the derived attribute - so it will not change in any editor etc. You have to write these yourself.

Solution

Here's a class provided by pvmellor. You can specify your derived attribute, and also which other attributes it depends on. Listeners are then added as appropriate and when any of your dependant attributes change, you'll fire an event for your derived attribute.

Example

E.g. You have a Class Library and a set of Books in it. Each Book has a pageCount attribute. The Library has a derived attribute totalPageCount that adds up all the pages of all the books. Then you can just write...

When this code was posted to the EMF newsgroup, this comment was made: "Here's a class I wrote that I've found useful and perhaps it may be useful to others" . I take this is meaning this code has been given to the public domain.

Properties Recipes

Recipe: Create your own property editor in a generated application

Problem

You want to edit your model properties using your own cell editor, rather than using EMF default one.

Solution

Create your own CustomizedPropertyDescritor that extends 'org.eclipse.emf.edit.ui.provider.PropertyDescriptor' and overrides 'CellEditor createPropertyEditor(Composite)'. In that method create your own CellEditor. Please refer to super implementation to know, how to enable your editor for particular types.

Create your CustomizedPropertySource that extends 'org.eclipse.emf.edit.ui.provider.PropertySource.class' and overrides 'IPropertyDescriptor createPropertyDescriptor(IItemPropertyDescriptor)'. The overidden method should return CustomizedPropertyDescriptor described in the previous paragraph.

Recipe: Create a property editor factory to use declaratively in any model

Problem

You want to edit your model properties using your own cell editor, rather than using EMF default one, but you want that to work in all model editors, including reflective editors, without having to specialize each and every one.

Solution

Create your own IPropertyEditorFactory implementation.

Register it in your plugin.xml.

Use it in on any GenDataType's Property Editor Factory or any GenFeature's Property Editor Factory, either in the Generator editor, or as GenModel annotations in your Ecore model in the Sample Ecore Editor.

The example below shows data types that use each of the supported instance types and are annotated directly in the Ecore model with GenModel annotations. The DateExample class has a corresponding attribute for each of the data types. Because each property editor factory is specified directly as an annotation in the Ecore model, they work even in the reflective editor. The example below shows a dynamic instance of DateExample selected to display its properties, and the cell editor activated for one of the properties.

* ComposedAdapterFactory : this adapts all the ItemProvider stuff from the EMF-generated .edit plugin to suit your needs
* AdapterFactoryEditingDomain : this is the read/write interface to your model's resource, it needs the adapter factory and a command stack
* AdapterFactoryItemDelegator : delegates from a model element (item) to the respective item provider from the .edit plugin
* AdapterFactoryLabelProvider : gets text for your model elements by asking the item provider
* BasicCommandStack : well...a basic command stack with some undo/redo support

To start implementing, open the default multi-page editor generated by EMF from your model. You need to merge parts of this into the forms editor, among them:

* resource management code (changed, saved and removed resources as well as the resourceChangeListener and partListener)
* editor state management code (isDirty() and all save-related methods)
* methods which handle events related to the above mentioned stuff
* the 3 methods documented below

initializeEditingDomain() : This method glues most of the above-mentioned components together. Call it in the editor's constructor. The XYZItemProviderAdapterFactory (generated by EMF in the .edit plugin) should already be added to the ComposedAdapterFactory (if not, add in the one you need).

createModel() : This loads your model's resource into the editing domain. If you don't need the diagnostic stuff you may skip that as I did. After the resource is loaded, your model instance can be created and used.

Create a new class extending FormPage and overload the constructor to give the class access to all components you need. This may be the model or parts of it, references to the form editor, the editing domain etc.

Implement the createFormContent(IManagedForm managedForm) method of the form page by creating form widgets as you like. For instance, you may traverse your model and create a text field for every property.

To fetch an element's property, instruct the above-mentioned ItemDelegator to fetch so-called "property descriptors" for this element. Just iterate over this list of IItemPropertyDescriptor's ("descriptor" is the loop variable here, it has to be final) and call

Now you may introspect this feature instance and decide what widget you want to create for it.
By looking at it's feature ID, you can discover which property the feature represents.
The actual property value you get by calling the ItemDelegator (I wrote a getter in my editor class):

That's basically it. Your mileage may vary. Things left to do include code to update the form upon resource changes.

Explanations

The important concept to grasp is that you interact with your model in a very indirect way. To utilize all the nice things the EMF framework offers out-of-the-box, you have to use its mechanics. I'm referring to the generated XYZItemProvider classes and the accompanying adapter factory. If you look at these you find they implement the interfaces IItemPropertySource and IItemLabelProvider. This enables the AdapterFactoryItemDelegator and AdapterFactoryLabelProvider to fetch properties and label text for each item, i.e., element of your model. They also implement IEditingDomainItemProvider which enables the AdapterFactoryEditingDomain to delegate command creation to the EMF-generated ItemProviderAdapter (all XYZItemProvider classes extend this).
The line where setPropertyValue is called is the important one - here the magic happens. This call is delegated to the
ItemProvider for the element you used and a SetCommand is created, added to the command stack we setup for our editing
domain, and executed. All editor state management like mark dirty, save, undo/redo is handled for you by EMF.

Credit

Most of the code was written by Eclipse EMF and Forms people, I just merged it to get a basic forms editor working. There may be easier and/or cleaner ways to get this done. I encourage you to add to this recipe or correct me if I got something wrong.

EMF.Edit Recipes

Recipe: Custom Labels

Problem

You want to provide customized text for an object's label in an EMF-generated editor. Further, if the customized text is derived from
other objects and their attributes, you want the label to be updated whenever those attribute values may change.

Solution

Modify the generated ItemProvider.getText() method to compose the value you wish.

If your label's value depends on other objects and their attributes:

Take care to test for null references and values.

Create a class that implements the org.eclipse.emf.edit.provider.INotifyChangedListener interface

An inner class of the target item provider class works well.

In the notifyChanged() method, check whether the notification is for one of the attributes upon which your custom label depends. If it is, then fire a new notification event whose notifier/element is your target object. Take care to prevent the new event from causing infinite recursion, remove the listener before firing the event, and add it back afterwards.

In the target item provider's constructor, create an instance of the above listener and add it to the adapter factory.

Override the dispose() method to remove the listener from the adapter factory.

If your label's value depends on attributes or references in the target object, ensure the notifyChanged() method in the target item provider fires a notification event for these cases. The ViewerNotification for these events need to indicate label updating.

Example

In this example, assume you want to customize the label for an instance of EMF class A. The value is derived from an attribute, name, of another class B that is referenced from A.

The above implementation checks that the modified object is the same instance that the target object references (as opposed to just any instance of B).

The new VewerNotification identifies the instance of A as the changed element, and the true argument signals the change requires a label update.

The removeListener() call prevents infinite recursion from the following fireNotifyChanged(). After the event is fired, the listener is added back to the adapter factory.

The ChangeListener is shared between different A instances, but when it calls getTarget(), he only has the last object the itemProvider were attached
to (and not all instances).
Therefore, if you choose to make the AItemProviderStatefull (by editing the genmodel for the A class : Properties View => Edit => ProviderType => Statefull),
don't add the second part of notifyChanged method (preceded by //other targets). However, if you want to keep the AItemProviderSingleton, this second part is necessary.

Instantiate the listener and add it to the adapter factory in the item provider's constructor:

Note that the last parameter for the ViewerNotification constructor indicates the label is to be updated.

References

None so far.

Credits

Mike Gering created the initial version of this recipe.

XMI/XML Serialization Recipes

Recipe: Data Migration

Problem

You need to migrate models built with prior versions of a metamodel. Some changes to
the metamodel may be handled without additional support, for example adding an EAttribute to an existing EClass
typically causes no migration issue. Other changes require programmatic support, for example renaming an EAttribute.

This recipe may be used to satisfy many, but not all, migration issues. Because this recipe assumes a model can be correctly
parsed as an XMI/XML document, it fails to handle cases where, for example, an EAttribute.ID changes.

The solution is to use extended metadata to map old metamodel elements to new ones, and (optionally) a resource handler to deal with cases that simple mapping doesn't solve.

Requirements:

The source and target models must have different namespace URIs.

XML references must not be based on feature names.

Steps:

Create an ecore2ecore mapping where the input/source is the old metamodel and the output/target is the new metamodel. In the IDE, you can right-click the old ecore file and select the "Map to Ecore..." menu item to launch a wizard.

Create an ecore2xml mapping from the ecore2ecore mapping. In the IDE you can right-click the ecore2ecore file created above and select the "Generate Ecore to XML Mapping..." menu item.

Create a ResourceFactory implementation (if you don't already have one) for your metamodel.

Extend org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl

Override createResource(URI)

Create an instance of XMIResource

Set the XMLResource.OPTION_EXTENDED_META_DATA on the load options. For the value of this option, pass a lazily-initialized reference to the ecore2xml model.

Set the XMLResource.OPTION_RECORD_UNKNOWN_FEATURE option to Boolean.TRUE so you can retrieve elements that were not resolved after the resource is loaded.

Set the XMLResource.OPTION_RESOURCE_HANDLER option to a resource handler class you provide.

Implement a ResourceHandler:

Subclass org.eclipse.emf.ecore.xmi.impl.BasicResourceHandler

Override the postLoad() method to retrieve and handle the unknown/unresolved elements

In the above fragment, several constants refer to old metamodel namespace URI and URIs for the new metamodel ecore file and ecore2xml file. Note that the "platform:/plugin/..." form indicates the ecore and ecore2xml files will be loaded from within the deployed plugin.

The extendedMetaData field will be lazily-initialized once and reused for creating new resource instances.

This is an example of a resource handler implementation. It overrides the postLoad() method to handle the unknown features. Unless you want the unknown features to be written back to the model when it is saved, you need to remove the ones you handle from the feature map.

Recipe: Using EMF for SOAP / Compatibility between EMF XML and Axis or JAX XML

Problem

You need build a SOAP service and you want to use EMF. Unfortunately, the XML generated by EMF vs the XML Generated by Axis/JAX don't seem to be compatible.

Solution

EMF defaults to working with complexTypes. Axis/JAX default to working with elements that are instances of those complex types. All you need to do is tell EMF that you want to use elements and everything works fine.

Requirements:*

None

Steps:*

The most important thing is to understand the difference between a complex type declaration and a global element declaration in XSD.

Basically the problem is that soap wants globally declared elements where EMF simply wants complexType definitions. I think of this as SOAP using 'instances' of types where as EMF usually works just with the 'types'.

Fortunately, EMF is brilliant and can work with the globally declared elements that SOAP needs. You just have to tell it what you want to do. Here's an example:

This declares that MathCalculateRequestTag is an instance of MathCalculateRequest (the type). SOAP and Axis can work with MathCalculateRequestTag and have no trouble at all.

Elements like this are manipulated using a DocumentRootImpl java object that will get generated along with your model. Here's how your code will change.

BTW, we wrap all of our EMF conversion code in a utility called SoapUtil.convertEMFtoString() and convertStringtoEMF(). I assume you have a similar conversion method. This technique does NOT change those methods. However it does change what is returned as you can see here:

All you have to do is use DocumentRootImpl and all your SOAP compatibility problems will go away.
If you read the XSD specs it makes sense why SOAP and EMF work the ways that they do. You just need to use the DocumentRoot as a bridge. Be aware that you need the DocumentRoot in both directions. For example both converEMFtoString() and convertStringToEMF() will take/return a DocumentRoot. Alternately you might have convertEMFtoDOM() and convertDOMtoEMF() depending on if you're using strings or DOM nodes.

NB: You must set the extended meta data option while loading the EMF resource. This will cause EMF to create a DocumentRoot instance and de-serialize the XML instance returned by the SOAP service as one of the DocumentRoot features (the feature which corresponds to the root element of the XML instance). If you don't set this option, EMF will try to load a class with the same name as the root element of the XML instance-- a class that most likely does not exist in your model. Here's how the resource load command can be implemented.

EMF is FANTASTIC for doing SOAP/SOA work. The models generated are far better than what you get with the other tooling plus it handles references which can *dramatically* reduce the size of your XML payload. With the ability to do diffs and change-tracking EMF becomes a huge win for SOAP.

Suggested Reading:*

XSD not the same as other languages, but a surprising number of SOAP developers have only a cursory understanding of XSD. This link provides an extremely thorough and comprehensible tour of XSD.