SlideShare una empresa de Scribd logo
1 de 8
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() ... ){
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();
//

Más contenido relacionado

La actualidad más candente

Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
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 TreesJamund Ferguson
 
Esprima - What is that
Esprima - What is thatEsprima - What is that
Esprima - What is thatAbhijeet Pawar
 
Building DSLs With Eclipse
Building DSLs With EclipseBuilding DSLs With Eclipse
Building DSLs With EclipsePeter Friese
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and EffectsRaymond Roestenburg
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran 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 & UXJWORKS 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 XtendKarsten Thoms
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
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 TutorialBui Kiet
 

La actualidad más candente (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 a EMF Tips n Tricks

Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano 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.pptAntoJoseph36
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
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 DublinNida Ismail Shah
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide LineGagan Vishal Mishra
 
Patterns in Eclipse
Patterns in EclipsePatterns in Eclipse
Patterns in EclipseMadhu Samuel
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
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, MacoscopeMacoscope
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsTonny Madsen
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia 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 applicationsJeff Durta
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu 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 patternsSamuel ROZE
 

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

Más de Kaniska Mandal

Machine learning advanced applications
Machine learning advanced applicationsMachine learning advanced applications
Machine learning advanced applicationsKaniska Mandal
 
MS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning AlgorithmMS CS - Selecting Machine Learning Algorithm
MS CS - Selecting Machine Learning AlgorithmKaniska 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 AnalyticsKaniska Mandal
 
Machine Learning Comparative Analysis - Part 1
Machine Learning Comparative Analysis - Part 1Machine Learning Comparative Analysis - Part 1
Machine Learning Comparative Analysis - Part 1Kaniska Mandal
 
Debugging over tcp and http
Debugging over tcp and httpDebugging over tcp and http
Debugging over tcp and httpKaniska Mandal
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceKaniska Mandal
 
Wondeland Of Modelling
Wondeland Of ModellingWondeland Of Modelling
Wondeland Of ModellingKaniska Mandal
 
The Road To Openness.Odt
The Road To Openness.OdtThe Road To Openness.Odt
The Road To Openness.OdtKaniska Mandal
 
Perils Of Url Class Loader
Perils Of Url Class LoaderPerils Of Url Class Loader
Perils Of Url Class LoaderKaniska Mandal
 
Making Applications Work Together In Eclipse
Making Applications Work Together In EclipseMaking Applications Work Together In Eclipse
Making Applications Work Together In EclipseKaniska Mandal
 
E4 Eclipse Super Force
E4 Eclipse Super ForceE4 Eclipse Super Force
E4 Eclipse Super ForceKaniska Mandal
 
Create a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkCreate a Customized GMF DnD Framework
Create a Customized GMF DnD FrameworkKaniska Mandal
 
Creating A Language Editor Using Dltk
Creating A Language Editor Using DltkCreating A Language Editor Using Dltk
Creating A Language Editor Using DltkKaniska Mandal
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate NotesKaniska Mandal
 
Converting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesConverting Db Schema Into Uml Classes
Converting Db Schema Into Uml ClassesKaniska Mandal
 
Graphical Model Transformation Framework
Graphical Model Transformation FrameworkGraphical Model Transformation Framework
Graphical Model Transformation FrameworkKaniska Mandal
 

Más de 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
 

Último

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 

Último (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 

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