Skip to main content
Jump to: navigation, search

Difference between revisions of "VIATRA/Addon/Databinding"

< VIATRA‎ | Addon
(Remove broken link)
(Updated to the revised databinding API)
Line 50: Line 50:
 
=== Observing match values  ===
 
=== Observing match values  ===
  
This class provides the getDatabindingAdapter factory method, which you can use to create DatabindingAdapter instances (based on a Pattern defintion object) that provide direct access to JFace observables based on the annotations provided for your pattern definition. '''Important note:''' if you are binding an IObservableValue instance obtained from the above mentioned class, it is important to pay attention on the binding's update strategy as '''you should not use a two-way updating strategy''' (because it would modify the pattern match parameter). For example if you use a DatabindingContext instance's bindValue method to create the binding, the suggested UpdateValueStrategy is the following:  
+
 
 +
The MatcherProperties class ([http://git.eclipse.org/c/viatra/org.eclipse.viatra.git/tree/addon/plugins/org.eclipse.viatra.addon.databinding.runtime/src/org/eclipse/viatra/addon/databinding/runtime/adapter/MatcherProperties.java source]) provides direct access to JFace observables based on the annotations provided for your pattern definition. '''Important note:''' if you are binding an IObservableValue instance obtained from the above mentioned class, it is important to pay attention on the binding's update strategy as '''you should not use a two-way updating strategy''' (because it would modify the pattern match parameter). For example if you use a DatabindingContext instance's bindValue method to create the binding, the suggested UpdateValueStrategy is the following:  
  
 
*UpdateValueStrategy.POLICY_NEVER in the UI to pattern match parameter binding  
 
*UpdateValueStrategy.POLICY_NEVER in the UI to pattern match parameter binding  
Line 90: Line 91:
 
<source lang="java">
 
<source lang="java">
 
//Initialize VIATRA query engine
 
//Initialize VIATRA query engine
ViatraQueryEngine engine = ViatraQueryEngine.on(new EMFScope(resourceSet));
+
    ViatraQueryEngine engine = ViatraQueryEngine.on(new EMFScope(resourceSet));
//Get the matcher for the query to be observed (HostInstances pattern)
+
    DataBindingPatterns.instance().prepare(engine);
HostInstancesMatcher matcher = HostInstancesMatcher.on(engine);
+
 
//Create a generic databinding adapter for the query specification
+
    //Get the matcher for the query to be observed (HostInstances pattern)
//It is responsible for creating observable value properties based on the annotations of the pattern
+
        HostInstancesMatcher matcher = HostInstancesMatcher.on(engine);
GenericDatabindingAdapter adapter = new GenericDatabindingAdapter(HostInstancesMatcher.querySpecification());
+
        //Create a generic databinding adapter for the query specification
//Bind the matches to the given TableViewer
+
        //It is responsible for creating observable value properties based on the annotations of the pattern
ViewerSupport.bind(
+
        //Bind the matches to the given TableViewer
tableViewer,
+
        ViewerSupport.bind(
//Get the matching results as an observable list
+
        //Specify the target table viewer
        ViatraObservables.observeMatchesAsList(matcher),
+
                tableViewer,
        //Specify observed proeprties
+
                //Get the matching results as an observable list
        new IValueProperty[] {  
+
                ViatraObservables.observeMatchesAsList(matcher),
adapter.getProperty("id"),
+
                //Specify observed proeprties
adapter.getProperty("node_ip"),
+
                new IValueProperty[] {  
adapter.getProperty("current_cpu"),
+
                MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(), "id"),
adapter.getProperty("current_hdd"),
+
                MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"node_ip"),
adapter.getProperty("current_ram"),
+
                MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"current_cpu"),
adapter.getProperty("total_cpu"),
+
                MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"current_hdd"),
adapter.getProperty("total_hdd"),
+
                MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"current_ram"),
adapter.getProperty("total_ram") });
+
                MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"total_cpu"),
 +
                MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"total_hdd"),
 +
                MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"total_ram") });
 
</source>  
 
</source>  
  
Line 123: Line 126:
 
//Initialize VIATRA query engine
 
//Initialize VIATRA query engine
 
ViatraQueryEngine engine = ViatraQueryEngine.on(new EMFScope(resourceSet));
 
ViatraQueryEngine engine = ViatraQueryEngine.on(new EMFScope(resourceSet));
 +
//Prepare target patterns
 +
DataBindingPatterns.instance().prepare(engine);
 
//Get the matcher for the query to be observed (ApplicationInstances pattern)
 
//Get the matcher for the query to be observed (ApplicationInstances pattern)
 
ApplicationInstancesMatcher matcher = ApplicationInstancesMatcher.on(engine);
 
ApplicationInstancesMatcher matcher = ApplicationInstancesMatcher.on(engine);
//Create a generic databinding adapter for the query specification
+
// Create a generic databinding adapter for the query specification
//It is responsible for creating observable value properties based on the annotations of the pattern
+
// It is responsible for creating observable value properties based on
GenericDatabindingAdapter adapter = new GenericDatabindingAdapter(ApplicationInstancesMatcher.querySpecification());
+
// the annotations of the pattern
 
//Bind the matches to the given ListViewer
 
//Bind the matches to the given ListViewer
ViewerSupport.bind(listViewer, ViatraObservables.observeMatchesAsSet(matcher), adapter.getProperty("id"));
+
ViewerSupport.bind(listViewer, ViatraObservables.observeMatchesAsSet(matcher), MatcherProperties.getValueProperty(ApplicationInstancesMatcher.querySpecification(), "id"));
  
 
//At this point, the results of the given pattern will appear in the list Viewer, the details however still need to be implemented
 
//At this point, the results of the given pattern will appear in the list Viewer, the details however still need to be implemented
Line 140: Line 145:
 
.singleSelection().observe(listViewer);
 
.singleSelection().observe(listViewer);
  
//Use the data binding context to bind the text property of the target textbox and the given property of the matcher.  
+
//Use the data binding context to bind the text property of the target textbox and the given property of the matcher.  
 
dataBindingContext.bindValue(
 
dataBindingContext.bindValue(
//Target textbox observable value
+
//Target textbox observable value
dbPassTarget,  
+
dbPassTarget,  
//Get the source observable value from the adapter
+
//Get the source observable value from the adapter
adapter.getProperty("db_pass").observeDetail(listSelection),
+
MatcherProperties.getValueProperty(ApplicationInstancesMatcher.querySpecification(), "db_pass").observeDetail(listSelection),  
//Define EMF update value strategy
+
//Define EMF update value strategy
//In this case its one directional
+
    //In this case its one directional
new EMFUpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER),
+
new EMFUpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER),
new EMFUpdateValueStrategy());
+
new EMFUpdateValueStrategy());
  
 
dataBindingContext.bindValue(dbUserTarget, adapter.getProperty("db_user").observeDetail(listSelection),  
 
dataBindingContext.bindValue(dbUserTarget, adapter.getProperty("db_user").observeDetail(listSelection),  

Revision as of 04:13, 1 April 2016

Data binding overview

Data binding is general technique that binds two data/information sources together and maintains synchronization of data. In UI data binding data objects are bound to UI elements and if the binding is done in the proper manner the changes in the data will be automatically reflected on the UI elements (for example a label will be automatically refreshed with new contents).

VIATRA provides a simple data binding facility that can be used to bind pattern matches to UI elements. The feature is mainly intended to be used to integrate VIATRA queries to newly developed user interfaces, however, the Query Explorer component also uses some related annotations. In summary, this document is intended to be used mainly by developers but the section dealing with data binding related annotations may be useful for VIATRA end-users too.

Data binding related pattern annotations

The following annotation can be used on patterns within the data binding context:

  • @QueryExplorer: the message parameter of the Query explorer annotation defines the label feature of the selected match.
  • @ObservableValue: allows the developer to customize the appearance of a match inside the Details panel. It defines an observable value (as defined in JFace databinding) which can be bound to an Eclipse/JFace UI.
    Annotation parameter(s):
    • name (String): the name of the parameter
    • expression (String): the attribute definition without '$' marks. For example @ObservableValue(name = "Year", expression="Y.startingDate")
      The parameters of the pattern are considered the default observable values of the matcher. This means, it is not required to present values like @ObservableValue(name="Y" expression="Y"). However, it is possible to redefine these values by simply defining a new value, e.g. @ObservableValue(name="Y" expression="Y.startingDate").
      It is also possible to use the annotation without parameters: in this case, it only represents that a default Observable matcher object should be generated with the default observable values. 
    • labelExpression: this annotation makes it possible to create observable string properties such as @ObservableValue(name = "TeacherStudent", labelExpression = "Teacher $T.name$ teaches Student $S.name$"), which are useful for presentation purposes inside a JFace viewer component.
The following example is from the school tutorial (see link on the bottom of this page under the 'Examples' section). Here, a pattern is given with various annotations.
// Step 7: combine everything, @PatternUI, @ObservableValue, @Handler
 
   /*
    * 
    * We want to find those years, which had courses taught by the busiest teacher
    * and included the most sociable students
    * 
    */
    @QueryExplorer(message="The busiest teacher $T.name$ taught the most sociable student $S.name$ in $Y.startingDate$")
    @ObservableValue(name = "Year", expression="Y.startingDate")
    @ObservableValue(name = "Teacher", expression="T.name")
    @ObservableValue(name = "Student", expression="S.name")
    @ObservableValue(name = "TeacherStudent", labelExpression = "Teacher $T.name$ teaches Student $S.name$")
    @Handler(fileExtension = "school")
    pattern finalPattern(Y:Year,C:Course,T:Teacher,S:Student) = {
    	Year.schoolClasses.courses(Y,C);
    	Course.teacher(C,T);
    	Student.schoolClass.courses(S,C);
 
    	find theOnesWithTheBiggestCircle(S);
    	find teachesTheMostCourses(T);
    }

The @QueryExplorer annotation will result that the match of the finalPattern pattern will have a label with the form of 'The busiest teacher $T.name$ taught the most sociable student $S.name$ in $Y.startingDate$' inside the Query Explorer. The attribute markers will be replaced with the appropriate attribute values based on the current pattern match.

VIATRA Data Binding API

VIATRA contains the "org.eclipse.viatra.addon.databinding.runtime" plug-in, which provides several useful features.

ViatraObservables class (source)

Observing match values

The MatcherProperties class (source) provides direct access to JFace observables based on the annotations provided for your pattern definition. Important note: if you are binding an IObservableValue instance obtained from the above mentioned class, it is important to pay attention on the binding's update strategy as you should not use a two-way updating strategy (because it would modify the pattern match parameter). For example if you use a DatabindingContext instance's bindValue method to create the binding, the suggested UpdateValueStrategy is the following:

  • UpdateValueStrategy.POLICY_NEVER in the UI to pattern match parameter binding
  • UpdateValueStrategy.POLICY_UPDATE in the pattern match parameter to UI binding

It is also worth noting that you must take care of the IObservableValue instances' life-cycle as the pattern match may be removed from the match set of the VIATRA query matcher (see "observing match sets" below).

Observing match sets

The ViatraObservables class provides means to observe the entire match set (query result set) as an observable list or set. This is the recommended and very efficient way of tracking changes in the query result set efficiently. See here for an example usage and further notes.

Example code

Annotated patterns

@ObservableValue(name = "id", expression = "host.id")
@ObservableValue(name = "node_ip", expression = "host.nodeIp")
@ObservableValue(name = "current_cpu", expression = "host.availableCpu")
@ObservableValue(name = "current_hdd", expression = "host.availableHdd")
@ObservableValue(name = "current_ram", expression = "host.availableRam")
@ObservableValue(name = "total_cpu", expression = "host.totalCpu")
@ObservableValue(name = "total_hdd", expression = "host.totalHdd")
@ObservableValue(name = "total_ram", expression = "host.totalRam") 
pattern hostInstances(host: HostInstance) {
	HostInstance(host);
}
 
@ObservableValue(name = "id", expression = "app.id")
@ObservableValue(name = "state", expression = "app.state")
@ObservableValue(name = "db_user", expression = "app.dbUser")
@ObservableValue(name = "db_pass", expression = "app.dbPassword")
@ObservableValue(name = "allocatedTo", expression = "app.allocatedTo")
pattern applicationInstances(app: ApplicationInstance) {
	ApplicationInstance(app);
}

Using Databinding to populate a table

//Initialize VIATRA query engine
    	ViatraQueryEngine engine = ViatraQueryEngine.on(new EMFScope(resourceSet));
    	DataBindingPatterns.instance().prepare(engine);
 
    	//Get the matcher for the query to be observed (HostInstances pattern)
        HostInstancesMatcher matcher = HostInstancesMatcher.on(engine);
        //Create a generic databinding adapter for the query specification
        //It is responsible for creating observable value properties based on the annotations of the pattern
        //Bind the matches to the given TableViewer
        ViewerSupport.bind(
        		//Specify the target table viewer
                tableViewer,
                //Get the matching results as an observable list
                ViatraObservables.observeMatchesAsList(matcher),
                //Specify observed proeprties
                new IValueProperty[] { 
                		MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(), "id"),
                		MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"node_ip"),
                		MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"current_cpu"),
                		MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"current_hdd"),
                		MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"current_ram"),
                		MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"total_cpu"),
                		MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"total_hdd"),
                		MatcherProperties.getValueProperty(HostInstancesMatcher.querySpecification(),"total_ram") });

Master - detail databinding with a list

The following code fragment is responsible for binding a list to the results of a VIATRA query, and also displays match details in text boxes. (Uses Master-detail binding)

//Create new data binding context
//It will be used for binding the pattern match details
DataBindingContext dataBindingContext = new DataBindingContext();
//Initialize VIATRA query engine
ViatraQueryEngine engine = ViatraQueryEngine.on(new EMFScope(resourceSet));
//Prepare target patterns
DataBindingPatterns.instance().prepare(engine);
//Get the matcher for the query to be observed (ApplicationInstances pattern)
ApplicationInstancesMatcher matcher = ApplicationInstancesMatcher.on(engine);
// Create a generic databinding adapter for the query specification
// It is responsible for creating observable value properties based on
// the annotations of the pattern
//Bind the matches to the given ListViewer
ViewerSupport.bind(listViewer, ViatraObservables.observeMatchesAsSet(matcher), MatcherProperties.getValueProperty(ApplicationInstancesMatcher.querySpecification(), "id"));
 
//At this point, the results of the given pattern will appear in the list Viewer, the details however still need to be implemented
//Define target observable values for both textboxes
IObservableValue dbUserTarget = WidgetProperties.text().observe(dbUser);
IObservableValue dbPassTarget = WidgetProperties.text().observe(dbPass);
 
//Observe the changes in the list selection        
IViewerObservableValue listSelection = ViewerProperties
	.singleSelection().observe(listViewer);
 
//Use the data binding context to bind the text property of the target textbox and the given property of the matcher.   
dataBindingContext.bindValue(
		//Target textbox observable value
		dbPassTarget, 
		//Get the source observable value from the adapter
		MatcherProperties.getValueProperty(ApplicationInstancesMatcher.querySpecification(), "db_pass").observeDetail(listSelection), 
		//Define EMF update value strategy
	    //In this case its one directional
		new EMFUpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER),
		new EMFUpdateValueStrategy());
 
dataBindingContext.bindValue(dbUserTarget, adapter.getProperty("db_user").observeDetail(listSelection), 
	new EMFUpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER),
	new EMFUpdateValueStrategy());

Other examples and useful resources

  • Please see the school example which demonstrates the usage of the above mentioned annotations.
  • The following tutorial is an in depth document about JFace/SWT data binding: http://www.vogella.com/articles/EclipseDataBinding/article.html
  • The DetailObserver class of the VIATRA Query Explorer gives a hint how the generated data binding code can be used (in this case for the Query Explorer's Details view). The DetailObserver class (source) extends the AbstractObservableList class, thus can be used in data binding contexts. Within the VIATRA Queries project it is used to serve as the input for a TableViewer which displays pattern match details. The TableViewer's content provider is an ObservableListContentProvider, this way data binding is automatically created and maintained.
    • The constuctor initializes the data structures and registers the IValueChangeListener instance on all pattern match parameters which were declared with an @ObservableValue annotation, thus having a getter for its observable value in the appropriate DatabindingAdapter subclass.
    • The addDetail and removeDetail methods modifiy the contents inside the view and notify (with the fireListChange call) the UI element that the backing content has changed.
    • We have registered the IValueChangeListener instance on all pattern match parameters in the constructor. Upon attribute modification this listener will be called and the appropriate element can be changed in the details view.

Back to the top