]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.common/src/org/simantics/db/common/utils/Transaction.java
Make Write-interfaces as @FunctionalInterface for lambdas
[simantics/platform.git] / bundles / org.simantics.db.common / src / org / simantics / db / common / utils / Transaction.java
1 /*******************************************************************************
2  * Copyright (c) 2007 VTT Technical Research Centre of Finland and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  *     VTT Technical Research Centre of Finland - initial API and implementation
10  *******************************************************************************/
11 package org.simantics.db.common.utils;
12
13 import java.util.Collection;
14 import java.util.Set;
15 import java.util.concurrent.Semaphore;
16
17 import org.simantics.databoard.accessor.Accessor;
18 import org.simantics.databoard.binding.Binding;
19 import org.simantics.databoard.type.Datatype;
20 import org.simantics.db.ReadGraph;
21 import org.simantics.db.RequestProcessor;
22 import org.simantics.db.Resource;
23 import org.simantics.db.Statement;
24 import org.simantics.db.WriteGraph;
25 import org.simantics.db.WriteOnlyGraph;
26 import org.simantics.db.common.request.DelayedWriteRequest;
27 import org.simantics.db.exception.AdaptionException;
28 import org.simantics.db.exception.BindingException;
29 import org.simantics.db.exception.CancelTransactionException;
30 import org.simantics.db.exception.DatabaseException;
31 import org.simantics.db.exception.DoesNotContainValueException;
32 import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
33 import org.simantics.db.exception.NoInverseException;
34 import org.simantics.db.exception.NoSingleResultException;
35 import org.simantics.db.exception.ResourceNotFoundException;
36 import org.simantics.db.exception.RuntimeDatabaseException;
37 import org.simantics.db.exception.ServiceException;
38 import org.simantics.db.exception.ValidationException;
39 import org.simantics.db.procedure.Procedure;
40 import org.simantics.db.request.DelayedWrite;
41 import org.simantics.db.request.Read;
42 import org.simantics.db.request.Write;
43 import org.simantics.utils.datastructures.Callback;
44
45 /**
46  * Synchronous Transaction. <p>
47  * 
48  * Hint: Import all methods as static.
49  * import static org.simantics.db.Transaction.*; 
50  * 
51  * Remember also to change Eclipse Preferences:
52  *   Organize Imports: number of static imports needed for .* on vakiona 99, siihen vaikka 3
53  *
54  * 
55  * Usage A:
56  * 
57  * startTransaction(session, true);
58  * try {
59  *  ...
60  *    commit();
61  * } finally {
62  *    endTransaction();
63  * }
64  * 
65  * Usage B:
66  * setGraph(g);
67  * ...
68  * setGraph(null);
69  *
70  * @author Toni Kalajainen <toni.kalajainen@vtt.fi>
71  */
72 public class Transaction {
73
74         public static enum Type {
75                 READ,
76                 WRITE,
77                 DELAYED_WRITE
78         }
79         
80         /** Thread local transactions */
81         private static ThreadLocal<TransactionInfo> transactions = new ThreadLocal<TransactionInfo>();
82         
83         static private class TransactionInfo {
84                 WriteGraph wg;
85                 ReadGraph rg;
86                 
87                 /** Semaphore that is released when the transaction is complete */
88                 Semaphore ts;
89                 
90                 /** Semaphore that is release after transaction ended */
91                 Semaphore es;
92                 
93                 /** Error */
94                 DatabaseException error;
95                 
96                 /** */
97                 boolean commit = false;
98                 
99                 TransactionInfo() {
100                 }
101                 
102                 TransactionInfo(Object graph) {
103                         if (graph instanceof WriteGraph) {
104                                 wg = (WriteGraph) graph;
105                                 rg = (ReadGraph) graph;
106                         } else if (graph instanceof ReadGraph) {
107                                 wg = null;
108                                 rg = (ReadGraph) graph;
109                         } else {
110                                 throw new RuntimeDatabaseException("Not a sync graph");
111                         }                       
112                 }
113         }
114         
115         public static ReadGraph readGraph() {
116                 TransactionInfo t = transactions.get();
117                 return t == null ? null : t.rg;
118         }
119         
120         public static WriteGraph writeGraph() {
121                 TransactionInfo t = transactions.get();
122                 return t == null ? null : t.wg;
123         }
124                 
125         public static Object setGraph(Object graph) {
126                 if (graph==null) {
127                         transactions.set(null);
128                         return null;
129                 }
130                 
131                 {
132                         Object oldGraph = null;
133                         TransactionInfo t = transactions.get();
134                         if (t!=null) {                          
135                                 oldGraph = t.rg;
136                                 if (graph instanceof WriteGraph) {
137                                         t.wg = (WriteGraph) graph;
138                                         t.rg = (ReadGraph) graph;
139                                 } else if (graph instanceof ReadGraph) {
140                                         t.wg = null;
141                                         t.rg = (ReadGraph) graph;
142                                 } else {
143                                         throw new RuntimeDatabaseException("Not a sync graph");
144                                 }                                                       
145                         } else {
146                                 t = new TransactionInfo(graph);
147                         }
148                         transactions.set(t);
149                         return oldGraph;
150                 }
151         }
152         
153         public static void startTransaction(RequestProcessor processor, boolean write) throws DatabaseException {
154                 startTransaction(processor, write ? Type.WRITE : Type.READ);
155         }
156         
157         public static void startTransaction(RequestProcessor processor, Type type) throws DatabaseException {
158                 switch (type) {
159                         case READ:
160                         {
161                                 if (transactions.get()!=null) throw new RuntimeDatabaseException("There is already a transaction.");
162                                 final Semaphore started = new Semaphore(0);
163                                 final TransactionInfo t = new TransactionInfo();
164                                 t.es = new Semaphore(0);
165                                 t.ts = new Semaphore(0);
166                                 transactions.set(t);
167
168                                 Read<Object> request = new Read<Object>() {
169                                         @Override
170                                         public Object perform(ReadGraph g) throws DatabaseException {
171                                                 t.wg = null;
172                                                 t.rg = g;
173                                                 started.release();
174                                                 try {
175                                                         t.ts.acquire();
176                                                 } catch (InterruptedException e) {
177                                                 }
178                                                 return null;
179                                         }
180                                 };
181                                 Procedure<Object> procedure = new Procedure<Object>() {
182                                     @Override
183                                     public void execute(Object result) {
184                                         t.es.release(9999);
185                                     }
186                                     @Override
187                                     public void exception(Throwable ex) {
188                                         if (ex instanceof DatabaseException)
189                                             t.error = (DatabaseException) ex;
190                                         else {
191                                             t.error = new DatabaseException(ex);
192                                         }
193                                         t.es.release(9999);
194                                     }
195                                 };
196
197                                 processor.asyncRequest(request, procedure);
198
199                                 // Wait until transaction has started
200                                 try {
201                                         // Sleep this thread until transaction has started
202                                         started.acquire(1);
203                                 } catch (InterruptedException e) {
204                                         throw new DatabaseException("Thread was interrupted.");
205                                 } finally {
206                                 }
207                         }
208                         break;
209
210                         case WRITE:
211                         {
212                                 if (transactions.get()!=null) throw new RuntimeDatabaseException("There is already a transaction.");
213                                 final Semaphore started = new Semaphore(0);
214                                 final TransactionInfo t = new TransactionInfo();
215                                 t.es = new Semaphore(0);
216                                 t.ts = new Semaphore(0);
217                                 transactions.set(t);
218
219                                 Callback<DatabaseException> callback = new Callback<DatabaseException>() {
220                                         @Override
221                                         public void run(DatabaseException parameter) {
222                                                 t.error = parameter;
223                                                 t.es.release(9999);
224                                         }
225                                 };
226
227                                 Write request =  new Write() { 
228                                         @Override
229                                         public void perform(WriteGraph g) throws DatabaseException {
230                                                 t.wg = g;
231                                                 t.rg = g;
232                                                 started.release();
233                                                 try {
234                                                         t.ts.acquire();
235                                                 } catch (InterruptedException e) {
236                                                 }
237                                                 if (!t.commit) throw new CancelTransactionException();
238                                         }
239                                 };
240
241                                 processor.asyncRequest( request, callback );
242
243                                 // Wait until transaction has started
244                                 try {
245                                         // Sleep this thread until transaction has started
246                                         started.acquire(1);
247                                 } catch (InterruptedException e) {
248                                         throw new DatabaseException("Thread was interrupted.");
249                                 } finally {
250                                 }
251                         }
252                         break;
253
254                         case DELAYED_WRITE:
255                         {
256                                 if (transactions.get()!=null) throw new RuntimeDatabaseException("There is already a transaction.");
257                                 final Semaphore started = new Semaphore(0);
258                                 final TransactionInfo t = new TransactionInfo();
259                                 t.es = new Semaphore(0);
260                                 t.ts = new Semaphore(0);
261                                 transactions.set(t);
262
263                                 Callback<DatabaseException> callback = new Callback<DatabaseException>() {
264                                         @Override
265                                         public void run(DatabaseException parameter) {
266                                                 t.error = parameter;
267                                                 t.es.release(9999);
268                                         }
269                                 };
270
271                                 DelayedWrite request =  new DelayedWriteRequest() { 
272                                         @Override
273                                         public void perform(WriteGraph g) throws DatabaseException {
274                                                 t.wg = g;
275                                                 t.rg = g;
276                                                 started.release();
277                                                 try {
278                                                         t.ts.acquire();
279                                                 } catch (InterruptedException e) {
280                                                 }
281                                                 if (!t.commit) throw new CancelTransactionException();
282                                         }
283                                 };
284
285                                 processor.asyncRequest( request, callback );
286
287                                 // Wait until transaction has started
288                                 try {
289                                         // Sleep this thread until transaction has started
290                                         started.acquire(1);
291                                 } catch (InterruptedException e) {
292                                         throw new DatabaseException("Thread was interrupted.");
293                                 } finally {
294                                 }
295                         }
296                         break;
297                 }
298         }
299         
300         /**
301          * Commits transaction if no error occurred 
302          * 
303          * @throws DatabaseException
304          */
305         public static void endTransaction() throws DatabaseException {
306                 TransactionInfo t = transactions.get();
307                 if (t == null) return; //throw new RuntimeDatabaseException("There is no transaction to commit.");
308                 
309                 t.ts.release(9999);
310                 
311                 try {
312                         t.es.acquire();
313                 } catch (InterruptedException e) {
314                         throw new DatabaseException(e);
315                 }                               
316                 
317                 if (t.error!=null) {
318                         if (t.error instanceof CancelTransactionException==false) throw t.error;                
319                 }
320                 transactions.set(null);
321         }
322
323         /**
324          * Commits transaction  
325          * 
326          * @throws DatabaseException
327          */
328         public static void commit() throws DatabaseException {
329                 TransactionInfo t = transactions.get();
330                 if (t == null) throw new RuntimeDatabaseException("There is not transaction to commit.");
331                 t.commit = true;
332                 endTransaction();
333         }
334         
335     public static String getURI(Resource resource) throws ResourceNotFoundException, ValidationException, ServiceException {
336         return readGraph().getPossibleURI(resource);
337     }
338     
339     public static String getPossibleURI(Resource resource) throws ResourceNotFoundException, ValidationException, ServiceException {
340         return readGraph().getPossibleURI(resource);
341     }
342         
343     public static Resource getResource(String uri) throws ResourceNotFoundException, ValidationException, ServiceException 
344     {
345         return readGraph().getResource(uri);
346     }
347
348     public static Resource getPossibleResource(String uri) throws ResourceNotFoundException, ValidationException, ServiceException
349     {
350         return readGraph().getPossibleResource(uri);
351     }
352     
353     public static Resource getBuiltin(String id) throws ResourceNotFoundException, ServiceException
354     {
355         return readGraph().getBuiltin(id);
356     }
357
358     public static Collection<Statement> getStatements(Resource subject, Resource relation) throws ManyObjectsForFunctionalRelationException, ServiceException
359     {
360         return readGraph().getStatements(subject, relation);
361     }
362
363     public static Collection<Statement> getAssertedStatements(Resource subject, Resource relation) throws ManyObjectsForFunctionalRelationException, ServiceException
364     {
365         return readGraph().getAssertedStatements(subject, relation);            
366     }    
367     
368     public static Collection<Resource> getPredicates(Resource subject) throws ServiceException
369     {
370         return readGraph().getPredicates(subject);      
371     }
372
373     public static Collection<Resource> getPrincipalTypes(Resource subject) throws ServiceException
374     {
375         return readGraph().getPrincipalTypes(subject);
376     }
377
378     public static Set<Resource> getTypes(Resource subject) throws ServiceException
379     {
380         return readGraph().getTypes(subject);
381     }
382
383     public static Set<Resource> getSupertypes(Resource subject) throws ServiceException
384     {
385         return readGraph().getSupertypes(subject);
386     }
387
388     public static Set<Resource> getSuperrelations(Resource subject) throws ServiceException
389     {
390         return readGraph().getSuperrelations(subject);
391     }
392
393     public static Collection<Resource> getObjects(Resource subject, Resource relation) throws ManyObjectsForFunctionalRelationException, ServiceException
394     {
395         return readGraph().getObjects(subject, relation);
396     }
397
398     public static Collection<Resource> getAssertedObjects(Resource subject, Resource relation) throws ManyObjectsForFunctionalRelationException, ServiceException
399     {
400         return readGraph().getAssertedObjects(subject, relation);
401     }
402     
403     public static Resource getInverse(Resource relation) throws NoInverseException, ManyObjectsForFunctionalRelationException, ServiceException
404     {
405         return readGraph().getInverse(relation);
406     }
407     
408     public static Resource getSingleObject(Resource subject, Resource relation) throws NoSingleResultException, ManyObjectsForFunctionalRelationException, ServiceException
409     {
410         return readGraph().getSingleObject(subject, relation);
411     }
412     
413     public static Statement getSingleStatement(Resource subject, Resource relation) throws NoSingleResultException, ManyObjectsForFunctionalRelationException, ServiceException
414     {
415         return readGraph().getSingleStatement(subject, relation);
416     }
417
418     public static Resource getSingleType(Resource subject) throws NoSingleResultException, ServiceException
419     {
420         return readGraph().getSingleType(subject);
421     }
422     
423     public static Resource getSingleType(Resource subject, Resource baseType) throws NoSingleResultException, ServiceException
424     {
425         return readGraph().getSingleType(subject, baseType);
426     }
427
428     public static <T> T getValue(Resource subject) throws DoesNotContainValueException, ServiceException
429     {
430         return readGraph().<T>getValue(subject);
431     }
432
433     public static <T> T getValue(Resource subject, Binding binding) throws DoesNotContainValueException, BindingException, ServiceException
434     {
435         return readGraph().<T>getValue(subject, binding);
436     }
437
438     public static <T> T getRelatedValue(Resource subject, Resource relation) throws NoSingleResultException, DoesNotContainValueException, ServiceException
439     {
440         return readGraph().<T>getRelatedValue(subject, relation);
441     }
442
443     public static <T> T getRelatedValue(Resource subject, Resource relation, Binding binding) throws NoSingleResultException, DoesNotContainValueException, BindingException, ServiceException
444     {
445         return readGraph().<T>getRelatedValue(subject, relation, binding);
446     }
447
448     public static <T> T adapt(Resource resource, Class<T> clazz) throws AdaptionException, ValidationException, ServiceException
449     {
450         return readGraph().adapt(resource, clazz);
451     }
452
453     public static <T> T adaptUnique(Resource resource, Class<T> clazz) throws AdaptionException, ValidationException, ServiceException
454     {
455         return readGraph().adaptUnique(resource, clazz);
456     }
457     
458     public static Resource getPossibleInverse(Resource relation) throws ManyObjectsForFunctionalRelationException, ServiceException
459     {
460         return readGraph().getPossibleInverse(relation);
461     }
462     
463     public static Resource getPossibleObject(Resource subject, Resource relation) throws ManyObjectsForFunctionalRelationException, ServiceException
464     {
465         return readGraph().getPossibleObject(subject, relation);
466     }
467     
468     public static Statement getPossibleStatement(Resource subject, Resource relation) throws ManyObjectsForFunctionalRelationException, ServiceException
469     {
470         return readGraph().getPossibleStatement(subject, relation);
471     }
472     
473     public static Resource getPossibleType(Resource subject, Resource baseType) throws ServiceException
474     {
475         return readGraph().getPossibleType(subject, baseType);
476     }
477     
478     public static <T> T getPossibleValue(Resource subject) throws ServiceException
479     {
480         return readGraph().<T>getPossibleValue(subject);
481     }
482     
483     public static <T> T getPossibleValue(Resource subject, Binding binding) throws BindingException, ServiceException
484     {
485         return readGraph().<T>getPossibleValue(subject, binding);
486     }
487
488     public static <T> T getPossibleRelatedValue(Resource subject, Resource relation) throws ManyObjectsForFunctionalRelationException, ServiceException
489     {
490         return readGraph().<T>getPossibleRelatedValue(subject, relation);
491     }
492     
493     public static <T> T getPossibleRelatedValue(Resource subject, Resource relation, Binding binding) throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException
494     {
495         return readGraph().<T>getPossibleRelatedValue(subject, relation, binding);
496     }
497     
498     public static <T> T getPossibleAdapter(Resource resource, Class<T> clazz) throws ValidationException, ServiceException
499     {
500         return readGraph().<T>getPossibleAdapter(resource, clazz);
501     }
502     
503     public static <T> T getPossibleUniqueAdapter(Resource resource, Class<T> clazz) throws ValidationException, ServiceException
504     {
505         return readGraph().<T>getPossibleUniqueAdapter(resource, clazz);
506     }
507     
508     public static boolean isInstanceOf(Resource resource, Resource type) throws ServiceException
509     {
510         return readGraph().isInstanceOf(resource, type);
511     }
512     
513     public static boolean isInheritedFrom(Resource resource, Resource type) throws ServiceException
514     {
515         return readGraph().isInheritedFrom(resource, type);
516     }
517     
518     public static boolean isSubrelationOf(Resource resource, Resource relation) throws ServiceException
519     {
520         return readGraph().isSubrelationOf(resource, relation);
521     }
522     
523     public static boolean hasStatement(Resource subject) throws ServiceException
524     {
525         return readGraph().hasStatement(subject);
526     }
527     
528     public static boolean hasStatement(Resource subject, Resource relation) throws ServiceException
529     {
530         return readGraph().hasStatement(subject, relation);
531     }
532     
533     public static boolean hasStatement(Resource subject, Resource relation, Resource object) throws ServiceException
534     {
535         return readGraph().hasStatement(subject, relation, object);
536     }
537     
538     public static boolean hasValue(Resource subject) throws ServiceException
539     {
540         return readGraph().hasValue(subject);
541     }
542     
543     public static Datatype getDataType(Resource subject) throws DatabaseException
544     {
545         return readGraph().getDataType(subject);
546     }
547     
548     public static <T extends Accessor> T getAccessor(Resource subject) throws DatabaseException
549     {
550         return readGraph().<T>getAccessor(subject);
551     }
552     
553     
554     /**
555      * Makes sure that the statements (s,p,o) and (o,p',s) are found in the
556      * graph, where p' is the inverse predicate of p. Contrary to
557      * {@link WriteOnlyGraph#claim(Resource, Resource, Resource, Resource)} this
558      * method assures that the the statement and its inverse are semantically
559      * valid after the invocation of this method.
560      * 
561      * @param subject subject, i.e. source resource of the statement to be
562      *        claimed
563      * @param predicate predicate resource of the statement to be claimed
564      * @param object object, i.e. target resource of the statement to be claimed
565      * @throws ServiceException
566      */
567     public static void claim(Resource subject, Resource predicate, Resource object) throws ServiceException {
568         writeGraph().claim(subject, predicate, object);
569     }
570
571     /**
572      * Sets literal value related to the specified resource with the specified
573      * predicate. If such value exists (s,p), the value is overridden with the
574      * new specified value.
575      * 
576      * @param resource
577      * @param predicate
578      * @param value Value of the literal (boxed primitive/String or
579      *        primitive/String array)
580      * @throws ManyObjectsForFunctionalRelationException
581      */
582     public static void claimValue(Resource resource, Resource predicate, Object value)
583     throws ManyObjectsForFunctionalRelationException, ServiceException, DatabaseException {
584         writeGraph().claimLiteral(resource, predicate, value);
585     }
586     public static void claimValue(Resource resource, Resource predicate, Object value, Binding binding)
587     throws BindingException, ManyObjectsForFunctionalRelationException, ServiceException, DatabaseException {
588         writeGraph().claimValue(resource, value, binding);
589     }
590     public static void claimValue(Resource resource, Resource predicate, Resource inverse, Resource type, Object value, Binding binding)
591     throws BindingException, ManyObjectsForFunctionalRelationException, ServiceException, DatabaseException {
592         writeGraph().claimLiteral(resource, predicate, inverse, type, value, binding);
593     }
594
595     /**
596      * Makes sure that no statements matching the patterns (s,?p,?o) and
597      * (?o,?p',s), where ?p' is the inverse predicate of ?p, exist in the graph.
598      * In other words, removes all statements outgoing from the specified
599      * resource along with the inverses of those statements.
600      * 
601      * @param subject
602      * @throws ServiceException
603      */
604     public static void deny(Resource subject) throws ServiceException {
605         writeGraph().deny(subject);
606     }
607
608     /**
609      * Makes sure that no statements matching the patterns (s,p,?o) and
610      * (?o,p',s), where p' is the inverse predicate of p, exist in the graph.
611      * Also statements where <code>isSubrelationOf(p, predicate)</code> returns
612      * <code>true</code> shall be removed. In other words, removes all
613      * statements outgoing from the specified resource with the specified
614      * predicate or any of its subrelations, along with the inverses of those
615      * statements.
616      * 
617      * @param subject
618      * @throws ServiceException
619      */
620     public static void deny(Resource subject, Resource predicate) throws ServiceException {
621         writeGraph().deny(subject, predicate);
622     }
623
624     /**
625      * Makes sure that no statements matching the patterns (s,p,o) and (o,p',s),
626      * where p' is the inverse predicate of p, exist in the graph. Contrary to
627      * {@link #denyStatement(Resource, Resource, Resource)}, all statements
628      * where <code>isSubrelationOf(p, predicate)</code> returns
629      * <code>true</code> shall be removed. In other words, removes all
630      * statements between the specified subject and object with the specified
631      * predicate or any of its subrelations, along with the inverses of those
632      * statements.
633      * 
634      * @param subject
635      * @param predicate
636      * @param object
637      * @throws ServiceException
638      */
639     public static void deny(Resource subject, Resource predicate, Resource object) throws ServiceException {
640         writeGraph().deny(subject, predicate, object);
641     }
642
643     /**
644      * Makes sure that no statements matching the patterns (s,p,o) and (o,p',s),
645      * where p' is the inverse predicate of p, exist in the graph. In other
646      * words, removes the specified statement and its possible inverse.
647      * 
648      * <p>
649      * This method behaves exactly like {@link #deny(Statement)}, it just takes
650      * the arguments as resources instead of a statement.
651      * 
652      * @param subject
653      * @throws ServiceException
654      * 
655      * @see {@link #deny(Statement)}
656      */
657     public static void denyStatement(Resource subject, Resource predicate, Resource object) throws ServiceException {
658         writeGraph().denyStatement(subject, predicate, object);
659     }
660
661     /**
662      * Makes sure that the specified statements (s,p,o) and its inverse
663      * statements (o,p',s), where p' is the inverse predicate of p, do not exist
664      * in the graph.
665      * 
666      * <p>
667      * This method behaves exactly like
668      * {@link #denyStatement(Resource, Resource, Resource)}, it just takes the
669      * arguments as a statement instead of 3 resources.
670      * 
671      * @param statement
672      * 
673      * @see #denyStatement(Resource, Resource, Resource)
674      */
675     public static void deny(Statement statement) throws ServiceException {
676         writeGraph().deny(statement);
677     }
678
679     /**
680      * Removes all statements (resource,predicate,?o) and literal contained by
681      * ?o.
682      * 
683      * @param resource
684      * @param predicate
685      * @throws ManyObjectsForFunctionalRelationException
686      */
687     public static void denyValue(Resource resource, Resource predicate) throws ManyObjectsForFunctionalRelationException, ServiceException {
688         writeGraph().denyValue(resource, predicate);
689     }
690     
691 }
692