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

* 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.

* 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.

* 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).

* 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).

−

'''Related recipes'''

+

'''References'''

−

None so far.

+

* Thread on the EMF newsgroup: "[http://dev.eclipse.org/newslists/news.eclipse.tools.emf/msg25933.html multiple namespaces in one editor supported?]"

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:

+

+

[[Image:DDLInEcoreEditor.png]]

+

+

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 [http://wiki.eclipse.org/index.php/EMF-FAQ#How_do_I_use_EMF_in_standalone_applications_.28such_as_an_ordinary_main.29.3F 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.

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.

+

* For that new EDataType

+

** create a contained EAnnotation,

+

** set the source to "http:///org/eclipse/emf/ecore/util/ExtendedMetaData",

+

** and create a Details Entry with key "baseType" and value "<Name>", i.e., the name of the EEnum.

+

* Use this new EDataType in place of the base EEnum for any EAttributes for which you want to allow null.

== Notification Framework Recipes ==

== Notification Framework Recipes ==

Line 217:

Line 428:

// find out the type of the notifier which could be either 'Book' or 'Library'

// find out the type of the notifier which could be either 'Book' or 'Library'

−

Object notifier = Notification.getNotifier();

+

Object notifier = n.getNotifier();

if (notifier instanceof Library) {

if (notifier instanceof Library) {

handleLibraryNotification(n);

handleLibraryNotification(n);

Line 228:

Line 439:

private void handleLibraryNotification(Notification n){

private void handleLibraryNotification(Notification n){

int featureID = n.getFeatureID(org.example.library.Library.class);

int featureID = n.getFeatureID(org.example.library.Library.class);

−

if (featureID = org.example.library.LibraryPackage.LIBRARY__BOOKS){

+

if (featureID == org.example.library.LibraryPackage.LIBRARY__BOOKS){

−

if (n.getType == Notification.ADD){

+

if (n.getEventType() == Notification.ADD){

Book b = (Book) n.getNewValue();

Book b = (Book) n.getNewValue();

System.out.println("New Book was added to the Library: + " b.getTitle());

System.out.println("New Book was added to the Library: + " b.getTitle());

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 ==

== Properties Recipes ==

Line 268:

Line 730:

* 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 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 CustomizePropertyDescriptor described in the previous paragraph.

+

* 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.

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.

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.

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.

+

+

'''Solution 1'''

+

+

See [[Edapt]].

+

+

'''Solution 2'''

+

+

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.

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.

+

+

<code><pre>

+

public Resource createResource(URI uri) {

+

XMIResource resource = (XMIResource) super.createResource(uri);

+

+

Map defaultLoadOptions = resource.getDefaultLoadOptions();

+

defaultLoadOptions.put(XMLResource.OPTION_EXTENDED_META_DATA,

+

getExtendedMetaData());

+

defaultLoadOptions.put(XMLResource.OPTION_RECORD_UNKNOWN_FEATURE,

+

Boolean.TRUE);

+

defaultLoadOptions.put(XMLResource.OPTION_RESOURCE_HANDLER,

+

new RulesResourceHandler());

+

return resource;

+

}

+

</pre></code>

+

This implementation of createResource() works by creating a instanceof XMIResource and setting various load options on it before returning it.

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.

+

+

<code><pre>

+

<extension

+

point="org.eclipse.emf.ecore.extension_parser">

+

<parser

+

class="com.ibm.adt.vce.rules.model.resource.RulesResourceFactoryImpl"

+

type="rules"/>

+

</extension>

+

</pre></code>

+

+

The above plugin extension associates the resource factory with the file extension for our models.

+

+

'''Credits'''

+

+

Kenn Hussey provided the base information for this recipe in a presentation at EclipseCon 2006.

+

Mike Gering contributed the initial version of this recipe.

+

+

===Recipe: Encryption ===

+

+

'''Problem'''

+

+

You need to encrypt your model during read and write

+

+

'''Solution'''

+

+

EMF has built in encryption

+

+

Requirements:

+

+

* None

+

+

Steps:

+

+

* Create your own factory with the encryption properties set

+

* register this factory to your model extension

+

* write and load your model using this factory

+

+

+

'''Example'''

+

+

Create an model based on the following interface.

+

+

+

<code><pre>

+

package mymodel;

+

import org.eclipse.emf.ecore.EObject;

+

/**

+

* @model

+

*/

+

+

public interface IPerson extends EObject {

+

/**

+

* @model default="";

+

*/

+

public String getLastname();

+

}

+

</pre> </code>

+

Create the following factory which sets the option for encryption.

+

+

<code><pre>

+

package factory;

+

import org.eclipse.emf.common.util.URI;

+

import org.eclipse.emf.ecore.resource.Resource;

+

import org.eclipse.emf.ecore.resource.impl.AESCipherImpl;

+

import org.eclipse.emf.ecore.xmi.XMIResource;

+

import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

+

+

public class MyXMIFactoryImpl extends XMIResourceFactoryImpl {

+

@Override

+

public Resource createResource(URI uri) {

+

XMIResourceFactoryImpl resFactory = new XMIResourceFactoryImpl();

+

XMIResource resource = (XMIResource) resFactory.createResource(uri);

+

try {

+

resource.getDefaultLoadOptions().put(Resource.OPTION_CIPHER,

+

new AESCipherImpl("12345"));

+

resource.getDefaultSaveOptions().put(Resource.OPTION_CIPHER,

+

new AESCipherImpl("12345"));

+

} catch (Exception e) {

+

e.printStackTrace();

+

}

+

return resource;

+

}

+

}

+

</pre> </code>

+

+

+

+

Create the following test class.

+

+

<code> <pre>

+

package load;

+

+

import java.io.IOException;

+

import java.util.Collections;

+

import java.util.Map;

+

import mymodel.IPerson;

+

import mymodel.MymodelFactory;

+

import mymodel.impl.MymodelPackageImpl;

+

import org.eclipse.emf.common.util.URI;

+

import org.eclipse.emf.ecore.resource.Resource;

+

import org.eclipse.emf.ecore.resource.ResourceSet;

+

import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;

+

import factory.MyXMIFactoryImpl;

+

+

public class Create {

+

public void create() {

+

MymodelPackage.eINSTANCE.eClass();

+

// Retrieve the default factory singleton

+

MymodelFactory factory = MymodelFactory.eINSTANCE;

+

+

// Create the content of the model via this program

+

IPerson person = factory.createIPerson();

+

+

person.setLastname("Lars");

+

// Register the XMI resource factory for the .website extension

+

Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;

+

Map<String, Object> m = reg.getExtensionToFactoryMap();

+

m.put("person", new MyXMIFactoryImpl());

+

+

// Obtain a new resource set

+

ResourceSet resSet = new ResourceSetImpl();

+

+

// Create a resource

+

Resource resource = resSet.createResource(URI

+

.createURI("mymodel.person"));

+

resource.getContents().add(person);

+

+

// Now save the content.

+

try {

+

resource.save(Collections.EMPTY_MAP);

+

} catch (IOException e) {

+

e.printStackTrace();

+

}

+

}

+

public void load() {

+

// Initialize the model

+

MymodelPackage.eINSTANCE.eClass();

+

// Register the XMI resource factory for the .website extension

+

Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;

+

Map<String, Object> m = reg.getExtensionToFactoryMap();

+

m.put("person", new MyXMIFactoryImpl());

+

ResourceSet resSet = new ResourceSetImpl();

+

Resource resource = resSet.getResource(URI

+

.createURI("mymodel.person"), true);

+

try {

+

IPerson person= (IPerson) resource.getContents().get(0);

+

System.out.println(person.getLastname());

+

} catch (Exception e) {

+

e.printStackTrace();

+

}

+

}

+

+

public static void main(String[] args){

+

Create test = new Create();

+

test.create();

+

test.load();

+

}

+

}

+

+

</pre> </code>

+

+

'''Credits'''

+

Lars Vogel wrote the initial version of this tutorial on http://www.vogella.de/articles/EclipseEMF/article.html#emfencryption and placed it into this wiki

+

+

+

===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:

+

+

Say you have a type such as this:

+

<code> <pre>

+

<xsd:complexType name='MathCalculateRequest' >

+

<xsd:complexContent>

+

<xsd:extension base='com.vsp.ancillary.model.service:BaseRequest'>

+

<xsd:sequence>

+

<xsd:element

+

name='exampleField'

+

type='xsd:string'

+

default='exampleValue'

+

>

+

</xsd:element>

+

</xsd:sequence>

+

</xsd:extension>

+

</xsd:complexContent>

+

</xsd:complexType>

+

</pre></code>

+

This is enough for EMF, but not enough for compatibility with Axis.

+

For Axis you also need this:

+

+

<code> <pre>

+

<!-- declared globally inside your schema tag -->

+

<!-- after the complexType is defined -->

+

<xsd:element name='MathCalculateRequestTag'

+

type='com.vsp.math.model.soap:MathCalculateRequest'/>

+

</pre></code>

+

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.

+

+

<code><pre>

+

Map<String, Object> opts = new HashMap<String, Object>();

+

opts.put(XMLResource.OPTION_EXTENDED_META_DATA, new Boolean(true));//or you could specify an ExtendedMetaData instance

+

Resource resource = ...

+

InputStream is = ...

+

resource.load(is, opts);

+

</pre></code>

+

+

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.

+

http://www.xfront.com/xml-schema.html

+

+

==EMF Reflective API recipes==

+

=== Recipe: Copying models from an EPackage implementation to another one ===

+

+

'''Problem'''

+

You've got two EPackage java implementation and you want to copy a model from one to the other.

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.

and create a Details Entry with key "baseType" and value "<Name>", i.e., the name of the EEnum.

Use this new EDataType in place of the base EEnum for any EAttributes for which you want to allow null.

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.

* 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.

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.