<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://dev.simantics.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Kalle+Kondelin</id>
	<title>Developer Documents - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://dev.simantics.org/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Kalle+Kondelin"/>
	<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php/Special:Contributions/Kalle_Kondelin"/>
	<updated>2026-04-06T00:49:24Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.43.0</generator>
	<entry>
		<id>https://dev.simantics.org/index.php?title=Tutorial:_Database_Development&amp;diff=2939</id>
		<title>Tutorial: Database Development</title>
		<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php?title=Tutorial:_Database_Development&amp;diff=2939"/>
		<updated>2012-09-03T12:05:56Z</updated>

		<summary type="html">&lt;p&gt;Kalle Kondelin: /* Explicit clustering */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Basic concepts =&lt;br /&gt;
;Session: Database session / connection that allows reading and writing the database using transactions.&lt;br /&gt;
;Transaction: A database operation; either read, or write operation. Simantics supports three types of transactions: Read, Write, and WriteOnly.&lt;br /&gt;
;Resource: A single object in the database.&lt;br /&gt;
;Statement: Triple consisting of subject, predicate, and object&lt;br /&gt;
;Literal: primitive value (int, double, String,..) or an array of primitive values.&lt;br /&gt;
&lt;br /&gt;
=Reading the database=&lt;br /&gt;
&lt;br /&gt;
==Literals==&lt;br /&gt;
&lt;br /&gt;
In this example we set a Label to show a Resource’s name. A resource&#039;s name is defined using the &#039;&#039;&#039;L0.HasName&#039;&#039;&#039; property relation.&lt;br /&gt;
&lt;br /&gt;
To support Layer0 URI &amp;amp;harr; resource mapping mechanism (see [[:Media:Layer0.pdf|Layer0.pdf]] section 4), resource names have certain restrictions.&lt;br /&gt;
* A single resource cannot have more than one statement objects with &#039;&#039;&#039;L0.ConsistsOf&#039;&#039;&#039;-predicate that have the same name. For example the following graph snippet in [[Graph File Format]] does not work with the URI &amp;amp;rarr; resource discovery mechanism:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
a : L0.Entity&lt;br /&gt;
    L0.ConsistsOf&lt;br /&gt;
        a : L0.Entity&lt;br /&gt;
        a : L0.Entity&lt;br /&gt;
        b : L0.Entity&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Synchronous read with a return value===&lt;br /&gt;
