Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.

Jump to: navigation, search

Difference between revisions of "EMF/Recipes"

< EMF
m (Recipe: Subclass EContentAdapter to receive notifications across non-containment references)
(XMI/XML Serialization Recipes)
Line 1,021: Line 1,021:
 
'''Credits'''
 
'''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
 
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:
 +
 +
<code><pre>
 +
// Pre-Element tag XML to EMF conversion:
 +
// input holds a <MathCalculateRequest>
 +
MathCalculateRequest foo = (MathCalculateRequest)util.convertStringToEMF(input);
 +
</pre></code>
 +
 +
<code><pre>
 +
// Post-Element tag XML to EMF conversion:
 +
// input holds a <MathCalculateRequestTag>
 +
DocumentRoot docRoot = (DocumentRoot)util.convertStringToEMF(input);
 +
MathCalculateRequest docRoot = dt.getMathCalculateRequestTag();
 +
</pre></code>
 +
 +
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.
 +
 +
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 databinding Recipes==
 
==EMF databinding Recipes==

Revision as of 13:42, 24 May 2008

This topic gathers recipe-style solutions for common needs developers using EMF have.

Code generation recipes

Recipe: Exploiting Substitution Groups Without Polluting Your Generated API

Problem

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

 folder.getMembersGroup().add(ResourcePackage.Literals.DOCUMENT_ROOT__FILE, file);

in order to add a "File" to the list of members.

Solution

Use ecore:suppressSubstitutionGroups="true" in your schema.

 <?xml version="1.0" encoding="UTF-8"?>
 <xsd:schema 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
     xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" 
     xmlns:resource="http://www.example.com/resource" 
     ecore:ignoreSubstitutionGroups="true" 
     targetNamespace="http://www.example.com/resource">
 
   <xsd:element name="fileSystem" type="resource:FileSystem"/>
   <xsd:complexType name="FileSystem">
     <xsd:sequence>
       <xsd:element ref="resource:folder" ecore:name="folders" maxOccurs="unbounded"/>
     </xsd:sequence>
   </xsd:complexType>
 
   <xsd:element name="member" ecore:name="members" type="resource:Resource" abstract="true"/>
   <xsd:complexType name="Resource" abstract="true">
     <xsd:attribute name="name" type="xsd:string"/>
   </xsd:complexType>
 
   <xsd:element name="folder" substitutionGroup="resource:member" type="resource:Folder"/>
   <xsd:complexType name="Folder">
     <xsd:complexContent>
       <xsd:extension base="resource:Resource">
         <xsd:sequence>
           <xsd:element ref="resource:member" ecore:name="members" maxOccurs="unbounded"/>
         </xsd:sequence>
       </xsd:extension>
     </xsd:complexContent>
   </xsd:complexType>
 
   <xsd:element name="file" substitutionGroup="resource:member" type="resource:File"/>
   <xsd:complexType name="File">
     <xsd:complexContent>
       <xsd:extension base="resource:Resource">
         <xsd:sequence>
         </xsd:sequence>
       </xsd:extension>
     </xsd:complexContent>
   </xsd:complexType>
 
 </xsd:schema>

Generate as normal and modify the generated resource factory to use the XMLResource.OPTION_ELEMENT_HANDLER option:

 /**
  * Creates an instance of the resource.
  * 
  * 
  * @generated NOT
  */
 @Override
 public Resource createResource(URI uri)
 {
   //...
   
   result.getDefaultSaveOptions().put(XMLResource.OPTION_ELEMENT_HANDLER, new ElementHandlerImpl(false));
   
   result.getDefaultLoadOptions().put(XMLResource.OPTION_SUPPRESS_DOCUMENT_ROOT, Boolean.TRUE);
   return result;
 }

In the generated ResourceExample.java in the com.example.resources.tests project you can now write code like this:

 Resource resource = resourceSet.createResource(URI.createURI("http:///My.resource"));
 FileSystem fileSystem = ResourceFactory.eINSTANCE.createFileSystem();
 Folder folder1 = ResourceFactory.eINSTANCE.createFolder();
 fileSystem.getFolders().add(folder1);
 folder1.setName("folder1");
 com.example.resource.File file1 = ResourceFactory.eINSTANCE.createFile();
 file1.setName("file1");
 folder1.getMembers().add(file1);
 resource.getContents().add(fileSystem);
 resource.save(System.out, null);
 ByteArrayOutputStream out = new ByteArrayOutputStream();
 resource.save(out, null);
 Resource resource2 = resourceSet.createResource(URI.createURI("http:///My2.resource"));
 resource2.load(new ByteArrayInputStream(out.toByteArray()), null);
 FileSystem loadedFileSystem = (FileSystem)resource2.getContents().get(0);
 resource2.save(System.err, null);

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:

 <?xml version="1.0" encoding="ASCII"?>
 <resource:fileSystem xmlns:resource="http://www.example.com/resource">
   <resource:folder name="folder1">
     <resource:file name="file1"/>
   </resource:folder>
 </resource:fileSystem>

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.

References



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:
<extension point="org.eclipse.emf.ecore.generated_package">
  <package
     uri = "mm.B"
     class = "mm.APackage"
</extension>
<extension point="org.eclipse.emf.ecore.generated_package">
  <package
     uri = "mm.A"
     class = "mm.APackage"
     genModel = "model/A.genmodel" />
</extension>
  • 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).

References

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:

class MyContentAdapter extends org.eclipse.emf.ecore.util.EContentAdapter {

    // start observing a Library model
    public void observeLibrary(org.example.library.Library l){
        l.eAdapters().add(this);
    }

    //override the notifyChanged method
    public void notifyChanged(Notification n){
        
        super.notifyChanged(n); // the superclass handles adding/removing this Adapter to new Books
        
        // find out the type of the notifier which could be either 'Book' or 'Library'
        Object notifier = n.getNotifier();
        if (notifier instanceof Library) {
            handleLibraryNotification(n);
        } else if (notifier instanceof Book) {
            handleBookNotification(n);
        }
    }

    // output a message about new books
    private void handleLibraryNotification(Notification n){
        int featureID = n.getFeatureID(org.example.library.Library.class);
        if (featureID == org.example.library.LibraryPackage.LIBRARY__BOOKS){
            if (n.getEventType() == Notification.ADD){
                Book b = (Book) n.getNewValue(); 
                System.out.println("New Book was added to the Library: + " b.getTitle());
            }
        }
    }

    // output a message about a book´s availability
    private void handleBookNotification(Notification n){
        int featureID = n.getFeatureID(org.example.library.Book.class);
        if (featureID == org.example.library.LibraryPackage.BOOK__AVAILABLE){
                Book b = (Book) n.getNotifier();
                System.out.println("The book " + b.getTitle() + " is now " + (b.isAvailable() ? "available" : "unavailable"));
        }
    }
}

References

  • Thread on the EMF newsgroup: "[1]"

Recipe: Subclass EContentAdapter to receive notifications across non-containment references

Problem

You want to observe changes in a whole containment tree, including ones across non-containment references.

Solution

  • Use the following subclass (or variation of it) to follow non-containment references
public class CrossDocumentContentAdapter extends EContentAdapter
{
    public CrossDocumentContentAdapter()
    {
        super();
    }

    /**
     * By default, all cross document references are followed. Usually this is
     * not a great idea so this class can be subclassed to customize.
     * 
     * @param feature
     *      a cross document reference
     * @return whether the adapter should follow it
     */
    protected boolean shouldAdapt(EStructuralFeature feature)
    {
        return true;
    }

    @Override
    protected void setTarget(EObject target)
    {
        super.setTarget(target);
        for (EContentsEList.FeatureIterator<EObject> featureIterator = (EContentsEList.FeatureIterator<EObject>) target.eCrossReferences()
                                                                                                                       .iterator(); featureIterator.hasNext();)
        {
            Notifier notifier = featureIterator.next();
            EStructuralFeature feature = featureIterator.feature();
            if (shouldAdapt(feature))
            {
                addAdapter(notifier);
            }
        }
    }

    @Override
    protected void unsetTarget(EObject target)
    {
        super.unsetTarget(target);
        for (EContentsEList.FeatureIterator<EObject> featureIterator = (EContentsEList.FeatureIterator<EObject>) target.eCrossReferences()
                                                                                                                       .iterator(); featureIterator.hasNext();)
        {
            Notifier notifier = featureIterator.next();
            EStructuralFeature feature = featureIterator.feature();
            if (shouldAdapt(feature))
            {
                removeAdapter(notifier);
            }
        }
    }

    @Override
    protected void selfAdapt(Notification notification)
    {
        super.selfAdapt(notification);
        if (notification.getNotifier() instanceof EObject)
        {
            Object feature = notification.getFeature();
            if (feature instanceof EReference)
            {
                EReference eReference = (EReference) feature;
                if (!eReference.isContainment() && shouldAdapt(eReference))
                {
                    handleContainment(notification);
                }
            }
        }
    }

}

Example

None.

References

  • Thread on the EMF newsgroup: "[2]"

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 CustomizePropertyDescriptor described in the previous paragraph.
  • Create your CustomizedAdapterFactoryContentProvider that extends 'org.eclipse.emf.edit.ui.provider.AdapterFactoryContentProvider' and overrides 'IPropertySource createPropertySource(Object, IItemPropertySource)' method. The overidden method should return CustomizedPropertySource.
  • In your generated .editor find the XyzEditor, and then, in 'IPropertySheetPage getPropertySheetPage()' replace the line

propertySheetPage.setPropertySourceProvider(new AdapterFactoryContentProvider(adapterFactory)); with a line that will set your CustomizedAdapterFactoryContentProvider.

Example

  /**
   * This accesses a cached version of the property sheet.
   * <!-- begin-user-doc -->
   * <!-- end-user-doc -->
   * @generated NOT
   */
  public IPropertySheetPage getPropertySheetPage()
  {
    if (propertySheetPage == null)
    {
      //...

      propertySheetPage.setPropertySourceProvider
        (new AdapterFactoryContentProvider(adapterFactory)
         {
           @Override
           protected IPropertySource createPropertySource(Object object, IItemPropertySource itemPropertySource)
           {
             return 
               new PropertySource(object, itemPropertySource)
               {
                 @Override
                 protected IPropertyDescriptor createPropertyDescriptor(IItemPropertyDescriptor itemPropertyDescriptor)
                 {
                   return 
                     new PropertyDescriptor(object, itemPropertyDescriptor)
                     {
                       @Override
                       public CellEditor createPropertyEditor(Composite composite)
                       {
                         // Test for your case based on the feature or the type of the feature.
                         // See the super method for details.
                         //
                         Object feature = temPropertyDescriptor.getFeature(this.object);
                         return super.createPropertyEditor(composite);
                       }
                     };
                 }
               };
           }
         });
    }

    return propertySheetPage;
  }

References

  • Thread on the search result: [3]
  • Blog on using Date control: [4]


Recipe: Create an Eclipse Forms editor with widgets for your properties

Problem

You want to edit your model properties using a custom non-tree-based forms editor, rather than using EMF default one.

Solution

  • You need the following components to get this working:
* 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).
	protected void initializeEditingDomain() {
		// Create an adapter factory that yields item providers.
		// For this to work this plugin needs the dependency on the 
		// EMF edit plugin generated from the ThetaML .ecore and .genmodel
		this.adapterFactory = new ComposedAdapterFactory(
				ComposedAdapterFactory.Descriptor.Registry.INSTANCE);

		this.adapterFactory
				.addAdapterFactory(new ResourceItemProviderAdapterFactory());
		this.adapterFactory
				.addAdapterFactory(new ThetamlItemProviderAdapterFactory());
		this.adapterFactory
				.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());

		// command stack that will notify this editor as commands are executed
		BasicCommandStack commandStack = new BasicCommandStack();

		// Add a listener to set the editor dirty of commands have been executed
		commandStack.addCommandStackListener(new CommandStackListener() {
			public void commandStackChanged(final EventObject event) {
				getContainer().getDisplay().asyncExec(new Runnable() {
					public void run() {
						editorDirtyStateChanged();
					}
				});
			}
		});

		// Create the editing domain with our adapterFactory and command stack.
		this.editingDomain = new AdapterFactoryEditingDomain(adapterFactory,
				commandStack, new HashMap<Resource, Boolean>());
		
		// These provide access to the model items, their property source and label
		this.itemDelegator = new AdapterFactoryItemDelegator(adapterFactory);
		this.labelProvider = new AdapterFactoryLabelProvider(adapterFactory);
	}
  • init() : Editor initialization comprises registering for part and resource events and creation of your model (see below).
	public void init(IEditorSite site, IEditorInput editorInput)
			throws PartInitException {
		super.init(site, editorInput);
		setPartName(editorInput.getName());
		site.getPage().addPartListener(partListener);
		createModel();
		ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceChangeListener,
				IResourceChangeEvent.POST_CHANGE);
	}
  • 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.
	public void createModel() {
	
		URI resourceURI = EditUIUtil.getURI(getEditorInput());
		Resource resource = null;
		try {
			// Load the resource through the editing domain.
			//
			resource = editingDomain.getResourceSet().getResource(resourceURI,
					true);
		} catch (Exception e) {
			resource = editingDomain.getResourceSet().getResource(resourceURI,
					false);
		}

		if (resource != null) {
			this.modelRoot = (Your_Model_Root_Element) resource.getContents().get(0);
		}
	}
  • 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
EObject feature = (EObject) descriptor.getFeature(your_element_instance);

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

Object value = ((EObject) editor.getItemDelegator().getEditableValue(your_element_instance)).eGet(your_feature_instance)

In most cases it will be a String value, so you just have to create a text field for it:

Text text = toolkit.createText(client, valueString, SWT.SINGLE);
  • To update your model when the user modifies the value in the form, you have to add a mofifyListener to handle this:
	if (value instanceof String) {
		text.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent event) {
				for (IItemPropertyDescriptor descriptor2 : variablePropertyDescriptors) {
					if (descriptor2.getId(formula).equals(descriptor.getId(formula))) {
						String newValueText = ((Text) event.widget).getText();
						descriptor2.setPropertyValue(formula, newValueText);
					}
				}
			}
		});
	}

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.

References

  • Article on Eclipse Forms: [5]
  • Example for a generic EMF Eclipse Forms editor : [6]
  • EMF.Edit framework overview : [7]

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.

Modify the getText() method in A's item provider:

public class AItemProvider
	extends OperandItemProvider
	implements	
		IEditingDomainItemProvider,	
		IStructuredItemContentProvider,	
		ITreeItemContentProvider,	
		IItemLabelProvider,	
		IItemPropertySource {

...
	/**
	 * This returns the label text for the adapted class.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated NOT
	 */
	public String getText(Object object) {
		A aObj = (A) object;
		String ref = aObj.getB() == null ? "???" : aObj.getB().getName();
		ref = ref == null ? "???" : ref;
		return getString("_UI_A_type")+" -> "+ref; //$NON-NLS-1$
	}

Create an inner class to listen for change modifications:

	class ChangeListener implements INotifyChangedListener {
		public void notifyChanged(Notification notification) {
			
			if(notification.getNotifier() != null &&  getTarget() != null && notification.getNotifier() == ((A) getTarget()).getB()) {
				((IChangeNotifier) getAdapterFactory()).removeListener(this);
				fireNotifyChanged(new ViewerNotification(notification, getTarget(), false, true));
				((IChangeNotifier) getAdapterFactory()).addListener(this);
			}
		}
	}

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.

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

public class AItemProvider
	extends OperandItemProvider
	implements	
		IEditingDomainItemProvider,	
		IStructuredItemContentProvider,	
		ITreeItemContentProvider,	
		IItemLabelProvider,	
		IItemPropertySource {

	private ChangeListener changeListener;

	/**
	 * This constructs an instance from a factory and a notifier.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated NOT
	 */
	public AItemProvider(AdapterFactory adapterFactory) {
		super(adapterFactory);
		if(adapterFactory instanceof IChangeNotifier) {
			IChangeNotifier cn = (IChangeNotifier) adapterFactory;
			changeListener = new ChangeListener();
			cn.addListener(changeListener);
		}
	}
...
}

Override the dispose() method:

public class AItemProvider
	extends OperandItemProvider
	implements	
		IEditingDomainItemProvider,	
		IStructuredItemContentProvider,	
		ITreeItemContentProvider,	
		IItemLabelProvider,	
		IItemPropertySource {
...
	/* (non-Javadoc)
	 * @see org.eclipse.emf.edit.provider.ItemProviderAdapter#dispose()
	 */
	public void dispose() {
		super.dispose();
		if(changeListener != null) {
			((IChangeNotifier)getAdapterFactory()).removeListener(changeListener);
		}
	}
...
}

Modify the target object's item provider notifyChanged() to fire a change event when the reference to B changes:

	/**
	 * This handles model notifications by calling {@link #updateChildren} to update any cached
	 * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated NOT
	 */
	public void notifyChanged(Notification notification) {
		updateChildren(notification);
		switch (notification.getFeatureID(A.class)) {
		case FooPackage.A__B:
			fireNotifyChanged(new ViewerNotification(notification, notification
					.getNotifier(), false, true));
			return;
		}
		super.notifyChanged(notification);
	}

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.

Solution

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
  • Create a URI Extension Parser Registry extension (org.eclipse.emf.ecore.extension_parser) in your plugin manifest.
  • Package the old metamodel ecore and ecore2xml files with your plugin.

Example

The following illustrates an example ResourceFactory implementation. The old metamodel namespace URI is "http://www.ibm.com/vce/1.0.0/rules", and the new one is "http://www.ibm.com/vce/1.0.1/rules".

public class RulesResourceFactoryImpl extends XMIResourceFactoryImpl {

	public static final String RULES_100_NS_URI = "http://www.ibm.com/vce/1.0.0/rules";
	public static final String RULES_PLATFORM_URI = "platform:/plugin/com.ibm.myplugin/model/Rules.ecore";
	public static final String RULES_100_PLATFORM_URI = "platform:/plugin/com.ibm.myplugin/model/Rules100_2_Rules.ecore2xml";

	private ExtendedMetaData extendedMetaData;
	...
}

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.

	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;
	}

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

	private ExtendedMetaData getExtendedMetaData() {
		if(extendedMetaData == null) {
			ResourceSet resourceSet = new ResourceSetImpl();
			EPackage.Registry ePackageRegistry = resourceSet.getPackageRegistry();
			ePackageRegistry.put(RULES_100_NS_URI, RulesPackage.eINSTANCE);
			ePackageRegistry.put(RULES_PLATFORM_URI, RulesPackage.eINSTANCE);
			resourceSet.setPackageRegistry(ePackageRegistry);
			Ecore2XMLRegistry ecore2xmlRegistry = new Ecore2XMLRegistryImpl(Ecore2XMLRegistry.INSTANCE);
			ecore2xmlRegistry.put(RULES_100_NS_URI,
					EcoreUtil.getObjectByType(
							resourceSet.getResource(URI.createURI(RULES_100_PLATFORM_URI), 
									true).getContents(),
									Ecore2XMLPackage.Literals.XML_MAP));
			extendedMetaData = new Ecore2XMLExtendedMetaData(EPackage.Registry.INSTANCE, ecore2xmlRegistry);			
		}
		return extendedMetaData;
	}

The extended metadata is initialzed once for the factory.

	class RulesResourceHandler extends BasicResourceHandler {

		public void postLoad(XMLResource resource, InputStream inputStream, Map options) {
			final Map extMap = resource.getEObjectToExtensionMap();
			for(Iterator itr = extMap.keySet().iterator(); itr.hasNext();) {
				EObject key = (EObject) itr.next();
				AnyType value = (AnyType) extMap.get(key);
				handleUnknownData(key, value);
			}
		}

		private void handleUnknownData(EObject eObj, AnyType unknownData) {
			handleUnknownFeatures(eObj, unknownData.getMixed());
			handleUnknownFeatures(eObj, unknownData.getAnyAttribute());
		}

		private void handleUnknownFeatures(EObject owner, FeatureMap featureMap) {
			for (Iterator iter = featureMap.iterator(); iter.hasNext();) {
				FeatureMap.Entry entry = (FeatureMap.Entry) iter.next();
				EStructuralFeature f = entry.getEStructuralFeature();
				if(handleUnknownFeature(owner, f, entry.getValue())) {
					iter.remove();
				}
			}
		}
		...
	}

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.

  <extension
        point="org.eclipse.emf.ecore.extension_parser">
     <parser
           class="com.ibm.adt.vce.rules.model.resource.RulesResourceFactoryImpl"
           type="rules"/>
  </extension>

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 build in encryption

Requirements:

  • None

Steps:

  • Create your own factor 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.


package mymodel;
import org.eclipse.emf.ecore.EObject;
/**
 * @model
 */

public interface IPerson extends EObject {
	/**
	 * @model default="";
	 */
	public String getLastname();
}

Create the following factory which sets the option for encryption.

	
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;
	}
}


Create the following test class.

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();
	}
}

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:

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

This is enough for EMF, but not enough for compatibility with Axis. For Axis you also need this:

<!-- declared globally inside your schema tag  -->
<!-- after the complexType is defined          -->
  <xsd:element name='MathCalculateRequestTag'
             type='com.vsp.math.model.soap:MathCalculateRequest'/>

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:

// Pre-Element tag XML to EMF conversion:
// input holds a <MathCalculateRequest>
MathCalculateRequest foo = (MathCalculateRequest)util.convertStringToEMF(input);
// Post-Element tag XML to EMF conversion:
// input holds a <MathCalculateRequestTag>
DocumentRoot docRoot = (DocumentRoot)util.convertStringToEMF(input);
MathCalculateRequest docRoot = dt.getMathCalculateRequestTag();

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.

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 databinding Recipes

Recipe: JFace Viewers and 1:n associations

Problem

You need to display the n-side of a 1:n association in a JFace Viewer. The Viewer needs to handle changes to the n-cardinality as well as changes to the n objects themself.

Solution

A combination of EMF's ObservableListContentProvider and the JFace's ObservableMapLabelProvider

Requirements:

EMF 2.4 (currently HEAD because of #216440)

Example

Display the Collection (more precisely an EList) of Addresses a Person object owns (Person#addresses) in a JFace TableViewer. Modifications to the EList as well as Address objects need to be handled.

// The model object which should be shown
Person aPerson = ModelFactory.eINSTANCE.createPerson();
...

// The content provider is responsible to handle add and
// remove notification for the Person#address EList
ObservableListContentProvider provider = new ObservableListContentProvider();
viewer.setContentProvider(provider);

// The label provider in turn handles the addresses
// The EStructuralFeature[] defines which fields get shown
// in the TableViewer columns
IObservableSet knownElements = provider.getKnownElements();
IObservableMap[] observeMaps = EMFObservables.
	observeMaps(knownElements, new EStructuralFeature[] {
	ModelPackage.Literals.PERSON_ADDRESS__STREET,
	ModelPackage.Literals.PERSON_ADDRESS__NUMBER,
	ModelPackage.Literals.PERSON_ADDRESS__ZIP,
	ModelPackage.Literals.PERSON_ADDRESS__COUNTRY);
ObservableMapLabelProvider labelProvider =
	new ObservableMapLabelProvider(observeMaps);
viewer.setLabelProvider(labelProvider);

// Person#addresses is the Viewer's input
viewer.setInput(EMFObservables.observeList(Realm.getDefault(), aPerson,
	ModelPackage.Literals.PERSON_ADDRESSES));

References

  • blog post motivating this recipe: [8]

Back to the top