SlideShare a Scribd company logo
Eclipse Modeling Framework – Tips n Tricks
1.Design a Model Provider API

Always invoke the singleton instance of a ModelProvider from anywhere in the
application as a single point contact for managing the lifecycle and behavior of model

      Ø It should contain the corresponding editing domain, file resource, resource set,
      associated editor part, navigator and tabbed propertypage sheet
      Ø It should maintain a single copy of the domain model in the memory.
                    getModel(IResource resource)
      Ø It should maintain the list of cross-references
      Ø It should be a resource-change listener so that
      o            it can un-load the model and delete the emf resource when the file
      resource is deleted
      o            It can modify the resource-uri when the file is moved / renamed
      Ø Whenever the resource uri is changed then using EcoreUtil CrossReferencer
      ModelProvider should find out what all models should be refactored
      Ø ModelProvider should also register all required ItemAdapterFactories
      Ø It should provide the custom persistence policy for the model if needed

2.Item Provider is the single-most powerful feature in EMF. They should be utilized
to the fullest. It provides the functions to

      Ø Implement content and label provider
                   By using mixin interfaces – delegate pattern
                   Public Object[] getchilren(Object object){
                      ITreeItemContentProvider adapter =
                   (ITreeItemContentProvider )
                      adapterFactory.adapt(object, ITreeItemContentProvider .class);
                      return aapter.getChildren(object).toArray();
                   }
      Ø Adapt the model objects to implement whatever interfaces the editors and
      views need.
      Ø Propagate the change-notifications to viewers
      Ø Act as command factory
      Ø Provide a property source for model objects
3. Effective usage of Common Command Fwk

getResult() should be overridden to return relevant model objects so that
(1)        result of one command can be input to another command
(2)        the required diagram element or xml node or language statement or property
section can be selected and highlighted
          getAffectedObjects()