One way to read information stored in the database is to use synchronous reads with a return value. Return value can be any Java class, and here it is String.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
try {&lt;br /&gt;
	String name = session.syncRequest(new Read&amp;lt;String&amp;gt;() {&lt;br /&gt;
		@Override&lt;br /&gt;
		public String perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
			Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
			return graph.getRelatedValue(resource, l0.HasName);&lt;br /&gt;
				&lt;br /&gt;
		}});&lt;br /&gt;
	label.setText(name);&lt;br /&gt;
} catch (DatabaseException e) {&lt;br /&gt;
	// handle exception here&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Database connection may fail during the transaction and send an exception. Therefore you have to handle the exception in some way. Here we have wrapped the transaction inside try-catch block. In real code the most common thing to do is to let the exception propagate back to UI code.&lt;br /&gt;
&lt;br /&gt;
All literals can be read the same way, you just have to provide correct relation. There are also other methods to read literals that behave differently:&lt;br /&gt;
*getRelatedValue(): returns literal or throws and exception if value is not found&lt;br /&gt;
*getPossibleRelatedValue(): returns literal value or null, if the value does not exist.&lt;br /&gt;
&lt;br /&gt;
=== Asynchronous read ===&lt;br /&gt;
&lt;br /&gt;
Asynchronous read allows creating requests that are processed in the background. If you don’t need the result immediately, it is recommended to use asynchronous reads for performance reasons or to prevent blocking UI threads.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new ReadRequest() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void run(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		final String name =  graph.getRelatedValue(resource, l0.HasName);&lt;br /&gt;
		Display.getDefault().asyncExec(new Runnable() {&lt;br /&gt;
			@Override&lt;br /&gt;
			public void run() {&lt;br /&gt;
				if (!label.isDisposed())&lt;br /&gt;
					label.setText(name);&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here we use separate Runnable to set the label’s text (SWT components must be accessed from main / SWT thread). Note that we have to check if the label is disposed before setting the text.&lt;br /&gt;
&lt;br /&gt;
===Asynchronous read with a Procedure===&lt;br /&gt;
Using a procedure allows you to handle possible exceptions caused by failed asynchronous transaction.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new Read&amp;lt;String&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public String perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		return graph.getRelatedValue(resource, l0.HasName);&lt;br /&gt;
	}&lt;br /&gt;
}, new Procedure&amp;lt;String&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void exception(Throwable t) {&lt;br /&gt;
		// handle exception here&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	@Override&lt;br /&gt;
	public void execute(final String name) {&lt;br /&gt;
		Display.getDefault().asyncExec(new Runnable() {&lt;br /&gt;
			@Override&lt;br /&gt;
			public void run() {&lt;br /&gt;
				if (!label.isDisposed())&lt;br /&gt;
					label.setText(name);&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Asynchronous read with a SyncListener===&lt;br /&gt;
Using &amp;lt;code&amp;gt;SyncListener&amp;lt;/code&amp;gt; with a read transaction leaves a listener to the database that notifies changes in the read data. There exist also &amp;lt;code&amp;gt;Listener&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;AsyncListener&amp;lt;/code&amp;gt; interfaces. SyncListener provides a &#039;&#039;ReadGraph&#039;&#039; for the listener, AsyncListener provides &#039;&#039;AsyncReadGraph&#039;&#039; for the user. Using &amp;lt;code&amp;gt;Listener&amp;lt;/code&amp;gt; provides no graph access at all, just a notification of a changed read request result.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new Read&amp;lt;String&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public String perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		return graph.getRelatedValue(resource, l0.HasName);&lt;br /&gt;
	}&lt;br /&gt;
}, new SyncListener&amp;lt;String&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void exception(ReadGraph graph, Throwable throwable) throws DatabaseException {&lt;br /&gt;
		// handle exception here&lt;br /&gt;
	}&lt;br /&gt;
			&lt;br /&gt;
	@Override&lt;br /&gt;
	public void execute(ReadGraph graph, final String name) throws DatabaseException {&lt;br /&gt;
		Display.getDefault().asyncExec(new Runnable() {&lt;br /&gt;
			@Override&lt;br /&gt;
			public void run() {&lt;br /&gt;
				if (!label.isDisposed())&lt;br /&gt;
					label.setText(name);&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public boolean isDisposed() {&lt;br /&gt;
		return label.isDisposed();&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here the listener updates the label when the name changes. The method isDisposed() controls lifecycle of the listener, and here when the label is disposed, the listener is released and it stops updating the label.&lt;br /&gt;
&lt;br /&gt;
==Resources==&lt;br /&gt;
Reading resources is similar to reading literals. Here is an example that reads all resources that are connected to a Resource with a ConsistsOf-relation:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
try {&lt;br /&gt;
	Collection&amp;lt;Resource&amp;gt; children = session.syncRequest(new Read&amp;lt;Collection&amp;lt;Resource&amp;gt;&amp;gt;() {&lt;br /&gt;
		@Override&lt;br /&gt;
		public Collection&amp;lt;Resource&amp;gt; perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
			Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
			return graph.getObjects(resource, l0.ConsistsOf);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
} catch (DatabaseException e) {&lt;br /&gt;
	// handle exception here&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Same asynchronous, Procedure, and Listener mechanisms work with reading resources. For example, you can use listener to be notified if resources are added or removed:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new Read&amp;lt;Collection&amp;lt;Resource&amp;gt;&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public Collection&amp;lt;Resource&amp;gt; perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		return graph.getObjects(resource, l0.ConsistsOf);&lt;br /&gt;
	}&lt;br /&gt;
},new AsyncListener&amp;lt;Collection&amp;lt;Resource&amp;gt;&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void exception(AsyncReadGraph graph, Throwable throwable){&lt;br /&gt;
		// handle exception here&lt;br /&gt;
	}&lt;br /&gt;
			&lt;br /&gt;
	@Override&lt;br /&gt;
	public void execute(AsyncReadGraph graph, Collection&amp;lt;Resource&amp;gt; result) {&lt;br /&gt;
		// this is run every time a resource is added or removed&lt;br /&gt;
	}&lt;br /&gt;
			&lt;br /&gt;
	@Override&lt;br /&gt;
	public boolean isDisposed() {&lt;br /&gt;
		// this must return true when the listener is not needed&lt;br /&gt;
		// anymore to release the listener&lt;br /&gt;
		return false;&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Writing the database=&lt;br /&gt;
==Explicit clustering==&lt;br /&gt;
&lt;br /&gt;
Here we show how you can influence the way resources are grouped by the underlying implemention. You can significantly improve the dynamic behaviour of the database by grouping resources that are likely to be referenced in the same context/operation. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
try {&lt;br /&gt;
        session.syncRequest(new WriteRequest() {&lt;br /&gt;
            @Override&lt;br /&gt;
            public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
                Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
                try {&lt;br /&gt;
                    graph.newClusterSet(l0.InstanceOf);&lt;br /&gt;
                } catch (ClusterSetExistException e) {&lt;br /&gt;
                    // Cluster set exits, no problem.&lt;br /&gt;
                }&lt;br /&gt;
                Resource newResource = graph.newResource(l0.InstanceOf);&lt;br /&gt;
                graph.claim(newResource, l0.InstanceOf, null, l0.Entity); &lt;br /&gt;
            }&lt;br /&gt;
        });&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is the same effect with setting a default for newResource method.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        session.syncRequest(new WriteRequest() {&lt;br /&gt;
            @Override&lt;br /&gt;
            public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
                Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
                Resource oldClusterSet = graph.setClusterSet4NewResource(l0.InstanceOf);&lt;br /&gt;
                try {&lt;br /&gt;
                    Resource newResource = graph.newResource();&lt;br /&gt;
                    graph.claim(newResource, l0.InstanceOf, null, l0.Entity);&lt;br /&gt;
                } finally {&lt;br /&gt;
                    graph.setClusterSet4NewResource(oldClusterSet);&lt;br /&gt;
                }&lt;br /&gt;
            }&lt;br /&gt;
        });&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Setting Literals==&lt;br /&gt;
&lt;br /&gt;
Here we set a name of a resource to “New name”. Both synchronous and asynchronous versions are similar, the only difference is that with synchronous way you have to handle the exception, while using an asynchronous write without a Procedure does not let you know if the transaction failed. Any exceptions will just be logged by the database client library.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
try {&lt;br /&gt;
	session.syncRequest(new WriteRequest() {&lt;br /&gt;
		@Override&lt;br /&gt;
		public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
			Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
			graph.claimLiteral(resource, l0.HasName, &amp;quot;New name&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
} catch (DatabaseException e) {&lt;br /&gt;
	// TODO Auto-generated catch block&lt;br /&gt;
	e.printStackTrace();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new WriteRequest() {	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		graph.claimLiteral(resource, l0.HasName, &amp;quot;New name&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Using a Procedure with an asynchronous write transaction is similar to read transactions, so we don’t have separate example of that. Note that listeners can only be used with read transactions, not write transactions.&lt;br /&gt;
===Creating new Resources===&lt;br /&gt;
Same synchronous and asynchronous mechanisms apply to writing new Resources. The difference is that with asynchronous you can use a Callback to check if write failed, or separate WriteResult and a Procedure to return and check custom results of a write transaction.&lt;br /&gt;
&lt;br /&gt;
Here is an example that creates a new library, gives it a name “New Library” and connects it to given resource.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new WriteRequest() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		Resource newResource = graph.newResource();&lt;br /&gt;
		graph.claim(newResource, l0.InstanceOf, l0.Library);&lt;br /&gt;
		graph.claimLiteral(newResource, l0.HasName, &amp;quot;New Library&amp;quot;);&lt;br /&gt;
		graph.claim(resource, l0.ConsistsOf, newResource);&lt;br /&gt;
				&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The key points here are:&lt;br /&gt;
*New resource are created with WriteGraph.newResource()&lt;br /&gt;
*You must set resource’s type using InstanceOf-relation.&lt;br /&gt;
*If you do not connect created resources anywhere, the resources become orphan resources. For orphan resources there is no statement path to/from the database root resource. They cannot be traversed and therefore found from the database.&lt;br /&gt;
&lt;br /&gt;
===Deleting resources===&lt;br /&gt;
Here is an example that removes everything the given resource consists of directly. In the end it removes all the statements from the given resource, thereby essentially removing the resource itself. A resource is considered to not exist if it has no statements, since there&#039;s nothing to define its nature.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new WriteRequest() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
                for (Resource consistsOf : graph.getObjects(resource, l0.ConsistsOf)) {&lt;br /&gt;
                    // Remove all statements (consistsOf, ?p, ?o) and their possible inverse statements&lt;br /&gt;
                    graph.deny(consistsOf);&lt;br /&gt;
                }&lt;br /&gt;
                // Remove resource itself by removing any statements to/from it.&lt;br /&gt;
                graph.deny(resource);&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Another example, that deletes the name of the given resource.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new WriteRequest() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
                graph.denyLiteral(resource, l0.HasName);&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The key points here are:&lt;br /&gt;
*deny -methods are used to delete statements from the database&lt;br /&gt;
*denyLiteral -methods are used to delete literal values from the database&lt;br /&gt;
*A resource that has no statements does not exist.&lt;br /&gt;
&lt;br /&gt;
=Example case: Product and Purchase management=&lt;br /&gt;
&lt;br /&gt;
In this example, we will implement a simple product and purchase management system. The system will allow user to define new products, and create new purchase orders. To keep the example simple, the products have just a name and unit cost, and purchase orders will have name of the customer and a list of ordered products.&lt;br /&gt;
&lt;br /&gt;
We have already implemented skeleton for the system. It contains basic user interface for creating products and purchases, but it lacks several features that we are going to add during this tutorial. The base code can be found from SVN:&lt;br /&gt;
&lt;br /&gt;
*https://www.simulationsite.net/svn/simantics/tutorials/trunk/org.simantics.example&lt;br /&gt;
*https://www.simulationsite.net/svn/simantics/tutorials/trunk/org.simantics.example.feature&lt;br /&gt;
&lt;br /&gt;
Ontology that we are using is defined in &#039;&#039;Example.pgraph&#039;&#039; file. It is in &#039;&#039;org.simantics.example/graph&#039;&#039; folder. To run the example application, use &#039;&#039;simantics-example.product&#039;&#039;. After starting the example product, you should get a user interface like the one in Figure 1.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Eclipse will complain that AsyncPurchaseEditorFinal.java does not compile, but it does not prevent&lt;br /&gt;
starting the application. &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Image:simantics_db_tutorial_start.png|thumb|600px|center|Figure 1: Tutorial application after one created product (Product 1) and one purchase.]]&lt;br /&gt;
&lt;br /&gt;
When you use the application you may notice following:&lt;br /&gt;
*Name of the customer or the date of the order is not shown anywhere.&lt;br /&gt;
*When purchase editor is open, new products won’t show up in it. Only closing and opening the editor shows the products.&lt;br /&gt;
*Adding new products to purchases can be done only in Example Browser&lt;br /&gt;
*While you can order several products, you cannot order multiple items of the same product.&lt;br /&gt;
&lt;br /&gt;
Org.simantics.example plug-in is split into four packages:&lt;br /&gt;
*editors: Purchase Editor implementation.&lt;br /&gt;
*handlers: UI actions.&lt;br /&gt;
*project: Project binding. See … for more details.&lt;br /&gt;
*resource:  Taxonomy generated from the used ontology.&lt;br /&gt;
&lt;br /&gt;
The most important parts of this tutorial are editors. AsyncPurchaseEditor and classes in handlers-package.&lt;br /&gt;
&lt;br /&gt;
==Adding the missing information to UI==&lt;br /&gt;
First we have to add new Text widgets to the Purchase Editor. At the beginning of AsyncPurchaseEditor.java you see:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// UI controls&lt;br /&gt;
private final Text totalCost;&lt;br /&gt;
private final TableViewer productViewer;&lt;br /&gt;
private final TableViewerColumn nameColumn;&lt;br /&gt;
private final TableViewerColumn costColumn;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Add new line after totalCost:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
private final Text customer;&lt;br /&gt;
private final Text date;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Then we have to instantiate text fields, create labels that inform user what the text fields mean, and setup the layout properly. In the beginning of the constructor modify:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Label l = new Label(this, SWT.NONE);&lt;br /&gt;
l.setText(&amp;quot;Total Price:&amp;quot;);&lt;br /&gt;
GridDataFactory.fillDefaults().applyTo(l);&lt;br /&gt;
&lt;br /&gt;
totalCost = new Text(this, SWT.NONE);&lt;br /&gt;
totalCost.setEditable(false);&lt;br /&gt;
GridDataFactory.fillDefaults().grab(true, false).applyTo(totalCost);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
To:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Label l = new Label(this, SWT.NONE);&lt;br /&gt;
l.setText(&amp;quot;Customer:&amp;quot;);&lt;br /&gt;
GridDataFactory.fillDefaults().applyTo(l);&lt;br /&gt;
        &lt;br /&gt;
customer = new Text(this, SWT.NONE);&lt;br /&gt;
customer.setEditable(false);&lt;br /&gt;
GridDataFactory.fillDefaults().grab(true, false).applyTo(customer);&lt;br /&gt;
&lt;br /&gt;
l = new Label(this, SWT.NONE);&lt;br /&gt;
l.setText(&amp;quot;Date:&amp;quot;);&lt;br /&gt;
GridDataFactory.fillDefaults().applyTo(l);&lt;br /&gt;
&lt;br /&gt;
date = new Text(this, SWT.NONE);&lt;br /&gt;
date.setEditable(false);&lt;br /&gt;
GridDataFactory.fillDefaults().grab(true, false).applyTo(date);&lt;br /&gt;
&lt;br /&gt;
l = new Label(this, SWT.NONE);&lt;br /&gt;
l.setText(&amp;quot;Total Price:&amp;quot;);&lt;br /&gt;
GridDataFactory.fillDefaults().applyTo(l);&lt;br /&gt;
&lt;br /&gt;
totalCost = new Text(this, SWT.NONE);&lt;br /&gt;
totalCost.setEditable(false);&lt;br /&gt;
GridDataFactory.fillDefaults().grab(true, false).applyTo(totalCost);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
And finally, we have to update text fields to show the data. Modify updateUI(Model m) method to contain:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
customer.setText(m.boughtBy);&lt;br /&gt;
date.setText(m.boughtAt);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Completed code is in org.simantics.example.phases.AsyncPurchaseEditorMiddle.hava&lt;br /&gt;
&lt;br /&gt;
==Fixing the editor updates==&lt;br /&gt;
Currently the Purchase Editor loads products in the purchase when the editor is opened, but if new products are added, editor’s user interface won’t update. To fix this, modify AsyncPurhaseEditor’s setInput(Resource) method. Currently the method is:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void setInput(Resource r) {&lt;br /&gt;
    this.input = r;&lt;br /&gt;
    if (input == null)&lt;br /&gt;
        return;&lt;br /&gt;
&lt;br /&gt;
    session.asyncRequest(new Read&amp;lt;Model&amp;gt;() {&lt;br /&gt;
       @Override&lt;br /&gt;
       public Model perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
           return loadModel(graph, input);&lt;br /&gt;
       }&lt;br /&gt;
    }, new Procedure&amp;lt;Model&amp;gt;() {&lt;br /&gt;
          @Override&lt;br /&gt;
          public void exception(Throwable throwable) {&lt;br /&gt;
                ExceptionUtils.logAndShowError(throwable);&lt;br /&gt;
          }&lt;br /&gt;
          @Override&lt;br /&gt;
          public void execute(final Model result) {&lt;br /&gt;
            // Set the loaded model as the model viewed by the UI.&lt;br /&gt;
            getDisplay().asyncExec(new Runnable() {&lt;br /&gt;
               @Override&lt;br /&gt;
               public void run() {&lt;br /&gt;
                  if (isDisposed())&lt;br /&gt;
                     return;&lt;br /&gt;
                  updateUI(result);&lt;br /&gt;
               }&lt;br /&gt;
            });&lt;br /&gt;
         }&lt;br /&gt;
   });&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Hint: You have to replace the Procedure with an Listener.&lt;br /&gt;
&lt;br /&gt;
Answer:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void setInput(Resource r) {&lt;br /&gt;
   this.input = r;&lt;br /&gt;
   if (input == null)&lt;br /&gt;
      return;&lt;br /&gt;
&lt;br /&gt;
   session.asyncRequest(new Read&amp;lt;Model&amp;gt;() {&lt;br /&gt;
      @Override&lt;br /&gt;
      public Model perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
         return loadModel(graph, input);&lt;br /&gt;
      }&lt;br /&gt;
   }, new Listener&amp;lt;Model&amp;gt;() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public boolean isDisposed() {&lt;br /&gt;
        	return AsyncPurchaseEditor.this.isDisposed();&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public void exception(AsyncReadGraph graph, Throwable throwable) {&lt;br /&gt;
        	ExceptionUtils.logAndShowError(throwable);&lt;br /&gt;
        }&lt;br /&gt;
            &lt;br /&gt;
        @Override&lt;br /&gt;
        public void execute(final Model result) {&lt;br /&gt;
            // Set the loaded model as the model viewed by the UI.&lt;br /&gt;
            getDisplay().asyncExec(new Runnable() {&lt;br /&gt;
               @Override&lt;br /&gt;
               public void run() {&lt;br /&gt;
                  if (AsyncPurchaseEditor.this.isDisposed())&lt;br /&gt;
                     return;&lt;br /&gt;
                  updateUI(result);&lt;br /&gt;
               }&lt;br /&gt;
            });&lt;br /&gt;
        }&lt;br /&gt;
    });&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
After this modification the editor should update its contents when the data is changed. You may try to add new product to purchase order when the editor is open to check that it really works.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Completed code is in org.simantics.example.phases.AsyncPurchaseEditorMiddle2.hava&lt;br /&gt;
&lt;br /&gt;
==Adding Context Menu to Purchase Editor==&lt;br /&gt;
We are going to add context menu to Purchase editor. The context menu will be used for adding new products to a purchase.&lt;br /&gt;
&lt;br /&gt;
There are several ways to implement the context menu in Eclipse. For sake of simplicity, we are not going to implement context menu that allows contributions from plug-in definitions (plugin.xml). &lt;br /&gt;
&lt;br /&gt;
The code that Example Browser uses in its menu is in handlers.AddProductsContributionItem. Sadly, we cannot reuse that implementation, since it uses Eclipse’s selection mechanism to interpret current purchase, while we want to use the purchase that editor has opened.&lt;br /&gt;
&lt;br /&gt;
Put this class to AsyncPurchaseEditor.java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class AddProductsContributionItem extends CompoundContributionItem {&lt;br /&gt;
&lt;br /&gt;
  public AddProductsContributionItem() {&lt;br /&gt;
    super();&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  public AddProductsContributionItem(String id) {&lt;br /&gt;
    super(id);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  @Override&lt;br /&gt;
  protected IContributionItem[] getContributionItems() {&lt;br /&gt;
&lt;br /&gt;
    ProductManagerImpl manager = SimanticsUI.getProject().getHint(ProductManager.PRODUCT_MANAGER);&lt;br /&gt;
&lt;br /&gt;
    Map&amp;lt;Resource, String&amp;gt; products = manager.getProducts();&lt;br /&gt;
&lt;br /&gt;
    final Resource purchase = input;&lt;br /&gt;
            &lt;br /&gt;
    IContributionItem[] result = new IContributionItem[products.size()];&lt;br /&gt;
    int i=0;&lt;br /&gt;
    System.out.println(&amp;quot;Products count = &amp;quot; + products.size());&lt;br /&gt;
    for(Map.Entry&amp;lt;Resource, String&amp;gt; entry : products.entrySet()) {&lt;br /&gt;
      final Resource product = entry.getKey();&lt;br /&gt;
      result[i++] = new ActionContributionItem(new Action(&amp;quot;Add &amp;quot; + entry.getValue()) {&lt;br /&gt;
        @Override&lt;br /&gt;
        public void run() {&lt;br /&gt;
          SimanticsUI.getSession().asyncRequest(new WriteRequest() {&lt;br /&gt;
            @Override&lt;br /&gt;
            public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
              Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
              if(!graph.hasStatement(purchase, l0.ConsistsOf, product))&lt;br /&gt;
                graph.claim(purchase, l0.ConsistsOf, product);&lt;br /&gt;
              }&lt;br /&gt;
           });&lt;br /&gt;
         }&lt;br /&gt;
      });&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
It is the same code as handlers.AddProductsContributionItem, but the selection mechanism has been replaced with the editor input.&lt;br /&gt;
&lt;br /&gt;
To add context menu to the editor, add this code to the end of AsyncPurchaseEditor’s constructor:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
final MenuManager manager = new MenuManager();&lt;br /&gt;
manager.add(new AddProductsContributionItem());&lt;br /&gt;
Menu menu = manager.createContextMenu(productViewer.getControl());&lt;br /&gt;
&lt;br /&gt;
this.addDisposeListener(new DisposeListener() {&lt;br /&gt;
			&lt;br /&gt;
    @Override&lt;br /&gt;
    public void widgetDisposed(DisposeEvent e) {&lt;br /&gt;
	manager.dispose();&lt;br /&gt;
    }&lt;br /&gt;
});&lt;br /&gt;
        &lt;br /&gt;
productViewer.getControl().setMenu(menu);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Completed code is in org.simantics.example.phases.AsyncPurchaseEditorMiddle3.hava&lt;br /&gt;
&lt;br /&gt;
==Supporting multiple items of the same product==&lt;br /&gt;
Current ontology is designed so that one purchase order contains products, but product count cannot be stored anywhere [Figure 2].&lt;br /&gt;
&lt;br /&gt;
[[Image:simantics_db_tutorial1.png|thumb|center|700px|Figure 2: Purchases contain only links to products, and there is no way to store product count.]]&lt;br /&gt;
&lt;br /&gt;
To add support for product count we have to change the ontology. We have to introduce new type “ProductPurchase” that will have link to ordered Product and property for product count [Figure 3]. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
[[File:simantics_db_tutorial2.png|thumb|center|700px|Figure 3: Purchases contain ProductCounts that link to Products.]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Open the ontology (example.pgraph) and add these to ExampleOntology:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
EXAMPLE.ProductCount &amp;lt;R L0.HasProperty : L0.FunctionalRelation&lt;br /&gt;
    L0.HasDomain EXAMPLE.ProductPurchase&lt;br /&gt;
    L0.HasRange L0.Double&lt;br /&gt;
&lt;br /&gt;
EXAMPLE.ProductPurchase &amp;lt;T L0.Entity&lt;br /&gt;
    @L0.singleProperty EXAMPLE.ProductCount&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After this clean the applications workspace, since now it has a database with old ontologies.&lt;br /&gt;
 &lt;br /&gt;
To get the application working, we must update AddProductContributionsItem.java and AsyncPurchaseEditor.java. We start with the AddProduct…java. Currently its wrote transaction is:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if(!graph.hasStatement(purchase, l0.ConsistsOf, product))&lt;br /&gt;
   graph.claim(purchase, l0.ConsistsOf, product);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This just creates a link between the Purchase and selected Product. We need to create an instance of ProductPurchase link it to the Purchase and to selected Product:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 for (Resource productPurchase : graph.getObjects(purchase, l0.ConsistsOf)) {&lt;br /&gt;
    if (graph.hasStatement(productPurchase, l0.ConsistsOf, product)) {&lt;br /&gt;
       double amount = graph.getRelatedValue(productPurchase, e.ProductCount);&lt;br /&gt;
       graph.claimLiteral(productPurchase, e.ProductCount, amount + 1.0);&lt;br /&gt;
       return;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
	&lt;br /&gt;
Resource productPurchase = graph.newResource();&lt;br /&gt;
graph.claim(productPurchase, l0.InstanceOf, e.ProductPurchase);&lt;br /&gt;
graph.claimLiteral(productPurchase, e.ProductCount, 1.0);&lt;br /&gt;
graph.claim(purchase, l0.ConsistsOf, productPurchase);&lt;br /&gt;
 graph.claim(productPurchase, l0.ConsistsOf, product);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This code checks first if the product is already in the purchase, and increases count by one if it is.&lt;br /&gt;
&lt;br /&gt;
Then we edit AsyncPurchaseEditor.java.  Start by adding “amount” to Item:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Item {&lt;br /&gt;
   String name;&lt;br /&gt;
   double costs;&lt;br /&gt;
   double amount;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Next, change loadModel() method to read the data in current form and include product count:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if (g.isInstanceOf(modelResource, ex.Purchase)) {&lt;br /&gt;
   Resource purchase = modelResource;&lt;br /&gt;
   m.boughtAt = g.getRelatedValue(purchase, ex.BoughtAt);&lt;br /&gt;
   m.boughtBy = g.getRelatedValue(purchase, ex.BoughtBy);&lt;br /&gt;
&lt;br /&gt;
   List&amp;lt;Item&amp;gt; items = new ArrayList&amp;lt;Item&amp;gt;();&lt;br /&gt;
   for (Resource productPurchase : g.getObjects(purchase, g.getBuiltins().ConsistsOf)) {&lt;br /&gt;
     	Resource product = g.getSingleObject(productPurchase, b.ConsistsOf);&lt;br /&gt;
      Item i = new Item();&lt;br /&gt;
      i.name = g.getRelatedValue(product, b.HasName);&lt;br /&gt;
      i.costs = g.getRelatedValue(product, ex.Costs);&lt;br /&gt;
      i.amount = g.getRelatedValue(productPurchase, ex.ProductCount);&lt;br /&gt;
      items.add(i);&lt;br /&gt;
   }&lt;br /&gt;
   m.items = items.toArray(new Item[items.size()]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Then update AddProductContributionItem inside AsyncPurchaseEditor.java to match the previous edit.&lt;br /&gt;
&lt;br /&gt;
To show the product count we have to add new column to the table. First, create a member for the column:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
private final TableViewerColumn amountColumn;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Then initialize the column in the AsyncPurchaseEditor’s constructor:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
amountColumn = new TableViewerColumn(productViewer, SWT.LEFT);&lt;br /&gt;
amountColumn.getColumn().setWidth(100);&lt;br /&gt;
amountColumn.getColumn().setText(&amp;quot;Amount&amp;quot;);&lt;br /&gt;
amountColumn.setLabelProvider(new CellLabelProvider() {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void update(ViewerCell cell) {&lt;br /&gt;
        Item i = (Item) cell.getElement();&lt;br /&gt;
        cell.setText(String.valueOf(i.amount));&lt;br /&gt;
    }&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
And last, change updateUI() method to calculate total costs correctly and update the table’s layout:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
private void updateUI(Model m) {&lt;br /&gt;
   // Update the UI based on the contents of the specified model.&lt;br /&gt;
   double total = 0;&lt;br /&gt;
   for (Item i : m.items) {&lt;br /&gt;
      total += i.costs * i.amount;&lt;br /&gt;
   }&lt;br /&gt;
   totalCost.setText(String.valueOf(total));&lt;br /&gt;
&lt;br /&gt;
   customer.setText(m.boughtBy);&lt;br /&gt;
   date.setText(m.boughtAt);&lt;br /&gt;
        &lt;br /&gt;
   productViewer.setInput(m);&lt;br /&gt;
&lt;br /&gt;
   nameColumn.getColumn().pack();&lt;br /&gt;
   costColumn.getColumn().pack();&lt;br /&gt;
   amountColumn.getColumn().pack();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
After these modifications, your application should look like in Figure 4.&lt;br /&gt;
&lt;br /&gt;
[[File:simantics_db_tutorial_amount.png|thumb|center|700px|Figure 4: Amount column has been added into the table.]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Completed code is in org.simantics.example.phases.AsyncPurchaseEditorFinal.java and completed ontology in example.pgraph.end&lt;br /&gt;
&lt;br /&gt;
[[Category: Database Development]]&lt;br /&gt;
[[Category: Tutorials]]&lt;/div&gt;</summary>
		<author><name>Kalle Kondelin</name></author>
	</entry>
	<entry>
		<id>https://dev.simantics.org/index.php?title=Tutorial:_Database_Development&amp;diff=2938</id>
		<title>Tutorial: Database Development</title>
		<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php?title=Tutorial:_Database_Development&amp;diff=2938"/>
		<updated>2012-09-03T11:25:16Z</updated>

		<summary type="html">&lt;p&gt;Kalle Kondelin: /* Setting Literals */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;= Basic concepts =&lt;br /&gt;
;Session: Database session / connection that allows reading and writing the database using transactions.&lt;br /&gt;
;Transaction: A database operation; either read, or write operation. Simantics supports three types of transactions: Read, Write, and WriteOnly.&lt;br /&gt;
;Resource: A single object in the database.&lt;br /&gt;
;Statement: Triple consisting of subject, predicate, and object&lt;br /&gt;
;Literal: primitive value (int, double, String,..) or an array of primitive values.&lt;br /&gt;
&lt;br /&gt;
=Reading the database=&lt;br /&gt;
&lt;br /&gt;
==Literals==&lt;br /&gt;
&lt;br /&gt;
In this example we set a Label to show a Resource’s name. A resource&#039;s name is defined using the &#039;&#039;&#039;L0.HasName&#039;&#039;&#039; property relation.&lt;br /&gt;
&lt;br /&gt;
To support Layer0 URI &amp;amp;harr; resource mapping mechanism (see [[:Media:Layer0.pdf|Layer0.pdf]] section 4), resource names have certain restrictions.&lt;br /&gt;
* A single resource cannot have more than one statement objects with &#039;&#039;&#039;L0.ConsistsOf&#039;&#039;&#039;-predicate that have the same name. For example the following graph snippet in [[Graph File Format]] does not work with the URI &amp;amp;rarr; resource discovery mechanism:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
a : L0.Entity&lt;br /&gt;
    L0.ConsistsOf&lt;br /&gt;
        a : L0.Entity&lt;br /&gt;
        a : L0.Entity&lt;br /&gt;
        b : L0.Entity&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Synchronous read with a return value===&lt;br /&gt;
One way to read information stored in the database is to use synchronous reads with a return value. Return value can be any Java class, and here it is String.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
try {&lt;br /&gt;
	String name = session.syncRequest(new Read&amp;lt;String&amp;gt;() {&lt;br /&gt;
		@Override&lt;br /&gt;
		public String perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
			Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
			return graph.getRelatedValue(resource, l0.HasName);&lt;br /&gt;
				&lt;br /&gt;
		}});&lt;br /&gt;
	label.setText(name);&lt;br /&gt;
} catch (DatabaseException e) {&lt;br /&gt;
	// handle exception here&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Database connection may fail during the transaction and send an exception. Therefore you have to handle the exception in some way. Here we have wrapped the transaction inside try-catch block. In real code the most common thing to do is to let the exception propagate back to UI code.&lt;br /&gt;
&lt;br /&gt;
All literals can be read the same way, you just have to provide correct relation. There are also other methods to read literals that behave differently:&lt;br /&gt;
*getRelatedValue(): returns literal or throws and exception if value is not found&lt;br /&gt;
*getPossibleRelatedValue(): returns literal value or null, if the value does not exist.&lt;br /&gt;
&lt;br /&gt;
=== Asynchronous read ===&lt;br /&gt;
&lt;br /&gt;
Asynchronous read allows creating requests that are processed in the background. If you don’t need the result immediately, it is recommended to use asynchronous reads for performance reasons or to prevent blocking UI threads.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new ReadRequest() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void run(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		final String name =  graph.getRelatedValue(resource, l0.HasName);&lt;br /&gt;
		Display.getDefault().asyncExec(new Runnable() {&lt;br /&gt;
			@Override&lt;br /&gt;
			public void run() {&lt;br /&gt;
				if (!label.isDisposed())&lt;br /&gt;
					label.setText(name);&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here we use separate Runnable to set the label’s text (SWT components must be accessed from main / SWT thread). Note that we have to check if the label is disposed before setting the text.&lt;br /&gt;
&lt;br /&gt;
===Asynchronous read with a Procedure===&lt;br /&gt;
Using a procedure allows you to handle possible exceptions caused by failed asynchronous transaction.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new Read&amp;lt;String&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public String perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		return graph.getRelatedValue(resource, l0.HasName);&lt;br /&gt;
	}&lt;br /&gt;
}, new Procedure&amp;lt;String&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void exception(Throwable t) {&lt;br /&gt;
		// handle exception here&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	@Override&lt;br /&gt;
	public void execute(final String name) {&lt;br /&gt;
		Display.getDefault().asyncExec(new Runnable() {&lt;br /&gt;
			@Override&lt;br /&gt;
			public void run() {&lt;br /&gt;
				if (!label.isDisposed())&lt;br /&gt;
					label.setText(name);&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Asynchronous read with a SyncListener===&lt;br /&gt;
Using &amp;lt;code&amp;gt;SyncListener&amp;lt;/code&amp;gt; with a read transaction leaves a listener to the database that notifies changes in the read data. There exist also &amp;lt;code&amp;gt;Listener&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;AsyncListener&amp;lt;/code&amp;gt; interfaces. SyncListener provides a &#039;&#039;ReadGraph&#039;&#039; for the listener, AsyncListener provides &#039;&#039;AsyncReadGraph&#039;&#039; for the user. Using &amp;lt;code&amp;gt;Listener&amp;lt;/code&amp;gt; provides no graph access at all, just a notification of a changed read request result.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new Read&amp;lt;String&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public String perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		return graph.getRelatedValue(resource, l0.HasName);&lt;br /&gt;
	}&lt;br /&gt;
}, new SyncListener&amp;lt;String&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void exception(ReadGraph graph, Throwable throwable) throws DatabaseException {&lt;br /&gt;
		// handle exception here&lt;br /&gt;
	}&lt;br /&gt;
			&lt;br /&gt;
	@Override&lt;br /&gt;
	public void execute(ReadGraph graph, final String name) throws DatabaseException {&lt;br /&gt;
		Display.getDefault().asyncExec(new Runnable() {&lt;br /&gt;
			@Override&lt;br /&gt;
			public void run() {&lt;br /&gt;
				if (!label.isDisposed())&lt;br /&gt;
					label.setText(name);&lt;br /&gt;
			}&lt;br /&gt;
		});&lt;br /&gt;
	}&lt;br /&gt;
	&lt;br /&gt;
	@Override&lt;br /&gt;
	public boolean isDisposed() {&lt;br /&gt;
		return label.isDisposed();&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Here the listener updates the label when the name changes. The method isDisposed() controls lifecycle of the listener, and here when the label is disposed, the listener is released and it stops updating the label.&lt;br /&gt;
&lt;br /&gt;
==Resources==&lt;br /&gt;
Reading resources is similar to reading literals. Here is an example that reads all resources that are connected to a Resource with a ConsistsOf-relation:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
try {&lt;br /&gt;
	Collection&amp;lt;Resource&amp;gt; children = session.syncRequest(new Read&amp;lt;Collection&amp;lt;Resource&amp;gt;&amp;gt;() {&lt;br /&gt;
		@Override&lt;br /&gt;
		public Collection&amp;lt;Resource&amp;gt; perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
			Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
			return graph.getObjects(resource, l0.ConsistsOf);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
} catch (DatabaseException e) {&lt;br /&gt;
	// handle exception here&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Same asynchronous, Procedure, and Listener mechanisms work with reading resources. For example, you can use listener to be notified if resources are added or removed:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new Read&amp;lt;Collection&amp;lt;Resource&amp;gt;&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public Collection&amp;lt;Resource&amp;gt; perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		return graph.getObjects(resource, l0.ConsistsOf);&lt;br /&gt;
	}&lt;br /&gt;
},new AsyncListener&amp;lt;Collection&amp;lt;Resource&amp;gt;&amp;gt;() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void exception(AsyncReadGraph graph, Throwable throwable){&lt;br /&gt;
		// handle exception here&lt;br /&gt;
	}&lt;br /&gt;
			&lt;br /&gt;
	@Override&lt;br /&gt;
	public void execute(AsyncReadGraph graph, Collection&amp;lt;Resource&amp;gt; result) {&lt;br /&gt;
		// this is run every time a resource is added or removed&lt;br /&gt;
	}&lt;br /&gt;
			&lt;br /&gt;
	@Override&lt;br /&gt;
	public boolean isDisposed() {&lt;br /&gt;
		// this must return true when the listener is not needed&lt;br /&gt;
		// anymore to release the listener&lt;br /&gt;
		return false;&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Writing the database=&lt;br /&gt;
==Explicit clustering==&lt;br /&gt;
&lt;br /&gt;
Here we show how you can influence the way resources are grouped by the underlying implemention. You can significantly improve the dynamic behaviour of the database by grouping resources that are likely to be referenced in the same context/operation. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
try {&lt;br /&gt;
        session.syncRequest(new WriteRequest() {&lt;br /&gt;
            @Override&lt;br /&gt;
            public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
                Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
                try {&lt;br /&gt;
                    graph.newClusterSet(l0.InstanceOf);&lt;br /&gt;
                } catch (ClusterSetExistException e) {&lt;br /&gt;
                    // Cluster set exits, no problem.&lt;br /&gt;
                }&lt;br /&gt;
                Resource newResource = graph.newResource(l0.InstanceOf);&lt;br /&gt;
                graph.claim(newResource, l0.InstanceOf, null, l0.Entity); &lt;br /&gt;
            }&lt;br /&gt;
        });&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here is the same effect with setting a default for newResource method.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
        session.syncRequest(new WriteRequest() {&lt;br /&gt;
            @Override&lt;br /&gt;
            public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
                Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
                try {&lt;br /&gt;
                    graph.newClusterSet(l0.InstanceOf);&lt;br /&gt;
                } catch (ClusterSetExistException e) {&lt;br /&gt;
                    // Cluster set exits, no problem.&lt;br /&gt;
                }&lt;br /&gt;
                Resource newResource = graph.newResource(l0.InstanceOf);&lt;br /&gt;
                graph.claim(newResource, l0.InstanceOf, null, l0.Entity); &lt;br /&gt;
            }&lt;br /&gt;
        });&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Setting Literals==&lt;br /&gt;
&lt;br /&gt;
Here we set a name of a resource to “New name”. Both synchronous and asynchronous versions are similar, the only difference is that with synchronous way you have to handle the exception, while using an asynchronous write without a Procedure does not let you know if the transaction failed. Any exceptions will just be logged by the database client library.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
try {&lt;br /&gt;
	session.syncRequest(new WriteRequest() {&lt;br /&gt;
		@Override&lt;br /&gt;
		public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
			Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
			graph.claimLiteral(resource, l0.HasName, &amp;quot;New name&amp;quot;);&lt;br /&gt;
		}&lt;br /&gt;
	});&lt;br /&gt;
} catch (DatabaseException e) {&lt;br /&gt;
	// TODO Auto-generated catch block&lt;br /&gt;
	e.printStackTrace();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new WriteRequest() {	&lt;br /&gt;
	@Override&lt;br /&gt;
	public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		graph.claimLiteral(resource, l0.HasName, &amp;quot;New name&amp;quot;);&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Using a Procedure with an asynchronous write transaction is similar to read transactions, so we don’t have separate example of that. Note that listeners can only be used with read transactions, not write transactions.&lt;br /&gt;
===Creating new Resources===&lt;br /&gt;
Same synchronous and asynchronous mechanisms apply to writing new Resources. The difference is that with asynchronous you can use a Callback to check if write failed, or separate WriteResult and a Procedure to return and check custom results of a write transaction.&lt;br /&gt;
&lt;br /&gt;
Here is an example that creates a new library, gives it a name “New Library” and connects it to given resource.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new WriteRequest() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
		Resource newResource = graph.newResource();&lt;br /&gt;
		graph.claim(newResource, l0.InstanceOf, l0.Library);&lt;br /&gt;
		graph.claimLiteral(newResource, l0.HasName, &amp;quot;New Library&amp;quot;);&lt;br /&gt;
		graph.claim(resource, l0.ConsistsOf, newResource);&lt;br /&gt;
				&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The key points here are:&lt;br /&gt;
*New resource are created with WriteGraph.newResource()&lt;br /&gt;
*You must set resource’s type using InstanceOf-relation.&lt;br /&gt;
*If you do not connect created resources anywhere, the resources become orphan resources. For orphan resources there is no statement path to/from the database root resource. They cannot be traversed and therefore found from the database.&lt;br /&gt;
&lt;br /&gt;
===Deleting resources===&lt;br /&gt;
Here is an example that removes everything the given resource consists of directly. In the end it removes all the statements from the given resource, thereby essentially removing the resource itself. A resource is considered to not exist if it has no statements, since there&#039;s nothing to define its nature.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new WriteRequest() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
                for (Resource consistsOf : graph.getObjects(resource, l0.ConsistsOf)) {&lt;br /&gt;
                    // Remove all statements (consistsOf, ?p, ?o) and their possible inverse statements&lt;br /&gt;
                    graph.deny(consistsOf);&lt;br /&gt;
                }&lt;br /&gt;
                // Remove resource itself by removing any statements to/from it.&lt;br /&gt;
                graph.deny(resource);&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Another example, that deletes the name of the given resource.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
session.asyncRequest(new WriteRequest() {&lt;br /&gt;
	@Override&lt;br /&gt;
	public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
		Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
                graph.denyLiteral(resource, l0.HasName);&lt;br /&gt;
	}&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The key points here are:&lt;br /&gt;
*deny -methods are used to delete statements from the database&lt;br /&gt;
*denyLiteral -methods are used to delete literal values from the database&lt;br /&gt;
*A resource that has no statements does not exist.&lt;br /&gt;
&lt;br /&gt;
=Example case: Product and Purchase management=&lt;br /&gt;
&lt;br /&gt;
In this example, we will implement a simple product and purchase management system. The system will allow user to define new products, and create new purchase orders. To keep the example simple, the products have just a name and unit cost, and purchase orders will have name of the customer and a list of ordered products.&lt;br /&gt;
&lt;br /&gt;
We have already implemented skeleton for the system. It contains basic user interface for creating products and purchases, but it lacks several features that we are going to add during this tutorial. The base code can be found from SVN:&lt;br /&gt;
&lt;br /&gt;
*https://www.simulationsite.net/svn/simantics/tutorials/trunk/org.simantics.example&lt;br /&gt;
*https://www.simulationsite.net/svn/simantics/tutorials/trunk/org.simantics.example.feature&lt;br /&gt;
&lt;br /&gt;
Ontology that we are using is defined in &#039;&#039;Example.pgraph&#039;&#039; file. It is in &#039;&#039;org.simantics.example/graph&#039;&#039; folder. To run the example application, use &#039;&#039;simantics-example.product&#039;&#039;. After starting the example product, you should get a user interface like the one in Figure 1.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Eclipse will complain that AsyncPurchaseEditorFinal.java does not compile, but it does not prevent&lt;br /&gt;
starting the application. &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[Image:simantics_db_tutorial_start.png|thumb|600px|center|Figure 1: Tutorial application after one created product (Product 1) and one purchase.]]&lt;br /&gt;
&lt;br /&gt;
When you use the application you may notice following:&lt;br /&gt;
*Name of the customer or the date of the order is not shown anywhere.&lt;br /&gt;
*When purchase editor is open, new products won’t show up in it. Only closing and opening the editor shows the products.&lt;br /&gt;
*Adding new products to purchases can be done only in Example Browser&lt;br /&gt;
*While you can order several products, you cannot order multiple items of the same product.&lt;br /&gt;
&lt;br /&gt;
Org.simantics.example plug-in is split into four packages:&lt;br /&gt;
*editors: Purchase Editor implementation.&lt;br /&gt;
*handlers: UI actions.&lt;br /&gt;
*project: Project binding. See … for more details.&lt;br /&gt;
*resource:  Taxonomy generated from the used ontology.&lt;br /&gt;
&lt;br /&gt;
The most important parts of this tutorial are editors. AsyncPurchaseEditor and classes in handlers-package.&lt;br /&gt;
&lt;br /&gt;
==Adding the missing information to UI==&lt;br /&gt;
First we have to add new Text widgets to the Purchase Editor. At the beginning of AsyncPurchaseEditor.java you see:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
// UI controls&lt;br /&gt;
private final Text totalCost;&lt;br /&gt;
private final TableViewer productViewer;&lt;br /&gt;
private final TableViewerColumn nameColumn;&lt;br /&gt;
private final TableViewerColumn costColumn;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Add new line after totalCost:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
private final Text customer;&lt;br /&gt;
private final Text date;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Then we have to instantiate text fields, create labels that inform user what the text fields mean, and setup the layout properly. In the beginning of the constructor modify:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Label l = new Label(this, SWT.NONE);&lt;br /&gt;
l.setText(&amp;quot;Total Price:&amp;quot;);&lt;br /&gt;
GridDataFactory.fillDefaults().applyTo(l);&lt;br /&gt;
&lt;br /&gt;
totalCost = new Text(this, SWT.NONE);&lt;br /&gt;
totalCost.setEditable(false);&lt;br /&gt;
GridDataFactory.fillDefaults().grab(true, false).applyTo(totalCost);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
To:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Label l = new Label(this, SWT.NONE);&lt;br /&gt;
l.setText(&amp;quot;Customer:&amp;quot;);&lt;br /&gt;
GridDataFactory.fillDefaults().applyTo(l);&lt;br /&gt;
        &lt;br /&gt;
customer = new Text(this, SWT.NONE);&lt;br /&gt;
customer.setEditable(false);&lt;br /&gt;
GridDataFactory.fillDefaults().grab(true, false).applyTo(customer);&lt;br /&gt;
&lt;br /&gt;
l = new Label(this, SWT.NONE);&lt;br /&gt;
l.setText(&amp;quot;Date:&amp;quot;);&lt;br /&gt;
GridDataFactory.fillDefaults().applyTo(l);&lt;br /&gt;
&lt;br /&gt;
date = new Text(this, SWT.NONE);&lt;br /&gt;
date.setEditable(false);&lt;br /&gt;
GridDataFactory.fillDefaults().grab(true, false).applyTo(date);&lt;br /&gt;
&lt;br /&gt;
l = new Label(this, SWT.NONE);&lt;br /&gt;
l.setText(&amp;quot;Total Price:&amp;quot;);&lt;br /&gt;
GridDataFactory.fillDefaults().applyTo(l);&lt;br /&gt;
&lt;br /&gt;
totalCost = new Text(this, SWT.NONE);&lt;br /&gt;
totalCost.setEditable(false);&lt;br /&gt;
GridDataFactory.fillDefaults().grab(true, false).applyTo(totalCost);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
And finally, we have to update text fields to show the data. Modify updateUI(Model m) method to contain:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
customer.setText(m.boughtBy);&lt;br /&gt;
date.setText(m.boughtAt);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Completed code is in org.simantics.example.phases.AsyncPurchaseEditorMiddle.hava&lt;br /&gt;
&lt;br /&gt;
==Fixing the editor updates==&lt;br /&gt;
Currently the Purchase Editor loads products in the purchase when the editor is opened, but if new products are added, editor’s user interface won’t update. To fix this, modify AsyncPurhaseEditor’s setInput(Resource) method. Currently the method is:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void setInput(Resource r) {&lt;br /&gt;
    this.input = r;&lt;br /&gt;
    if (input == null)&lt;br /&gt;
        return;&lt;br /&gt;
&lt;br /&gt;
    session.asyncRequest(new Read&amp;lt;Model&amp;gt;() {&lt;br /&gt;
       @Override&lt;br /&gt;
       public Model perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
           return loadModel(graph, input);&lt;br /&gt;
       }&lt;br /&gt;
    }, new Procedure&amp;lt;Model&amp;gt;() {&lt;br /&gt;
          @Override&lt;br /&gt;
          public void exception(Throwable throwable) {&lt;br /&gt;
                ExceptionUtils.logAndShowError(throwable);&lt;br /&gt;
          }&lt;br /&gt;
          @Override&lt;br /&gt;
          public void execute(final Model result) {&lt;br /&gt;
            // Set the loaded model as the model viewed by the UI.&lt;br /&gt;
            getDisplay().asyncExec(new Runnable() {&lt;br /&gt;
               @Override&lt;br /&gt;
               public void run() {&lt;br /&gt;
                  if (isDisposed())&lt;br /&gt;
                     return;&lt;br /&gt;
                  updateUI(result);&lt;br /&gt;
               }&lt;br /&gt;
            });&lt;br /&gt;
         }&lt;br /&gt;
   });&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Hint: You have to replace the Procedure with an Listener.&lt;br /&gt;
&lt;br /&gt;
Answer:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public void setInput(Resource r) {&lt;br /&gt;
   this.input = r;&lt;br /&gt;
   if (input == null)&lt;br /&gt;
      return;&lt;br /&gt;
&lt;br /&gt;
   session.asyncRequest(new Read&amp;lt;Model&amp;gt;() {&lt;br /&gt;
      @Override&lt;br /&gt;
      public Model perform(ReadGraph graph) throws DatabaseException {&lt;br /&gt;
         return loadModel(graph, input);&lt;br /&gt;
      }&lt;br /&gt;
   }, new Listener&amp;lt;Model&amp;gt;() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public boolean isDisposed() {&lt;br /&gt;
        	return AsyncPurchaseEditor.this.isDisposed();&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        @Override&lt;br /&gt;
        public void exception(AsyncReadGraph graph, Throwable throwable) {&lt;br /&gt;
        	ExceptionUtils.logAndShowError(throwable);&lt;br /&gt;
        }&lt;br /&gt;
            &lt;br /&gt;
        @Override&lt;br /&gt;
        public void execute(final Model result) {&lt;br /&gt;
            // Set the loaded model as the model viewed by the UI.&lt;br /&gt;
            getDisplay().asyncExec(new Runnable() {&lt;br /&gt;
               @Override&lt;br /&gt;
               public void run() {&lt;br /&gt;
                  if (AsyncPurchaseEditor.this.isDisposed())&lt;br /&gt;
                     return;&lt;br /&gt;
                  updateUI(result);&lt;br /&gt;
               }&lt;br /&gt;
            });&lt;br /&gt;
        }&lt;br /&gt;
    });&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
After this modification the editor should update its contents when the data is changed. You may try to add new product to purchase order when the editor is open to check that it really works.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Completed code is in org.simantics.example.phases.AsyncPurchaseEditorMiddle2.hava&lt;br /&gt;
&lt;br /&gt;
==Adding Context Menu to Purchase Editor==&lt;br /&gt;
We are going to add context menu to Purchase editor. The context menu will be used for adding new products to a purchase.&lt;br /&gt;
&lt;br /&gt;
There are several ways to implement the context menu in Eclipse. For sake of simplicity, we are not going to implement context menu that allows contributions from plug-in definitions (plugin.xml). &lt;br /&gt;
&lt;br /&gt;
The code that Example Browser uses in its menu is in handlers.AddProductsContributionItem. Sadly, we cannot reuse that implementation, since it uses Eclipse’s selection mechanism to interpret current purchase, while we want to use the purchase that editor has opened.&lt;br /&gt;
&lt;br /&gt;
Put this class to AsyncPurchaseEditor.java:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class AddProductsContributionItem extends CompoundContributionItem {&lt;br /&gt;
&lt;br /&gt;
  public AddProductsContributionItem() {&lt;br /&gt;
    super();&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  public AddProductsContributionItem(String id) {&lt;br /&gt;
    super(id);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  @Override&lt;br /&gt;
  protected IContributionItem[] getContributionItems() {&lt;br /&gt;
&lt;br /&gt;
    ProductManagerImpl manager = SimanticsUI.getProject().getHint(ProductManager.PRODUCT_MANAGER);&lt;br /&gt;
&lt;br /&gt;
    Map&amp;lt;Resource, String&amp;gt; products = manager.getProducts();&lt;br /&gt;
&lt;br /&gt;
    final Resource purchase = input;&lt;br /&gt;
            &lt;br /&gt;
    IContributionItem[] result = new IContributionItem[products.size()];&lt;br /&gt;
    int i=0;&lt;br /&gt;
    System.out.println(&amp;quot;Products count = &amp;quot; + products.size());&lt;br /&gt;
    for(Map.Entry&amp;lt;Resource, String&amp;gt; entry : products.entrySet()) {&lt;br /&gt;
      final Resource product = entry.getKey();&lt;br /&gt;
      result[i++] = new ActionContributionItem(new Action(&amp;quot;Add &amp;quot; + entry.getValue()) {&lt;br /&gt;
        @Override&lt;br /&gt;
        public void run() {&lt;br /&gt;
          SimanticsUI.getSession().asyncRequest(new WriteRequest() {&lt;br /&gt;
            @Override&lt;br /&gt;
            public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
              Layer0 l0 = Layer0.getInstance(graph);&lt;br /&gt;
              if(!graph.hasStatement(purchase, l0.ConsistsOf, product))&lt;br /&gt;
                graph.claim(purchase, l0.ConsistsOf, product);&lt;br /&gt;
              }&lt;br /&gt;
           });&lt;br /&gt;
         }&lt;br /&gt;
      });&lt;br /&gt;
    }&lt;br /&gt;
    return result;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
It is the same code as handlers.AddProductsContributionItem, but the selection mechanism has been replaced with the editor input.&lt;br /&gt;
&lt;br /&gt;
To add context menu to the editor, add this code to the end of AsyncPurchaseEditor’s constructor:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
final MenuManager manager = new MenuManager();&lt;br /&gt;
manager.add(new AddProductsContributionItem());&lt;br /&gt;
Menu menu = manager.createContextMenu(productViewer.getControl());&lt;br /&gt;
&lt;br /&gt;
this.addDisposeListener(new DisposeListener() {&lt;br /&gt;
			&lt;br /&gt;
    @Override&lt;br /&gt;
    public void widgetDisposed(DisposeEvent e) {&lt;br /&gt;
	manager.dispose();&lt;br /&gt;
    }&lt;br /&gt;
});&lt;br /&gt;
        &lt;br /&gt;
productViewer.getControl().setMenu(menu);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Completed code is in org.simantics.example.phases.AsyncPurchaseEditorMiddle3.hava&lt;br /&gt;
&lt;br /&gt;
==Supporting multiple items of the same product==&lt;br /&gt;
Current ontology is designed so that one purchase order contains products, but product count cannot be stored anywhere [Figure 2].&lt;br /&gt;
&lt;br /&gt;
[[Image:simantics_db_tutorial1.png|thumb|center|700px|Figure 2: Purchases contain only links to products, and there is no way to store product count.]]&lt;br /&gt;
&lt;br /&gt;
To add support for product count we have to change the ontology. We have to introduce new type “ProductPurchase” that will have link to ordered Product and property for product count [Figure 3]. &lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
[[File:simantics_db_tutorial2.png|thumb|center|700px|Figure 3: Purchases contain ProductCounts that link to Products.]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Open the ontology (example.pgraph) and add these to ExampleOntology:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
EXAMPLE.ProductCount &amp;lt;R L0.HasProperty : L0.FunctionalRelation&lt;br /&gt;
    L0.HasDomain EXAMPLE.ProductPurchase&lt;br /&gt;
    L0.HasRange L0.Double&lt;br /&gt;
&lt;br /&gt;
EXAMPLE.ProductPurchase &amp;lt;T L0.Entity&lt;br /&gt;
    @L0.singleProperty EXAMPLE.ProductCount&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After this clean the applications workspace, since now it has a database with old ontologies.&lt;br /&gt;
 &lt;br /&gt;
To get the application working, we must update AddProductContributionsItem.java and AsyncPurchaseEditor.java. We start with the AddProduct…java. Currently its wrote transaction is:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if(!graph.hasStatement(purchase, l0.ConsistsOf, product))&lt;br /&gt;
   graph.claim(purchase, l0.ConsistsOf, product);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This just creates a link between the Purchase and selected Product. We need to create an instance of ProductPurchase link it to the Purchase and to selected Product:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 for (Resource productPurchase : graph.getObjects(purchase, l0.ConsistsOf)) {&lt;br /&gt;
    if (graph.hasStatement(productPurchase, l0.ConsistsOf, product)) {&lt;br /&gt;
       double amount = graph.getRelatedValue(productPurchase, e.ProductCount);&lt;br /&gt;
       graph.claimLiteral(productPurchase, e.ProductCount, amount + 1.0);&lt;br /&gt;
       return;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
	&lt;br /&gt;
Resource productPurchase = graph.newResource();&lt;br /&gt;
graph.claim(productPurchase, l0.InstanceOf, e.ProductPurchase);&lt;br /&gt;
graph.claimLiteral(productPurchase, e.ProductCount, 1.0);&lt;br /&gt;
graph.claim(purchase, l0.ConsistsOf, productPurchase);&lt;br /&gt;
 graph.claim(productPurchase, l0.ConsistsOf, product);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This code checks first if the product is already in the purchase, and increases count by one if it is.&lt;br /&gt;
&lt;br /&gt;
Then we edit AsyncPurchaseEditor.java.  Start by adding “amount” to Item:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Item {&lt;br /&gt;
   String name;&lt;br /&gt;
   double costs;&lt;br /&gt;
   double amount;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Next, change loadModel() method to read the data in current form and include product count:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if (g.isInstanceOf(modelResource, ex.Purchase)) {&lt;br /&gt;
   Resource purchase = modelResource;&lt;br /&gt;
   m.boughtAt = g.getRelatedValue(purchase, ex.BoughtAt);&lt;br /&gt;
   m.boughtBy = g.getRelatedValue(purchase, ex.BoughtBy);&lt;br /&gt;
&lt;br /&gt;
   List&amp;lt;Item&amp;gt; items = new ArrayList&amp;lt;Item&amp;gt;();&lt;br /&gt;
   for (Resource productPurchase : g.getObjects(purchase, g.getBuiltins().ConsistsOf)) {&lt;br /&gt;
     	Resource product = g.getSingleObject(productPurchase, b.ConsistsOf);&lt;br /&gt;
      Item i = new Item();&lt;br /&gt;
      i.name = g.getRelatedValue(product, b.HasName);&lt;br /&gt;
      i.costs = g.getRelatedValue(product, ex.Costs);&lt;br /&gt;
      i.amount = g.getRelatedValue(productPurchase, ex.ProductCount);&lt;br /&gt;
      items.add(i);&lt;br /&gt;
   }&lt;br /&gt;
   m.items = items.toArray(new Item[items.size()]);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Then update AddProductContributionItem inside AsyncPurchaseEditor.java to match the previous edit.&lt;br /&gt;
&lt;br /&gt;
To show the product count we have to add new column to the table. First, create a member for the column:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
private final TableViewerColumn amountColumn;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Then initialize the column in the AsyncPurchaseEditor’s constructor:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
amountColumn = new TableViewerColumn(productViewer, SWT.LEFT);&lt;br /&gt;
amountColumn.getColumn().setWidth(100);&lt;br /&gt;
amountColumn.getColumn().setText(&amp;quot;Amount&amp;quot;);&lt;br /&gt;
amountColumn.setLabelProvider(new CellLabelProvider() {&lt;br /&gt;
    @Override&lt;br /&gt;
    public void update(ViewerCell cell) {&lt;br /&gt;
        Item i = (Item) cell.getElement();&lt;br /&gt;
        cell.setText(String.valueOf(i.amount));&lt;br /&gt;
    }&lt;br /&gt;
});&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
And last, change updateUI() method to calculate total costs correctly and update the table’s layout:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
private void updateUI(Model m) {&lt;br /&gt;
   // Update the UI based on the contents of the specified model.&lt;br /&gt;
   double total = 0;&lt;br /&gt;
   for (Item i : m.items) {&lt;br /&gt;
      total += i.costs * i.amount;&lt;br /&gt;
   }&lt;br /&gt;
   totalCost.setText(String.valueOf(total));&lt;br /&gt;
&lt;br /&gt;
   customer.setText(m.boughtBy);&lt;br /&gt;
   date.setText(m.boughtAt);&lt;br /&gt;
        &lt;br /&gt;
   productViewer.setInput(m);&lt;br /&gt;
&lt;br /&gt;
   nameColumn.getColumn().pack();&lt;br /&gt;
   costColumn.getColumn().pack();&lt;br /&gt;
   amountColumn.getColumn().pack();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
After these modifications, your application should look like in Figure 4.&lt;br /&gt;
&lt;br /&gt;
[[File:simantics_db_tutorial_amount.png|thumb|center|700px|Figure 4: Amount column has been added into the table.]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Completed code is in org.simantics.example.phases.AsyncPurchaseEditorFinal.java and completed ontology in example.pgraph.end&lt;br /&gt;
&lt;br /&gt;
[[Category: Database Development]]&lt;br /&gt;
[[Category: Tutorials]]&lt;/div&gt;</summary>
		<author><name>Kalle Kondelin</name></author>
	</entry>
	<entry>
		<id>https://dev.simantics.org/index.php?title=Undo_Mechanism&amp;diff=2268</id>
		<title>Undo Mechanism</title>
		<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php?title=Undo_Mechanism&amp;diff=2268"/>
		<updated>2011-09-15T11:20:07Z</updated>

		<summary type="html">&lt;p&gt;Kalle Kondelin: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page documents a simple global non contextual undo/redo mechanism.&lt;br /&gt;
&lt;br /&gt;
== Mechanism ==&lt;br /&gt;
&lt;br /&gt;
Database client keeps a global list of undoable/redoable operations. Operations are added to undo list during commit. Each commit creates a change set to server which defines the changes to resource values and statements. Change set also contains metadata for interpreting the change. The metadata format is defined by client and the server can not read or interpret it. Each operation has unique change set identifier. Sequential operations are tagged as combined by giving them the same operation id. All operations with same id will be treated as single undoable/redoable operation. Database client groups all change sets created within one write request as one operation. &lt;br /&gt;
&lt;br /&gt;
== Undo and redo handling ==&lt;br /&gt;
&lt;br /&gt;
If crtl-z and crtl-y keys are mapped to call DiagramUndo/RedoHandler then the undo/redo mechanism is activated. The handlers undo/redo one operation from the global undo/redo lists with each button press. It is desirable that each developer who develops requests that modify the graph comment them as the following example shows.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    session.syncRequest(new WriteRequest() {&lt;br /&gt;
        @Override&lt;br /&gt;
        public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
            // Do your modifications.&lt;br /&gt;
            Layer0 b = Layer0.getInstance(graph);&lt;br /&gt;
            Resource s = graph.newResource();&lt;br /&gt;
            graph.claim(s, b.InstanceOf, b.Entity);&lt;br /&gt;
            &lt;br /&gt;
            // Add comment to change set.&lt;br /&gt;
            CommentMetadata cm = graph.getMetadata(CommentMetadata.class);&lt;br /&gt;
            cm.add(&amp;quot;My comment.&amp;quot;);&lt;br /&gt;
            graph.addMetadata(cm);&lt;br /&gt;
        }&lt;br /&gt;
    });&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This can be done by the following procedure:&lt;br /&gt;
&lt;br /&gt;
* Do the operation.&lt;br /&gt;
* Check from graph history view which change sets have been created and that they are commented properly.&lt;/div&gt;</summary>
		<author><name>Kalle Kondelin</name></author>
	</entry>
	<entry>
		<id>https://dev.simantics.org/index.php?title=Undo_Mechanism&amp;diff=2174</id>
		<title>Undo Mechanism</title>
		<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php?title=Undo_Mechanism&amp;diff=2174"/>
		<updated>2011-08-18T09:15:31Z</updated>

		<summary type="html">&lt;p&gt;Kalle Kondelin: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page documents a mechanism for defining context specific undo/redo operations.&lt;br /&gt;
&lt;br /&gt;
== Mechanism ==&lt;br /&gt;
&lt;br /&gt;
Client keeps context specifc lists of undoable/redoable operations. Operations are added to undo list during commit if committed request has an undo context. Each commit creates a change set to server which defines the changes to resource values and statements. Change set also contains metadata for interpreting the change. The metadata format is defined by client and the server can not read or interpret it. Each operation has unique change set identifier. Sequential operations can be tagged as combined by giving them the same operation id. All operations with same id will be treated as single undoable/redoable operation.&lt;br /&gt;
&lt;br /&gt;
== Procedure ==&lt;br /&gt;
&lt;br /&gt;
Create context&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    Session session = getSession();&lt;br /&gt;
    UndoContext uctx = new UndoContextEx();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Create request with context&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    session.syncRequest(new UndoWriteRequest(uctx, true) {&lt;br /&gt;
        @Override&lt;br /&gt;
        public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
            // Do your modifications.&lt;br /&gt;
            Layer0 b = Layer0.getInstance(graph);&lt;br /&gt;
            Resource s = graph.newResource();&lt;br /&gt;
            graph.claim(s, b.InstanceOf, b.Entity);&lt;br /&gt;
            &lt;br /&gt;
            // Add comment to change set.&lt;br /&gt;
            CommentMetadata cm = graph.getMetadata(CommentMetadata.class);&lt;br /&gt;
            cm.add(&amp;quot;My comment.&amp;quot;);/&lt;br /&gt;
            graph.addMetadata(cm);&lt;br /&gt;
        }&lt;br /&gt;
    });&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Use undo and redo operations&lt;br /&gt;
&lt;br /&gt;
    UndoRedoSupport support = session.getService(UndoRedoSupport.class);&lt;br /&gt;
    uctx.undo(support);&lt;br /&gt;
    uctx.redo(support);&lt;br /&gt;
&lt;br /&gt;
== Diagram undo and redo handling ==&lt;br /&gt;
&lt;br /&gt;
Each diagram viewer has its own undo context which can be get with getAdapter call. Crtl-z and crtl-y keys are mapped to call DiagramUndo/RedoHandler which uses getAdapter call to get the undo context and then calls undo/redo operation. Each developer who develops diagram(s)) must check that wanted operations are undoable for the diagram undo to be consistent. This can be done by the following procedure:&lt;br /&gt;
&lt;br /&gt;
* Do the operation.&lt;br /&gt;
* Check from local history view which change sets have been created.&lt;br /&gt;
* Check from undo view that change sets are combined to operations and added to the undo context correctly.&lt;/div&gt;</summary>
		<author><name>Kalle Kondelin</name></author>
	</entry>
	<entry>
		<id>https://dev.simantics.org/index.php?title=Undo_Mechanism&amp;diff=2173</id>
		<title>Undo Mechanism</title>
		<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php?title=Undo_Mechanism&amp;diff=2173"/>
		<updated>2011-08-16T06:46:21Z</updated>

		<summary type="html">&lt;p&gt;Kalle Kondelin: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page documents a mechanism for defining context specific undo/redo operations.&lt;br /&gt;
&lt;br /&gt;
== Mechanism ==&lt;br /&gt;
&lt;br /&gt;
Client keeps context specifc lists of undoable/redoable operations. Operations are added to undo list during commit if committed request has an undo context. Each commit creates a change set to server which defines the changes to resource values and statements. Change set also contains metadata for interpreting the change. The metadata format is defined by client and the server can not read or interpret it. Each operation has unique change set identifier. Sequential operations can be tagged as combined by giving them the same operation id. All operations with same id will be treated as single undoable/redoable operation.&lt;br /&gt;
&lt;br /&gt;
== Procedure ==&lt;br /&gt;
&lt;br /&gt;
Create context&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    Session session = getSession();&lt;br /&gt;
    UndoContext uctx = new UndoContextEx();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Create request with context&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    session.syncRequest(new UndoWriteRequest(uctx, true) {&lt;br /&gt;
        @Override&lt;br /&gt;
        public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
            // Do your modifications.&lt;br /&gt;
            Layer0 b = Layer0.getInstance(graph);&lt;br /&gt;
            Resource s = graph.newResource();&lt;br /&gt;
            graph.claim(s, b.InstanceOf, b.Entity);&lt;br /&gt;
            &lt;br /&gt;
            // Add comment to change set.&lt;br /&gt;
            CommentMetadata cm = graph.getMetadata(CommentMetadata.class);&lt;br /&gt;
            cm.add(&amp;quot;My comment.&amp;quot; + cu);/&lt;br /&gt;
            graph.addMetadata(cm);&lt;br /&gt;
        }&lt;br /&gt;
    });&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Use undo and redo operations&lt;br /&gt;
&lt;br /&gt;
    UndoRedoSupport support = session.getService(UndoRedoSupport.class);&lt;br /&gt;
    uctx.undo(support);&lt;br /&gt;
    uctx.redo(support);&lt;br /&gt;
&lt;br /&gt;
== Diagram undo and redo handling ==&lt;br /&gt;
&lt;br /&gt;
Each diagram viewer has its own undo context which can be get with getAdapter call. Crtl-z and crtl-y keys are mapped to call DiagramUndo/RedoHandler which uses getAdapter call to get the undo context and then calls undo/redo operation. Each developer who develops diagram(s)) must check that wanted operations are undoable for the diagram undo to be consistent. This can be done by the following procedure:&lt;br /&gt;
&lt;br /&gt;
* Do the operation.&lt;br /&gt;
* Check from local history view which change sets have been created.&lt;br /&gt;
* Check from undo view that change sets are combined to operations and added to the undo context correctly.&lt;/div&gt;</summary>
		<author><name>Kalle Kondelin</name></author>
	</entry>
	<entry>
		<id>https://dev.simantics.org/index.php?title=Undo_Mechanism&amp;diff=2171</id>
		<title>Undo Mechanism</title>
		<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php?title=Undo_Mechanism&amp;diff=2171"/>
		<updated>2011-08-09T07:17:41Z</updated>

		<summary type="html">&lt;p&gt;Kalle Kondelin: Created page with &amp;quot;This page documents a mechanism for defining context specific undo/redo operations.  == Mechanism ==  Client keeps context specifc lists of undoable/redoable operations. Operatio...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;This page documents a mechanism for defining context specific undo/redo operations.&lt;br /&gt;
&lt;br /&gt;
== Mechanism ==&lt;br /&gt;
&lt;br /&gt;
Client keeps context specifc lists of undoable/redoable operations. Operations are added to undo list during commit if committed request has an undo context. Each commit creates a change set to server which defines the changes to resource values and statements. Change set also contains metadata for interpreting the change. The metadata format is defined by client and the server can not read or interpret it. Each operation has unique change set identifier. Sequential operations can be tagged as combined by giving them the same operation id. All operations with same id will be treated as single undoable/redoable operation.&lt;br /&gt;
&lt;br /&gt;
== Procedure ==&lt;br /&gt;
&lt;br /&gt;
Create context&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    Session session = getSession();&lt;br /&gt;
    UndoContext uctx = new UndoContextEx();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Create request with context&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
    session.syncRequest(new UndoWriteRequest(uctx, true) {&lt;br /&gt;
        @Override&lt;br /&gt;
        public void perform(WriteGraph graph) throws DatabaseException {&lt;br /&gt;
            // Do your modifications.&lt;br /&gt;
            Layer0 b = Layer0.getInstance(graph);&lt;br /&gt;
            Resource s = graph.newResource();&lt;br /&gt;
            graph.claim(s, b.InstanceOf, b.Entity);&lt;br /&gt;
            &lt;br /&gt;
            // Add comment to change set.&lt;br /&gt;
            CommentMetadata cm = graph.getMetadata(CommentMetadata.class);&lt;br /&gt;
            graph.addMetadata(cm.add(&amp;quot;Added connection &amp;quot; + cu));&lt;br /&gt;
        }&lt;br /&gt;
    });&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Use undo and redeo operations&lt;br /&gt;
&lt;br /&gt;
    UndoRedoSupport support = session.getService(UndoRedoSupport.class);&lt;br /&gt;
    uctx.undo(support);&lt;br /&gt;
    uctx.redo(support);&lt;/div&gt;</summary>
		<author><name>Kalle Kondelin</name></author>
	</entry>
	<entry>
		<id>https://dev.simantics.org/index.php?title=Org.simantics.db.tests&amp;diff=465</id>
		<title>Org.simantics.db.tests</title>
		<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php?title=Org.simantics.db.tests&amp;diff=465"/>
		<updated>2010-10-06T08:19:25Z</updated>

		<summary type="html">&lt;p&gt;Kalle Kondelin: /* Running tests manually */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
This package provides small set of tests for testing DB subsystem. Testing is divided into suites for different purposes as follows:&lt;br /&gt;
&lt;br /&gt;
* Regression: This suite is designed to verify the main functionality of the system. It should be run as often as possible when something changes.&lt;br /&gt;
&lt;br /&gt;
* Performance: This suite is designed to benchmark the solution.&lt;br /&gt;
&lt;br /&gt;
* Stress: This suite is designed to ensure long-term functionality of the solution. These tests are demanding and can only be run at selected times.&lt;br /&gt;
&lt;br /&gt;
== Requirements ==&lt;br /&gt;
&lt;br /&gt;
* Individual tests and test suites can be run automatically or manually. &lt;br /&gt;
 &lt;br /&gt;
* Handling of global paramters. These are among others:&lt;br /&gt;
** running against virtual graph or server graph&lt;br /&gt;
** transaction policy&lt;br /&gt;
** java vm size&lt;br /&gt;
** etc&lt;br /&gt;
&lt;br /&gt;
* Reporting of test results.&lt;br /&gt;
** for individual tests and suites&lt;br /&gt;
*** performance time&lt;br /&gt;
*** configuration&lt;br /&gt;
** history of previous tests&lt;br /&gt;
&lt;br /&gt;
== Running tests manually ==&lt;br /&gt;
&lt;br /&gt;
Automated tests are run as ant script by hudson. The script is build.xml file in org.simantics.db.tests directory. The tests expect the same environment as the development environment for the db client i.e. org.simantics.db.build, etc.&lt;br /&gt;
&lt;br /&gt;
The script needs to know where the target directory is. Target directory is the directory containing those dependent plugins that are not part of db client code, e.g. org.simantics.databord, etc. The default target directory is &amp;quot;${user.home}/targetDir&amp;quot;. If this is not correct give the correct path with &amp;quot;-Dtarget.dir=&amp;lt;correct-path&amp;gt;&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
* Command &amp;quot;ant regression&amp;quot; runs the regression tests. &lt;br /&gt;
* Command &amp;quot;ant performance&amp;quot; runs the performance tests.&lt;br /&gt;
* Command &amp;quot;ant stress&amp;quot; runs the stress tests.&lt;br /&gt;
&lt;br /&gt;
== Running  tests in Eclipse ==&lt;br /&gt;
&lt;br /&gt;
Each test has its own launcher in launch directory and corresponding java class:&lt;br /&gt;
&lt;br /&gt;
* RegressionTests.launch and RegressionTests.java&lt;br /&gt;
* PerformanceTests.launch and PerformanceTests.java&lt;br /&gt;
* StressTests.launch and StressTests.java&lt;br /&gt;
* TempTests.launch and TempTests.java&lt;br /&gt;
&lt;br /&gt;
Either run the launcher with run as junit test or open the class and run it as junit test. Note that the latter only works if you use run as junit. If you for example choose run as junit plugin test then eclipse will modify the launcher and thing will not work.&lt;br /&gt;
&lt;br /&gt;
If you are using 64 bit eclipse the only way to get the tests working at the moment is to use 32 bit JRE.&lt;br /&gt;
&lt;br /&gt;
== Running tests in Hudson ==&lt;br /&gt;
&lt;br /&gt;
The automated tests are run by Hudson. See [http://dev.simupedia.com:12000/]. The automated tests are run every night and the test environment is reloaded if there are any changes in the source plugins. See svn-externals properties [https://www.simulationsite.net/svn/simantics-build/db/tests/trunk/tester] which is used by hudson to load tests environment. The target platform directory [[svn:target/branches/1.1]] is not currently loaded automatically.&lt;br /&gt;
&lt;br /&gt;
==Writing tests using DB==&lt;br /&gt;
Use the following test template:&lt;br /&gt;
&lt;br /&gt;
 public class TestXXX {&lt;br /&gt;
     &lt;br /&gt;
     Session session;&lt;br /&gt;
     &lt;br /&gt;
     @Before &lt;br /&gt;
     public void connect() throws Exception {&lt;br /&gt;
         // Try to load and register the Driver instance with the driver manager&lt;br /&gt;
         Class.forName(&amp;quot;fi.vtt.simantics.procore.ProCoreDriver&amp;quot;);&lt;br /&gt;
 &lt;br /&gt;
         // Connect to the server at the specified host and credentials.&lt;br /&gt;
         session = Manager.getSession(&amp;quot;procore&amp;quot;, InetSocketAddress.createUnresolved(&amp;quot;localhost&amp;quot;, 6667), &lt;br /&gt;
                 &amp;quot;Default User&amp;quot;, &amp;quot;&amp;quot;);        &lt;br /&gt;
     }&lt;br /&gt;
     &lt;br /&gt;
     @After&lt;br /&gt;
     public void disconnect() throws Exception {&lt;br /&gt;
         session.getService(LifecycleSupport.class).close(); &lt;br /&gt;
     }&lt;br /&gt;
     &lt;br /&gt;
     @Test&lt;br /&gt;
     public void sometest() throws Exception {&lt;br /&gt;
         // using session&lt;br /&gt;
     }&lt;br /&gt;
     &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The plugin must have [[org.simantics.db]] in dependency list and [[org.simantics.db.procore]] in imported packages list. Run the test as a plug-in test. It is enough to include the plugin [[org.simantics.db.procore.protocol]] and all its requirements to the run configuration of the test. You must run ProCore manually in port 6667 for the test to work.&lt;br /&gt;
&lt;br /&gt;
== Download ==&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;background-color: #e9e9e9; border: 1px solid #aaaaaa; width: 75%;&amp;quot;&lt;br /&gt;
| &#039;&#039;&#039;Version&#039;&#039;&#039;&lt;br /&gt;
| &#039;&#039;&#039;SVN Source Tag&#039;&#039;&#039;&lt;br /&gt;
|- style=&amp;quot;background-color: #f9f9f9; &amp;quot; |&lt;br /&gt;
| 1.1.0&lt;br /&gt;
| [[svn:db/tags/1.1.0/]]&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Change Log ==&lt;br /&gt;
&#039;&#039;&#039;1.2&#039;&#039;&#039;&lt;br /&gt;
* ...&lt;br /&gt;
&lt;br /&gt;
== Roadmap ==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;1.2&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
* Initial stab at regression test suite.&lt;br /&gt;
* Initial stab virtual graph, transaction policy and vm parametrizations.&lt;/div&gt;</summary>
		<author><name>Kalle Kondelin</name></author>
	</entry>
	<entry>
		<id>https://dev.simantics.org/index.php?title=Org.simantics.db.tests&amp;diff=464</id>
		<title>Org.simantics.db.tests</title>
		<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php?title=Org.simantics.db.tests&amp;diff=464"/>
		<updated>2010-10-06T08:18:14Z</updated>

		<summary type="html">&lt;p&gt;Kalle Kondelin: /* Running  tests in Eclipse */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
This package provides small set of tests for testing DB subsystem. Testing is divided into suites for different purposes as follows:&lt;br /&gt;
&lt;br /&gt;
* Regression: This suite is designed to verify the main functionality of the system. It should be run as often as possible when something changes.&lt;br /&gt;
&lt;br /&gt;
* Performance: This suite is designed to benchmark the solution.&lt;br /&gt;
&lt;br /&gt;
* Stress: This suite is designed to ensure long-term functionality of the solution. These tests are demanding and can only be run at selected times.&lt;br /&gt;
&lt;br /&gt;
== Requirements ==&lt;br /&gt;
&lt;br /&gt;
* Individual tests and test suites can be run automatically or manually. &lt;br /&gt;
 &lt;br /&gt;
* Handling of global paramters. These are among others:&lt;br /&gt;
** running against virtual graph or server graph&lt;br /&gt;
** transaction policy&lt;br /&gt;
** java vm size&lt;br /&gt;
** etc&lt;br /&gt;
&lt;br /&gt;
* Reporting of test results.&lt;br /&gt;
** for individual tests and suites&lt;br /&gt;
*** performance time&lt;br /&gt;
*** configuration&lt;br /&gt;
** history of previous tests&lt;br /&gt;
&lt;br /&gt;
== Running tests manually ==&lt;br /&gt;
&lt;br /&gt;
Automated tests are run as ant script by hudson. The script is build.xml file in org.simantics.db.tests directory. The tests expect the same environment as the development environment for the db client i.e. org.simantics.db.build, etc.&lt;br /&gt;
&lt;br /&gt;
The script needs to know where the target directory is. Target directory is the directory containing those dependent plugins that are not part of db client code, e.g. org.simantics.databord, etc. The default target directory is &amp;quot;${user.home}/targetDir&amp;quot;. If this is not correct give the correct path with &amp;quot;-Dtarget.dir=&amp;lt;correct-path&amp;gt;&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
* Command &amp;quot;ant basic&amp;quot; runs the regression tests. &lt;br /&gt;
* Command &amp;quot;ant quality&amp;quot; runs the performance tests.&lt;br /&gt;
* Command &amp;quot;ant large&amp;quot; runs the stress tests.&lt;br /&gt;
&lt;br /&gt;
== Running  tests in Eclipse ==&lt;br /&gt;
&lt;br /&gt;
Each test has its own launcher in launch directory and corresponding java class:&lt;br /&gt;
&lt;br /&gt;
* RegressionTests.launch and RegressionTests.java&lt;br /&gt;
* PerformanceTests.launch and PerformanceTests.java&lt;br /&gt;
* StressTests.launch and StressTests.java&lt;br /&gt;
* TempTests.launch and TempTests.java&lt;br /&gt;
&lt;br /&gt;
Either run the launcher with run as junit test or open the class and run it as junit test. Note that the latter only works if you use run as junit. If you for example choose run as junit plugin test then eclipse will modify the launcher and thing will not work.&lt;br /&gt;
&lt;br /&gt;
If you are using 64 bit eclipse the only way to get the tests working at the moment is to use 32 bit JRE.&lt;br /&gt;
&lt;br /&gt;
== Running tests in Hudson ==&lt;br /&gt;
&lt;br /&gt;
The automated tests are run by Hudson. See [http://dev.simupedia.com:12000/]. The automated tests are run every night and the test environment is reloaded if there are any changes in the source plugins. See svn-externals properties [https://www.simulationsite.net/svn/simantics-build/db/tests/trunk/tester] which is used by hudson to load tests environment. The target platform directory [[svn:target/branches/1.1]] is not currently loaded automatically.&lt;br /&gt;
&lt;br /&gt;
==Writing tests using DB==&lt;br /&gt;
Use the following test template:&lt;br /&gt;
&lt;br /&gt;
 public class TestXXX {&lt;br /&gt;
     &lt;br /&gt;
     Session session;&lt;br /&gt;
     &lt;br /&gt;
     @Before &lt;br /&gt;
     public void connect() throws Exception {&lt;br /&gt;
         // Try to load and register the Driver instance with the driver manager&lt;br /&gt;
         Class.forName(&amp;quot;fi.vtt.simantics.procore.ProCoreDriver&amp;quot;);&lt;br /&gt;
 &lt;br /&gt;
         // Connect to the server at the specified host and credentials.&lt;br /&gt;
         session = Manager.getSession(&amp;quot;procore&amp;quot;, InetSocketAddress.createUnresolved(&amp;quot;localhost&amp;quot;, 6667), &lt;br /&gt;
                 &amp;quot;Default User&amp;quot;, &amp;quot;&amp;quot;);        &lt;br /&gt;
     }&lt;br /&gt;
     &lt;br /&gt;
     @After&lt;br /&gt;
     public void disconnect() throws Exception {&lt;br /&gt;
         session.getService(LifecycleSupport.class).close(); &lt;br /&gt;
     }&lt;br /&gt;
     &lt;br /&gt;
     @Test&lt;br /&gt;
     public void sometest() throws Exception {&lt;br /&gt;
         // using session&lt;br /&gt;
     }&lt;br /&gt;
     &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The plugin must have [[org.simantics.db]] in dependency list and [[org.simantics.db.procore]] in imported packages list. Run the test as a plug-in test. It is enough to include the plugin [[org.simantics.db.procore.protocol]] and all its requirements to the run configuration of the test. You must run ProCore manually in port 6667 for the test to work.&lt;br /&gt;
&lt;br /&gt;
== Download ==&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;background-color: #e9e9e9; border: 1px solid #aaaaaa; width: 75%;&amp;quot;&lt;br /&gt;
| &#039;&#039;&#039;Version&#039;&#039;&#039;&lt;br /&gt;
| &#039;&#039;&#039;SVN Source Tag&#039;&#039;&#039;&lt;br /&gt;
|- style=&amp;quot;background-color: #f9f9f9; &amp;quot; |&lt;br /&gt;
| 1.1.0&lt;br /&gt;
| [[svn:db/tags/1.1.0/]]&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Change Log ==&lt;br /&gt;
&#039;&#039;&#039;1.2&#039;&#039;&#039;&lt;br /&gt;
* ...&lt;br /&gt;
&lt;br /&gt;
== Roadmap ==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;1.2&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
* Initial stab at regression test suite.&lt;br /&gt;
* Initial stab virtual graph, transaction policy and vm parametrizations.&lt;/div&gt;</summary>
		<author><name>Kalle Kondelin</name></author>
	</entry>
	<entry>
		<id>https://dev.simantics.org/index.php?title=Org.simantics.db.tests&amp;diff=460</id>
		<title>Org.simantics.db.tests</title>
		<link rel="alternate" type="text/html" href="https://dev.simantics.org/index.php?title=Org.simantics.db.tests&amp;diff=460"/>
		<updated>2010-10-06T08:05:38Z</updated>

		<summary type="html">&lt;p&gt;Kalle Kondelin: /* Running tests manually */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
This package provides small set of tests for testing DB subsystem. Testing is divided into suites for different purposes as follows:&lt;br /&gt;
&lt;br /&gt;
* Regression: This suite is designed to verify the main functionality of the system. It should be run as often as possible when something changes.&lt;br /&gt;
&lt;br /&gt;
* Performance: This suite is designed to benchmark the solution.&lt;br /&gt;
&lt;br /&gt;
* Stress: This suite is designed to ensure long-term functionality of the solution. These tests are demanding and can only be run at selected times.&lt;br /&gt;
&lt;br /&gt;
== Requirements ==&lt;br /&gt;
&lt;br /&gt;
* Individual tests and test suites can be run automatically or manually. &lt;br /&gt;
 &lt;br /&gt;
* Handling of global paramters. These are among others:&lt;br /&gt;
** running against virtual graph or server graph&lt;br /&gt;
** transaction policy&lt;br /&gt;
** java vm size&lt;br /&gt;
** etc&lt;br /&gt;
&lt;br /&gt;
* Reporting of test results.&lt;br /&gt;
** for individual tests and suites&lt;br /&gt;
*** performance time&lt;br /&gt;
*** configuration&lt;br /&gt;
** history of previous tests&lt;br /&gt;
&lt;br /&gt;
== Running tests manually ==&lt;br /&gt;
&lt;br /&gt;
Automated tests are run as ant script by hudson. The script is build.xml file in org.simantics.db.tests directory. The tests expect the same environment as the development environment for the db client i.e. org.simantics.db.build, etc.&lt;br /&gt;
&lt;br /&gt;
The script needs to know where the target directory is. Target directory is the directory containing those dependent plugins that are not part of db client code, e.g. org.simantics.databord, etc. The default target directory is &amp;quot;${user.home}/targetDir&amp;quot;. If this is not correct give the correct path with &amp;quot;-Dtarget.dir=&amp;lt;correct-path&amp;gt;&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
* Command &amp;quot;ant basic&amp;quot; runs the regression tests. &lt;br /&gt;
* Command &amp;quot;ant quality&amp;quot; runs the performance tests.&lt;br /&gt;
* Command &amp;quot;ant large&amp;quot; runs the stress tests.&lt;br /&gt;
&lt;br /&gt;
== Running  tests in Eclipse ==&lt;br /&gt;
&lt;br /&gt;
Set up the test environment by running &amp;quot;ant build-env&amp;quot;. After this you can launch the tests from org.simantics.db.tests.launch directory in eclipse.&lt;br /&gt;
&lt;br /&gt;
== Running tests in Hudson ==&lt;br /&gt;
&lt;br /&gt;
The automated tests are run by Hudson. See [http://dev.simupedia.com:12000/]. The automated tests are run every night and the test environment is reloaded if there are any changes in the source plugins. See svn-externals properties [https://www.simulationsite.net/svn/simantics-build/db/tests/trunk/tester] which is used by hudson to load tests environment. The target platform directory [[svn:target/branches/1.1]] is not currently loaded automatically.&lt;br /&gt;
&lt;br /&gt;
==Writing tests using DB==&lt;br /&gt;
Use the following test template:&lt;br /&gt;
&lt;br /&gt;
 public class TestXXX {&lt;br /&gt;
     &lt;br /&gt;
     Session session;&lt;br /&gt;
     &lt;br /&gt;
     @Before &lt;br /&gt;
     public void connect() throws Exception {&lt;br /&gt;
         // Try to load and register the Driver instance with the driver manager&lt;br /&gt;
         Class.forName(&amp;quot;fi.vtt.simantics.procore.ProCoreDriver&amp;quot;);&lt;br /&gt;
 &lt;br /&gt;
         // Connect to the server at the specified host and credentials.&lt;br /&gt;
         session = Manager.getSession(&amp;quot;procore&amp;quot;, InetSocketAddress.createUnresolved(&amp;quot;localhost&amp;quot;, 6667), &lt;br /&gt;
                 &amp;quot;Default User&amp;quot;, &amp;quot;&amp;quot;);        &lt;br /&gt;
     }&lt;br /&gt;
     &lt;br /&gt;
     @After&lt;br /&gt;
     public void disconnect() throws Exception {&lt;br /&gt;
         session.getService(LifecycleSupport.class).close(); &lt;br /&gt;
     }&lt;br /&gt;
     &lt;br /&gt;
     @Test&lt;br /&gt;
     public void sometest() throws Exception {&lt;br /&gt;
         // using session&lt;br /&gt;
     }&lt;br /&gt;
     &lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
The plugin must have [[org.simantics.db]] in dependency list and [[org.simantics.db.procore]] in imported packages list. Run the test as a plug-in test. It is enough to include the plugin [[org.simantics.db.procore.protocol]] and all its requirements to the run configuration of the test. You must run ProCore manually in port 6667 for the test to work.&lt;br /&gt;
&lt;br /&gt;
== Download ==&lt;br /&gt;
&lt;br /&gt;
{| style=&amp;quot;background-color: #e9e9e9; border: 1px solid #aaaaaa; width: 75%;&amp;quot;&lt;br /&gt;
| &#039;&#039;&#039;Version&#039;&#039;&#039;&lt;br /&gt;
| &#039;&#039;&#039;SVN Source Tag&#039;&#039;&#039;&lt;br /&gt;
|- style=&amp;quot;background-color: #f9f9f9; &amp;quot; |&lt;br /&gt;
| 1.1.0&lt;br /&gt;
| [[svn:db/tags/1.1.0/]]&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Change Log ==&lt;br /&gt;
&#039;&#039;&#039;1.2&#039;&#039;&#039;&lt;br /&gt;
* ...&lt;br /&gt;
&lt;br /&gt;
== Roadmap ==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;1.2&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
* Initial stab at regression test suite.&lt;br /&gt;
* Initial stab virtual graph, transaction policy and vm parametrizations.&lt;/div&gt;</summary>
		<author><name>Kalle Kondelin</name></author>
	</entry>
</feed>