View
227
Download
5
Category
Preview:
Citation preview
Technology Tutorial
Software Engineering 2
(02162)
- Details and Advanced Concepts -
Patrick Könemann (pk@imm.dtu.dk)
Oct 19th 2009
2
Previous Tutorials.
1. A view and a selection listener for file types
public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.setContentProvider(new ArrayContentProvider());
viewer.setLabelProvider(new LabelProvider());
getSite().getPage().addSelectionListener(this);
}
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
List<String> list = new ArrayList<String>();
if (selection instanceof StructuredSelection) {
StructuredSelection str = (StructuredSelection) selection;
if (!str.isEmpty()) {
for (Object obj : str.toList()) {
if (obj instanceof IResource) {
IResource resource = (IResource) obj;
list.add(resource.getName() + " (type: " + resource.getFileExtension() +
", path: " + resource.getFullPath().toString() + ")");
}
}
}
}
viewer.setInput(list);
}
3
Previous Tutorials..
1. A view and a selection listener for file types
2. Create an EMF model (for Petrinets), generate code, and install a
command (for simulation) as a popup action for transitions
4
Previous Tutorials…
1. A view and a selection listener for file types
2. Create an EMF model (for Petrinets), generate code, and install a
command (for simulation) as a popup action for transitions
3. Create a compound command for creating an object and set its initial id
5
Previous Tutorials….
1. A view and a selection listener for file types
2. Create an EMF model (for Petrinets), generate code, and install a
command (for simulation) as a popup action for transitions
3. Create a compound command for creating an object and set its initial id
4. Use GMF to generate a graphical
editor for Petrinets and install
a command (for simulation) as a
popup action for transition figures
6
Previous Tutorials…..
1. A view and a selection listener for file types
2. Create an EMF model (for Petrinets), generate code, and install a
command (for simulation) as a popup action for transitions
3. Create a compound command for creating an object and set its initial id
4. Use GMF to generate a graphical
editor for Petrinets and install
a command (for simulation) as a
popup action for transition figures
5. A simple dashboard view for
Petrinets with listeners/adapters
showing the current number of
tokens on selected places
7
Motivation
This lecture covers advanced topics after the regular tutorials.
But didn’t we get enough tutorials
yet?!
These were just the basics.
The following advanced concepts probably save a lot of time later.
Then why listening now?!
We can read things later in the slides!
Good, do that!
But following now will help you understand things much better.
And not everything I say is in the slides ;-)
8
Overview
Topic Concepts Examples Slides
Resources in
Eclipse
Dialogs
OCL in EMF / GMF
GMF:
Graphical properties
in the model
GMF: Architecture
GMF: Decorator
9
Resources in Eclipse: Examples
C:\se2\workspace\
.metadata\
dk.dtu.imm.se2.petrinet\
model\
petrinet.ecore
petrinet.genmodel
src\
…
bin\
…
META-INF\
MANIFEST.MF
.project
plugin.xml
Images are also stored as IFiles ;-)
java.io.File
java.io.File
java.io.File
java.io.File
java.io.File
java.io.File
java.io.File
java.io.File
java.io.File
java.io.File
java.io.File
java.io.File
IWorkspace
(metadata directory)
IProject
IFolder
IFile
IFile
IFolder
(source files)
IFolder
(compiled files)
IFolder
IFile
(IProjectDescription)
IFile
How do you access
these items in Java?
10
Resources in Eclipse: Class hierarchy
How to navigate? [brief excerpt from the JavaDoc]
• IResource.exists(): boolean Check whether the resource exists
• IResource.getFullPath(): IPath Returns the full, absolute path of this
resource relative to the workspace.
• IResource.getLocationURI(): URI Get the URI of this ressource
• IContainer.members(): IResource[] Get handles to all resources contained here
• IContainer.getFile(String file): IFile Get a handle to a file contained here
• IFolder.create(…): void Create this folder (assuming it does not exist)
• IFile.create(…): void Create this file (assuming it does not exist)
Open that dialog with ”Ctrl + t”
11
Resources in Eclipse: Handles
• Access to a resource is managed by a ”handle”:
• ”There is no guarantee or requirement that the resource itself exists
until you try to do something with the handle.“ [Eclipse help]
petrinetModel: IFile
fullPath = ”/dk.dtu.imm.se2.petrinet/model/Petrinet.ecore”
IFile petrinetModel = modelFolder.getFile("Petinet.ecore");
MessageDialog.openInformation(shell, "petrinet model path",
petrinetModel.getFullPath().toString() + "\n" +
"File exists: " + petrinetModel.exists());
What will be
shown here?
12
Resources in Eclipse: URIs
Syntax for Uniform Resource Identifiers
<URI scheme>:<path>#<fragment>
Examples: – http://imm.dtu.dk/~pk/
– http://modeldiff.imm.dtu.dk/modeldiff/#documentation
– platform:/resource/dk.dtu.imm.se2.petrinet/plugin.xml
– platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore#//EReference
URIs also in your models (as XMI):
– wiper.componentdefinition
– wipersystem.deployment
– test.petrinet
Resource is
located in the
workspace
Resource is
located in a
running plugin
Reference to an
EClass within the
EMF meta model
Platform independent!
13
"platform:/resource/CASETool-Examples/WiperSystem/controller.componentdefinition"
Resources in Eclipse: Load a Resource
A resource can be loaded with a given URI
• via the bundle of the local plugin activator:
platform:/resource/dk.dtu.imm.se2.dashboard/icons/dashboard.gif
• EMF provides simple methods for loading models:
1. Create resource set
2. ask it for a resource using a URI
final URL imageURL = PluginActivator.getDefault().getBundle().getEntry("icons/dashboard.gif");
final Image image = ImageDescriptor.createFromURL(imageURL).createImage();
final ResourceSet resourceSet = new ResourceSetImpl();
final URI uri = URI.createURI(
);
final Resource resource = resourceSet.getResource(uri, true);
final EObject compDef = resource.getContents().get(0);
Located in
workspace
Project Folder File
14
Resources in Eclipse: References
• Eclipse help (Help Help Contents):
Platform Plug-in Developer Guide Programmer’s Guide
Resources overview Resources and the file system
• Uniform Resource Identifier (URI) – Generic Syntax:
http://labs.apache.org/webarch/uri/rfc/rfc3986.html
15
Progress…
Topic Concepts Examples Slides
Resources in Eclipse No direct access!
Use “wrapper” for
accessing resources
IFile, IFolder, URI 9 – 14
Dialogs
OCL in EMF / GMF
GMF:
Graphical properties
in the model
GMF: Architecture
GMF: Decorator
16
Dialog: Examples
if (MessageDialog.openQuestion(shell,
“Disconnect?”,
“Do you really want to disconnect from the running simulation?")) {
…
new InputDialog(shell, "Name?", "Please enter a name.", "system1", null).open();
new ResourceDialog(shell,
"Select deployment", SWT.OPEN | SWT.SINGLE).open();
17
Dialog: More Examples
WorkspaceResourceDialog.openFileSelection(shell,
"Select files", "Please select input file(s)",
false, null, filters);
WorkspaceResourceDialog.openNewFile(shell, "Save file",
"Please select output file", null, null);
Suggested path
Filters for the files
List<ViewerFilter> filters = new ArrayList<ViewerFilter>();
filters.add(new ViewerFilter() {
@Override
public boolean select(Viewer viewer,
Object parentElement, Object element) {
if (element instanceof IFile) {
return ((IFile)element).
getFileExtension().equals("deployment");
} else return true;
}
});
18
Dialogs: Yet More Examples
MessageDialog dialog = new MessageDialog(shell,
"File already exists", image,
"'" + file.getName() + "' already exists.\nWhat do you want to do?",
MessageDialog.WARNING, buttons, 1);
String[] buttons = new String[]{
"Overwrite",
"Save as '" + fileAlternative.getName() + "'",
"Cancel“
};
MessageDialog dialog = new MessageDialog(shell,
"File already exists", image,
"'" + file.getName() + "' already exists.\nWhat do you want to do?",
MessageDialog.WARNING, buttons, 1);
switch (dialog.open()) {
case 0: return file;
case 1: return fileAlternative;
default: return null;
}
19
Dialogs: Which one?!
• Does a dialog already exist for my purpose?
– Yes? Use it!
– No? Pick the closet one, inherit from it, and adjust it for your needs!
• How do I find existing dialogs?
– Type Hierarchy of existing dialogs
– Plug-in Spy on open dialogs
Open with
Alt + Shift + F1
Quick Type Hierarchy
with Ctrl + t
20
Dialogs: References
• Eclipse Help (Help Help Contents):
Platform Plug-in Developer Guide > Programmer's Guide > Dialogs and wizards
• JavaDoc
• JFace Snippets: http://wiki.eclipse.org/JFaceSnippets
21
Progress…
Topic Concepts Examples Slides
Resources in Eclipse No direct access!
Use “wrapper” for
accessing resources
IFile, IFolder, URI 9 – 14
Dialogs Use existing ones!
(static & dynamic)
MessageDialog,
InputDialog,
ResourceDialog, …
16 – 20
OCL in EMF / GMF
GMF:
Graphical properties
in the model
GMF: Architecture
GMF: Decorator
22
OCL: in EMF and GMF
• What is wrong with the deployment?
– free_software is not on a node
– wiper_on_a_chip is on a node
• Goal: validate that the models are correct!
– Hard-coding constraints… but I am lazy…
– Model constraints in OCL (Object Constraint Language)
self.definition->size() > 0 and
self.definition.hardware self.definition->size() > 0 and
not self.definition.hardware
What is
wrong here?
23
OCL: Constraints for modeling
Constraint for
connections:
The messages at
the out-port must
be receivable at
the in-port!
24
OCL: Constraints for modeling
Constraint for
connections:
The messages at
the out-port must
be receivable at
the in-port! Context (self)
In OCL: self.source.definition.out->forAll( m1 | self.target.definition._in->exists(m2 | m1=m2 )) and
self.target.definition.out->forAll( m1 | self.source.definition._in->exists(m2 | m1=m2 ))
In OCL: self.
In OCL: self.source.definition.out->forAll( m1 | self.target.definition._in->exists(m2 | m1=m2 ))
In OCL: self.source.definition.out->forAll( m1 | self.target.definition._in->exists( ))
In OCL: self.source.
In OCL: self.source.definition.
In OCL: self.source.definition.out
In OCL: self.source.definition.out->forAll( self.target.definition._in )
25
OCL: brief overview
OCL expressions:
• start from the context object (in OCL called self)
• may access attributes and methods (by dot-notation and resp. names)
• may navigate along associations
• may call operations and built-in functions
OCL…
• … is independent from a concrete programing language and
is tuned to formulate typical constraints on MOF and UML models
• … also allows us to formulate pre and post conditions of methods
• … can be used to ”implement” some methods and derived attributes
• … can be used for validation of models
26
OCL: use in GMF
• Different kinds of OCL Constraints are supported by GMF editors:
– Live mode:
During work on model
(slide 23)
– Non-live mode:
Explicit validation
(slide 22)
– Severity:
• Information
• Warning
• Error
Context (self)
[ Examples in DeploymentEditor.gmfmap ]
27
OCL: Interactive Console
The Interactive OCL Console
allows to evaluate
OCL expressions live
Context (self)
must be selected
Evaluation
results
Code completion !!!
Select OCL
Console here
28
OCL: References
• OCL Definition: http://www.omg.org/spec/OCL/2.0/
• OCL in Eclipse: http://wiki.eclipse.org/MDT-OCL
• GMF Constraints in general: http://wiki.eclipse.org/GMF_Constraints
• Validation in GMF: http://wiki.eclipse.org/GMF_Tutorial_Part_2
• OCL in EMF (advanced!): http://www.eclipse.org/articles/article.php?file=Article-
EMF-Codegen-with-OCL/index.html
• OCL for GMF requires an additional feature installed (unfortunately):
Helpful plugins MDT OCL All-in-One
Tool for checking the correct syntact of OCL constraints and for evaluating
constraints at runtime (”Interactive OCL Console”):
From Update site:
http://download.eclipse.org/modeling/mdt/ocl/updates/releases
Install
”OCL All-in-One SDK” (latest version)
29
32
Progress…
Topic Concepts Examples Slides
Resources in Eclipse No direct access!
Use “wrapper” for
accessing resources
IFile, IFolder, URI 9 – 14
Dialogs Use existing ones!
(static & dynamic)
MessageDialog,
InputDialog,
ResourceDialog, …
16 – 20
OCL in EMF / GMF Constraints in the model:
Object Constraint
Language
Deployment model;
OCL Console
22 – 31
GMF: Graphical
properties in the
model
GMF: Architecture
GMF: Decorator
33
Model vs. View: Reminder
[ From Lecture 1: SE2-L01.pdf ]
34
Model vs. View
Model: instance of a meta model
A view on the
Dashboard
meta model
Several views
on a Dashboard
model
What is a model?
What is a view?
A view on a model is one representation of
the entire model or of a part of the model.
There might be several representations of the
same model element in a view.
In the model, each element exists only once!
35
Model vs. View: GMF
Contents of the ”_diagram” file:
• Each graphical element is stored as
a ”Node”
• GMF stores graphical information
for each Node:
position, size, font style, colours, …
contains
the model
is just one
representation
36
Model vs. View: Dashboard Motivation
Dashboard
model(s)
Dashboard editor Dashboard view
Creating
Dashboard
model
Visualizing
Dashboard model
during simulation
What is the
problem?
All graphical
information is
missing in the
model!
.dashboar
d
_diagram
37
Model vs. View: Storing graphical details in the model
1. Make your model capable of storing the graphical details
2. Install a listener on graphical
elements which updates the
location attributes each time
a figure is created/moved
3. Hook listener into your editor, e.g. in ResourceSetInfo in DiagramDocumentProvider
protected class ResourceSetInfo extends ElementInfo {
/** @generated NOT */
private GraphicElementListener graphicElementListener = new GraphicElementListener();
/** @generated NOT */
public ResourceSetInfo(IDiagramDocument document, IEditorInput editorInput) {
[...]
getResourceSet().getResources().get(0).eAdapters().add(graphicElementListener);
}
/** @generated NOT */
public void dispose() {
getResourceSet().getResources().get(0).eAdapters().remove(graphicElementListener);
[...]
}
38
Model vs. View: Graphical Element Listener
public class GraphicElementListener extends EContentAdapter {
private NotificationFilter modifiedFilter;
public GraphicElementListener() {
modifiedFilter = NotificationFilter.createEventTypeFilter(Notification.SET).or(
NotificationFilter.createEventTypeFilter(Notification.UNSET)).or(
NotificationFilter.createEventTypeFilter(Notification.ADD)).or(
NotificationFilter.createEventTypeFilter(Notification.REMOVE));
}
public void notifyChanged(Notification notification) {
if (notification.getNotifier() instanceof EObject) {
super.notifyChanged(notification);
}
if (modifiedFilter.matches(notification)
&& (notification instanceof ENotificationImpl)
&& (notification.getNotifier() instanceof EObject)) {
ENotificationImpl eNotification = (ENotificationImpl) notification;
EObject eNotifier = (EObject) eNotification.getNotifier();
if (NotationPackage.eINSTANCE.getBounds().isSuperTypeOf(eNotifier.eClass())) {
updateNodeBounds(eNotification, eNotifier);
}
}
}
private void updateNodeBounds(ENotificationImpl eNotification, EObject eNotifier) {
int featureID = eNotification.getFeatureID(EAttribute.class);
EObject modelElement = ((View) eNotifier.eContainer()).getElement();
if (modelElement instanceof ILocation){
ILocation location = (ILocation) modelElement;
switch (featureID) {
case NotationPackage.BOUNDS__X:
location.setX(eNotification.getNewIntValue());
break;
case NotationPackage.BOUNDS__Y:
location.setY(eNotification.getNewIntValue());
break;
}
}
}
}
filter for notification types
handle the notification event call updateNodeBounds
Update the location for all ILocation objects:
call setX(…) and setY(…)
extends Adapter (Listener)
39
Progress…
Topic Concepts Examples Slides
Resources in Eclipse No direct access!
Use “wrapper” for
accessing resources
IFile, IFolder, URI 9 – 14
Dialogs Use existing ones!
(static & dynamic)
MessageDialog,
InputDialog,
ResourceDialog, …
16 – 20
OCL in EMF / GMF Constraints in the model:
Object Constraint
Language
Deployment model;
OCL Console
22 – 31
GMF:
Graphical properties
in the model
Model vs. View Saving the position of
figures in the model
33 – 38
GMF: Architecture
GMF: Decorator
40
GMF Architecture
[Introduction to GMF, EclipseCon 2006]
The important relevant parts:
• .diagram.edit.commands Commands for creating elements
• .diagram.edit.parts Controller (and views!) for all model elements
• .diagram.edit.policies General editing rules and restrictions
• .diagram.part Main classes
(Editor, Wizard, Palette, Toolbar, Model provider, …)
• .diagram.providers Item providers for edit-parts
41
fig
View
(Figures)
42
GMF Architecture: MVC pattern
Controller
(EditParts)
Model
Located in you
EMF model plugin
Located in
.diagram.edit.parts
Also located in
.diagram.edit.parts
Observer
pattern
(Listeners)
Direct
access
Model
Root
“Diagram”
EditPart
Diagram
Figure
42
MVC excursion: GMF vs. Pattern idea
fig
View Controller Model
[ From Lecture 2: SE2-L02.pdf ]
• Controller and View are
tightly coupled in GMF!
• No queries from the view
to the model
43
GMF Architecture: The EditParts
• EditParts are controllers
– Create Figures
– Define Figure Layout
– Set graphical properties (not stored in the model)
– Contain Figures
• Let’s have a look at the PlaceEditPart of the Petrinet editor…
• Tipp:
Create your own package for your customized figures and integrate your figures in the .gmfgraph file
(unless you need to customize what is not possible to define in gmfgraph)
!!!
Dashboard editor does
probably not need
customized figures!
44
Progress…
Topic Concepts Examples Slides
Resources in Eclipse No direct access!
Use “wrapper” for
accessing resources
IFile, IFolder, URI 9 – 14
Dialogs Use existing ones!
(static & dynamic)
MessageDialog,
InputDialog,
ResourceDialog, …
16 – 20
OCL in EMF / GMF Constraints in the model:
Object Constraint
Language
Deployment model;
OCL Console
22 – 31
GMF:
Graphical properties
in the model
Model vs. View Saving the position of
figures in the model
33 – 38
GMF: Architecture Model-View-Controller
pattern
EditParts, Figures,
ModelElements
40 – 43
GMF: Decorator
45
Decorator: Examples
• A decorator ’decorates’ an existing element by adding something
– Overlay images, examples above
– Adding behavior to a method by delegation, e.g. streams
– Adding components on a GUI, e.g. scrollbars
• Advantages:
– Existing element is not changed!
– Different decorators possible, either nested or alternative
Where are the
decodators?
46
Decorator: The Pattern
Nested decorators:
1. the image
2. inner frame
3. outer frame
[ Design Patterns – Simply ]
47
Decorators: Realization in GMF
1. Implement a decorator by extending AbstractDecorator
• overwrite the refresh() method
• make sure changes to model elements are recognized:
install an observer on the model element and handle updates
2. Implement a decorator provider by extending AbstractProvider
and implementing IDecoratorProvider
• responsible for the creation of the decorator for the correct model elements
3. Register the decorator provider at the extension point: org.eclipse.gmf.runtime.diagram.ui.decorator.providers
[details in http://eclipsezilla.eclipsecon.org/php/attachment.php?bugid=3624]
48
Decorator: References
• Gamma, E.; Helm, R.; Johnson, R. & Vlissides, J.
Design Patterns: Elements of Reusable Object-Oriented Software
Addison-Wesley, 1995
• Design Patterns – Simply:
http://sourcemaking.com/design_patterns/decorator
• Decorating shapes in GMF (slides 44-51):
http://eclipsezilla.eclipsecon.org/php/attachment.php?bugid=3624
• GMF Tutorial:
http://wiki.eclipse.org/GMF_Tutorial_Part_2#Shortcuts
49
Summary
Topic Concepts Examples Slides
Resources in Eclipse No direct access!
Use “wrapper” for
accessing resources
IFile, IFolder, URI 9 – 14
Dialogs Use existing ones!
(static & dynamic)
MessageDialog,
InputDialog,
ResourceDialog, …
16 – 20
OCL in EMF / GMF Constraints in the model:
Object Constraint
Language
Deployment model;
OCL Console
22 – 31
GMF:
Graphical properties
in the model
Model vs. View Saving the position of
figures in the model
33 – 38
GMF: Architecture Model-View-Controller
pattern
EditParts, Figures,
ModelElements
40 – 43
GMF: Decorator Decorator design pattern Decorating figures;
Initial state in
component definition
45 – 48
Recommended