4.WorkingModel – should be reloaded when the resource is modified/deleted
if (workingModelListener == null) {
    workingModelListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
  if (WorkingModel.PROP_DIRTY.equals(evt.getPropertyName())) {

             editorDirtyStateChanged();                     }
else if (WorkingModel.PROP_RELOADED.equals(evt.
                   .getPropertyName())) {
    reloadModel((IFile) getWorkingModel()
                .getEclipseResources().get(0));               }
else if (WorkingModel.PROP_REMOVED.equals.getPropertyName())) {
                Object newLocation = evt.getNewValue();
   if(newLocation == null) {
              cleanupModelCopyOfDeletedResource();
             close(false);                              }
else if (newLocation instanceof IPath) {                        // file is renamed
   IFile newFile = ResourcesPlugin.getWorkspace()
       .getRoot().getFile( (IPath) newLocation);
  if (newFile != null && newFile.exists()) {
               reloadModel(newFile);                      }
  else {
         close(false);                                    }
          }
 else {
        close(false);
 }

5. How to find EMF References ?

private Node findReferingModel(EObject eo) {
 Collection<Setting> referrers = EcoreUtil.UsageCrossReferencer.find(eo,
                                      eo.eResource());
 Iterator<Setting> it = referrers.iterator();
  while (it.hasNext()) {
      Setting referer = (Setting) it.next();
      EObject referredObj = referer.getEObject();
      return referredObj;
}

6. Why Notification Listeners in EMF are also called Adapters ?

A. Apart from observing the changes in eObjects, they also help - extending the
behavior i.e. support additional interfaces without subclassing - (Adapter pattern)

Attaching an Adapter as Observer :

Adapter myEObjectObserver = ...
myEObjectObserver.eAdapters().add(myEObjectObserver);

Attaching an Adapter as a Behaviour Extension :

MyEObject myEObject = ....
AdapterFactory myEObjectAdapterFactory = ....
Object myEObjectType <==
if(myEObjectAdapterFactory.isFactoryType(myEObjectType )){
Adapter myEObjectAdapter =
      myEObjectAdapterFactory.adapt(myEObject, myEObjectType);
.....
}

Attaching an adapter to all the eobjects under the root

So far we have seen how to adapt to the changes to a particular EObject.

Q. Now how to adapt to all the objects in the containment hierarchy, a resource and a set
of related resources :
EContentAdapter - can be attached to a root object, a resource or even a resourseset.

7. What is resource-proxy and on-demand resource loading ?

A. Say PO Entity simply refers to an Item Entity i.e. there is no by-value
aggregation/strong composition i.e. no containment reference between PO and Item
EObjects.

Basically there is a cross-document reference

So in this case there will be one poReource with poURI and an itemResource with
itemURI.
When we call rsourseSet.getReource(poURI) --> the ResourseSet will start traversing
the resource eobject-tree and load all eObjects. But for any references to objects in
itemResource , instead of traversing itemResource the ResourseSet will set the
references to Proxies (* an uninitialized instance of the actual target class * with the
actual URI).

When - po.getItem() - will be invoked, the proxies will be resolved and actual Item
EObjects will be loaded on demand.

8. How to get the objects modified during the last execute() / undo() / redo() ?
>> command.getAffectedObjects()

These objects should be used for selecting/highlighting the viewers

9.Some useful Commands :
>> Moving objects up - down in Viewer : MoveCommand
>> Replacing an object in multiplicity-many features : ReplaceCommand
>> Creating a duplicate object : CopyCommand
>> Create a new object and add it to a feature of EObject : CreateChildCommand
>> Delete an eobject from parent container along with all references : DeleteCommand

10. What is the role of Editing Domain ?

AdapterFactoryEditingDomain -- (i) creates command thru item provider, (ii)
maintaining editor's commandstack, (iii) maintaining resource set

11. Ecore Model Optimization "
>> If a particular reference is always -containment- and can never be cross-document;
then resolveProxies should be set to false

11. How to define a custom data type ?
>> We should not refer a highly complicated Java Class as data type.
>> Instead we should model the Java_Class as EClass and then create an EDtaType
where instanceClass should refer to that EClass.

12. How to maintain in-memory temporary ELists which need not be persisted ?
These model elements should be declared as - volatile, transient, non-changeable and
deived.

public EList getSpecialModelObjects(){
  ArrayList specialModelObjects = new ArrayList();
  for(... getmodelObjects() ... ){

Recommended for you

Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode

Understanding bytecode and what bytecode is likely to be generated by a Java compiler helps the Java programmer in the same way that knowledge of assembler helps the C or C++ programmer. Java bytecode is the form of instructions that Java virtual machine executes. This knowledge is crucial when debugging and doing performance and memory usage tuning. The presenter will share his knowledge on what bytecode means for your platform and how to create compiler while using some awesome tools.

java virtual machinejava fusion 2012sysiq
Akka in-action
Akka in-actionAkka in-action
Akka in-action

Slides from Akka in Action live coding session at Xebicon demonstrating a simple app using Scala, Akka and Spray. Both single node and clustered.

sprayakkascala
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees

ASTs are an incredibly powerful tool for understanding and manipulating JavaScript. We'll explore this topic by looking at examples from ESLint, a pluggable static analysis tool, and Browserify, a client-side module bundler. Through these examples we'll see how ASTs can be great for analyzing and even for modifying your JavaScript. This talk should be interesting to anyone that regularly builds apps in JavaScript either on the client-side or on the server-side.

javascript
if(...){
     specialModelObjects.add();
  }
  }
return new ECoreEList.UnmodifiableEList(this, , specialComposites.siz(),
specialComposites.toArray());
}

13. What to do if you want to create a unique list which should contain elements of
a particular type ?
  Elist locations = new EDataTypeUniqueEList(String.class, this,
EPO2Package.GLOBAL_ADDRESS_LOCTION);

14. How to suppress creation of eobjects ?
Simply clear the GenModel property – “Root Extends Interface” –

15. How to control the command's appearance i.e. decorate the actions ?

The item provider is an IchangeNotifier to support DECORATOR pattern – an
ItemProviderDecorator registers itself as a listener for the Item Provider that it
decorates.
The commands need to implement CommandActionDelegate interface to provide
implementation for retrieving images and labels.

16. How to use custom adapter factories ?
Create a ComposedAdapterFactory and include the item provider for the classes that are
not part of the model along with the regular item provider factories.

17. How to refresh a viewer and set the selection on particular elements ?

editingDomain.getCommandStack().addCommandStackListener( new
CommandStacklistener() {
public void commandStackChanged(final EventObject event) {
             getContainer().getDisplay().asyncExec( new Runnable() {
             public void run() {
             firePropertyChange(IEditorPart.PROP_Dirty);
            Command mostRecentCommand =
                   ((CommandStack)event.getSource()).getMostRecentCommand();
       if (mostRecentCommand != null) {
             setSelectionToViewer(mostRecentCommand.getAffectedObjects());
        } // --- set selection
if (propertySheetPage != null && !propertySheetPage.getControl().isDisposed())
{
               propertySheetPage.refresh();
           }
          );
    });

18. How to use the Item Provider Factories as Label and Content Providers ?
>> selectionViewer.setContentProvider(new
     AdapterFactoryContentProvider(composedAdapterFactory));
>> selectionViewer.setLabelProvider(new
AdapterFactoryLabelProvider(composedAdapterFactory));

19. Remember Action Bar Contributor – invokes the child-descriptors as specified by
the item-providers to create the actions.

20. How to register a custom Resource Factory against a file type ?

resourceSet.getRespourceFactoryRegistry().getExtensionToFactoryMap().put(“substvar
”, new SvarResourceFactoryImpl())

21. While creating URI if the file path contains space, use encoding mechanism.

URI.createURI(encoding_flag) …

18. How to encrypt/decrypt the stream data ?

Save/Load OPTION_CIPHER, OPTION_ZIP
(URIConverter.Cipher) DESCipherImpl → CryptoCipherImpl

19. How to query XML data using EMF ?

XMLResource resource = (XmlResource)rs.createResource(
  URI.createPlatformResourceURI(“/project/sample.xml”, true));
resource.getContents().add(supplier);
Map options = new HashMap();
options.put(XMLResource.OPTION_KEEP_DEFAULT_CONTENT, Boolean.TRUE);
Document document = resource.save(null, options, null);
DOMHelper helper = resource.getDOMHelper();
NodeList nodes = XpathAPI.selectNodeList(document, query)
for(...) {
Node node = nodes.item(i)
Item item = (Item)helper.getValue(node);
}

20. How to serialize and load qname correctly ?

A. First we need to set the option OPTION_EXTENDED_META_DATA as true for
loading and saving element in the MyResourceFactoryImpl#createResource() :

XMLResource result = new XMLResourceImpl(uri);
result.getDefaultSaveOptions().put(XMLResource.OPTION_EXTENDED_META_DA
TA, Boolean.TRUE);
result.getDefaultLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DA
TA, Boolean.TRUE);

B. Always use - AddCommand / RemoveCommand / SetCommand /
EMFOpertionCommand / EMFCommandOperation - instead of RecordingCommand ;
because RecordingCommand does not load / store QNames properly while
undoing/redoing. I have raised a Bug in Eclipse that I shall post here soon …

21. How to load emf resource from a plugin jar ?

Lets assume that an emf resource file has been contributed to an extension-point.
Now while reading the extension points; one can find out the name of the plugin.

IConfigurationElement[] elements = extensions[i].getConfigurationElements();
IContributor contributor = elements[j].getContributor();
String bundleId = contributor.getName();

URI uri = URI.createPlatformPluginURI("/" + bundleId + "/"+ filePath, true);
Resource resource = ResourceSetFactory.getResourceSet().createResource(uri);
resource .load(null);
EList contents = resource .getContents();

22. How to customize the copy functionality of EcoreUtil ?

EcoreUtil.Copier testCopier = new Ecoreutil.Copier() {

protected void copyContainment(EReference eRef, EObject eObj, EObject copyEObj) {
// skip the unwanted feature
if(eRef != unwanted_feature) {
super.copyContainment(eRef, eObj, copyEobj);
}
}
//
testCopier.copyAll(testObjects);
testCopier.copyReferences();
//

Recommended for you

Java Annotations and Pre-processing
Java  Annotations and Pre-processingJava  Annotations and Pre-processing
Java Annotations and Pre-processing

Java pre-processing and annotations talk. How to do it? How it works? Why to do it? Github code: https://github.com/luanpotter/annotation-preprocessing https://github.com/luanpotter/reflection-utils

javaprogrammingoracle
Esprima - What is that
Esprima - What is thatEsprima - What is that
Esprima - What is that

Esprima is a JavaScript parser that produces an abstract syntax tree (AST) from JavaScript code. The AST can then be traversed and analyzed to gather metadata and perform tasks like syntax validation, code completion, and instrumentation. Esprima supports ECMAScript 5.1 and below and can be used from browsers, Node.js, RequireJS, and other environments/packages. It parses code into a JSON AST and has options to customize the output.

esprimajavascriptparser
Akka tips
Akka tipsAkka tips
Akka tips

Hakking tips 'n tricks: practical patterns, tips and tricks working with Akka actors! http://www.meetup.com/Reactive-Amsterdam/events/231908511/

More Related Content

What's hot

JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
JavaScript on the GPU
JavaScript on the GPUJavaScript on the GPU
JavaScript on the GPU
Jarred Nicholls
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
Akka in-action
Akka in-actionAkka in-action
Akka in-action
Raymond Roestenburg
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees
Jamund Ferguson
 
Java Annotations and Pre-processing
Java  Annotations and Pre-processingJava  Annotations and Pre-processing
Java Annotations and Pre-processing
Danilo Pereira De Luca
 
Esprima - What is that
Esprima - What is thatEsprima - What is that
Esprima - What is that
Abhijeet Pawar
 
Akka tips
Akka tipsAkka tips
Building DSLs With Eclipse
Building DSLs With EclipseBuilding DSLs With Eclipse
Building DSLs With Eclipse
Peter Friese
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
Simon Willison
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
Raymond Roestenburg
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Tran Khoa
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
Recipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with XtendRecipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with Xtend
Karsten Thoms
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
Heiko Behrens
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
Fwdays
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 

What's hot (20)

JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
JavaScript on the GPU
JavaScript on the GPUJavaScript on the GPU
JavaScript on the GPU
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Akka in-action
Akka in-actionAkka in-action
Akka in-action
 
Don't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax TreesDon't Be Afraid of Abstract Syntax Trees
Don't Be Afraid of Abstract Syntax Trees
 
Java Annotations and Pre-processing
Java  Annotations and Pre-processingJava  Annotations and Pre-processing
Java Annotations and Pre-processing
 
Esprima - What is that
Esprima - What is thatEsprima - What is that
Esprima - What is that
 
Akka tips
Akka tipsAkka tips
Akka tips
 
Building DSLs With Eclipse
Building DSLs With EclipseBuilding DSLs With Eclipse
Building DSLs With Eclipse
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Recipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with XtendRecipes to build Code Generators for Non-Xtext Models with Xtend
Recipes to build Code Generators for Non-Xtext Models with Xtend
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Nikita Popov "What��s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 

Similar to EMF Tips n Tricks

Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
AntoJoseph36
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Make School
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
Jason Straughan
 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
Gagan Vishal Mishra
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon Dublin
Nida Ismail Shah
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide Line
Gagan Vishal Mishra
 
Patterns in Eclipse
Patterns in EclipsePatterns in Eclipse
Patterns in Eclipse
Madhu Samuel
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
Shawn Brito
 
6976.ppt
6976.ppt6976.ppt
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
Macoscope
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard Views
Tonny Madsen
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
Basuke Suzuki
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
Dan Hinojosa
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Subramanyan Murali
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Nascenia IT
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
Mohammad Shaker
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Fu Cheng
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
Samuel ROZE
 

Similar to EMF Tips n Tricks (20)

Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Design patterns in PHP
Design patterns in PHPDesign patterns in PHP
Design patterns in PHP
 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
 
The state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon DublinThe state of hooking into Drupal - DrupalCon Dublin
The state of hooking into Drupal - DrupalCon Dublin
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide Line
 
Patterns in Eclipse
Patterns in EclipsePatterns in Eclipse
Patterns in Eclipse
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
6976.ppt
6976.ppt6976.ppt
6976.ppt
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard Views
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
How I started to love design patterns
How I started to love design patternsHow I started to love design patterns
How I started to love design patterns
 

More from Kaniska Mandal

Machine learning advanced applications
Machine learning advanced applicationsMachine learning advanced applications
Machine learning advanced applications
Kaniska Mandal
 
MS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning AlgorithmMS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning Algorithm
Kaniska Mandal
 
Core concepts and Key technologies - Big Data Analytics
Core concepts and Key technologies - Big Data AnalyticsCore concepts and Key technologies - Big Data Analytics
Core concepts and Key technologies - Big Data Analytics
Kaniska Mandal
 
Machine Learning Comparative Analysis - Part 1
Machine Learning Comparative Analysis - Part 1Machine Learning Comparative Analysis - Part 1
Machine Learning Comparative Analysis - Part 1
Kaniska Mandal
 
Debugging over tcp and http
Debugging over tcp and httpDebugging over tcp and http
Debugging over tcp and http
Kaniska Mandal
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
Kaniska Mandal
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
Kaniska Mandal
 
Wondeland Of Modelling
Wondeland Of ModellingWondeland Of Modelling
Wondeland Of Modelling
Kaniska Mandal
 
The Road To Openness.Odt
The Road To Openness.OdtThe Road To Openness.Odt
The Road To Openness.Odt
Kaniska Mandal
 
Perils Of Url Class Loader
Perils Of Url Class LoaderPerils Of Url Class Loader
Perils Of Url Class Loader
Kaniska Mandal
 
Making Applications Work Together In Eclipse
Making Applications Work Together In EclipseMaking Applications Work Together In Eclipse
Making Applications Work Together In Eclipse
Kaniska Mandal
 
Eclipse Tricks
Eclipse TricksEclipse Tricks
Eclipse Tricks
Kaniska Mandal
 
E4 Eclipse Super Force
E4 Eclipse Super ForceE4 Eclipse Super Force
E4 Eclipse Super Force
Kaniska Mandal
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD Framework
Kaniska Mandal
 
Creating A Language Editor Using Dltk
Creating A Language Editor Using DltkCreating A Language Editor Using Dltk
Creating A Language Editor Using Dltk
Kaniska Mandal
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
Kaniska Mandal
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
Kaniska Mandal
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml Classes
Kaniska Mandal
 
Graphical Model Transformation Framework
Graphical Model Transformation FrameworkGraphical Model Transformation Framework
Graphical Model Transformation Framework
Kaniska Mandal
 
Mashup Magic
Mashup MagicMashup Magic
Mashup Magic
Kaniska Mandal
 

More from Kaniska Mandal (20)

Machine learning advanced applications
Machine learning advanced applicationsMachine learning advanced applications
Machine learning advanced applications
 
MS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning AlgorithmMS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning Algorithm
 
Core concepts and Key technologies - Big Data Analytics
Core concepts and Key technologies - Big Data AnalyticsCore concepts and Key technologies - Big Data Analytics
Core concepts and Key technologies - Big Data Analytics
 
Machine Learning Comparative Analysis - Part 1
Machine Learning Comparative Analysis - Part 1Machine Learning Comparative Analysis - Part 1
Machine Learning Comparative Analysis - Part 1
 
Debugging over tcp and http
Debugging over tcp and httpDebugging over tcp and http
Debugging over tcp and http
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
 
Wondeland Of Modelling
Wondeland Of ModellingWondeland Of Modelling
Wondeland Of Modelling
 
The Road To Openness.Odt
The Road To Openness.OdtThe Road To Openness.Odt
The Road To Openness.Odt
 
Perils Of Url Class Loader
Perils Of Url Class LoaderPerils Of Url Class Loader
Perils Of Url Class Loader
 
Making Applications Work Together In Eclipse
Making Applications Work Together In EclipseMaking Applications Work Together In Eclipse
Making Applications Work Together In Eclipse
 
Eclipse Tricks
Eclipse TricksEclipse Tricks
Eclipse Tricks
 
E4 Eclipse Super Force
E4 Eclipse Super ForceE4 Eclipse Super Force
E4 Eclipse Super Force
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD Framework
 
Creating A Language Editor Using Dltk
Creating A Language Editor Using DltkCreating A Language Editor Using Dltk
Creating A Language Editor Using Dltk
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml Classes
 
Graphical Model Transformation Framework
Graphical Model Transformation FrameworkGraphical Model Transformation Framework
Graphical Model Transformation Framework
 
Mashup Magic
Mashup MagicMashup Magic
Mashup Magic
 

Recently uploaded

Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Bert Blevins
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
Bert Blevins
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
Stephanie Beckett
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
Lidia A.
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
SynapseIndia
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Chris Swan
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
RaminGhanbari2
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
Mark Billinghurst
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
Stephanie Beckett
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
rajancomputerfbd
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
UiPathCommunity
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
HackersList
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
ArgaBisma
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 

Recently uploaded (20)

Advanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly DetectionAdvanced Techniques for Cyber Security Analysis and Anomaly Detection
Advanced Techniques for Cyber Security Analysis and Anomaly Detection
 
Password Rotation in 2024 is still Relevant
Password Rotation in 2024 is still RelevantPassword Rotation in 2024 is still Relevant
Password Rotation in 2024 is still Relevant
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptxRPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
RPA In Healthcare Benefits, Use Case, Trend And Challenges 2024.pptx
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
 
What's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptxWhat's New in Copilot for Microsoft365 May 2024.pptx
What's New in Copilot for Microsoft365 May 2024.pptx
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
UiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs ConferenceUiPath Community Day Kraków: Devs4Devs Conference
UiPath Community Day Kraków: Devs4Devs Conference
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
How Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdfHow Social Media Hackers Help You to See Your Wife's Message.pdf
How Social Media Hackers Help You to See Your Wife's Message.pdf
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 

EMF Tips n Tricks

  • 1. Eclipse Modeling Framework – Tips n Tricks 1.Design a Model Provider API Always invoke the singleton instance of a ModelProvider from anywhere in the application as a single point contact for managing the lifecycle and behavior of model Ø It should contain the corresponding editing domain, file resource, resource set, associated editor part, navigator and tabbed propertypage sheet Ø It should maintain a single copy of the domain model in the memory. getModel(IResource resource) Ø It should maintain the list of cross-references Ø It should be a resource-change listener so that o it can un-load the model and delete the emf resource when the file resource is deleted o It can modify the resource-uri when the file is moved / renamed Ø Whenever the resource uri is changed then using EcoreUtil CrossReferencer ModelProvider should find out what all models should be refactored Ø ModelProvider should also register all required ItemAdapterFactories Ø It should provide the custom persistence policy for the model if needed 2.Item Provider is the single-most powerful feature in EMF. They should be utilized to the fullest. It provides the functions to Ø Implement content and label provider By using mixin interfaces – delegate pattern Public Object[] getchilren(Object object){ ITreeItemContentProvider adapter = (ITreeItemContentProvider ) adapterFactory.adapt(object, ITreeItemContentProvider .class); return aapter.getChildren(object).toArray(); } Ø Adapt the model objects to implement whatever interfaces the editors and views need. Ø Propagate the change-notifications to viewers Ø Act as command factory Ø Provide a property source for model objects 3. Effective usage of Common Command Fwk getResult() should be overridden to return relevant model objects so that (1) result of one command can be input to another command
  • 2. (2) the required diagram element or xml node or language statement or property section can be selected and highlighted getAffectedObjects() 4.WorkingModel – should be reloaded when the resource is modified/deleted if (workingModelListener == null) { workingModelListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if (WorkingModel.PROP_DIRTY.equals(evt.getPropertyName())) { editorDirtyStateChanged(); } else if (WorkingModel.PROP_RELOADED.equals(evt. .getPropertyName())) { reloadModel((IFile) getWorkingModel() .getEclipseResources().get(0)); } else if (WorkingModel.PROP_REMOVED.equals.getPropertyName())) { Object newLocation = evt.getNewValue(); if(newLocation == null) { cleanupModelCopyOfDeletedResource(); close(false); } else if (newLocation instanceof IPath) { // file is renamed IFile newFile = ResourcesPlugin.getWorkspace() .getRoot().getFile( (IPath) newLocation); if (newFile != null && newFile.exists()) { reloadModel(newFile); } else { close(false); } } else { close(false); } 5. How to find EMF References ? private Node findReferingModel(EObject eo) { Collection<Setting> referrers = EcoreUtil.UsageCrossReferencer.find(eo, eo.eResource()); Iterator<Setting> it = referrers.iterator(); while (it.hasNext()) { Setting referer = (Setting) it.next(); EObject referredObj = referer.getEObject(); return referredObj;
  • 3. } 6. Why Notification Listeners in EMF are also called Adapters ? A. Apart from observing the changes in eObjects, they also help - extending the behavior i.e. support additional interfaces without subclassing - (Adapter pattern) Attaching an Adapter as Observer : Adapter myEObjectObserver = ... myEObjectObserver.eAdapters().add(myEObjectObserver); Attaching an Adapter as a Behaviour Extension : MyEObject myEObject = .... AdapterFactory myEObjectAdapterFactory = .... Object myEObjectType <== if(myEObjectAdapterFactory.isFactoryType(myEObjectType )){ Adapter myEObjectAdapter = myEObjectAdapterFactory.adapt(myEObject, myEObjectType); ..... } Attaching an adapter to all the eobjects under the root So far we have seen how to adapt to the changes to a particular EObject. Q. Now how to adapt to all the objects in the containment hierarchy, a resource and a set of related resources : EContentAdapter - can be attached to a root object, a resource or even a resourseset. 7. What is resource-proxy and on-demand resource loading ? A. Say PO Entity simply refers to an Item Entity i.e. there is no by-value aggregation/strong composition i.e. no containment reference between PO and Item EObjects. Basically there is a cross-document reference So in this case there will be one poReource with poURI and an itemResource with itemURI.
  • 4. When we call rsourseSet.getReource(poURI) --> the ResourseSet will start traversing the resource eobject-tree and load all eObjects. But for any references to objects in itemResource , instead of traversing itemResource the ResourseSet will set the references to Proxies (* an uninitialized instance of the actual target class * with the actual URI). When - po.getItem() - will be invoked, the proxies will be resolved and actual Item EObjects will be loaded on demand. 8. How to get the objects modified during the last execute() / undo() / redo() ? >> command.getAffectedObjects() These objects should be used for selecting/highlighting the viewers 9.Some useful Commands : >> Moving objects up - down in Viewer : MoveCommand >> Replacing an object in multiplicity-many features : ReplaceCommand >> Creating a duplicate object : CopyCommand >> Create a new object and add it to a feature of EObject : CreateChildCommand >> Delete an eobject from parent container along with all references : DeleteCommand 10. What is the role of Editing Domain ? AdapterFactoryEditingDomain -- (i) creates command thru item provider, (ii) maintaining editor's commandstack, (iii) maintaining resource set 11. Ecore Model Optimization " >> If a particular reference is always -containment- and can never be cross-document; then resolveProxies should be set to false 11. How to define a custom data type ? >> We should not refer a highly complicated Java Class as data type. >> Instead we should model the Java_Class as EClass and then create an EDtaType where instanceClass should refer to that EClass. 12. How to maintain in-memory temporary ELists which need not be persisted ? These model elements should be declared as - volatile, transient, non-changeable and deived. public EList getSpecialModelObjects(){ ArrayList specialModelObjects = new ArrayList(); for(... getmodelObjects() ... ){
  • 5. if(...){ specialModelObjects.add(); } } return new ECoreEList.UnmodifiableEList(this, , specialComposites.siz(), specialComposites.toArray()); } 13. What to do if you want to create a unique list which should contain elements of a particular type ? Elist locations = new EDataTypeUniqueEList(String.class, this, EPO2Package.GLOBAL_ADDRESS_LOCTION); 14. How to suppress creation of eobjects ? Simply clear the GenModel property – “Root Extends Interface” – 15. How to control the command's appearance i.e. decorate the actions ? The item provider is an IchangeNotifier to support DECORATOR pattern – an ItemProviderDecorator registers itself as a listener for the Item Provider that it decorates. The commands need to implement CommandActionDelegate interface to provide implementation for retrieving images and labels. 16. How to use custom adapter factories ? Create a ComposedAdapterFactory and include the item provider for the classes that are not part of the model along with the regular item provider factories. 17. How to refresh a viewer and set the selection on particular elements ? editingDomain.getCommandStack().addCommandStackListener( new CommandStacklistener() { public void commandStackChanged(final EventObject event) { getContainer().getDisplay().asyncExec( new Runnable() { public void run() { firePropertyChange(IEditorPart.PROP_Dirty); Command mostRecentCommand = ((CommandStack)event.getSource()).getMostRecentCommand(); if (mostRecentCommand != null) { setSelectionToViewer(mostRecentCommand.getAffectedObjects()); } // --- set selection
  • 6. if (propertySheetPage != null && !propertySheetPage.getControl().isDisposed()) { propertySheetPage.refresh(); } ); }); 18. How to use the Item Provider Factories as Label and Content Providers ? >> selectionViewer.setContentProvider(new AdapterFactoryContentProvider(composedAdapterFactory)); >> selectionViewer.setLabelProvider(new AdapterFactoryLabelProvider(composedAdapterFactory)); 19. Remember Action Bar Contributor – invokes the child-descriptors as specified by the item-providers to create the actions. 20. How to register a custom Resource Factory against a file type ? resourceSet.getRespourceFactoryRegistry().getExtensionToFactoryMap().put(“substvar ”, new SvarResourceFactoryImpl()) 21. While creating URI if the file path contains space, use encoding mechanism. URI.createURI(encoding_flag) … 18. How to encrypt/decrypt the stream data ? Save/Load OPTION_CIPHER, OPTION_ZIP (URIConverter.Cipher) DESCipherImpl → CryptoCipherImpl 19. How to query XML data using EMF ? XMLResource resource = (XmlResource)rs.createResource( URI.createPlatformResourceURI(“/project/sample.xml”, true)); resource.getContents().add(supplier); Map options = new HashMap(); options.put(XMLResource.OPTION_KEEP_DEFAULT_CONTENT, Boolean.TRUE); Document document = resource.save(null, options, null); DOMHelper helper = resource.getDOMHelper(); NodeList nodes = XpathAPI.selectNodeList(document, query) for(...) { Node node = nodes.item(i)
  • 7. Item item = (Item)helper.getValue(node); } 20. How to serialize and load qname correctly ? A. First we need to set the option OPTION_EXTENDED_META_DATA as true for loading and saving element in the MyResourceFactoryImpl#createResource() : XMLResource result = new XMLResourceImpl(uri); result.getDefaultSaveOptions().put(XMLResource.OPTION_EXTENDED_META_DA TA, Boolean.TRUE); result.getDefaultLoadOptions().put(XMLResource.OPTION_EXTENDED_META_DA TA, Boolean.TRUE); B. Always use - AddCommand / RemoveCommand / SetCommand / EMFOpertionCommand / EMFCommandOperation - instead of RecordingCommand ; because RecordingCommand does not load / store QNames properly while undoing/redoing. I have raised a Bug in Eclipse that I shall post here soon … 21. How to load emf resource from a plugin jar ? Lets assume that an emf resource file has been contributed to an extension-point. Now while reading the extension points; one can find out the name of the plugin. IConfigurationElement[] elements = extensions[i].getConfigurationElements(); IContributor contributor = elements[j].getContributor(); String bundleId = contributor.getName(); URI uri = URI.createPlatformPluginURI("/" + bundleId + "/"+ filePath, true); Resource resource = ResourceSetFactory.getResourceSet().createResource(uri); resource .load(null); EList contents = resource .getContents(); 22. How to customize the copy functionality of EcoreUtil ? EcoreUtil.Copier testCopier = new Ecoreutil.Copier() { protected void copyContainment(EReference eRef, EObject eObj, EObject copyEObj) { // skip the unwanted feature if(eRef != unwanted_feature) { super.copyContainment(eRef, eObj, copyEobj); }