Multiple reader thread support for db client
[simantics/platform.git] / bundles / org.simantics.db.procore / src / fi / vtt / simantics / procore / internal / WriteStateBase.java
1 package fi.vtt.simantics.procore.internal;
2
3 import java.util.concurrent.Semaphore;
4
5 import org.simantics.db.common.utils.Logger;
6 import org.simantics.db.exception.DatabaseException;
7 import org.simantics.db.procedure.Procedure;
8 import org.simantics.db.request.WriteTraits;
9
10 /**
11  * @author Tuukka Lehtonen
12  *
13  * @param <T> result value type
14  */
15 public class WriteStateBase<T> {
16
17     final protected WriteTraits request;
18     final protected Semaphore notify;
19     final protected Procedure<T> procedure;
20
21     protected T result;
22     protected Throwable exception;
23
24     public WriteStateBase(WriteTraits request, Semaphore notify, Procedure<T> procedure) {
25         assert(request != null);
26
27         this.request = request;
28         this.notify = notify;
29         this.procedure = procedure;
30     }
31
32     public WriteTraits getRequest() {
33         return request;
34     }
35
36     @SuppressWarnings("unchecked")
37     public void setResult(Object result) {
38         this.result = (T) result;
39     }
40
41     public void except(Throwable throwable) {
42         this.exception = throwable;
43     }
44
45 //    public void cancel(CancelTransactionException e) {
46 //        this.exception = e;
47 //    }
48 //
49 //    public boolean isCanceled() {
50 //        return exception instanceof CancelTransactionException;
51 //    }
52
53     public boolean isExcepted() {
54         return exception != null;
55     }
56
57     public void finish() {
58
59         if(procedure != null) {
60
61             try {
62                 // Callback is client code, we have to be prepared for it to throw unexpected exceptions.
63                 // All we can do here is to log those, can't really pass them anywhere.
64                 if (procedure != null) {
65                     if(isExcepted()) {
66                         if(exception instanceof DatabaseException) procedure.exception(exception);
67                         else procedure.exception(new DatabaseException(exception));
68                     }
69                     else procedure.execute(result);
70                 }
71             } catch (Throwable t) {
72                 Logger.defaultLogError("Write request callback caused an unexpected error, see exception.", t);
73                 if (SessionImplSocket.DEBUG)
74                     t.printStackTrace();
75             }
76
77         }
78
79         if(notify != null) notify.release();
80
81     }
82
83 }