]> gerrit.simantics Code Review - simantics/platform.git/commitdiff
Still working for multiple readers
authorAntti Villberg <antti.villberg@semantum.fi>
Thu, 14 Jun 2018 14:16:54 +0000 (17:16 +0300)
committerAntti Villberg <antti.villberg@semantum.fi>
Thu, 26 Jul 2018 20:59:48 +0000 (23:59 +0300)
gitlab #5
gitlab #6

Change-Id: Ica299d5dd091a641a7a1a18e1093602a9027dd57

78 files changed:
bundles/org.simantics.browsing.ui.common/src/org/simantics/browsing/ui/common/internal/GENodeQueryManager.java
bundles/org.simantics.browsing.ui.common/src/org/simantics/browsing/ui/common/internal/IGraphExplorerContext.java
bundles/org.simantics.browsing.ui.common/src/org/simantics/browsing/ui/common/viewpoints/ViewpointStub.java
bundles/org.simantics.browsing.ui.nattable/src/org/simantics/browsing/ui/nattable/NatTableGraphExplorer.java
bundles/org.simantics.browsing.ui.swt/src/org/simantics/browsing/ui/swt/GraphExplorerImpl.java
bundles/org.simantics.browsing.ui.swt/src/org/simantics/browsing/ui/swt/GraphExplorerImpl2.java
bundles/org.simantics.browsing.ui/src/org/simantics/browsing/ui/PrimitiveQueryUpdater.java
bundles/org.simantics.db.common/META-INF/MANIFEST.MF
bundles/org.simantics.db.common/src/org/simantics/db/common/primitiverequest/PossibleAdapter.java
bundles/org.simantics.db.common/src/org/simantics/db/common/procedure/BlockingAsyncProcedure.java [new file with mode: 0644]
bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/AsyncBarrierImpl.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/ReadGraphImpl.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/WriteGraphImpl.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AssertedPredicates.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AssertedStatements.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncMultiReadEntry.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/AsyncReadEntry.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/BinaryQueryHash.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CacheEntryBase.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/ChildMap.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/CodeGen.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/DirectObjects.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/DirectPredicates.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/DirectSuperRelations.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/ExternalReadEntry.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/MultiReadEntry.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/Objects.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/OrderedSet.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/PossibleSuperRelation.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/Predicates.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/PrincipalTypes.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCache.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryCacheBase.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryProcessor.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/QueryThread.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/ReadEntry.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/RelationInfoQuery.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/Statements.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/SuperRelations.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/SuperTypes.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/TypeHierarchy.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/Types.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/URIToResource.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/UnaryQueryHash.java
bundles/org.simantics.db.impl/src/org/simantics/db/impl/query/ValueQuery.java
bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/RuntimeEnvironmentRequest2.java
bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/variable/NodeValueRequest.java
bundles/org.simantics.db.procore/src/fi/vtt/simantics/procore/internal/ClusterTable.java
bundles/org.simantics.db.procore/src/fi/vtt/simantics/procore/internal/SessionImplSocket.java
bundles/org.simantics.db.procore/src/fi/vtt/simantics/procore/internal/SessionRequestManager.java
bundles/org.simantics.db.services/src/org/simantics/db/services/adaption/AdaptionService2.java
bundles/org.simantics.desktop.product/plugin.xml
bundles/org.simantics.diagram/src/org/simantics/diagram/adapter/DiagramContentRequest.java
bundles/org.simantics.diagram/src/org/simantics/diagram/adapter/GraphToDiagramSynchronizer.java
bundles/org.simantics.diagram/src/org/simantics/diagram/internal/DebugPolicy.java
bundles/org.simantics.document.server/META-INF/MANIFEST.MF
bundles/org.simantics.document.server/src/org/simantics/document/server/request/DocumentRequest.java
bundles/org.simantics.document.server/src/org/simantics/document/server/request/NodeRequest.java
bundles/org.simantics.document.server/src/org/simantics/document/server/request/NodesRequest.java
bundles/org.simantics.document.server/src/org/simantics/document/server/request/NodesRequest2.java
bundles/org.simantics.document.server/src/org/simantics/document/server/request/ServerSCLValueRequest.java
bundles/org.simantics.g2d/src/org/simantics/g2d/diagram/participant/ElementPainter.java
bundles/org.simantics.modeling.ui/META-INF/MANIFEST.MF
bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/diagramEditor/DiagramViewerLoadJob.java
bundles/org.simantics.modeling/adapters.xml
bundles/org.simantics.modeling/src/org/simantics/modeling/ImmutableComponentPropertyContentRequest.java
bundles/org.simantics.modeling/src/org/simantics/modeling/ImmutableComponentVariable.java
bundles/org.simantics.modeling/src/org/simantics/modeling/ImmutableComponentVariableBuilder.java
bundles/org.simantics.modeling/src/org/simantics/modeling/ImmutableComponentVariableContent.java
bundles/org.simantics.modeling/src/org/simantics/modeling/ImmutableComponentVariableContentRequest.java
bundles/org.simantics.modeling/src/org/simantics/modeling/SCLExternalValue.java [new file with mode: 0644]
bundles/org.simantics.modeling/src/org/simantics/modeling/scl/GraphModuleSourceRepository.java
bundles/org.simantics.scl.db/src/org/simantics/scl/db/SCLFunctions.java
bundles/org.simantics.structural2/src/org/simantics/structural2/scl/CompileStructuralValueRequest.java
bundles/org.simantics.threadlog/build.properties
bundles/org.simantics.threadlog/scl/Simantics/ThreadLog.scl [new file with mode: 0644]
bundles/org.simantics.threadlog/src/org/simantics/threadlog/internal/Activator.java
features/org.simantics.document.base.feature/feature.xml

index 6921a3b2fab092a171ade1b348b65614ec5f987c..d6bba94bff8ad194f517c7adca8ce68cd3033dd4 100644 (file)
@@ -511,4 +511,8 @@ public class GENodeQueryManager implements NodeQueryManager, PrimitiveQueryUpdat
        ge.getCache().decRef(context);
     }
     
+    public void execFromQuery(Runnable runnable) {
+       ge.execFromQuery(runnable);
+    }
+    
 }
index b832f6c66e1e021fa2c7f02b00c835b7639a9a65..342153604baebea307e22a4bf52b47fb4be7f2d2 100644 (file)
@@ -60,5 +60,6 @@ public interface IGraphExplorerContext extends IDisposable {
     int getActivityInt();
 
     void scheduleQueryUpdate(Runnable r);
+    void execFromQuery(Runnable r);
 
 }
index 4895d3f75425ed00df79a8703c7656a41e52c18a..b33b57a0b720df1b5a20f5b0aefcd1c57260afb0 100644 (file)
@@ -29,10 +29,21 @@ public abstract class ViewpointStub implements Viewpoint {
     protected Boolean        hasChildren = Viewpoint.PENDING_HAS_CHILDREN;
 
     final public void setChildren(PrimitiveQueryUpdater updater, NodeContext[] children) {
+       
         if (children == null)
             throw new NullPointerException(this + ": null children produced by " + getClass().getName());
-        for(NodeContext c : children) updater.incRef(c);
-        for(NodeContext c : this.children) updater.decRef(c);
+        
+        final NodeContext[] currentChildren = this.children;
+        
+        updater.execFromQuery(new Runnable() {
+
+                       @Override
+                       public void run() {
+                       for(NodeContext c : children) updater.incRef(c);
+                       for(NodeContext c : currentChildren) updater.decRef(c);
+                       }
+               
+        });
         this.children = children;
     }
 
index be6a73a0c05dbff44a460e4b5de85bd9000947fb..6a9cdd5f55ef09b85dfda8d134d3483284d76e47 100644 (file)
@@ -2384,6 +2384,11 @@ public class NatTableGraphExplorer extends GraphExplorerImplBase implements Grap
             }
         }
 
+        @Override
+        public void execFromQuery(java.lang.Runnable r) {
+               ge.queryUpdateScheduler.execute(r);        
+        }
+
         Runnable QUERY_UPDATE_SCHEDULER = new Runnable() {
             @Override
             public void run() {
index 3cf5f7478cd7af3dc23ff412db75eac0628f87c1..5d64b8ad4c86736eb8d636aa1c8e31f22978fe40 100644 (file)
@@ -466,6 +466,11 @@ class GraphExplorerImpl extends GraphExplorerImplBase implements Listener, Graph
                 queryUpdateScheduler.execute(QUERY_UPDATE_SCHEDULER);
             }
         }
+        
+        @Override
+        public void execFromQuery(java.lang.Runnable r) {
+               queryUpdateScheduler.execute(r);        
+        }
 
         Runnable QUERY_UPDATE_SCHEDULER = new Runnable() {
             @Override
index af0fa25a355019468aecd5a89f6a6f950e69833e..7cc07765b156477c2ab86e220abe274f9112dc1a 100644 (file)
@@ -1610,6 +1610,11 @@ public class GraphExplorerImpl2 extends GraphExplorerImplBase implements GraphEx
             }
         }
 
+        @Override
+        public void execFromQuery(java.lang.Runnable r) {
+               ge.queryUpdateScheduler.execute(r);        
+        }
+
         Runnable QUERY_UPDATE_SCHEDULER = new Runnable() {
             @Override
             public void run() {
index c10df01b0e5287be95c66e36d1bb548d28a5d97f..c48e947a808b80dc3e3a61c69eda60ba2e5003c2 100644 (file)
@@ -63,5 +63,7 @@ public interface PrimitiveQueryUpdater {
     
     void incRef(NodeContext context);
     void decRef(NodeContext context);
+    
+    void execFromQuery(Runnable runnable);
 
 }
\ No newline at end of file
index f0ac2886df4121bcd59921b225dd35eab588285c..b05ec52cd8dd199bf04d81dcfc7735d1dba87e19 100644 (file)
@@ -25,6 +25,7 @@ Export-Package: org.simantics.db.common,
  org.simantics.db.common.internal.config;x-friends:="org.simantics.db.procore",
  org.simantics.db.common.issue,
  org.simantics.db.common.primitiverequest,
+ org.simantics.db.common.procedure,
  org.simantics.db.common.procedure.adapter,
  org.simantics.db.common.procedure.guarded,
  org.simantics.db.common.procedure.single,
index 61a47ecb12a96443620f5c546b29bc2fda50813d..983e1c5465289174a1d66a066e318a67e8456902 100644 (file)
  *******************************************************************************/
 package org.simantics.db.common.primitiverequest;
 
-import org.simantics.db.AsyncReadGraph;
+import org.simantics.db.ReadGraph;
 import org.simantics.db.Resource;
-import org.simantics.db.procedure.AsyncProcedure;
-import org.simantics.db.request.AsyncRead;
+import org.simantics.db.adaption.AdaptionService;
+import org.simantics.db.common.request.BinaryRead;
+import org.simantics.db.exception.DatabaseException;
 
-final public class PossibleAdapter<T> implements AsyncRead<T> {
+final public class PossibleAdapter<T> extends BinaryRead<Resource,Class<T>, T> {
 
-       final private Resource resource;
-    final private Class<T> clazz;
-    
-    @Override
-    public int hashCode() {
-        return resource.hashCode() + 31 * clazz.hashCode();
-    }
-    
-    @Override
-    public boolean equals(Object object) {
-        if (this == object)
-            return true;
-        else if (object == null)
-            return false;
-        else if (getClass() != object.getClass())
-            return false;
-        PossibleAdapter<?> r = (PossibleAdapter<?>)object;
-        return resource.equals(r.resource) && clazz.equals(r.clazz);
-    }
-
-    @Override
-    public int threadHash() {
-       return hashCode();
-    }
-
-    @Override
-    public int getFlags() {
-        return 0;
-    }
-    
     public PossibleAdapter(Resource resource, Class<T> clazz) {
-        this.resource = resource;
-        this.clazz = clazz;
+       super(resource, clazz);
     }
 
     @Override
-    public void perform(AsyncReadGraph graph, AsyncProcedure<T> procedure) {
-        
-        graph.forPossibleAdapted(resource, clazz, procedure);
-        
+    public T perform(ReadGraph graph) throws DatabaseException {
+       
+               final AdaptionService service = graph.peekService(AdaptionService.class);
+               return service.adapt(graph, parameter, parameter, Resource.class, parameter2, true);
+               
     }
 
 }
diff --git a/bundles/org.simantics.db.common/src/org/simantics/db/common/procedure/BlockingAsyncProcedure.java b/bundles/org.simantics.db.common/src/org/simantics/db/common/procedure/BlockingAsyncProcedure.java
new file mode 100644 (file)
index 0000000..d239c87
--- /dev/null
@@ -0,0 +1,108 @@
+/*******************************************************************************
+ * Copyright (c) 2007, 2010 Association for Decentralized Information Management
+ * in Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ *     VTT Technical Research Centre of Finland - initial API and implementation
+ *******************************************************************************/
+package org.simantics.db.common.procedure;
+
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.simantics.db.AsyncReadGraph;
+import org.simantics.db.common.utils.Logger;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.procedure.AsyncProcedure;
+
+public class BlockingAsyncProcedure<Result> implements AsyncProcedure<Result> {
+
+       final private Object key;
+    private Result result = null;
+    private Throwable exception = null;
+    final private AsyncProcedure<Result> procedure;
+    final private Semaphore semaphore = new Semaphore(0);
+//    final private AtomicBoolean latch;
+    
+    public BlockingAsyncProcedure(AsyncProcedure<Result> procedure, Object key) {
+//     assert(procedure != null);
+       this.key = key;
+        this.procedure = procedure;
+        if(key == null)
+               System.err.println("asd");
+        //System.err.println("BlockingAsyncProcedure " + key);
+//        latch = new AtomicBoolean(false);
+    }
+    
+    @Override
+    public void execute(AsyncReadGraph graph, Result result) {
+        this.result = result;
+        semaphore.release();
+//        if(latch.compareAndSet(false, true)) {
+               try {
+                       if(procedure != null) procedure.execute(graph, result);
+               } catch (Throwable throwable) {
+               Logger.defaultLogError("AsyncProcedure.execute threw for " + procedure, throwable);
+               }
+//             } finally {
+////                   System.err.println("ResultCallWrappedSingleQueryProcedure4 dec " + key);
+//             }
+//        } else {
+//             Logger.defaultLogError("Procedure was called many times (this time is execute)");
+//        }
+    }
+
+    @Override
+    public void exception(AsyncReadGraph graph, Throwable t) {
+        this.exception = t;
+        semaphore.release();
+//        if(latch.compareAndSet(false, true)) {
+               try {
+                       if(procedure != null) procedure.exception(graph, t);
+               } catch (Throwable throwable) {
+               Logger.defaultLogError("AsyncProcedure.exception threw for " + procedure, throwable);
+               } finally {
+               }
+//        } else {
+//             Logger.defaultLogError("Procedure was called many times (this time is exception)");
+//        }
+        
+    }
+    
+    public Result get() throws DatabaseException {
+       
+       try {
+                       boolean success = semaphore.tryAcquire(10, TimeUnit.SECONDS);
+                       if(!success) throw new DatabaseException("Timeout while waiting for async request to complete: " + key);
+               } catch (InterruptedException e) {
+                       throw new DatabaseException(e);
+               }
+       
+       if(exception != null) {
+               if(exception instanceof DatabaseException) throw (DatabaseException)exception;
+               throw new DatabaseException(exception);
+       } else {
+               return result;
+       }
+       
+    }
+    
+    public Result getResult() {
+        return result;
+    }
+    
+    public Throwable getException() {
+        return exception;
+    }
+       
+    @Override
+    public String toString() {
+        return "." + procedure; 
+    }
+    
+}
index 7184acbc5242de4029abe6606eb806e37f424193..fb771a35ae606e1bdb0bebebdd55c501c0339ec7 100644 (file)
@@ -324,13 +324,13 @@ final public class AsyncBarrierImpl extends AtomicInteger implements AsyncBarrie
                                        if(Development.DEVELOPMENT) {
 
                                                impl.processor.threadLocks[0].lock();
-                                               System.err.println("-queues=" + impl.processor.queues[0].size());
+//                                             System.err.println("-queues=" + impl.processor.queues[0].size());
                                                impl.processor.threadLocks[0].unlock();
-                                               System.err.println("-own=" + impl.processor.ownTasks[0].size());
-                                               System.err.println("-ownSync=" + impl.processor.ownSyncTasks[0].size());
-                                               for(SessionTask task : impl.processor.ownSyncTasks[0]) {
-                                                       System.err.println("--" + task);
-                                               }
+//                                             System.err.println("-own=" + impl.processor.ownTasks[0].size());
+//                                             System.err.println("-ownSync=" + impl.processor.ownSyncTasks[0].size());
+//                                             for(SessionTask task : impl.processor.ownSyncTasks[0]) {
+//                                                     System.err.println("--" + task);
+//                                             }
 
                                        }
 
index c6e41f6189dec87cd4022f5712c08e9701d2b58c..f0147e047e001cf6f82d809a269aec65e100ed13 100644 (file)
@@ -88,6 +88,7 @@ import org.simantics.db.common.primitiverequest.UniqueAdapter;
 import org.simantics.db.common.primitiverequest.Value;
 import org.simantics.db.common.primitiverequest.ValueImplied;
 import org.simantics.db.common.primitiverequest.VariantValueImplied;
+import org.simantics.db.common.procedure.BlockingAsyncProcedure;
 import org.simantics.db.common.procedure.adapter.AsyncMultiProcedureAdapter;
 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
@@ -136,6 +137,7 @@ import org.simantics.db.impl.ResourceImpl;
 import org.simantics.db.impl.internal.RandomAccessValueSupport;
 import org.simantics.db.impl.internal.ResourceData;
 import org.simantics.db.impl.procedure.CallWrappedSingleQueryProcedure4;
+import org.simantics.db.impl.procedure.InternalProcedure;
 import org.simantics.db.impl.procedure.ResultCallWrappedQueryProcedure4;
 import org.simantics.db.impl.procedure.ResultCallWrappedSingleQueryProcedure4;
 import org.simantics.db.impl.query.CacheEntry;
@@ -144,6 +146,7 @@ import org.simantics.db.impl.query.QueryCacheBase;
 import org.simantics.db.impl.query.QueryProcessor;
 import org.simantics.db.impl.query.QuerySupport;
 import org.simantics.db.impl.query.TripleIntProcedure;
+import org.simantics.db.impl.query.QueryProcessor.SessionTask;
 import org.simantics.db.impl.support.ResourceSupport;
 import org.simantics.db.procedure.AsyncListener;
 import org.simantics.db.procedure.AsyncMultiListener;
@@ -283,8 +286,17 @@ public class ReadGraphImpl implements ReadGraph {
 
                try {
 
-                       return syncRequest(new org.simantics.db.common.primitiverequest.Resource(
-                                       id));
+//                     assert (id != null);
+//                     assert (procedure != null);
+//
+//                     processor.forResource(this, id, procedure);
+//
+////                   return syncRequest(new org.simantics.db.common.primitiverequest.Resource(
+////                                   id));
+                       
+                       Integer rid = QueryCache.resultURIToResource(this, id, parent, null);
+                       if(rid == 0) throw new ResourceNotFoundException(id);
+                       return processor.querySupport.getResource(rid);
 
                } catch (ResourceNotFoundException e) {
 
@@ -314,8 +326,10 @@ public class ReadGraphImpl implements ReadGraph {
 
                try {
 
-                       return syncRequest(new org.simantics.db.common.primitiverequest.Resource(
-                                       id));
+                       return getResource(id);
+                       
+//                     return syncRequest(new org.simantics.db.common.primitiverequest.Resource(
+//                                     id));
 
                } catch (ResourceNotFoundException e) {
                        
@@ -2050,10 +2064,12 @@ public class ReadGraphImpl implements ReadGraph {
                        throws DatabaseException {
 
                assert (request != null);
-               AsyncReadProcedure<T> procedure = new AsyncReadProcedure<T>();
-               syncRequest(request, procedure);
-               procedure.checkAndThrow();
-               return procedure.result;
+//             AsyncReadProcedure<T> procedure = new AsyncReadProcedure<T>();
+               BlockingAsyncProcedure<T> ap = new BlockingAsyncProcedure<>(null, request);
+               syncRequest(request, ap);
+               return ap.get();
+//             procedure.checkAndThrow();
+//             return procedure.result;
                
 //             return syncRequest(request, new AsyncProcedureAdapter<T>());
 
@@ -2085,14 +2101,18 @@ public class ReadGraphImpl implements ReadGraph {
 
                ListenerBase listener = getListenerBase(procedure);
 
-               final ResultCallWrappedSingleQueryProcedure4<T> wrapper = new ResultCallWrappedSingleQueryProcedure4<T>(
-                               procedure, request);
+               BlockingAsyncProcedure<T> ap = new BlockingAsyncProcedure<>(procedure, request);
+               
+//             final ResultCallWrappedSingleQueryProcedure4<T> wrapper = new ResultCallWrappedSingleQueryProcedure4<T>(
+//                             procedure, request);
                
-               QueryCache.runnerAsyncReadEntry(this, request, parent, listener, wrapper);
+               QueryCache.runnerAsyncReadEntry(this, request, parent, listener, ap, true);
                
                //processor.query(this, request, parent, wrapper, listener);
                
-               return wrapper.getResult();
+               return ap.get();
+               
+//             return wrapper.getResult();
 
 //             if (parent != null || listener != null || ((request.getFlags() & RequestFlags.SCHEDULE) > 0)) {
 //
@@ -2160,10 +2180,14 @@ public class ReadGraphImpl implements ReadGraph {
                ListenerBase listener = getListenerBase(procedure);
                assert(listener == null);
 
+               BlockingAsyncProcedure<T> ap = new BlockingAsyncProcedure<>(procedure, request);
+               
 //             final ResultCallWrappedSingleQueryProcedure4<T> wrapper = new ResultCallWrappedSingleQueryProcedure4<T>(
 //                             procedure, request);
 
-               QueryCache.runnerAsyncReadEntry(this, request, parent, listener, procedure);
+               QueryCache.runnerAsyncReadEntry(this, request, parent, listener, ap, true);
+               
+               ap.get();
 
        }
 
@@ -5400,47 +5424,64 @@ public class ReadGraphImpl implements ReadGraph {
 
                assert (request != null);
                assert (procedure != null);
+       
+               processor.schedule(Integer.MIN_VALUE, new SessionTask(request, processor.THREAD_MASK+1, -1) {
 
-               final ListenerBase listener = getListenerBase(procedure);
-
-               if (parent != null || listener != null) {
-
-                       try {
-                               QueryCache.runnerReadEntry(this, request, parent, listener, procedure);
-                               //processor.query(this, request, parent, procedure,listener);
-                       } catch (DatabaseException e) {
-                               Logger.defaultLogError(e);
-                               // This throwable has already been transferred to procedure at this point - do nothing about it
-                               //
-                       }
-                       
-               } else {
-
-//                     final ReadGraphImpl newGraph = newSync();
-
-                       try {
-
-                               T result = request.perform(this);
-                               
-                               try {
-                                       procedure.execute(this, result);
-                               } catch (Throwable t) {
-                                       Logger.defaultLogError(t);
-                               }
-
-                       } catch (Throwable t) {
-
+                       @Override
+                       public void run(int thread) {
                                try {
-                                       procedure.exception(this, t);
-                               } catch (Throwable t2) {
-                                       Logger.defaultLogError(t2);
+                                       final ListenerBase listener = getListenerBase(procedure);
+                                       QueryCache.runnerReadEntry(ReadGraphImpl.this, request, parent, listener, procedure, false);
+                               } catch (DatabaseException e) {
+                                       Logger.defaultLogError(e);
                                }
-
-                       } finally {
-
                        }
+                       
+               });
 
-               }
+               
+//             quer
+//
+//             final ListenerBase listener = getListenerBase(procedure);
+//
+//             if (parent != null || listener != null) {
+//
+//                     try {
+//                             QueryCache.runnerReadEntry(this, request, parent, listener, procedure);
+//                             //processor.query(this, request, parent, procedure,listener);
+//                     } catch (DatabaseException e) {
+//                             Logger.defaultLogError(e);
+//                             // This throwable has already been transferred to procedure at this point - do nothing about it
+//                             //
+//                     }
+//                     
+//             } else {
+//
+////                   final ReadGraphImpl newGraph = newSync();
+//
+//                     try {
+//
+//                             T result = request.perform(this);
+//                             
+//                             try {
+//                                     procedure.execute(this, result);
+//                             } catch (Throwable t) {
+//                                     Logger.defaultLogError(t);
+//                             }
+//
+//                     } catch (Throwable t) {
+//
+//                             try {
+//                                     procedure.exception(this, t);
+//                             } catch (Throwable t2) {
+//                                     Logger.defaultLogError(t2);
+//                             }
+//
+//                     } finally {
+//
+//                     }
+//
+//             }
 
        }
 
@@ -5512,38 +5553,55 @@ public class ReadGraphImpl implements ReadGraph {
                assert (request != null);
                assert (procedure != null);
 
-               final ListenerBase listener = getListenerBase(procedure);
+               //final ListenerBase listener = getListenerBase(procedure);
 
-               if (parent != null || listener != null) {
+               processor.schedule(Integer.MIN_VALUE, new SessionTask(request, processor.THREAD_MASK+1, -1) {
 
-                       try {
-                               QueryCache.runnerAsyncReadEntry(this, request, parent, listener, procedure);
-                               //processor.query(this, request, parent, procedure, listener);
-                       } catch (DatabaseException e) {
-                               Logger.defaultLogError(e);
+                       @Override
+                       public void run(int thread) {
+                               try {
+                                       final ListenerBase listener = getListenerBase(procedure);
+                                       QueryCache.runnerAsyncReadEntry(ReadGraphImpl.this, request, parent, listener, procedure, false);
+                               } catch (DatabaseException e) {
+                                       Logger.defaultLogError(e);
+                               }
                        }
+                       
+               });
 
-               } else {
-
-                       try {
-                               
-                               request.perform(this, new CallWrappedSingleQueryProcedure4<T>(procedure, request));
-
-                       } catch (Throwable t) {
-
-                               if (t instanceof DatabaseException)
-                                       procedure.exception(this, t);
-                               else
-                                       procedure
-                                                       .exception(
-                                                                       this,
-                                                                       new DatabaseException(
-                                                                                       "Unexpected exception in ReadGraph.asyncRequest(SingleAsyncRead, SingleProcedure)",
-                                                                                       t));
+               
 
-                       }
 
-               }
+//             if (parent != null || listener != null) {
+//
+//                     try {
+//                             QueryCache.runnerAsyncReadEntry(this, request, parent, listener, procedure);
+//                             //processor.query(this, request, parent, procedure, listener);
+//                     } catch (DatabaseException e) {
+//                             Logger.defaultLogError(e);
+//                     }
+//
+//             } else {
+//
+//                     try {
+//                             
+//                             request.perform(this, new CallWrappedSingleQueryProcedure4<T>(procedure, request));
+//
+//                     } catch (Throwable t) {
+//
+//                             if (t instanceof DatabaseException)
+//                                     procedure.exception(this, t);
+//                             else
+//                                     procedure
+//                                                     .exception(
+//                                                                     this,
+//                                                                     new DatabaseException(
+//                                                                                     "Unexpected exception in ReadGraph.asyncRequest(SingleAsyncRead, SingleProcedure)",
+//                                                                                     t));
+//
+//                     }
+//
+//             }
 
        }
 
index ca485f9893957ff784075f686b87221e843fce50..8462433f1b49e50a3e0fc4068f5aea067237db0a 100644 (file)
@@ -802,6 +802,10 @@ final public class WriteGraphImpl extends ReadGraphImpl implements WriteGraph {
         Layer0 b = getBuiltins();
         initBuiltinValues(b);       
         
+        if(resource.toString().equals("[id=$319492]") && predicate.toString().equals("[id=$235477]"))
+               System.err.println("foobar2");
+               
+        
         Statement literalStatement = getPossibleStatement(resource, predicate);
 
         if(literalStatement != null && resource.equals(literalStatement.getSubject())) {
index 410db7118e31f59888e07d9672127a97d01b275b..184276412f7a3251690dd62b72be51c67eeceb1f 100644 (file)
@@ -82,7 +82,7 @@ final public class AssertedPredicates extends CollectionUnaryQuery<IntProcedure>
 
        }
 
-    @Override
+    //@Override
     public Object compute(ReadGraphImpl graph, final IntProcedure proc) throws DatabaseException {
 
        QueryProcessor processor = graph.processor;
index 90daa9a845fe4fad3e9979eed02ab169fc14cc25..eba1205e1f94dfd4a5dac0177d0b56cfc90d8a51 100644 (file)
@@ -137,7 +137,7 @@ final public class AssertedStatements extends CollectionBinaryQuery<TripleIntPro
         
     }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, final TripleIntProcedure procedure) throws DatabaseException {
                computeForEach(graph, r1(), r2(), this, procedure);
                return getResult();
index ba08114c6a8261330846c5411ab1902a7f73a9ca..6f718f1fe4d2407cb92ee0cbd445e3dd2e1d3382 100644 (file)
@@ -170,7 +170,7 @@ final public class AsyncMultiReadEntry<T> extends CacheEntryBase<AsyncMultiProce
                else return request.toString() + statusOrException;
        }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, AsyncMultiProcedure<T> procedure) throws DatabaseException {
        return graph.processor.cache.performQuery(graph, request, this, procedure);
        }
index 8e6cbd145a78d9a1aacf3b99f20c396a789beaae..08f0ad8b5f689e189348b1af64a46e2d2a97c8b7 100644 (file)
@@ -45,6 +45,8 @@ final public class AsyncReadEntry<T> extends CacheEntryBase<AsyncProcedure<T>> {
     
     final public void addOrSet(AsyncReadGraph graph, Object item) {
 
+//     System.err.println("addOrSet " + request + " " + Thread.currentThread() + " " + item);
+       
        assert(isPending());
 
         synchronized(this) {
@@ -142,7 +144,7 @@ final public class AsyncReadEntry<T> extends CacheEntryBase<AsyncProcedure<T>> {
            
        }
 
-    @Override
+    //@Override
     public Object compute(ReadGraphImpl graph, AsyncProcedure<T> procedure) throws DatabaseException {
 
        ReadGraphImpl queryGraph = graph.withParent(this);
index 833eafc4c41dc0b3b4072391866bb8c51fd48ec0..b460a22bd06762b5d4b253b470813b9a92bc7875 100644 (file)
@@ -45,11 +45,6 @@ abstract public class BinaryQueryHash<Procedure> extends THash {
             throw new Error("Not possible!");
         }
 
-               @Override
-               public Object compute(ReadGraphImpl graph, Procedure procedure) throws DatabaseException {
-            throw new Error("Not possible!");
-               }
-
                @Override
                Object performFromCache(ReadGraphImpl graph, Procedure procedure) throws DatabaseException {
             throw new Error("Not possible!");
index 1506b54afc3041eacc2cc7718505960b64f34654..dea5de5a78d791799a63ae9898fb48dfdee6c84f 100644 (file)
@@ -460,6 +460,6 @@ abstract public class CacheEntryBase<Procedure> extends CacheEntry<Procedure> {
        public CacheEntryBase() {
        }
        
-    abstract public Object compute(ReadGraphImpl graph, Procedure procedure) throws DatabaseException;
+    //abstract public Object compute(ReadGraphImpl graph, Procedure procedure) throws DatabaseException;
     
 }
index 9f24ba64023a62b439c8c5bdc84345b826fae4ed..7dd00d29ba7815443809c556070647c78d8a6ebc 100644 (file)
@@ -32,7 +32,7 @@ final public class ChildMap extends UnaryQuery<InternalProcedure<ObjectResourceI
                provider.cache.remove(this);
        }
        
-    @Override
+    //@Override
        public Object compute(ReadGraphImpl graph, final InternalProcedure<ObjectResourceIdMap<String>> procedure) throws DatabaseException {
                computeForEach(graph, id, this, procedure);
                return getResult();
index ed60398478b8a70933b1f28ef8e201147b975394..008faeea51589b1671a51a18d3f06ef4e72f5701 100644 (file)
@@ -38,15 +38,15 @@ public class CodeGen {
                content.append("\n");
        }
        
-       public void generateQuery(StringBuilder content, String clazz, String[] signature, boolean runnerShortcut) {
-               generateGetOrCreate(content, clazz, signature);
+       public void generateQuery(StringBuilder content, String clazz, String[] signature, boolean runnerShortcut, boolean genAsync) {
+               generateGetOrCreate(content, clazz, signature, genAsync);
                generateRemove(content, clazz, signature);
-               generateRunner(content, clazz, signature, runnerShortcut);
+               generateRunner(content, clazz, signature, runnerShortcut, genAsync);
        }
        
-       public void generateRunner(StringBuilder content, String clazz, String[] signature, boolean shortcut) {
+       public void generateRunner(StringBuilder content, String clazz, String[] signature, boolean shortcut, boolean genAsync) {
                
-               line(content, "public static void runner" + clazz + "(ReadGraphImpl graph, " + signature[0] + ", CacheEntry parent, ListenerBase listener, " + signature[4] + " procedure) throws DatabaseException {");
+               line(content, "public static void runner" + clazz + "(ReadGraphImpl graph, " + signature[0] + ", CacheEntry parent, ListenerBase listener, final " + signature[4] + " procedure" + (genAsync ? ", boolean isSync" : "") + ") throws DatabaseException {");
                line(content, "    QueryCache cache  = graph.processor.cache;");
                if(shortcut) {
                        line(content, "    if(parent == null && listener == null && !cache.shouldCache(graph.processor, " + signature[1] + ")) {");
@@ -54,13 +54,30 @@ public class CodeGen {
                        line(content, "        return;");
                        line(content, "    }");
                }
-               line(content, "    if(procedure == null) procedure = emptyProcedure" + clazz + ";");
-               line(content, "    " + clazz + " entry = (" + clazz + ")cache.getOrCreate" + clazz + "(" + signature[1] + ");");
-               line(content, "    ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);");
-               line(content, "    if(entry.isReady()) entry.performFromCache(graph, procedure);");
+               line(content, "    " + clazz + " entry = (" + clazz + ")cache.getOrCreate" + clazz + "(" + signature[1] + (genAsync ? ", isSync" : "") + ");");
+               if(genAsync) {
+                       line(content, "    if(entry == null) {");
+                       line(content, "        graph.processor.schedule(Integer.MIN_VALUE, new SessionTask(r, graph.processor.THREAD_MASK+1, -1) {");
+                       line(content, "            @Override");
+                       line(content, "            public void run(int thread) {");
+                       line(content, "                try {");
+                       line(content, "                    assert(!isSync);");
+                       line(content, "                    runner" + clazz + "(graph, r, parent, listener, procedure, isSync);");
+                       line(content, "                } catch (DatabaseException e) {");
+                       line(content, "                    Logger.defaultLogError(e);");
+                       line(content, "                }");
+                       line(content, "            }");
+                       line(content, "        });");
+                       line(content, "        return;");
+                       line(content, "    }");
+               }
+               line(content, "    " + signature[4] + " procedure_ = procedure != null ? procedure : emptyProcedure" + clazz + ";");
+               line(content, "    ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);");
+               line(content, "    if(entry.isReady()) entry.performFromCache(graph, procedure_);");
                line(content, "    else {");
-               if(shortcut) line(content, "        " + clazz + ".computeForEach(graph, " + signature[1] + ", entry, procedure);");
-               else line(content, "        entry.compute(graph, procedure);"); 
+               line(content, "      assert(entry.isPending());");
+               if(shortcut) line(content, "        " + clazz + ".computeForEach(graph, " + signature[1] + ", entry, procedure_);");
+               else line(content, "        entry.compute(graph, procedure_);"); 
                line(content, "        if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());");
                line(content, "    }");
                line(content, "}");
@@ -81,11 +98,11 @@ public class CodeGen {
 
        }
 
-       public void generateGetOrCreate(StringBuilder content, String clazz, String[] signature) {
+       public void generateGetOrCreate(StringBuilder content, String clazz, String[] signature, boolean genAsync) {
                
                String lower = Character.toLowerCase(clazz.charAt(0)) + clazz.substring(1);
                
-               line(content, "" + clazz + " getOrCreate" + clazz + "(" + signature[0] + ") throws DatabaseException {");
+               line(content, "" + clazz + " getOrCreate" + clazz + "(" + signature[0] + (genAsync ? ", boolean isSync" : "") + ") throws DatabaseException {");
                line(content, "    " + clazz + " existing = null;");
                line(content, "    synchronized(" + lower + "Map) {");
                line(content, "        existing = (" + clazz + ")" + lower + "Map.get(" + signature[1] + ");");
@@ -102,7 +119,14 @@ public class CodeGen {
                line(content, "            return existing;");
                line(content, "        }");
                line(content, "    }");
-               line(content, "    if(existing.isPending()) waitPending(existing);");
+               if(genAsync) {
+                       line(content, "    if(existing.isPending()) {");
+                       line(content, "      if(isSync) waitPending(existing);");
+                       line(content, "      else return null;");
+                       line(content, "    }");
+               } else {
+                       line(content, "    if(existing.isPending()) waitPending(existing);");
+               }
                line(content, "    return existing;");
                line(content, "}");
                line(content, "");
@@ -127,9 +151,11 @@ public class CodeGen {
                     
                     content.append("import org.simantics.db.ObjectResourceIdMap;\n");
                     content.append("import org.simantics.db.RelationInfo;\n");
+                    content.append("import org.simantics.db.common.utils.Logger;\n");
                     content.append("import org.simantics.db.exception.DatabaseException;\n");
                     content.append("import org.simantics.db.impl.graph.ReadGraphImpl;\n");
                     content.append("import org.simantics.db.impl.procedure.InternalProcedure;\n");
+                    content.append("import org.simantics.db.impl.query.QueryProcessor.SessionTask;\n");
                     content.append("import org.simantics.db.procedure.AsyncMultiProcedure;\n");
                     content.append("import org.simantics.db.procedure.AsyncProcedure;\n");
                     content.append("import org.simantics.db.procedure.ListenerBase;\n");
@@ -149,31 +175,31 @@ public class CodeGen {
                     line(content,"}");
                     content.append("\n");
                     
-                    generateQuery(content, "Objects", signatureR2IP, true);
-                    generateQuery(content, "Statements", signatureR2TIP, true);
-                    generateQuery(content, "DirectObjects", signatureR2IP, true);
-                    generateQuery(content, "RelationInfoQuery", signatureR1RelationInfo, true);
-                    generateQuery(content, "URIToResource", signatureID1, true);
-                    generateQuery(content, "ValueQuery", signatureR1Bytes, true);
-                    generateQuery(content, "OrderedSet", signatureR1IP, true);
-                    generateQuery(content, "PrincipalTypes", signatureR1IP, true);
-                    generateQuery(content, "DirectPredicates", signatureR1IntSet, true);
-                    generateQuery(content, "Predicates", signatureR1IntSet, true);
-                    generateQuery(content, "ReadEntry", signatureRead, true);
-                    generateQuery(content, "AsyncReadEntry", signatureAsyncRead, true);
-                    generateQuery(content, "Types", signatureR1IntSet, true);
+                    generateQuery(content, "Objects", signatureR2IP, true, false);
+                    generateQuery(content, "Statements", signatureR2TIP, true, false);
+                    generateQuery(content, "DirectObjects", signatureR2IP, true, false);
+                    generateQuery(content, "RelationInfoQuery", signatureR1RelationInfo, true, false);
+                    generateQuery(content, "URIToResource", signatureID1, true, false);
+                    generateQuery(content, "ValueQuery", signatureR1Bytes, true, false);
+                    generateQuery(content, "OrderedSet", signatureR1IP, true, false);
+                    generateQuery(content, "PrincipalTypes", signatureR1IP, true, false);
+                    generateQuery(content, "DirectPredicates", signatureR1IntSet, true, false);
+                    generateQuery(content, "Predicates", signatureR1IntSet, true, false);
+                    generateQuery(content, "ReadEntry", signatureRead, true, true);
+                    generateQuery(content, "AsyncReadEntry", signatureAsyncRead, true, true);
+                    generateQuery(content, "Types", signatureR1IntSet, true, false);
                     //generateQuery(content, "NamespaceIndex", signatureID2, true);
-                    generateQuery(content, "ChildMap", signatureChildMap, true);
+                    generateQuery(content, "ChildMap", signatureChildMap, true, false);
 
-                    generateQuery(content, "AssertedStatements", signatureR2TIP, false);
-                    generateQuery(content, "AssertedPredicates", signatureR1IP, false);
-                    generateQuery(content, "DirectSuperRelations", signatureR1IP, false);
-                    generateQuery(content, "SuperTypes", signatureR1IntSet, false);
-                    generateQuery(content, "TypeHierarchy", signatureR1IntSet, false);
-                    generateQuery(content, "SuperRelations", signatureR1IntSet, false);
-                    generateQuery(content, "MultiReadEntry", signatureMultiRead, false);
-                    generateQuery(content, "AsyncMultiReadEntry", signatureAsyncMultiRead, false);
-                    generateQuery(content, "ExternalReadEntry", signatureExternalRead, false);
+                    generateQuery(content, "AssertedStatements", signatureR2TIP, false, false);
+                    generateQuery(content, "AssertedPredicates", signatureR1IP, false, false);
+                    generateQuery(content, "DirectSuperRelations", signatureR1IP, false, false);
+                    generateQuery(content, "SuperTypes", signatureR1IntSet, false, false);
+                    generateQuery(content, "TypeHierarchy", signatureR1IntSet, false, false);
+                    generateQuery(content, "SuperRelations", signatureR1IntSet, false, false);
+                    generateQuery(content, "MultiReadEntry", signatureMultiRead, false, false);
+                    generateQuery(content, "AsyncMultiReadEntry", signatureAsyncMultiRead, false, false);
+                    generateQuery(content, "ExternalReadEntry", signatureExternalRead, false, false);
                     content.append("}\n");
                     FileUtils.writeFile(source, content.toString().getBytes());
                 } catch (MalformedURLException e) {
index c38a50b561fa643538a4f9bfd0d4dd6a09391a95..117056410bfacbbe1492ea3407ba56472a3ff369 100644 (file)
@@ -51,7 +51,7 @@ final public class DirectObjects extends CollectionBinaryQuery<IntProcedure> {
                provider.cache.remove(this);
        }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, final IntProcedure procedure) throws DatabaseException {
                computeForEach(graph, r1(), r2(), this, procedure);
                return getResult();
index feb0533efb4c06f626d4e45b158ca288076c192c..63c54effe47f2e405320abe19e7a431af686bc70 100644 (file)
@@ -33,7 +33,7 @@ final public class DirectPredicates extends CollectionUnaryQuery<InternalProcedu
                provider.cache.remove(this);
        }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, InternalProcedure<IntSet> procedure) throws DatabaseException {
            return computeForEach(graph, id, this, procedure);
        }
index 3932f7da6031bc4b083b53d327e6128aa2438864..621bdad969157b7a9f1f64726e5ffbf1b5f4ae15 100644 (file)
@@ -62,7 +62,7 @@ final public class DirectSuperRelations extends UnaryQuery<IntProcedure> {
 
        }
 
-       @Override
+       //@Override
        public Object compute(final ReadGraphImpl graph, final IntProcedure procedure) throws DatabaseException {
 
                QueryProcessor processor = graph.processor;
index 40b6f6fab408ac8d37ed13224cb2953e0ff9d469..bd99e1bc4a174368a46a5fa0f8f7db289e8ef6df 100644 (file)
@@ -193,7 +193,7 @@ final public class ExternalReadEntry<T> extends CacheEntryBase<AsyncProcedure<T>
        // Do nothing - the state is already set and cannot be recomputed on demand
     }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, AsyncProcedure<T> procedure) throws DatabaseException {
        return graph.processor.cache.performQuery(graph, request, this, procedure);
        }
index 8d1003b801525d26a436061d8355f3a47b539527..f2fff24cfc7ac213de3890331806509d68808575 100644 (file)
@@ -204,7 +204,7 @@ final public class MultiReadEntry<T> extends CacheEntryBase<AsyncMultiProcedure<
                else return request.toString() + statusOrException;
        }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, AsyncMultiProcedure<T> procedure) throws DatabaseException {
        return graph.processor.cache.performQuery(graph, request, this, procedure);
        }
index 62fb3bdb8c73c3449b091501d7d275264ab6a889..1883d9c1f52e67d647e4c011c628c2aa38f4c47a 100644 (file)
@@ -648,7 +648,7 @@ final public class Objects extends CollectionBinaryQuery<IntProcedure> {
 
        }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, final IntProcedure procedure) throws DatabaseException {
                computeForEach(graph, r1(), r2(), this, procedure);
                return getResult();
index 38c6be6e1f30fc60e6b0a06dae1d5542c2f9b671..9e7bb5c92ee39778b877f428a0aa336fe629db61 100644 (file)
@@ -76,7 +76,7 @@ final public class OrderedSet extends CollectionUnaryQuery<IntProcedure> {
         setResult(new IntArray());
     }
        
-    @Override
+    //@Override
     public Object compute(ReadGraphImpl graph, final IntProcedure procedure) throws DatabaseException {
        computeForEach(graph, id, this, procedure);
         return getResult();
index 50e14d962f879df12cc62beb3154ade31e58db02..d391cec9c9fc44fe4890fd8acc395d249872b37f 100644 (file)
@@ -70,7 +70,7 @@ final public class PossibleSuperRelation extends UnaryQuery<IntProcedure> {
 
        }
 
-       @Override
+       //@Override
        public Object compute(final ReadGraphImpl graph, final IntProcedure procedure) throws DatabaseException {
 
                QueryProcessor processor = graph.processor;
index e5cb6dfa146e10f6cf5b6b909554e56abe532cc0..03b17bba5cfba708064f2a9ed84b115348af8f4d 100644 (file)
@@ -77,7 +77,7 @@ final public class Predicates extends UnaryQuery<InternalProcedure<IntSet>> {
 
     }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, final InternalProcedure<IntSet> procedure) throws DatabaseException {
                computeForEach(graph, id, this, procedure);
                return getResult();
index 81c0efc20737d50e862f0d000bdf445488b871f5..af4d20ebca440dca89c2cdedef24bf11248f02f4 100644 (file)
@@ -75,7 +75,7 @@ final public class PrincipalTypes extends CollectionUnaryQuery<IntProcedure> {
 
        }
 
-       @Override
+       //@Override
        public Object compute(final ReadGraphImpl graph, final IntProcedure proc) throws DatabaseException {
                return computeForEach(graph, id, this, proc);
        }
index 49e02dece32049884f7a3907e85f960f2bf27f64..3e7a25190df94fe225f803bea23215c770727417 100644 (file)
@@ -2,9 +2,11 @@ package org.simantics.db.impl.query;
 
 import org.simantics.db.ObjectResourceIdMap;
 import org.simantics.db.RelationInfo;
+import org.simantics.db.common.utils.Logger;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.impl.graph.ReadGraphImpl;
 import org.simantics.db.impl.procedure.InternalProcedure;
+import org.simantics.db.impl.query.QueryProcessor.SessionTask;
 import org.simantics.db.procedure.AsyncMultiProcedure;
 import org.simantics.db.procedure.AsyncProcedure;
 import org.simantics.db.procedure.ListenerBase;
@@ -49,18 +51,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerObjects(ReadGraphImpl graph, int r1, int r2, CacheEntry parent, ListenerBase listener, IntProcedure procedure) throws DatabaseException {
+    public static void runnerObjects(ReadGraphImpl graph, int r1, int r2, CacheEntry parent, ListenerBase listener, final IntProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r1,r2)) {
             Objects.computeForEach(graph, r1,r2, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureObjects;
         Objects entry = (Objects)cache.getOrCreateObjects(r1,r2);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        IntProcedure procedure_ = procedure != null ? procedure : emptyProcedureObjects;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            Objects.computeForEach(graph, r1,r2, entry, procedure);
+          assert(entry.isPending());
+            Objects.computeForEach(graph, r1,r2, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -92,18 +95,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerStatements(ReadGraphImpl graph, int r1, int r2, CacheEntry parent, ListenerBase listener, TripleIntProcedure procedure) throws DatabaseException {
+    public static void runnerStatements(ReadGraphImpl graph, int r1, int r2, CacheEntry parent, ListenerBase listener, final TripleIntProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r1,r2)) {
             Statements.computeForEach(graph, r1,r2, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureStatements;
         Statements entry = (Statements)cache.getOrCreateStatements(r1,r2);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        TripleIntProcedure procedure_ = procedure != null ? procedure : emptyProcedureStatements;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            Statements.computeForEach(graph, r1,r2, entry, procedure);
+          assert(entry.isPending());
+            Statements.computeForEach(graph, r1,r2, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -135,18 +139,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerDirectObjects(ReadGraphImpl graph, int r1, int r2, CacheEntry parent, ListenerBase listener, IntProcedure procedure) throws DatabaseException {
+    public static void runnerDirectObjects(ReadGraphImpl graph, int r1, int r2, CacheEntry parent, ListenerBase listener, final IntProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r1,r2)) {
             DirectObjects.computeForEach(graph, r1,r2, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureDirectObjects;
         DirectObjects entry = (DirectObjects)cache.getOrCreateDirectObjects(r1,r2);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        IntProcedure procedure_ = procedure != null ? procedure : emptyProcedureDirectObjects;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            DirectObjects.computeForEach(graph, r1,r2, entry, procedure);
+          assert(entry.isPending());
+            DirectObjects.computeForEach(graph, r1,r2, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -178,18 +183,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerRelationInfoQuery(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, InternalProcedure<RelationInfo> procedure) throws DatabaseException {
+    public static void runnerRelationInfoQuery(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final InternalProcedure<RelationInfo> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             RelationInfoQuery.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureRelationInfoQuery;
         RelationInfoQuery entry = (RelationInfoQuery)cache.getOrCreateRelationInfoQuery(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<RelationInfo> procedure_ = procedure != null ? procedure : emptyProcedureRelationInfoQuery;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            RelationInfoQuery.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            RelationInfoQuery.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -221,18 +227,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerURIToResource(ReadGraphImpl graph, String id, CacheEntry parent, ListenerBase listener, InternalProcedure<Integer> procedure) throws DatabaseException {
+    public static void runnerURIToResource(ReadGraphImpl graph, String id, CacheEntry parent, ListenerBase listener, final InternalProcedure<Integer> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, id)) {
             URIToResource.computeForEach(graph, id, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureURIToResource;
         URIToResource entry = (URIToResource)cache.getOrCreateURIToResource(id);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<Integer> procedure_ = procedure != null ? procedure : emptyProcedureURIToResource;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            URIToResource.computeForEach(graph, id, entry, procedure);
+          assert(entry.isPending());
+            URIToResource.computeForEach(graph, id, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -264,18 +271,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerValueQuery(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, InternalProcedure<byte[]> procedure) throws DatabaseException {
+    public static void runnerValueQuery(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final InternalProcedure<byte[]> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             ValueQuery.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureValueQuery;
         ValueQuery entry = (ValueQuery)cache.getOrCreateValueQuery(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<byte[]> procedure_ = procedure != null ? procedure : emptyProcedureValueQuery;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            ValueQuery.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            ValueQuery.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -307,18 +315,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerOrderedSet(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, IntProcedure procedure) throws DatabaseException {
+    public static void runnerOrderedSet(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final IntProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             OrderedSet.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureOrderedSet;
         OrderedSet entry = (OrderedSet)cache.getOrCreateOrderedSet(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        IntProcedure procedure_ = procedure != null ? procedure : emptyProcedureOrderedSet;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            OrderedSet.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            OrderedSet.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -350,18 +359,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerPrincipalTypes(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, IntProcedure procedure) throws DatabaseException {
+    public static void runnerPrincipalTypes(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final IntProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             PrincipalTypes.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedurePrincipalTypes;
         PrincipalTypes entry = (PrincipalTypes)cache.getOrCreatePrincipalTypes(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        IntProcedure procedure_ = procedure != null ? procedure : emptyProcedurePrincipalTypes;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            PrincipalTypes.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            PrincipalTypes.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -393,18 +403,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerDirectPredicates(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, InternalProcedure<IntSet> procedure) throws DatabaseException {
+    public static void runnerDirectPredicates(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final InternalProcedure<IntSet> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             DirectPredicates.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureDirectPredicates;
         DirectPredicates entry = (DirectPredicates)cache.getOrCreateDirectPredicates(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<IntSet> procedure_ = procedure != null ? procedure : emptyProcedureDirectPredicates;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            DirectPredicates.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            DirectPredicates.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -436,23 +447,24 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerPredicates(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, InternalProcedure<IntSet> procedure) throws DatabaseException {
+    public static void runnerPredicates(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final InternalProcedure<IntSet> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             Predicates.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedurePredicates;
         Predicates entry = (Predicates)cache.getOrCreatePredicates(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<IntSet> procedure_ = procedure != null ? procedure : emptyProcedurePredicates;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            Predicates.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            Predicates.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
     
-    ReadEntry getOrCreateReadEntry(Read<?> r) throws DatabaseException {
+    ReadEntry getOrCreateReadEntry(Read<?> r, boolean isSync) throws DatabaseException {
         ReadEntry existing = null;
         synchronized(readEntryMap) {
             existing = (ReadEntry)readEntryMap.get(r);
@@ -469,7 +481,10 @@ public class QueryCache extends QueryCacheBase {
                 return existing;
             }
         }
-        if(existing.isPending()) waitPending(existing);
+        if(existing.isPending()) {
+          if(isSync) waitPending(existing);
+          else return null;
+        }
         return existing;
     }
     
@@ -479,23 +494,38 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerReadEntry(ReadGraphImpl graph, Read<?> r, CacheEntry parent, ListenerBase listener, AsyncProcedure procedure) throws DatabaseException {
+    public static void runnerReadEntry(ReadGraphImpl graph, Read<?> r, CacheEntry parent, ListenerBase listener, final AsyncProcedure procedure, boolean isSync) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             ReadEntry.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureReadEntry;
-        ReadEntry entry = (ReadEntry)cache.getOrCreateReadEntry(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        ReadEntry entry = (ReadEntry)cache.getOrCreateReadEntry(r, isSync);
+        if(entry == null) {
+            graph.processor.schedule(Integer.MIN_VALUE, new SessionTask(r, graph.processor.THREAD_MASK+1, -1) {
+                @Override
+                public void run(int thread) {
+                    try {
+                        assert(!isSync);
+                        runnerReadEntry(graph, r, parent, listener, procedure, isSync);
+                    } catch (DatabaseException e) {
+                        Logger.defaultLogError(e);
+                    }
+                }
+            });
+            return;
+        }
+        AsyncProcedure procedure_ = procedure != null ? procedure : emptyProcedureReadEntry;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            ReadEntry.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            ReadEntry.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
     
-    AsyncReadEntry getOrCreateAsyncReadEntry(AsyncRead<?> r) throws DatabaseException {
+    AsyncReadEntry getOrCreateAsyncReadEntry(AsyncRead<?> r, boolean isSync) throws DatabaseException {
         AsyncReadEntry existing = null;
         synchronized(asyncReadEntryMap) {
             existing = (AsyncReadEntry)asyncReadEntryMap.get(r);
@@ -512,7 +542,10 @@ public class QueryCache extends QueryCacheBase {
                 return existing;
             }
         }
-        if(existing.isPending()) waitPending(existing);
+        if(existing.isPending()) {
+          if(isSync) waitPending(existing);
+          else return null;
+        }
         return existing;
     }
     
@@ -522,18 +555,33 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerAsyncReadEntry(ReadGraphImpl graph, AsyncRead<?> r, CacheEntry parent, ListenerBase listener, AsyncProcedure procedure) throws DatabaseException {
+    public static void runnerAsyncReadEntry(ReadGraphImpl graph, AsyncRead<?> r, CacheEntry parent, ListenerBase listener, final AsyncProcedure procedure, boolean isSync) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             AsyncReadEntry.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureAsyncReadEntry;
-        AsyncReadEntry entry = (AsyncReadEntry)cache.getOrCreateAsyncReadEntry(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        AsyncReadEntry entry = (AsyncReadEntry)cache.getOrCreateAsyncReadEntry(r, isSync);
+        if(entry == null) {
+            graph.processor.schedule(Integer.MIN_VALUE, new SessionTask(r, graph.processor.THREAD_MASK+1, -1) {
+                @Override
+                public void run(int thread) {
+                    try {
+                        assert(!isSync);
+                        runnerAsyncReadEntry(graph, r, parent, listener, procedure, isSync);
+                    } catch (DatabaseException e) {
+                        Logger.defaultLogError(e);
+                    }
+                }
+            });
+            return;
+        }
+        AsyncProcedure procedure_ = procedure != null ? procedure : emptyProcedureAsyncReadEntry;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            AsyncReadEntry.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            AsyncReadEntry.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -565,18 +613,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerTypes(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, InternalProcedure<IntSet> procedure) throws DatabaseException {
+    public static void runnerTypes(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final InternalProcedure<IntSet> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             Types.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureTypes;
         Types entry = (Types)cache.getOrCreateTypes(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<IntSet> procedure_ = procedure != null ? procedure : emptyProcedureTypes;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            Types.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            Types.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -608,18 +657,19 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerChildMap(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, InternalProcedure<ObjectResourceIdMap<String>> procedure) throws DatabaseException {
+    public static void runnerChildMap(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final InternalProcedure<ObjectResourceIdMap<String>> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
         if(parent == null && listener == null && !cache.shouldCache(graph.processor, r)) {
             ChildMap.computeForEach(graph, r, null, procedure);
             return;
         }
-        if(procedure == null) procedure = emptyProcedureChildMap;
         ChildMap entry = (ChildMap)cache.getOrCreateChildMap(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<ObjectResourceIdMap<String>> procedure_ = procedure != null ? procedure : emptyProcedureChildMap;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            ChildMap.computeForEach(graph, r, entry, procedure);
+          assert(entry.isPending());
+            ChildMap.computeForEach(graph, r, entry, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -651,14 +701,15 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerAssertedStatements(ReadGraphImpl graph, int r1, int r2, CacheEntry parent, ListenerBase listener, TripleIntProcedure procedure) throws DatabaseException {
+    public static void runnerAssertedStatements(ReadGraphImpl graph, int r1, int r2, CacheEntry parent, ListenerBase listener, final TripleIntProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
-        if(procedure == null) procedure = emptyProcedureAssertedStatements;
         AssertedStatements entry = (AssertedStatements)cache.getOrCreateAssertedStatements(r1,r2);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        TripleIntProcedure procedure_ = procedure != null ? procedure : emptyProcedureAssertedStatements;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            entry.compute(graph, procedure);
+          assert(entry.isPending());
+            entry.compute(graph, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -690,14 +741,15 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerAssertedPredicates(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, IntProcedure procedure) throws DatabaseException {
+    public static void runnerAssertedPredicates(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final IntProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
-        if(procedure == null) procedure = emptyProcedureAssertedPredicates;
         AssertedPredicates entry = (AssertedPredicates)cache.getOrCreateAssertedPredicates(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        IntProcedure procedure_ = procedure != null ? procedure : emptyProcedureAssertedPredicates;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            entry.compute(graph, procedure);
+          assert(entry.isPending());
+            entry.compute(graph, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -729,14 +781,15 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerDirectSuperRelations(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, IntProcedure procedure) throws DatabaseException {
+    public static void runnerDirectSuperRelations(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final IntProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
-        if(procedure == null) procedure = emptyProcedureDirectSuperRelations;
         DirectSuperRelations entry = (DirectSuperRelations)cache.getOrCreateDirectSuperRelations(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        IntProcedure procedure_ = procedure != null ? procedure : emptyProcedureDirectSuperRelations;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            entry.compute(graph, procedure);
+          assert(entry.isPending());
+            entry.compute(graph, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -768,14 +821,15 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerSuperTypes(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, InternalProcedure<IntSet> procedure) throws DatabaseException {
+    public static void runnerSuperTypes(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final InternalProcedure<IntSet> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
-        if(procedure == null) procedure = emptyProcedureSuperTypes;
         SuperTypes entry = (SuperTypes)cache.getOrCreateSuperTypes(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<IntSet> procedure_ = procedure != null ? procedure : emptyProcedureSuperTypes;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            entry.compute(graph, procedure);
+          assert(entry.isPending());
+            entry.compute(graph, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -807,14 +861,15 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerTypeHierarchy(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, InternalProcedure<IntSet> procedure) throws DatabaseException {
+    public static void runnerTypeHierarchy(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final InternalProcedure<IntSet> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
-        if(procedure == null) procedure = emptyProcedureTypeHierarchy;
         TypeHierarchy entry = (TypeHierarchy)cache.getOrCreateTypeHierarchy(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<IntSet> procedure_ = procedure != null ? procedure : emptyProcedureTypeHierarchy;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            entry.compute(graph, procedure);
+          assert(entry.isPending());
+            entry.compute(graph, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -846,14 +901,15 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerSuperRelations(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, InternalProcedure<IntSet> procedure) throws DatabaseException {
+    public static void runnerSuperRelations(ReadGraphImpl graph, int r, CacheEntry parent, ListenerBase listener, final InternalProcedure<IntSet> procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
-        if(procedure == null) procedure = emptyProcedureSuperRelations;
         SuperRelations entry = (SuperRelations)cache.getOrCreateSuperRelations(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        InternalProcedure<IntSet> procedure_ = procedure != null ? procedure : emptyProcedureSuperRelations;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            entry.compute(graph, procedure);
+          assert(entry.isPending());
+            entry.compute(graph, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -885,14 +941,15 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerMultiReadEntry(ReadGraphImpl graph, MultiRead<?> r, CacheEntry parent, ListenerBase listener, AsyncMultiProcedure procedure) throws DatabaseException {
+    public static void runnerMultiReadEntry(ReadGraphImpl graph, MultiRead<?> r, CacheEntry parent, ListenerBase listener, final AsyncMultiProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
-        if(procedure == null) procedure = emptyProcedureMultiReadEntry;
         MultiReadEntry entry = (MultiReadEntry)cache.getOrCreateMultiReadEntry(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        AsyncMultiProcedure procedure_ = procedure != null ? procedure : emptyProcedureMultiReadEntry;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            entry.compute(graph, procedure);
+          assert(entry.isPending());
+            entry.compute(graph, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -924,14 +981,15 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerAsyncMultiReadEntry(ReadGraphImpl graph, AsyncMultiRead<?> r, CacheEntry parent, ListenerBase listener, AsyncMultiProcedure procedure) throws DatabaseException {
+    public static void runnerAsyncMultiReadEntry(ReadGraphImpl graph, AsyncMultiRead<?> r, CacheEntry parent, ListenerBase listener, final AsyncMultiProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
-        if(procedure == null) procedure = emptyProcedureAsyncMultiReadEntry;
         AsyncMultiReadEntry entry = (AsyncMultiReadEntry)cache.getOrCreateAsyncMultiReadEntry(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        AsyncMultiProcedure procedure_ = procedure != null ? procedure : emptyProcedureAsyncMultiReadEntry;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            entry.compute(graph, procedure);
+          assert(entry.isPending());
+            entry.compute(graph, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
@@ -963,14 +1021,15 @@ public class QueryCache extends QueryCacheBase {
         }
     }
     
-    public static void runnerExternalReadEntry(ReadGraphImpl graph, ExternalRead<?> r, CacheEntry parent, ListenerBase listener, AsyncProcedure procedure) throws DatabaseException {
+    public static void runnerExternalReadEntry(ReadGraphImpl graph, ExternalRead<?> r, CacheEntry parent, ListenerBase listener, final AsyncProcedure procedure) throws DatabaseException {
         QueryCache cache  = graph.processor.cache;
-        if(procedure == null) procedure = emptyProcedureExternalReadEntry;
         ExternalReadEntry entry = (ExternalReadEntry)cache.getOrCreateExternalReadEntry(r);
-        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure, false);
-        if(entry.isReady()) entry.performFromCache(graph, procedure);
+        AsyncProcedure procedure_ = procedure != null ? procedure : emptyProcedureExternalReadEntry;
+        ListenerEntry listenerEntry = cache.registerDependencies(graph, entry, parent, listener, procedure_, false);
+        if(entry.isReady()) entry.performFromCache(graph, procedure_);
         else {
-            entry.compute(graph, procedure);
+          assert(entry.isPending());
+            entry.compute(graph, procedure_);
             if(listenerEntry != null) cache.primeListenerEntry(listenerEntry, entry.getResult());
         }
     }
index d6924c708a9738fa1cd517fc686f1cb461369cc7..24a2dbe960be9ec03877a241ca0580f79ef4b3ab 100644 (file)
@@ -2,6 +2,7 @@ package org.simantics.db.impl.query;
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.concurrent.Semaphore;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.simantics.db.AsyncReadGraph;
@@ -640,7 +641,7 @@ public class QueryCacheBase {
                        try {
                                Thread.sleep(1);
                                counter++;
-                               if(counter > 1000) {
+                               if(counter > 5000) {
                                        CacheEntryBase base = ((CacheEntryBase)entry);
 //                                     if(base.created != null) {
 //                                             System.err.println("created:");
@@ -918,6 +919,7 @@ public class QueryCacheBase {
        private AsyncProcedure<T> procedure;
        private T result = null;
        private Throwable throwable = null;
+       private Semaphore s = new Semaphore(0);
        
        AsyncProcedureWrapper(AsyncProcedure<T> procedure) {
                this.procedure = procedure;
@@ -927,15 +929,22 @@ public class QueryCacheBase {
                public void execute(AsyncReadGraph graph, T result) {
                        if(procedure != null) procedure.execute(graph, result);
                        this.result = result;
+                       s.release();
                }
 
                @Override
                public void exception(AsyncReadGraph graph, Throwable throwable) {
                        if(procedure != null) procedure.exception(graph, throwable);
                        this.throwable = throwable;
+                       s.release();
                }
                
                public T get() throws DatabaseException {
+                       try {
+                               s.acquire();
+                       } catch (InterruptedException e) {
+                               e.printStackTrace();
+                       }
                        if(throwable != null) {
                                if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
                                else throw new DatabaseException(throwable);
@@ -1100,7 +1109,13 @@ public class QueryCacheBase {
 
     public static <T> T resultReadEntry(ReadGraphImpl graph, Read r, CacheEntry parent, ListenerBase listener, AsyncProcedure<T> procedure) throws DatabaseException {
        AsyncProcedureWrapper<T> wrap = new AsyncProcedureWrapper<>(procedure);
-        QueryCache.runnerReadEntry(graph, r, parent, listener, wrap);
+        QueryCache.runnerReadEntry(graph, r, parent, listener, wrap, true);
+        return wrap.get();
+    }
+
+    public static <T> T resultAsyncReadEntry(ReadGraphImpl graph, AsyncRead r, CacheEntry parent, ListenerBase listener, AsyncProcedure<T> procedure) throws DatabaseException {
+       AsyncProcedureWrapper<T> wrap = new AsyncProcedureWrapper<>(procedure);
+        QueryCache.runnerAsyncReadEntry(graph, r, parent, listener, wrap, true);
         return wrap.get();
     }
 
index f1e9233eb685b7fe87cb47ca4c00704503edec9a..2908bd43a83680fc7f24e3fe2faafb1b25bc1b53 100644 (file)
@@ -151,7 +151,9 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap
 
        QueryThread[]                                   executors;
 
-       public ArrayList<SessionTask>[]                           queues;
+//     public ArrayList<SessionTask>[]                           queues;
+       
+       public LinkedList<SessionTask>                           freeScheduling = new LinkedList<SessionTask>();
 
        enum ThreadState {
 
@@ -163,11 +165,11 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap
        public ReentrantLock[]                                                                  threadLocks;
        public Condition[]                                                                          threadConditions;
 
-       public ArrayList<SessionTask>[]                           ownTasks;
+       //public ArrayList<SessionTask>[]                           ownTasks;
 
-       public ArrayList<SessionTask>[]                           ownSyncTasks;
+       //public ArrayList<SessionTask>[]                           ownSyncTasks;
 
-       ArrayList<SessionTask>[]                           delayQueues;
+       //ArrayList<SessionTask>[]                           delayQueues;
        
        final Object querySupportLock;
        
@@ -176,19 +178,21 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap
        public void close() {
        }
 
-       final public void scheduleOwn(int caller, SessionTask request) {
-               ownTasks[caller].add(request);
-       }
+//     final public void scheduleOwn(int caller, SessionTask request) {
+//             ownTasks[caller].add(request);
+//     }
 
        final public void scheduleAlways(int caller, SessionTask request) {
 
-               int performer = request.thread;
-               if(caller == performer) {
-                       ownTasks[caller].add(request);
-               } else {
-                       schedule(caller, request);
-               }
+//             int performer = request.thread;
+//             if(caller == performer) {
+//                     ownTasks[caller].add(request);
+//             } else {
+//                     schedule(caller, request);
+//             }
 
+               schedule(caller, request);
+               
        }
 
        final public void schedule(int caller, SessionTask request) {
@@ -202,19 +206,43 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap
 
                assert(request != null);
 
-               if(caller == performer) {
-                       request.run(caller);
-               } else {
-                       ReentrantLock queueLock = threadLocks[performer];
-                       queueLock.lock();
-                       queues[performer].add(request);
-                       // This thread could have been sleeping
-                       if(queues[performer].size() == 1) {
-                               if(ThreadState.SLEEP == threadStates[performer]) sleepers.decrementAndGet();
-                               threadConditions[performer].signalAll();
-                       }
-                       queueLock.unlock();
-               }
+//             if(caller == performer) {
+//                     request.run(caller);
+//             } else {
+                       
+//                     if(performer == THREADS) {
+                               
+                               synchronized(querySupportLock) {
+                                       
+                                       freeScheduling.add(request);
+
+                                       //System.err.println("schedule free task " + request + " => " + freeScheduling.size());
+
+                                       for(int i=0;i<THREADS;i++) {
+                                               ReentrantLock queueLock = threadLocks[i];
+                                               queueLock.lock();
+                                               //queues[performer].add(request);
+                                               //if(ThreadState.SLEEP == threadStates[i]) sleepers.decrementAndGet();
+                                               threadConditions[i].signalAll();
+                                               queueLock.unlock();
+                                       }
+
+                               }
+
+                               return;
+                               
+//                     }
+//                     
+//                     ReentrantLock queueLock = threadLocks[performer];
+//                     queueLock.lock();
+//                     queues[performer].add(request);
+//                     // This thread could have been sleeping
+//                     if(queues[performer].size() == 1) {
+//                             //if(ThreadState.SLEEP == threadStates[performer]) sleepers.decrementAndGet();
+//                             threadConditions[performer].signalAll();
+//                     }
+//                     queueLock.unlock();
+//             }
 
        }
 
@@ -311,26 +339,26 @@ final public class QueryProcessor extends AbstractDisposable implements ReadGrap
                querySupportLock = core.getLock();
 
                executors = new QueryThread[THREADS];
-               queues = new ArrayList[THREADS];
+//             queues = new ArrayList[THREADS];
                threadLocks = new ReentrantLock[THREADS];
                threadConditions = new Condition[THREADS];
                threadStates = new ThreadState[THREADS];
-               ownTasks = new ArrayList[THREADS];
-               ownSyncTasks = new ArrayList[THREADS];
-               delayQueues = new ArrayList[THREADS * THREADS];
+//             ownTasks = new ArrayList[THREADS];
+//             ownSyncTasks = new ArrayList[THREADS];
+//             delayQueues = new ArrayList[THREADS * THREADS];
 
                //        freeSchedule = new AtomicInteger(0);
 
-               for (int i = 0; i < THREADS * THREADS; i++) {
-                       delayQueues[i] = new ArrayList<SessionTask>();
-               }
+//             for (int i = 0; i < THREADS * THREADS; i++) {
+//                     delayQueues[i] = new ArrayList<SessionTask>();
+//             }
 
                for (int i = 0; i < THREADS; i++) {
 
                        //            tasks[i] = new ArrayList<Runnable>();
-                       ownTasks[i] = new ArrayList<SessionTask>();
-                       ownSyncTasks[i] = new ArrayList<SessionTask>();
-                       queues[i] = new ArrayList<SessionTask>();
+//                     ownTasks[i] = new ArrayList<SessionTask>();
+//                     ownSyncTasks[i] = new ArrayList<SessionTask>();
+//                     queues[i] = new ArrayList<SessionTask>();
                        threadLocks[i] = new ReentrantLock();
                        threadConditions[i] = threadLocks[i].newCondition();
                        //            limits[i] = false;
index a5e79244e10e16e532ad843e56a75cb64f2b763c..07a390a51eafa254965f919fb8f03839b56576ff 100644 (file)
@@ -21,30 +21,32 @@ class QueryThread extends Thread implements SessionThread {
 
        private Session session;
        private QuerySupport querySupport;
+       final private QueryProcessor processor;
 
        final private ArrayList<SessionTask> tasks = new ArrayList<SessionTask>();
-       final private ArrayList<SessionTask> own;
-       final private ArrayList<SessionTask> ownSync;
-       final private ArrayList<SessionTask> queue;
+//     final private ArrayList<SessionTask> own;
+//     final private ArrayList<SessionTask> ownSync;
+//     final private ArrayList<SessionTask> queue;
        final private ReentrantLock lock;
        final private Condition condition;
        final private Object querySupportLock;
        final private int THREADS;
        final private AtomicInteger sleepers;
        final private ThreadState[] threadStates;
-       final private ArrayList<SessionTask>[] delayQueues;
+//     final private ArrayList<SessionTask>[] delayQueues;
        final private QueryThread[] executors;
        final private ReentrantLock[] threadLocks;
-       final private ArrayList<SessionTask>[] queues;
-       final private ArrayList<SessionTask>[] ownSyncTasks;
+//     final private ArrayList<SessionTask>[] queues;
+//     final private ArrayList<SessionTask>[] ownSyncTasks;
 
        public QueryThread(Session session, QueryProcessor processor, int index, String name) {
                super(QueryProcessor.QueryThreadGroup, null, name);
                this.session = session;
+               this.processor = processor;
                this.index = index;
-               own = processor.ownTasks[index];
-               ownSync = processor.ownSyncTasks[index];
-               queue = processor.queues[index];
+//             own = processor.ownTasks[index];
+//             ownSync = processor.ownSyncTasks[index];
+//             queue = processor.queues[index];
                lock = processor.threadLocks[index];
                condition = processor.threadConditions[index];
                querySupportLock = processor.querySupportLock;
@@ -52,11 +54,11 @@ class QueryThread extends Thread implements SessionThread {
                sleepers = processor.sleepers;
                querySupport = processor.querySupport;
                threadStates = processor.threadStates;
-               delayQueues = processor.delayQueues;
+//             delayQueues = processor.delayQueues;
                executors = processor.executors;
                threadLocks = processor.threadLocks;
-               queues = processor.queues;
-               ownSyncTasks = processor.ownSyncTasks;
+//             queues = processor.queues;
+//             ownSyncTasks = processor.ownSyncTasks;
        }
 
        synchronized void dispose() {
@@ -101,37 +103,47 @@ class QueryThread extends Thread implements SessionThread {
                        while(true) {
 
                                // Perform own tasks first
-                               if(tasks.addAll(own)) {
-                                       own.clear();
-                               } else if (doWait && !ownSync.isEmpty()) {
-                                       tasks.add(ownSync.remove(ownSync.size()-1));
-                               }
+//                             if(tasks.addAll(own)) {
+//                                     own.clear();
+//                             } else if (doWait && !ownSync.isEmpty()) {
+//                                     tasks.add(ownSync.remove(ownSync.size()-1));
+//                             }
 
                                // Try some queued tasks
-                               lock.lock();
-                               if(tasks.addAll(queue)) {
-                                       queue.clear();
-                                       lock.unlock();
-                                       return tasks;
-                               } else {
-                                       lock.unlock();
-                               }
+//                             lock.lock();
+//                             if(tasks.addAll(queue)) {
+//                                     queue.clear();
+//                                     lock.unlock();
+//                                     return tasks;
+//                             } else {
+//                                     lock.unlock();
+//                             }
 
                                // Return tasks if some were found
                                if(!tasks.isEmpty()) return tasks;
+                               
                                if(!doWait) return null;
 
                                synchronized (querySupportLock) {
 
-                                       lock.lock();
+//                                     System.err.println("check free tasks for QT " + index + " (" + processor.freeScheduling + ")");
                                        
-                                       // Just maybe someone inserted tasks and notified just before synchronized block
-                                       if(tasks.addAll(queue)) {
-                                               queue.clear();
-                                               lock.unlock();
+                                       if(!processor.freeScheduling.isEmpty()) {
+                                               tasks.add(processor.freeScheduling.removeFirst());
                                                return tasks;
                                        }
 
+                                       lock.lock();
+                                       
+                                       // Just maybe someone inserted tasks and notified just before synchronized block
+//                                     if(tasks.addAll(queue)) {
+//                                             queue.clear();
+//                                             lock.unlock();
+//                                             return tasks;
+//                                     }
+                                       
+//                                     System.err.println("QT " + index + ", sleepers = " + sleepers);
+
                                        // We are the last one awake
                                        if(sleepers.incrementAndGet() == THREADS) {
 
@@ -141,9 +153,9 @@ class QueryThread extends Thread implements SessionThread {
                                                if(querySupport == null) System.err.println("null qs");
                                                querySupport.ceased(index);
 
-                                               if(tasks.addAll(own)) {
-                                                       own.clear();
-                                               }
+//                                             if(tasks.addAll(own)) {
+//                                                     own.clear();
+//                                             }
                                                //                                      System.err.println("tasks after ceased: " + tasks.size());
                                                if(!tasks.isEmpty()) {
                                                        lock.unlock();
@@ -170,6 +182,8 @@ class QueryThread extends Thread implements SessionThread {
                                threadStates[index] = ThreadState.SLEEP;
                                condition.await();
 
+                               sleepers.decrementAndGet();
+
                                // We are done
                                if(isDisposed()) {
                                        threadStates[index] = ThreadState.DISPOSED;
@@ -197,17 +211,17 @@ class QueryThread extends Thread implements SessionThread {
 
                boolean didExecute = false;
 
-               for(int performer=0;performer<THREADS;performer++) {
-                       if(!delayQueues[index * THREADS + performer].isEmpty()) {
-                               synchronized(executors[performer]) {
-                                       threadLocks[performer].lock();
-                                       queues[performer].addAll(delayQueues[index * THREADS + performer]);
-                                       delayQueues[index * THREADS + performer].clear();
-                                       executors[performer].notify();
-                                       threadLocks[performer].unlock();
-                               }
-                       }
-               }
+//             for(int performer=0;performer<THREADS;performer++) {
+//                     if(!delayQueues[index * THREADS + performer].isEmpty()) {
+//                             synchronized(executors[performer]) {
+//                                     threadLocks[performer].lock();
+//                                     queues[performer].addAll(delayQueues[index * THREADS + performer]);
+//                                     delayQueues[index * THREADS + performer].clear();
+//                                     executors[performer].notify();
+//                                     threadLocks[performer].unlock();
+//                             }
+//                     }
+//             }
 
                if(tasks.isEmpty()) {
                        ArrayList<SessionTask> finished = newTasks(false, tasks);
@@ -218,12 +232,13 @@ class QueryThread extends Thread implements SessionThread {
 
                        SessionTask task = tasks.remove(tasks.size() - 1);
 
-                       if(task.syncCaller == index) {
-                               ownSyncTasks[index].add(task);
-                       } else {
+//                     if(task.syncCaller == index) {
+//                             ownSyncTasks[index].add(task);
+//                     } else {
                                task.run(index);
+//                             System.err.println("QT(s) " + index + " runs " + task);
                                didExecute = true;
-                       }
+//                     }
 
                }
 
@@ -248,21 +263,22 @@ class QueryThread extends Thread implements SessionThread {
                                while(!tasks.isEmpty()) {
 
                                        SessionTask task = tasks.remove(tasks.size()-1);
+//                                     System.err.println("QT " + index + " runs " + task);
                                        task.run(index);
 
                                }
 
-                               for(int performer=0;performer<THREADS;performer++) {
-                                       if(!delayQueues[index * THREADS + performer].isEmpty()) {
-                                               synchronized(executors[performer]) {
-                                                       threadLocks[performer].lock();
-                                                       queues[performer].addAll(delayQueues[index * THREADS + performer]);
-                                                       delayQueues[index * THREADS + performer].clear();
-                                                       executors[performer].notify();
-                                                       threadLocks[performer].unlock();
-                                               }
-                                       }
-                               }
+//                             for(int performer=0;performer<THREADS;performer++) {
+//                                     if(!delayQueues[index * THREADS + performer].isEmpty()) {
+//                                             synchronized(executors[performer]) {
+//                                                     threadLocks[performer].lock();
+//                                                     queues[performer].addAll(delayQueues[index * THREADS + performer]);
+//                                                     delayQueues[index * THREADS + performer].clear();
+//                                                     executors[performer].notify();
+//                                                     threadLocks[performer].unlock();
+//                                             }
+//                                     }
+//                             }
 
                        }
 
index 8abbb86c8745499246b311b5648a7dcc499eecf9..115a4a5a1509db803a88140b038d9f475b1e3305 100644 (file)
@@ -45,6 +45,8 @@ final public class ReadEntry<T> extends CacheEntryBase<AsyncProcedure<T>> {
     }
        
     final public Object addOrSet(AsyncReadGraph graph, Object result) {
+       
+//     System.err.println("addOrSet " + request + " " + Thread.currentThread() + " " + result);
 
        assert(assertPending());
        
@@ -100,7 +102,7 @@ final public class ReadEntry<T> extends CacheEntryBase<AsyncProcedure<T>> {
         
     }
     
-    @Override
+    //@Override
     public Object compute(ReadGraphImpl graph, AsyncProcedure<T> procedure) throws DatabaseException {
 
                ReadGraphImpl queryGraph = graph.withParent(this);
index d55768aaa1a04cea220b146882cdf614e0353fd9..204a0005af1178a19efc6bc2edee8f9ea3747f07 100644 (file)
@@ -41,6 +41,7 @@ final public class RelationInfoQuery extends UnaryQuery<InternalProcedure<Relati
                        
                        @Override
                        public void execute(ReadGraphImpl graph, int i) throws DatabaseException {
+                               if(done) return;
                                done = true;
                                RelationInfo result = new RelationInfo(r, isFunctional, isFinal, true);
                                if(entry != null) entry.setResult(result);
@@ -49,22 +50,20 @@ final public class RelationInfoQuery extends UnaryQuery<InternalProcedure<Relati
 
                        @Override
                        public void finished(ReadGraphImpl graph) throws DatabaseException {
-                               if(!done) {
-                                       done = true;
-                                       RelationInfo result = new RelationInfo(r, isFunctional, isFinal, false);
-                                       if(entry != null) entry.setResult(result);
-                                       proc.execute(graph, result);
-                               }
+                               if(done) return;
+                               done = true;
+                               RelationInfo result = new RelationInfo(r, isFunctional, isFinal, false);
+                               if(entry != null) entry.setResult(result);
+                               proc.execute(graph, result);
                        }
 
                        @Override
                        public void exception(ReadGraphImpl graph, Throwable throwable) throws DatabaseException {
-                               if(!done) {
-                                       done = true;
-                                       DatabaseException e = new DatabaseException("Internal error in RelationInfoQuery");
-                                       if(entry != null) entry.except(e);
-                                       proc.exception(graph, e);
-                               }
+                               if(done) return;
+                               done = true;
+                               DatabaseException e = new DatabaseException("Internal error in RelationInfoQuery");
+                               if(entry != null) entry.except(e);
+                               proc.exception(graph, e);
                        }
                        
                });
@@ -85,7 +84,7 @@ final public class RelationInfoQuery extends UnaryQuery<InternalProcedure<Relati
         
        }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, final InternalProcedure<RelationInfo> procedure) throws DatabaseException {
                computeForEach(graph, id, this, procedure);
                return getResult();
index e1a106aaac540cc019262d03f1688194bbd23fd2..ad4700aa826d6178f9447f81fa8e606ddfd13f0f 100644 (file)
@@ -135,6 +135,10 @@ final public class Statements extends CollectionBinaryQuery<TripleIntProcedure>
        
     final static private void forSingleAssertion(ReadGraphImpl graph, final int r1, final int r2, final Statements entry, final TripleIntProcedure procedure) throws DatabaseException {
         
+       if(entry != null) {
+               assert(entry.isPending());
+       }
+       
        IntArray map = getAssertionMap(graph, r1, r2, entry);
        if(map == null) {
             if(entry != null) entry.finish(graph, procedure);
@@ -647,15 +651,13 @@ final public class Statements extends CollectionBinaryQuery<TripleIntProcedure>
         }
         
     }
-    
-    @Override
-    public Object compute(ReadGraphImpl graph, final TripleIntProcedure procedure) throws DatabaseException {
-       computeForEach(graph, r1(), r2(), this, procedure);
-       return getResult();
-    }
        
     public static void computeForEach(ReadGraphImpl graph, final int r1, final int r2, final Statements entry, final TripleIntProcedure procedure) throws DatabaseException {
        
+       if(entry != null) {
+               assert(entry.isPending());
+       }
+       
        QueryCache.runnerRelationInfoQuery(graph, r2, entry, null, new InternalProcedure<RelationInfo>() {
 
             @Override
@@ -690,6 +692,7 @@ final public class Statements extends CollectionBinaryQuery<TripleIntProcedure>
 
         synchronized(this) {
             setReady();
+            //new Exception(toString() + " is READY").printStackTrace();
         }
 
         IntArray v = (IntArray)getResult();
@@ -761,7 +764,7 @@ final public class Statements extends CollectionBinaryQuery<TripleIntProcedure>
     @Override
     public void recompute(ReadGraphImpl graph) throws DatabaseException {
         
-        compute(graph, new TripleIntProcedureAdapter() {
+        computeForEach(graph, r1(), r2(), this, new TripleIntProcedureAdapter() {
 
             @Override
             public void finished(ReadGraphImpl graph) {
index 0f076fb34ddb13823ea08389e78def15df14ee30..b8d29b7e6ea995299e9baa11cc6c6c1be4a78c11 100644 (file)
@@ -69,7 +69,7 @@ final public class SuperRelations extends UnaryQuery<InternalProcedure<IntSet>>
         
     }
 
-       @Override
+       //@Override
        public Object compute(final ReadGraphImpl graph, final InternalProcedure<IntSet> procedure) throws DatabaseException {
 
                QueryProcessor processor = graph.processor;
index 06fabb2d7380c73a803948912bd899727e88f247..a01c84699ce3181febae84ac376f7f93bf62e234 100644 (file)
@@ -33,7 +33,7 @@ final public class SuperTypes extends UnaryQuery<InternalProcedure<IntSet>> {
                provider.cache.remove(this);
        }
 
-       @Override
+       //@Override
        public Object compute(ReadGraphImpl graph, final InternalProcedure<IntSet> procedure) throws DatabaseException {
                return computeForEach(graph, id, this, procedure);
        }
index 9da45946999098752d3a5322f1e13eb66874b046..ad4581bb6a3e6045c877193dd9aecf8e6c316fd7 100644 (file)
@@ -33,7 +33,7 @@ final public class TypeHierarchy extends UnaryQuery<InternalProcedure<IntSet>> {
                provider.cache.remove(this);
        }
 
-       @Override
+       //@Override
        public IntSet compute(ReadGraphImpl graph, final InternalProcedure<IntSet> procedure) throws DatabaseException {
 
                QueryProcessor processor = graph.processor;
index 155bc209bf27d2edc1a4d771f14d74047d1eeebd..512045e17be63f354fd12a41a9d87cfd17d1afca 100644 (file)
@@ -30,7 +30,7 @@ final public class Types extends UnaryQuery<InternalProcedure<IntSet>> {
                provider.cache.remove(this);
        }
 
-       @Override
+       //@Override
        public Object compute(final ReadGraphImpl graph, final InternalProcedure<IntSet> procedure) throws DatabaseException {
                computeForEach(graph, id, this, procedure);
                return getResult();
index b29d518df13789956002f48a88902432daa30e92..794bcc8edc3258fdee965278321c41f8e3789156 100644 (file)
@@ -30,7 +30,7 @@ public class URIToResource extends StringQuery<InternalProcedure<Integer>> {
        provider.cache.remove(this);
     }
     
-    @Override
+    //@Override
     public Object compute(ReadGraphImpl graph, final InternalProcedure<Integer> procedure) throws DatabaseException {
        computeForEach(graph, id, this, procedure);
         return getResult();
index fd1035a78eed6bf5722830f290536c82f6b39ba5..11c2fe6fade53fe61c7d5823a04c46d2e7444c41 100644 (file)
@@ -50,11 +50,6 @@ abstract public class UnaryQueryHash<Procedure> extends THash {
             throw new Error("Not possible.");
                }
 
-               @Override
-               public Object compute(ReadGraphImpl graph, Procedure procedure) throws DatabaseException {
-            throw new Error("Not possible.");
-               }
-
                @Override
                Object performFromCache(ReadGraphImpl graph, Procedure procedure) throws DatabaseException {
             throw new Error("Not possible.");
index 1521d31936d8e3946addd015b62ac9ce68b77cbe..b96e13d42fc14d177779ef021564dfb1fdd22fed 100644 (file)
@@ -43,18 +43,9 @@ final public class ValueQuery extends UnaryQuery<InternalProcedure<byte[]>> {
                
        }
 
-    public static byte[] computeForEach(ReadGraphImpl graph, final int r) {
-
-        graph.ensureLoaded(r);
-        
-        return graph.getValue(r);
-        
-    }
-       
-       @Override
-       public Object compute(ReadGraphImpl graph, final InternalProcedure<byte[]> procedure) throws DatabaseException {
-               return computeForEach(graph, id, this, procedure);
-    }
+//     public Object compute(ReadGraphImpl graph, final InternalProcedure<byte[]> procedure) throws DatabaseException {
+//             return computeForEach(graph, id, this, procedure);
+//    }
     
     @Override
     public String toString() {
@@ -63,13 +54,13 @@ final public class ValueQuery extends UnaryQuery<InternalProcedure<byte[]>> {
 
     @Override
     public Object performFromCache(ReadGraphImpl graph, InternalProcedure<byte[]> procedure) throws DatabaseException {
-       return compute(graph, procedure);
+       return computeForEach(graph, id, this, procedure);
     }
     
     @Override
     public void recompute(ReadGraphImpl graph) throws DatabaseException {
        
-        compute(graph,  new InternalProcedure<byte[]>() {
+       computeForEach(graph, id, this, new InternalProcedure<byte[]>() {
 
             @Override
             public void execute(ReadGraphImpl graph, byte[] result) {
index 4bbd480020141b5e602c9e7f73fb1b8170410995..9faf02cc8550ea8b34fcd780cafdaa60c9e47812 100644 (file)
@@ -111,9 +111,11 @@ public class RuntimeEnvironmentRequest2 extends BinaryRead<Resource, Resource, R
         fillEnvironmentSpecification(environmentSpecification);
 
         Layer0 L0 = Layer0.getInstance(graph);
-        Collection<Resource> sclModules = graph.syncRequest(new ObjectsWithType(parameter, L0.ConsistsOf, L0.SCLModule));
-        for (Resource sclModule : sclModules)
-            environmentSpecification.importModule(graph.getURI(sclModule), "");
+        if(parameter != null) {
+               Collection<Resource> sclModules = graph.syncRequest(new ObjectsWithType(parameter, L0.ConsistsOf, L0.SCLModule));
+               for (Resource sclModule : sclModules)
+                   environmentSpecification.importModule(graph.getURI(sclModule), "");
+        }
 
         Resource mainModule = Layer0Utils.getPossibleChild(graph, parameter2, "SCLMain");
         if(mainModule != null)
index 2bd089d1e8ed1589ecadb76f6f18662169b405ef..103c3183bd857f888767b34fd21ce3a2158c92fb 100644 (file)
@@ -57,7 +57,7 @@ class NodeValueRequest extends ParametrizedPrimitiveRead<Pair<VariableNode,Bindi
     public void register(ReadGraph graph, final Listener<Variant> procedure) {
        
        VariableNode node = parameter.first;
-
+       
         if(procedure.isDisposed()) {
                
                // We are not listening
@@ -201,7 +201,11 @@ class NodeValueRequest extends ParametrizedPrimitiveRead<Pair<VariableNode,Bindi
         try {
                Variant newValue = get(parameter);
             if (wasRun && ObjectUtils.objectEquals(value, newValue)) {
-                //System.out.println("CACHE VALUE MATCH (" + newValue + ") for " + node.node);
+               try {
+                       //System.err.println("CACHE VALUE MATCH (" + newValue + ") for " + node.node);
+               } catch (Throwable t) {
+                       
+               }
                 return;
             }
             value = newValue;
index 7df13315f8f68b093fdbf6cb91b0359b5bb909e1..f30e6e156f13b0a4f8d37d3ad84b2ce3d4903a27 100644 (file)
@@ -900,7 +900,7 @@ public final class ClusterTable implements IClusterTable {
     }
     
     @SuppressWarnings("unchecked")
-    public final <T extends ClusterI> T getClusterByResourceKey(final int resourceKey) {
+    public synchronized final <T extends ClusterI> T getClusterByResourceKey(final int resourceKey) {
         int clusterKey = ClusterTraitsBase.getClusterKeyFromResourceKeyNoThrow(resourceKey);
         if (ClusterTraitsBase.isVirtualClusterKey(clusterKey))
             throw new RuntimeException("Tried to get a persistent cluster for a virtual resource.");
index f3b6c2e0b9ba8c065746f0b17b49efc5d83cac27..08d740f267d55daef3c38a8f205b0a75f7919154 100644 (file)
@@ -50,6 +50,7 @@ import org.simantics.db.authentication.UserAuthenticationAgent;
 import org.simantics.db.authentication.UserAuthenticator;
 import org.simantics.db.common.Indexing;
 import org.simantics.db.common.TransactionPolicyRelease;
+import org.simantics.db.common.procedure.BlockingAsyncProcedure;
 import org.simantics.db.common.procedure.adapter.AsyncMultiProcedureAdapter;
 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
 import org.simantics.db.common.procedure.wrapper.NoneToAsyncListener;
@@ -1496,9 +1497,9 @@ public abstract class SessionImplSocket implements Session, WriteRequestSchedule
         assert (request != null);
         assert (procedure != null);
 
-        int thread = request.hashCode() & queryProvider2.THREAD_MASK;
+        //int thread = request.hashCode() & queryProvider2.THREAD_MASK;
 
-        requestManager.scheduleRead(new SessionRead(request, throwable, notify, thread, thread) {
+        requestManager.scheduleRead(new SessionRead(request, throwable, notify, queryProvider2.THREAD_MASK + 1, -1) {
 
             @Override
             public void run(int thread) {
@@ -1535,7 +1536,7 @@ public abstract class SessionImplSocket implements Session, WriteRequestSchedule
 
                                };
                                
-                               QueryCache.runnerReadEntry(newGraph, request, null, listener, ap);
+                               QueryCache.runnerReadEntry(newGraph, request, null, listener, ap, true);
                                
                        } catch (Throwable t) {
                            // This is handled by the AsyncProcedure
@@ -1630,7 +1631,8 @@ public abstract class SessionImplSocket implements Session, WriteRequestSchedule
                     if (listener != null) {
 
                         try {
-                               QueryCache.runnerAsyncReadEntry(newGraph, request, null, listener, procedure);
+                               QueryCacheBase.resultAsyncReadEntry(newGraph, request, null, listener, procedure);
+                               //QueryCache.runnerAsyncReadEntry(newGraph, request, null, listener, procedure, true);
                                                        //newGraph.processor.query(newGraph, request, null, procedure, listener);
                                                } catch (DatabaseException e) {
                                                        Logger.defaultLogError(e);
@@ -1638,20 +1640,21 @@ public abstract class SessionImplSocket implements Session, WriteRequestSchedule
 
                     } else {
 
-                        final ResultCallWrappedSingleQueryProcedure4<T> wrapper = new ResultCallWrappedSingleQueryProcedure4<T>(
-                                procedure, "request");
-
-                        try {
+//                        final ResultCallWrappedSingleQueryProcedure4<T> wrapper = new ResultCallWrappedSingleQueryProcedure4<T>(
+//                                procedure, "request");
 
-//                            newGraph.state.barrier.inc();
+                       BlockingAsyncProcedure<T> wrap = new BlockingAsyncProcedure<T>(procedure, request);
 
-                            request.perform(newGraph, wrapper);
+                       try {
 
-//                            newGraph.waitAsync(request);
+                            request.perform(newGraph, wrap);
+                            wrap.get();
 
                         } catch (Throwable t) {
 
-                            wrapper.exception(newGraph, t);
+                               wrap.exception(newGraph, t);
+                               
+//                            wrapper.exception(newGraph, t);
 //                            newGraph.waitAsync(request);
 
 
@@ -3521,7 +3524,7 @@ public abstract class SessionImplSocket implements Session, WriteRequestSchedule
 
     public int getAmountOfQueryThreads() {
         // This must be a power of two
-        return 4;
+        return 16;
 //        return Integer.highestOneBit(Runtime.getRuntime().availableProcessors());
     }
 
index a29d6ce045bc619ceae803dfe7bf6d48cb03241a..fb2e1e720c292a71824e4083bf5c490b0e591ae6 100644 (file)
@@ -216,6 +216,9 @@ public class SessionRequestManager {
                                if(!session.state.isAlive()) return;
 
                                WriteState<?> writeState = session.writeState;
+                               
+                               assert(writeState != null);
+                               
                                WriteGraphImpl graph = writeState.getGraph();
 
                                if(writeState.isExcepted()) {
@@ -296,7 +299,9 @@ public class SessionRequestManager {
                        
                } else {
 
-                   throw new IllegalStateException("State in ceased should be WRITE or READ or INIT (was " + state + ")"); 
+                       // Spurious wakeup
+                       
+                   //throw new IllegalStateException("State in ceased should be WRITE or READ or INIT (was " + state + ")"); 
                        
                }
                
@@ -349,6 +354,8 @@ public class SessionRequestManager {
 
                boolean inUpdate = state == State.WRITE_UPDATE;
 
+               //System.err.println("schedule write " + task);
+               
                assert(State.INIT != state);
                //task.combine = combine != null ? combine : inUpdate;
                if(State.IDLE == state) {
index 47a14ddbcbccc7424bec9fe1ea059c588dffc24d..7cc87e30b155869c4219b47ac045404cd9361b1d 100644 (file)
@@ -20,6 +20,7 @@ import org.simantics.db.ReadGraph;
 import org.simantics.db.Resource;
 import org.simantics.db.adaption.Adapter;
 import org.simantics.db.adaption.AdaptionService;
+import org.simantics.db.common.procedure.BlockingAsyncProcedure;
 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
 import org.simantics.db.common.procedure.single.SyncReadProcedure;
 import org.simantics.db.common.request.BinaryRead;
@@ -583,11 +584,15 @@ public class AdaptionService2 implements AdaptionService {
     public <T, C> T adapt(ReadGraph g, Resource r, C context, Class<C> contextClass, Class<T> targetClass, boolean possible) throws DatabaseException {
 
        Adapter<T,C> adapter = getAdapter(g, r, context, contextClass, targetClass, possible);
+       if(adapter == null) return null;
        
-               SyncReadProcedure<T> procedure = new SyncReadProcedure<T>();
-       adapter.adapt(g, r, context, procedure);
-               procedure.checkAndThrow();
-               return procedure.result;
+       BlockingAsyncProcedure<T> ap = new BlockingAsyncProcedure<T>(null, adapter);
+       
+//             SyncReadProcedure<T> procedure = new SyncReadProcedure<T>();
+       adapter.adapt(g, r, context, ap);
+       return ap.get();
+//             procedure.checkAndThrow();
+//             return procedure.result;
        
     }
     
index c80090f5f27acba985ecd30d3bfcc7ad3d2fd88f..a4495a4b373aaac47c0634414a40c5c028ce5f78 100644 (file)
@@ -7,10 +7,10 @@
       <product
             application="org.simantics.workbench.application"
             description="Simantics Desktop Environment"
-            name="Simantics Desktop">
+            name="TestingStation Server">
          <property
                name="appName"
-               value="Simantics Desktop"/>
+               value="TestingStation Server"/>
          <property
                name="aboutImage"
                value="platform:/plugin/org.simantics.desktop.ui/icons/simantics256.png">
index 56063b990f71e771180a75acfd06db99b09877fa..fe7479e5df20a5dfdf0d59a605370414d754219d 100644 (file)
@@ -17,13 +17,17 @@ import gnu.trove.procedure.TIntProcedure;
 import gnu.trove.set.hash.THashSet;
 
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Set;
+import java.util.concurrent.Semaphore;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import org.simantics.db.AsyncReadGraph;
 import org.simantics.db.ReadGraph;
 import org.simantics.db.Resource;
+import org.simantics.db.common.primitiverequest.OrderedSet;
 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
+import org.simantics.db.common.utils.OrderedSetUtils;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.procedure.AsyncMultiProcedure;
 import org.simantics.db.procedure.AsyncProcedure;
@@ -71,124 +75,149 @@ public class DiagramContentRequest extends BaseRequest<Resource, DiagramContents
         // These help loading result.elements in the correct order.
         final AtomicInteger index = new AtomicInteger();
         final TIntArrayList unrecognizedElementIndices = new TIntArrayList();
-
-        g.forOrderedSet(data, new AsyncMultiProcedure<Resource>() {
-
-            @Override
-            public void execute(AsyncReadGraph graph, final Resource component) {
-
-                // Must add the elements to the result set here in order to
-                // keep their order the same as in the ordered set.
-                final int elementIndex = index.getAndIncrement();
-                result.elements.add(component);
-
-                graph.forTypes(component, new AsyncProcedure<Set<Resource>>() {
-
-                    @Override
-                    public void exception(AsyncReadGraph graph, Throwable t) {
-                        if (errorHandler != null)
-                            errorHandler.error(t.getMessage(), t);
-                    }
-
-                    @Override
-                    public void execute(AsyncReadGraph graph, Set<Resource> types) {
-                        if (types.contains(DIA.Connection)) {
-                            if (types.contains(DIA.RouteGraphConnection)) {
-                                graph.asyncRequest(new RouteGraphConnectionPartRequest(errorHandler, DIA, component),
-                                        new ProcedureAdapter<RouteGraphConnectionPartData>() {
-                                    @Override
-                                    public void execute(RouteGraphConnectionPartData partData) {
-                                        synchronized (result) {
-                                            for (EdgeResource link : partData.links) {
-                                                result.routeLinks.add(link);
-                                                result.partToConnection.put(link, component);
-                                                result.connectionToParts.add(component, link);
-                                            }
-                                            for (Resource line : partData.routeLines) {
-                                                result.routeLines.add(line);
-                                                result.connectionToParts.add(component, line);
-                                                result.partToConnection.put(line, component);
-                                            }
-                                            for (Resource point : partData.routePoints) {
-                                                result.routePoints.add(point);
-                                                result.connectionToParts.add(component, point);
-                                                result.partToConnection.put(point, component);
-                                            }
-                                        }
-                                    }
-                                });
-
-                                synchronized (result.routeGraphConnectionSet) {
-                                    result.routeGraphConnectionSet.add(component);
-                                }
-                            } else {
-                                graph.asyncRequest(new ConnectionPartRequest(errorHandler, DIA, component),
-                                        new ProcedureAdapter<ConnectionPartData>() {
-                                    @Override
-                                    public void execute(ConnectionPartData partData) {
-                                        synchronized (result) {
-                                            for (EdgeResource er : partData.edges) {
-                                                result.connectionSegments.add(er);
-                                                result.partToConnection.put(er, component);
-                                                result.connectionToParts.add(component, er);
-                                            }
-                                            for (Resource bp : partData.branchPoints) {
-                                                result.branchPoints.add(bp);
-                                                result.connectionToParts.add(component, bp);
-                                                result.partToConnection.put(bp, component);
-                                            }
-                                        }
-                                    }
-                                });
-
-                                synchronized (result.connectionSet) {
-                                    result.connectionSet.add(component);
-                                }
-                            }
-                        }
-                        else if (types.contains(DIA.Element)) {
-                            synchronized (result.nodeSet) {
-                                result.nodeSet.add(component);
-                            }
-                        }
-                        else {
-                            synchronized (unrecognizedElementIndices) {
-                                // Unrecognized element, mark it to be
-                                // removed after everything is processed.
-                                unrecognizedElementIndices.add(elementIndex);
-                            }
-                        }
-                    }
-
-                });
-
-            }
-
+        
+        Collection<Resource> components = OrderedSetUtils.toList(g, data);
+        
+        Semaphore s = new Semaphore(0);
+        
+        for(Resource component : components) {
+               
+            // Must add the elements to the result set here in order to
+            // keep their order the same as in the ordered set.
+            final int elementIndex = index.getAndIncrement();
+            result.elements.add(component);
+
+               Set<Resource> types = g.getTypes(component);
+               
+                if (types.contains(DIA.Connection)) {
+                 if (types.contains(DIA.RouteGraphConnection)) {
+                     g.asyncRequest(new RouteGraphConnectionPartRequest(errorHandler, DIA, component),
+                             new ProcedureAdapter<RouteGraphConnectionPartData>() {
+                         @Override
+                         public void execute(RouteGraphConnectionPartData partData) {
+                             synchronized (result) {
+                                 for (EdgeResource link : partData.links) {
+                                     result.routeLinks.add(link);
+                                     result.partToConnection.put(link, component);
+                                     result.connectionToParts.add(component, link);
+                                 }
+                                 for (Resource line : partData.routeLines) {
+                                     result.routeLines.add(line);
+                                     result.connectionToParts.add(component, line);
+                                     result.partToConnection.put(line, component);
+                                 }
+                                 for (Resource point : partData.routePoints) {
+                                     result.routePoints.add(point);
+                                     result.connectionToParts.add(component, point);
+                                     result.partToConnection.put(point, component);
+                                 }
+                             }
+                             s.release();
+                         }
+                     });
+
+                     synchronized (result.routeGraphConnectionSet) {
+                         result.routeGraphConnectionSet.add(component);
+                     }
+                 } else {
+                     g.asyncRequest(new ConnectionPartRequest(errorHandler, DIA, component),
+                             new ProcedureAdapter<ConnectionPartData>() {
+                         @Override
+                         public void execute(ConnectionPartData partData) {
+                             synchronized (result) {
+                                 for (EdgeResource er : partData.edges) {
+                                     result.connectionSegments.add(er);
+                                     result.partToConnection.put(er, component);
+                                     result.connectionToParts.add(component, er);
+                                 }
+                                 for (Resource bp : partData.branchPoints) {
+                                     result.branchPoints.add(bp);
+                                     result.connectionToParts.add(component, bp);
+                                     result.partToConnection.put(bp, component);
+                                 }
+                             }
+                             s.release();
+                         }
+                     });
+
+                     synchronized (result.connectionSet) {
+                         result.connectionSet.add(component);
+                     }
+                 }
+             }
+             else if (types.contains(DIA.Element)) {
+                 synchronized (result.nodeSet) {
+                     result.nodeSet.add(component);
+                 }
+                 s.release();
+
+             }
+             else {
+                 synchronized (unrecognizedElementIndices) {
+                     // Unrecognized element, mark it to be
+                     // removed after everything is processed.
+                     unrecognizedElementIndices.add(elementIndex);
+                 }
+                 s.release();
+             }         
+               
+        }
+
+        try {
+                       s.acquire(components.size());
+               } catch (InterruptedException e) {
+                       e.printStackTrace();
+               }
+        
+        // Remove elements that were not recognized in descending order.
+        unrecognizedElementIndices.sort();
+        unrecognizedElementIndices.forEachDescending(new TIntProcedure() {
             @Override
-            public void finished(AsyncReadGraph graph) {
-                // Remove elements that were not recognized in descending order.
-                unrecognizedElementIndices.sort();
-                unrecognizedElementIndices.forEachDescending(new TIntProcedure() {
-                    @Override
-                    public boolean execute(int index) {
-                        result.elements.remove(index);
-                        return true;
-                    }
-                });
-
-                // Help successive request executions by remembering the previous
-                // element count. This will relieve some ArrayList reallocation
-                // strain down the road.
-                previousElementCount = result.elements.size();
-            }
-
-            @Override
-            public void exception(AsyncReadGraph graph, Throwable t) {
-                if (errorHandler != null)
-                    errorHandler.error(t.getMessage(), t);
+            public boolean execute(int index) {
+                result.elements.remove(index);
+                return true;
             }
         });
 
+        // Help successive request executions by remembering the previous
+        // element count. This will relieve some ArrayList reallocation
+        // strain down the road.
+        previousElementCount = result.elements.size();
+        
+
+//        g.forOrderedSet(data, new AsyncMultiProcedure<Resource>() {
+//
+//            @Override
+//            public void execute(AsyncReadGraph graph, final Resource component) {
+//
+//                graph.forTypes(component, new AsyncProcedure<Set<Resource>>() {
+//
+//                    @Override
+//                    public void exception(AsyncReadGraph graph, Throwable t) {
+//                        if (errorHandler != null)
+//                            errorHandler.error(t.getMessage(), t);
+//                    }
+//
+//                    @Override
+//                    public void execute(AsyncReadGraph graph, Set<Resource> types) {
+//                       
+//                    }
+//
+//                });
+//
+//            }
+//
+//            @Override
+//            public void finished(AsyncReadGraph graph) {
+//            }
+//
+//            @Override
+//            public void exception(AsyncReadGraph graph, Throwable t) {
+//                if (errorHandler != null)
+//                    errorHandler.error(t.getMessage(), t);
+//            }
+//        });
+
         return result;
     }
 }
\ No newline at end of file
index dd6c9b7d10f7e7e916264a30bc3f24af71180627..3e404cf565b96163ad27d1c3532169e14b243bd8 100644 (file)
@@ -1302,6 +1302,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                     // ITask task5 = ThreadLogger.getInstance().begin("DiagramContentRequest2");
                     ITask task42 = ThreadLogger.getInstance().begin("DiagramContentRequest2");
                     DiagramContents contents = g.syncRequest(query);
+                    System.err.println("contents: " + contents);
                     task42.finish();
                     // task5.finish();
                     monitor.worked(10);
@@ -1623,7 +1624,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
             this.removedRouteGraphConnections.clear();
         }
 
-        void processNodes(AsyncReadGraph graph) {
+        void processNodes(ReadGraph graph) throws DatabaseException {
 
             for (Map.Entry<Resource, Change> entry : changes.elements.entrySet()) {
 
@@ -1635,7 +1636,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                         IElement mappedElement = getMappedElement(element);
                         if (mappedElement == null) {
                             if (DebugPolicy.DEBUG_NODE_LOAD)
-                                graph.asyncRequest(new ReadRequest() {
+                                graph.syncRequest(new ReadRequest() {
                                     @Override
                                     public void run(ReadGraph graph) throws DatabaseException {
                                         System.out.println("    EXTERNALLY ADDED ELEMENT: "
@@ -1699,7 +1700,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                                     }
                                 };
 
-                                graph.asyncRequest(new ConnectionRequest(canvas, diagram, element, errorHandler, loadListener), new AsyncProcedure<IElement>() {
+                                graph.syncRequest(new ConnectionRequest(canvas, diagram, element, errorHandler, loadListener), new AsyncProcedure<IElement>() {
                                     @Override
                                     public void execute(AsyncReadGraph graph, final IElement e) {
                                         if (e == null)
@@ -1792,7 +1793,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                                 };
 
                                 //System.out.println("NODE REQUEST: " + element);
-                                graph.asyncRequest(new NodeRequest(canvas, diagram, element, loadListener), new AsyncProcedure<IElement>() {
+                                graph.syncRequest(new NodeRequest(canvas, diagram, element, loadListener), new AsyncProcedure<IElement>() {
                                     @Override
                                     public void execute(AsyncReadGraph graph, IElement e) {
                                         if (e == null)
@@ -1826,7 +1827,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                     case REMOVED: {
                         IElement e = getMappedElement(element);
                         if (DebugPolicy.DEBUG_NODE_LOAD)
-                            graph.asyncRequest(new ReadRequest() {
+                            graph.syncRequest(new ReadRequest() {
                                 @Override
                                 public void run(ReadGraph graph) throws DatabaseException {
                                     System.out.println("    EXTERNALLY REMOVED ELEMENT: "
@@ -1932,7 +1933,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
             }
         }
 
-        void processRouteGraphConnections(AsyncReadGraph graph) {
+        void processRouteGraphConnections(ReadGraph graph) throws DatabaseException {
             for (Map.Entry<Resource, Change> entry : changes.routeGraphConnections.entrySet()) {
                 final Resource connection = entry.getKey();
 
@@ -2010,7 +2011,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                             }
                         };
 
-                        graph.asyncRequest(new ConnectionRequest(canvas, diagram, connection, errorHandler, loadListener), new Procedure<IElement>() {
+                        graph.syncRequest(new ConnectionRequest(canvas, diagram, connection, errorHandler, loadListener), new Procedure<IElement>() {
                             @Override
                             public void execute(final IElement e) {
                                 if (e == null)
@@ -2052,7 +2053,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
             return assertMappedConnection(connection);
         }
 
-        void processBranchPoints(AsyncReadGraph graph) {
+        void processBranchPoints(ReadGraph graph) throws DatabaseException {
             for (Map.Entry<Resource, Change> entry : changes.branchPoints.entrySet()) {
 
                 final Resource element = entry.getKey();
@@ -2063,7 +2064,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                         IElement mappedElement = getMappedElement(element);
                         if (mappedElement == null) {
                             if (DebugPolicy.DEBUG_NODE_LOAD)
-                                graph.asyncRequest(new ReadRequest() {
+                                graph.syncRequest(new ReadRequest() {
                                     @Override
                                     public void run(ReadGraph graph) throws DatabaseException {
                                         System.out.println("    EXTERNALLY ADDED BRANCH POINT: "
@@ -2115,7 +2116,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                                 }
                             };
 
-                            graph.asyncRequest(new NodeRequest(canvas, diagram, element, loadListener), new AsyncProcedure<IElement>() {
+                            graph.syncRequest(new NodeRequest(canvas, diagram, element, loadListener), new AsyncProcedure<IElement>() {
                                 @Override
                                 public void execute(AsyncReadGraph graph, IElement e) {
                                     if (e != null) {
@@ -2141,7 +2142,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                     case REMOVED: {
                         IElement e = getMappedElement(element);
                         if (DebugPolicy.DEBUG_NODE_LOAD)
-                            graph.asyncRequest(new ReadRequest() {
+                            graph.syncRequest(new ReadRequest() {
                                 @Override
                                 public void run(ReadGraph graph) throws DatabaseException {
                                     System.out.println("    EXTERNALLY REMOVED BRANCH POINT: "
@@ -2158,7 +2159,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
             }
         }
 
-        void processConnectionSegments(AsyncReadGraph graph) {
+        void processConnectionSegments(ReadGraph graph) throws DatabaseException {
             ConnectionSegmentAdapter adapter = connectionSegmentAdapter;
 
             for (Map.Entry<EdgeResource, Change> entry : changes.connectionSegments.entrySet()) {
@@ -2170,7 +2171,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                         IElement mappedElement = getMappedElement(seg);
                         if (mappedElement == null) {
                             if (DebugPolicy.DEBUG_EDGE_LOAD)
-                                graph.asyncRequest(new ReadRequest() {
+                                graph.syncRequest(new ReadRequest() {
                                     @Override
                                     public void run(ReadGraph graph) throws DatabaseException {
                                         System.out.println("    EXTERNALLY ADDED CONNECTION SEGMENT: " + seg.toString()
@@ -2178,7 +2179,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                                     }
                                 });
 
-                            graph.asyncRequest(new EdgeRequest(canvas, errorHandler, canvasListenerSupport, diagram, adapter, seg), new AsyncProcedure<IElement>() {
+                            graph.syncRequest(new EdgeRequest(canvas, errorHandler, canvasListenerSupport, diagram, adapter, seg), new AsyncProcedure<IElement>() {
                                 @Override
                                 public void execute(AsyncReadGraph graph, IElement e) {
                                     if (DebugPolicy.DEBUG_EDGE_LOAD)
@@ -2206,7 +2207,7 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
                     case REMOVED: {
                         final IElement e = getMappedElement(seg);
                         if (DebugPolicy.DEBUG_EDGE_LOAD)
-                            graph.asyncRequest(new ReadRequest() {
+                            graph.syncRequest(new ReadRequest() {
                                 @Override
                                 public void run(ReadGraph graph) throws DatabaseException {
                                     System.out.println("    EXTERNALLY REMOVED CONNECTION SEGMENT: " + seg.toString() + " - "
@@ -2260,9 +2261,9 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
             Object task = Timing.BEGIN("processNodesConnections");
             //System.out.println("---- PROCESS NODES & CONNECTIONS BEGIN");
             if (!changes.elements.isEmpty()) {
-                graph.syncRequest(new AsyncReadRequest() {
+                graph.syncRequest(new ReadRequest() {
                     @Override
-                    public void run(AsyncReadGraph graph) {
+                    public void run(ReadGraph graph) throws DatabaseException {
                         processNodes(graph);
                     }
                     @Override
@@ -2277,9 +2278,9 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
 
             //System.out.println("---- PROCESS BRANCH POINTS BEGIN");
             if (!changes.branchPoints.isEmpty()) {
-                graph.syncRequest(new AsyncReadRequest() {
+                graph.syncRequest(new ReadRequest() {
                     @Override
-                    public void run(AsyncReadGraph graph) {
+                    public void run(ReadGraph graph) throws DatabaseException {
                         processBranchPoints(graph);
                     }
                     @Override
@@ -2295,9 +2296,9 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
 
             //System.out.println("---- PROCESS CONNECTION SEGMENTS BEGIN");
             if (!changes.connectionSegments.isEmpty()) {
-                graph.syncRequest(new AsyncReadRequest() {
+                graph.syncRequest(new ReadRequest() {
                     @Override
-                    public void run(AsyncReadGraph graph) {
+                    public void run(ReadGraph graph) throws DatabaseException {
                         processConnectionSegments(graph);
                     }
                     @Override
@@ -2312,9 +2313,9 @@ public class GraphToDiagramSynchronizer extends AbstractDisposable implements ID
 
             task = Timing.BEGIN("processRouteGraphConnections");
             if (!changes.routeGraphConnections.isEmpty()) {
-                graph.syncRequest(new AsyncReadRequest() {
+                graph.syncRequest(new ReadRequest() {
                     @Override
-                    public void run(AsyncReadGraph graph) {
+                    public void run(ReadGraph graph) throws DatabaseException {
                         processRouteGraphConnections(graph);
                     }
                     @Override
index 1ca5121eaa415ac319f00fa318b92b310e42e2e8..5e6eddc71fd143d214edd042d239c01d80211db2 100644 (file)
@@ -20,39 +20,39 @@ import org.simantics.diagram.synchronization.IModifiableSynchronizationContext;
  */
 public final class DebugPolicy {
 
-    public static boolean DEBUG = false;
+    public static boolean DEBUG = true;
 
     public static boolean DEBUG_GRAPH_WRITEBACK               = false;
     public static boolean DEBUG_GRAPH_WRITEBACK_MODIFICATION  = false;
 
     public static boolean DEBUG_TERMINAL_SEARCH               = false;
 
-    public static boolean DEBUG_LOAD                          = false;
-    public static boolean DEBUG_NODE_LOAD                     = false;
-    public static boolean DEBUG_CONNECTION_LOAD               = false;
-    public static boolean DEBUG_EDGE_LOAD                     = false;
-    public static boolean DEBUG_CONNECTION_VISUALS_LOAD       = false;
-    public static boolean DEBUG_TRANSFORM_LOAD                = false;
+    public static boolean DEBUG_LOAD                          = true;
+    public static boolean DEBUG_NODE_LOAD                     = true;
+    public static boolean DEBUG_CONNECTION_LOAD               = true;
+    public static boolean DEBUG_EDGE_LOAD                     = true;
+    public static boolean DEBUG_CONNECTION_VISUALS_LOAD       = true;
+    public static boolean DEBUG_TRANSFORM_LOAD                = true;
 
     public static double  DETERMINANT_LIMIT_HIGH              = 1e24;
     public static double  DETERMINANT_LIMIT_LOW               = 1e-24;
     public static double  TRANSLATION_LIMIT_HIGH              = 1e32;
 
-    public static boolean DEBUG_EDGE_LISTENER                 = false;
-
-    public static boolean DEBUG_GENERAL_ELEMENT_UPDATE        = false;
-    public static boolean DEBUG_GENERAL_ELEMENT_UPDATE_DETAIL = false;
-    public static boolean DEBUG_GRAPH_UPDATE                  = false;
-    public static boolean DEBUG_DIAGRAM_UPDATE                = false;
-    public static boolean DEBUG_DIAGRAM_UPDATE_DETAIL         = false;
-    public static boolean DEBUG_NODE_UPDATE                   = false;
-    public static boolean DEBUG_CONNECTION_UPDATE             = false;
-    public static boolean DEBUG_EDGE_UPDATE                   = false;
-
-    public static boolean DEBUG_LISTENER_BASE                 = false;
-    public static boolean DEBUG_DIAGRAM_LISTENER              = false;
-    public static boolean DEBUG_NODE_LISTENER                 = false;
-    public static boolean DEBUG_CONNECTION_LISTENER           = false;
+    public static boolean DEBUG_EDGE_LISTENER                 = true;
+
+    public static boolean DEBUG_GENERAL_ELEMENT_UPDATE        = true;
+    public static boolean DEBUG_GENERAL_ELEMENT_UPDATE_DETAIL = true;
+    public static boolean DEBUG_GRAPH_UPDATE                  = true;
+    public static boolean DEBUG_DIAGRAM_UPDATE                = true;
+    public static boolean DEBUG_DIAGRAM_UPDATE_DETAIL         = true;
+    public static boolean DEBUG_NODE_UPDATE                   = true;
+    public static boolean DEBUG_CONNECTION_UPDATE             = true;
+    public static boolean DEBUG_EDGE_UPDATE                   = true;
+
+    public static boolean DEBUG_LISTENER_BASE                 = true;
+    public static boolean DEBUG_DIAGRAM_LISTENER              = true;
+    public static boolean DEBUG_NODE_LISTENER                 = true;
+    public static boolean DEBUG_CONNECTION_LISTENER           = true;
 
     /**
      * Enables tracing of
index a86daf09a2f593667a0bfa8a698da3c606e6e376..875ff601fa3b244b464bfae6afaf817f0c6a47d2 100644 (file)
@@ -1,4 +1,4 @@
-Manifest-Version: 1.0
+vManifest-Version: 1.0
 Bundle-ManifestVersion: 2
 Bundle-Name: Document Server
 Bundle-SymbolicName: org.simantics.document.server;singleton:=true
@@ -24,8 +24,7 @@ Require-Bundle:
  org.simantics.document.server.io;visibility:=reexport,
  org.simantics.scl.db;bundle-version="0.1.3",
  org.slf4j.api,
- org.simantics.simulator.toolkit,
- org.simantics.simulator.toolkit.db;visibility:=reexport
+ org.simantics.threadlog
 Bundle-ActivationPolicy: lazy
 Bundle-Activator: org.simantics.document.server.Activator
 Export-Package: org.simantics.document.server,
@@ -33,7 +32,6 @@ Export-Package: org.simantics.document.server,
  org.simantics.document.server.client,
  org.simantics.document.server.handler,
  org.simantics.document.server.request,
- org.simantics.document.server.serverResponse,
- org.simantics.document.server.state
+ org.simantics.document.server.serverResponse
 Import-Package: org.simantics.layer0.utils.direct
 Bundle-ClassPath: .
index 9a53060bef2c0b246a21e465da1f0e53756d2f17..87b244c88ba28e1c43129cdf098a43e2f7781201 100644 (file)
@@ -6,17 +6,22 @@ import java.util.Comparator;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
 
 import org.simantics.db.ReadGraph;
 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.layer0.request.VariableRead;
 import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.procedure.Listener;
 import org.simantics.document.server.JSONObject;
+import org.simantics.threadlog.Task;
+import org.simantics.threadlog.ThreadLog;
 
 public class DocumentRequest extends VariableRead<List<JSONObject>> {
        
-       public static boolean PROFILE = false;
+       public static boolean PROFILE = true;
        // Thresholds in microseconds
        public static int PROFILE_THRESHOLD_NODEREQUEST = 2000;
        public static int PROFILE_THRESHOLD_VALUEREQUEST = 500;
@@ -25,48 +30,119 @@ public class DocumentRequest extends VariableRead<List<JSONObject>> {
         super(var);
        }
 
+    static class NodeRequestE extends NodeRequest {
+
+       static int count1 = 0;
+       static int count = 0;
+       
+               public NodeRequestE(Variable node) {
+                       super(node);
+                       count1++;
+                       System.err.println("create NodeRequest count = " + count1);
+                       if(count1 == 600)
+                               System.err.println("asd");
+               }
+               
+               @Override
+               public JSONObject perform(ReadGraph graph) throws DatabaseException {
+                       count++;
+                       System.err.println("perform NodeRequest count = " + count);
+                       
+                       return super.perform(graph);
+               }
+       
+    }
+    
        @Override
        public List<JSONObject> perform(ReadGraph graph) throws DatabaseException {
+       
+               Task task = ThreadLog.BEGIN("DocumentRequest " + variable.getURI(graph));
                
-               long s = System.nanoTime();
+               try {
                
-        Set<Variable> nodes = graph.syncRequest(new NodesRequest(variable), TransientCacheAsyncListener.<Set<Variable>>instance());
-        HashSet<JSONObject> rs = new HashSet<JSONObject>(); // result
-        if(nodes.isEmpty()) {
-            return Collections.emptyList();
-        }
-        
-        
-        /*TreeMap<String, Variable> nodeMap = new TreeMap<String, Variable>();
-        
-        for (Variable node : nodes) {
-               nodeMap.put(node.getURI(graph), node);
-        }
-        System.out.println("*************************************************************************");
-        for (Variable node : nodeMap.values()) {
-               System.out.println("               " + node.getURI(graph));
-        }*/
-        
-        for(Variable node : nodes) {
-            rs.add(graph.syncRequest(new NodeRequest(node), TransientCacheAsyncListener.<JSONObject>instance()));
-        }
+                       long s = System.nanoTime();
+                       
+               Set<Variable> nodes = graph.syncRequest(new NodesRequest(variable), TransientCacheAsyncListener.<Set<Variable>>instance());
+               HashSet<JSONObject> rs = new HashSet<JSONObject>(); // result
+               if(nodes.isEmpty()) {
+                   return Collections.emptyList();
+               }
+               
+               
+               /*TreeMap<String, Variable> nodeMap = new TreeMap<String, Variable>();
+               
+               for (Variable node : nodes) {
+                       nodeMap.put(node.getURI(graph), node);
+               }
+               System.out.println("*************************************************************************");
+               for (Variable node : nodeMap.values()) {
+                       System.out.println("               " + node.getURI(graph));
+               }*/
+
+               Semaphore done = new Semaphore(0);
+               
+               for(Variable node : nodes) {
+                       
+                       graph.asyncRequest(new NodeRequestE(node), new Listener<JSONObject>() {
 
-               ArrayList<JSONObject> result = new ArrayList<JSONObject>(rs);
-               Collections.sort(result, new Comparator<JSONObject>() {
+                                       @Override
+                                       public void execute(JSONObject result) {
+                                               synchronized(rs) {
+                                                       rs.add(result);
+                                               }
+                                               done.release();
+                                       }
 
-                       @Override
-                       public int compare(JSONObject o1, JSONObject o2) {
-                               return o1.id.compareTo(o2.id);
+                                       @Override
+                                       public void exception(Throwable t) {
+                                               t.printStackTrace();
+                                               done.release();
+                                       }
+
+                                       @Override
+                                       public boolean isDisposed() {
+                                               return true;
+                                       }
+                                       
+                               });
+                       
+//                 rs.add(graph.syncRequest(new NodeRequest(node), TransientCacheAsyncListener.<JSONObject>instance()));
+                       
+               }
+               
+               try {
+                       boolean success = done.tryAcquire(nodes.size(), 10, TimeUnit.MILLISECONDS);
+                       while(!success) {
+                               success = done.tryAcquire(nodes.size(), 10, TimeUnit.MILLISECONDS);
+                               System.err.println("still trying to acquire semaphore, avail = " + done.availablePermits() );
+                       }
+                               
+                       } catch (InterruptedException e) {
+                               e.printStackTrace();
                        }
+       
+                       ArrayList<JSONObject> result = new ArrayList<JSONObject>(rs);
+                       Collections.sort(result, new Comparator<JSONObject>() {
+       
+                               @Override
+                               public int compare(JSONObject o1, JSONObject o2) {
+                                       return o1.id.compareTo(o2.id);
+                               }
+                               
+                       });
+               
+               if(PROFILE) {
+                       long dura = System.nanoTime()-s;
+                       System.err.println("DocumentRequest " + System.identityHashCode(this) + " in " + 1e-6*dura + "ms. " + variable.getURI(graph));
+               }
+       
+                       return result;
+                       
+               } finally {
                        
-               });
-        
-        if(PROFILE) {
-               long dura = System.nanoTime()-s;
-               System.err.println("DocumentRequest " + System.identityHashCode(this) + " in " + 1e-6*dura + "ms. " + variable.getURI(graph));
-        }
+                       task.end();
 
-               return result;
+               }
 
        }
 }
\ No newline at end of file
index 50c8827efdf73d4cb7e238cac0a169de61462120..c9dfe893433d379b083fa40cbb6a1a559d62024c 100644 (file)
@@ -1,17 +1,13 @@
 package org.simantics.document.server.request;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
 import org.simantics.db.ReadGraph;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.layer0.request.VariableRead;
 import org.simantics.db.layer0.variable.Variable;
 import org.simantics.document.server.DocumentServerUtils.AttributesRequest;
 import org.simantics.document.server.JSONObject;
-import org.simantics.utils.datastructures.Pair;
+import org.simantics.threadlog.Task;
+import org.simantics.threadlog.ThreadLog;
 
 public class NodeRequest extends VariableRead<JSONObject> {
 
@@ -28,16 +24,27 @@ public class NodeRequest extends VariableRead<JSONObject> {
 
        long s = System.nanoTime();
 
-       JSONObject staticContent = graph.syncRequest(new AttributesRequest(variable));
+               Task task = ThreadLog.BEGIN("NodeRequest " + variable.getURI(graph));
+               
+               try {
 
-       if(DocumentRequest.PROFILE) {
-               long dura = System.nanoTime()-s;
-               if(dura > DocumentRequest.PROFILE_THRESHOLD_NODEREQUEST * 1e3) {
-                       System.err.println("NodeRequest " + System.identityHashCode(this) + " in " + 1e-6*dura + "ms. " + variable.getURI(graph));
-               }
-       }
+                       JSONObject staticContent = graph.syncRequest(new AttributesRequest(variable));
+
+                       if(DocumentRequest.PROFILE) {
+                               long dura = System.nanoTime()-s;
+                               if(dura > DocumentRequest.PROFILE_THRESHOLD_NODEREQUEST * 1e3) {
+                                       System.err.println("NodeRequest " + System.identityHashCode(this) + " in " + 1e-6*dura + "ms. " + variable.getURI(graph));
+                               }
+                       }
 
-       return staticContent;
+       
+               return staticContent;
+
+       } finally {
+               
+               task.end();
+               
+       }
 
     }
 
index f3f1177fc4d1f613950bc7b4f7d56e2ec010105f..c44febbe4a0d11020c61db1a90306f6eae4d20c9 100644 (file)
@@ -15,6 +15,8 @@ import org.simantics.structural.stubs.StructuralResource2;
 
 public class NodesRequest extends VariableRead<Set<Variable>> {
 
+       public static boolean PROFILE = false;
+
     public NodesRequest(Variable var) {
         super(var);
        }
@@ -35,7 +37,7 @@ public class NodesRequest extends VariableRead<Set<Variable>> {
                        nodes.addAll(childNodes);
                }
                
-        if(DocumentRequest.PROFILE) {
+        if(PROFILE) {
                long dura = System.nanoTime()-s;
                System.err.println("NodesRequest " + System.identityHashCode(this) + " in " + 1e-6*dura + "ms. " + variable.getURI(graph));
         }
index 0f57a01c03f2cfc87ff34c9f3a1339fa9dbe9d52..b3dc73cc9e640d0d183e3def293c0f4854c71c7f 100644 (file)
@@ -24,6 +24,8 @@ public class NodesRequest2 extends VariableRead<Set<Variable>> {
            
                DocumentationResource DOC = DocumentationResource.getInstance(graph);
 
+               System.err.println("NodesRequest " + variable.getURI(graph));
+               
                Resource type = variable.getPossibleType(graph);
                if(type == null) return Collections.emptySet();
                
index 9655e0f86d96e074b7d9a9fa9027343209736667..b2dc03b73f3fee14c847a686f9b7fe6c6229d886 100644 (file)
@@ -1,5 +1,6 @@
 package org.simantics.document.server.request;
 
+import java.util.Collections;
 import java.util.Map;
 
 import org.simantics.databoard.Bindings;
@@ -104,10 +105,16 @@ public class ServerSCLValueRequest extends AbstractExpressionCompilationRequest<
                                return Pair.make(type, root);
                        } else {
                                Resource doc = graph.syncRequest(new PossibleTypedParent(component, DocumentationResource.getInstance(graph).Document));
-                               Resource componentType = graph.getSingleType(doc);
-                Resource root = graph.syncRequest(new IndexRoot(doc));
-            //    System.err.println("getComponentTypeAndRoot4 " + graph.getPossibleURI(component) + " => " + graph.getPossibleURI(componentType) + " " + graph.getPossibleURI(root));
-                               return Pair.make(componentType, root);
+                               if(doc != null) {
+                                       Resource componentType = graph.getSingleType(doc);
+                       Resource root = graph.syncRequest(new IndexRoot(doc));
+                                       return Pair.make(componentType, root);
+                               } else {
+                                       System.err.println("component = " + component);
+                                       Resource root = graph.syncRequest(new IndexRoot(component));
+//                                     Resource componentType = graph.getSingleType(doc);
+                                       return Pair.make(null, root);
+                               }
                        }
                }
                throw new IllegalStateException();
@@ -161,10 +168,14 @@ public class ServerSCLValueRequest extends AbstractExpressionCompilationRequest<
                        public CompilationContext perform(ReadGraph graph)
                                        throws DatabaseException {
                                RuntimeEnvironment runtimeEnvironment = graph.syncRequest(getRuntimeEnvironmentRequest(parameter.first, parameter.second));
-                               Map<String, ComponentTypeProperty> propertyMap =
-                                               graph.syncRequest(new ReadComponentTypeInterfaceRequest(parameter.first, runtimeEnvironment.getEnvironment()),
-                                                               TransientCacheListener.<Map<String, ComponentTypeProperty>>instance());
-                               return new CompilationContext(runtimeEnvironment, propertyMap);
+                               if(parameter.first != null) {
+                                       Map<String, ComponentTypeProperty> propertyMap =
+                                                       graph.syncRequest(new ReadComponentTypeInterfaceRequest(parameter.first, runtimeEnvironment.getEnvironment()),
+                                                                       TransientCacheListener.<Map<String, ComponentTypeProperty>>instance());
+                                       return new CompilationContext(runtimeEnvironment, propertyMap);
+                               } else {
+                                       return new CompilationContext(runtimeEnvironment, Collections.emptyMap());
+                               }
                        }
                });
        }
index ba575c630ffb1aff08024fe8e482d2f5423c8116..1f2bd210257aacb2779e6e7d002a2a43dccb362e 100644 (file)
@@ -140,7 +140,7 @@ public class ElementPainter extends AbstractDiagramParticipant implements Compos
                 final AffineTransform transform, final Rectangle2D bounds, final Color color);
     }
 
-    private static final boolean DEBUG                  = false;
+    private static final boolean DEBUG                  = true;
 
     public static final int      ELEMENT_PAINT_PRIORITY = 10;
 
index ef01473085d4a70f5d77e4bd2e37b53b2cb8eb8d..4cee3449c5edbfea66949273a0c552c84c09c148 100644 (file)
@@ -61,7 +61,8 @@ Require-Bundle: org.simantics.project;bundle-version="1.0.0",
  org.simantics.image.ui;bundle-version="1.0.0",
  org.simantics.export.core;bundle-version="1.0.0",
  org.slf4j.api,
- org.simantics.graphfile.ontology
+ org.simantics.graphfile.ontology,
+ org.simantics.threadlog
 Export-Package: org.simantics.modeling.ui,
  org.simantics.modeling.ui.actions,
  org.simantics.modeling.ui.chart.property,
index 85f0dbbe7b432f35548a38488fa30491407036a9..926ec6ae3a79bd5cd3076aeceb13d3e948f1e4d1 100644 (file)
@@ -22,6 +22,8 @@ import org.simantics.db.exception.CancelTransactionException;
 import org.simantics.g2d.diagram.DiagramHints;
 import org.simantics.g2d.diagram.IDiagram;
 import org.simantics.modeling.ui.Activator;
+import org.simantics.threadlog.Task;
+import org.simantics.threadlog.ThreadLog;
 import org.simantics.utils.DataContainer;
 import org.simantics.utils.threads.ThreadUtils;
 
@@ -42,10 +44,12 @@ public class DiagramViewerLoadJob extends DatabaseJob {
 
         try {
             Object task = BEGIN("DV.loadDiagram");
+            System.err.println("foo1");
             final IDiagram diagram = viewer.loadDiagram(mon.newChild(100), viewer.diagramResource);
             if (diagram == null)
                 return Status.CANCEL_STATUS;
             END(task);
+            System.err.println("foo2");
 
             // Start an activation for the input resource.
             // This will activate mapping if necessary.
@@ -126,14 +130,14 @@ public class DiagramViewerLoadJob extends DatabaseJob {
 
     protected static Object BEGIN(String name) {
         if (PROFILE) {
-            //return ThreadLog.BEGIN(name);
+            return ThreadLog.BEGIN(name);
         }
         return null;
     }
 
     protected static void END(Object task) {
         if (PROFILE) {
-            //((Task) task).end();
+            ((Task) task).end();
         }
     }
 }
index 3c3802df6e8608b197a4b5040d3f0ca9c889ab06..7e8ca4827f1905b55d06484af80ab54409ee136d 100644 (file)
                </type>
        </target>
 
+       <target interface="org.simantics.db.ExternalValue">
+               <resource uri="http://www.simantics.org/Modeling-0.0/Functions/sclValue"
+                       class="org.simantics.modeling.SCLExternalValue">
+               </resource>
+       </target>
+       
 </adapters>
\ No newline at end of file
index 32db2bb90445ae4b904453b030e398ba9b75bc77..61ffac8374c5481bb80684c30163277a7065a3e3 100644 (file)
@@ -16,6 +16,7 @@ import org.simantics.db.layer0.request.PropertyInfo;
 import org.simantics.db.layer0.request.UnescapedPropertyMapOfResource;
 import org.simantics.db.layer0.variable.ValueAccessor;
 import org.simantics.db.layer0.variable.Variable;
+import org.simantics.diagram.Logger;
 import org.simantics.layer0.Layer0;
 import org.simantics.scl.runtime.SCLContext;
 import org.simantics.scl.runtime.function.Function1;
@@ -79,9 +80,13 @@ public class ImmutableComponentPropertyContentRequest extends BinaryRead<Resourc
 
                                        ExternalValue ev = graph.adapt(converter, ExternalValue.class);
                                        if(ev instanceof ConverterExternalValue) {
-                                               ConverterExternalValue cev = (ConverterExternalValue)ev; 
-                                               Function1 fn  = cev.getFunction(graph, resource, value, pi.predicate);
-                                               return new ImmutableComponentPropertyContent(pi, value, null, fn);
+                                               ConverterExternalValue cev = (ConverterExternalValue)ev;
+                                               try {
+                                                       Function1 fn  = cev.getFunction(graph, resource, value, pi.predicate);
+                                                       return new ImmutableComponentPropertyContent(pi, value, null, fn);
+                                               } catch (DatabaseException e) {
+                                                       Logger.defaultLogError(e);
+                                               }
                                        } else {
                                                System.err.println("Undefined converter " + graph.getURI(converter));
                                        }
index 6ed9273906e090dc805e52d7583f5d139cd99988..5deac4e9413fcfbee3f24d69625e326af851a8e0 100644 (file)
@@ -12,6 +12,7 @@ import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.layer0.variable.AbstractChildVariable;
 import org.simantics.db.layer0.variable.StandardGraphChildVariable;
 import org.simantics.db.layer0.variable.Variable;
+import org.simantics.structural.stubs.StructuralResource2;
 
 public class ImmutableComponentVariable extends AbstractChildVariable {
 
@@ -71,6 +72,11 @@ public class ImmutableComponentVariable extends AbstractChildVariable {
 
        @Override
        public Variable getPossibleChild(ReadGraph graph, String name) throws DatabaseException {
+               
+               if(content.procedural) {
+                       return new StandardGraphChildVariable(parent, null, content.resource).getPossibleChild(graph, name);
+               }
+               
                if(content.children == null) return null;
                ImmutableComponentVariableContent c = content.children.get(name);
                if(c == null) return null;
@@ -79,12 +85,18 @@ public class ImmutableComponentVariable extends AbstractChildVariable {
        
        @Override
        public Collection<Variable> getChildren(ReadGraph graph) throws DatabaseException {
+
+               if(content.procedural) {
+                       return new StandardGraphChildVariable(parent, null, content.resource).getChildren(graph);
+               }
+               
                if(content.children == null) return Collections.emptyList();
                ArrayList<Variable> result = new ArrayList<Variable>(content.children.size());
                for(ImmutableComponentVariableContent c : content.children.values()) {
                        result.add(new ImmutableComponentVariable(this, c));
                }
                return result;
+               
        }
        
        @Override
index 37c882c643ffdfde1959ad2df6f55e7c32735ee8..87a342f13b9fa0284e17e961e66dfb736446a629 100644 (file)
@@ -3,6 +3,7 @@ package org.simantics.modeling;
 import org.simantics.db.ReadGraph;
 import org.simantics.db.Resource;
 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
+import org.simantics.db.common.request.PossibleIndexRoot;
 import org.simantics.db.common.utils.NameUtils;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.layer0.variable.StandardGraphChildVariable;
@@ -15,7 +16,17 @@ public class ImmutableComponentVariableBuilder<Node> implements VariableBuilder<
 
        @Override
        public Variable buildChild(ReadGraph graph, Variable parent, VariableNode<Node> node, Resource child) throws DatabaseException {
-               if(graph.isImmutable(child)) {
+               boolean isImmutable = graph.isImmutable(child);
+               Resource possibleIndexRoot = graph.syncRequest(new PossibleIndexRoot(child));
+               if(possibleIndexRoot != null) {
+//                     String puri = graph.getURI(possibleIndexRoot);
+//                     if(puri.contains("ModelBroker")) 
+//                             isImmutable = true;
+//                     if(NameUtils.getSafeName(graph, child).equals("Project"))
+//                             isImmutable = false;
+               }
+               if(isImmutable) {
+//                     System.err.println("ImmutableComponentVariableContentRequest " + parent.getURI(graph) + " " + NameUtils.getSafeName(graph, child));
                        ImmutableComponentVariableContent content = graph.syncRequest(new ImmutableComponentVariableContentRequest(child), TransientCacheListener.instance());
                        return new ImmutableComponentVariable(parent, content);
                } else {
index 5124228a06dda746eeeeb73afd7e99e4faa9c0a0..95998f33b060116cf1bb3419a807ed7ad35f2112 100644 (file)
@@ -8,6 +8,7 @@ public class ImmutableComponentVariableContent {
 
        final public Resource resource;
        final public String name;
+       boolean procedural = false;
        public Map<String,ImmutableComponentVariableContent> children;
        public Map<String,ImmutableComponentPropertyContent> properties;
        
index ac08c945e11ce52a9d7618ba95f1ed6bc03429e4..cef62c242633e7708131a47a7c92dc0b0148149d 100644 (file)
@@ -12,6 +12,7 @@ import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.layer0.request.PropertyInfo;
 import org.simantics.db.layer0.request.UnescapedPropertyMapOfResource;
 import org.simantics.layer0.Layer0;
+import org.simantics.structural.stubs.StructuralResource2;
 import org.simantics.structural2.ConnectionImpl;
 import org.simantics.structural2.Functions.StructuralChildMapOfResource;
 import org.simantics.structural2.queries.ConnectionPointMapOfResource;
@@ -28,6 +29,11 @@ public class ImmutableComponentVariableContentRequest extends ResourceRead<Immut
                Layer0 L0 = Layer0.getInstance(graph);
                String name = graph.getRelatedValue(resource, L0.HasName, Bindings.STRING);
                ImmutableComponentVariableContent result = new ImmutableComponentVariableContent(resource, name);
+
+               StructuralResource2 STR = StructuralResource2.getInstance(graph);
+               Resource componentType = graph.getPossibleType(resource, STR.Component);
+               if(componentType != null)
+                       result.procedural = graph.isInstanceOf(componentType, STR.ProceduralComponentType); 
                
                Map<String,PropertyInfo> pis = graph.syncRequest(new UnescapedPropertyMapOfResource(resource));
                
diff --git a/bundles/org.simantics.modeling/src/org/simantics/modeling/SCLExternalValue.java b/bundles/org.simantics.modeling/src/org/simantics/modeling/SCLExternalValue.java
new file mode 100644 (file)
index 0000000..513d8d6
--- /dev/null
@@ -0,0 +1,28 @@
+package org.simantics.modeling;
+
+import org.simantics.db.ConverterExternalValue;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.scl.reflection.ReflectionUtils;
+import org.simantics.scl.reflection.ValueNotFoundException;
+import org.simantics.scl.runtime.function.Function1;
+import org.simantics.structural2.scl.CompileStructuralValueRequest;
+
+public class SCLExternalValue implements ConverterExternalValue {
+
+       @Override
+       public <T> T getValue(ReadGraph graph, Resource resource) throws DatabaseException {
+               try {
+                       return (T)ReflectionUtils.getValue(ModelingResources.URIs.Functions_sclValue).getValue();
+               } catch (ValueNotFoundException e) {
+                       throw new DatabaseException(e);
+               }
+       }
+
+       @Override
+       public Function1 getFunction(ReadGraph graph, Resource s, Resource o, Resource p) throws DatabaseException {
+               return CompileStructuralValueRequest.compile(graph, s, o, p);
+       }
+
+}
index f3f5b917067a887a992b948a52760a3813b13f6e..9fda66d070400d814429227363804eb8ebe014a3 100644 (file)
@@ -78,7 +78,9 @@ public enum GraphModuleSourceRepository implements ModuleSourceRepository {
                 SCLContext context = SCLContext.getCurrent();
                 Object oldGraph = context.put("graph", graph);
                 try {
-                    listener.notifyAboutUpdate();
+                       synchronized(GraphModuleSourceRepository.class) {
+                               listener.notifyAboutUpdate();
+                       }
                 } finally {
                     listener = null;
                     context.put("graph", oldGraph);
index 23c1ad508ef09d68b10d0ac22649c7d3004d17cb..48dcd3824b9096439509a9866a04d1fbd45f4060 100644 (file)
@@ -36,6 +36,7 @@ import org.simantics.scl.osgi.SCLOsgi;
 import org.simantics.scl.runtime.SCLContext;
 import org.simantics.scl.runtime.function.Function;
 import org.simantics.scl.runtime.function.Function1;
+import org.simantics.scl.runtime.reporting.SCLReportingHandler;
 import org.simantics.scl.runtime.tuple.Tuple;
 import org.simantics.scl.runtime.tuple.Tuple0;
 import org.simantics.utils.DataContainer;
@@ -122,15 +123,18 @@ public class SCLFunctions {
         if (graph != null) {
             return (T)f.apply(Tuple0.INSTANCE);
         } else {
+            final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
             return Simantics.getSession().syncRequest(new WriteResultRequest<T>() {
                 @Override
                 public T perform(WriteGraph graph) throws DatabaseException {
                     SCLContext.push(context);
+                    SCLReportingHandler oldPrinter = (SCLReportingHandler)context.put(SCLReportingHandler.REPORTING_HANDLER, printer);
                     ReadGraph oldGraph = (ReadGraph)context.put(GRAPH, graph);
                     try {
                         return (T)f.apply(Tuple0.INSTANCE);
                     } finally {
                         context.put(GRAPH, oldGraph);
+                        context.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
                         SCLContext.pop();
                     }
                 }
index 3b54c0f62c871ceff88fa8ef5cc3ac4dbc95b955..4e1503c2df46511aac8c5a3c28591eb10fb8dd6c 100644 (file)
@@ -49,6 +49,10 @@ public class CompileStructuralValueRequest extends AbstractCompileStructuralValu
         }
     }
     
+       public static Function1<Variable, Object> compile(ReadGraph graph, Resource s, Resource o, Resource p) throws DatabaseException {
+           return graph.syncRequest(new CompileStructuralValueRequest(s, o, p), TransientCacheListener.<Function1<Variable,Object>>instance());
+       }
+    
     @Override
     protected String getExpressionText(ReadGraph graph)
             throws DatabaseException {
index dfa46571bba26df766d0c2656b9133051b8a9ca5..3e4e0e1f137b58f213cd90680ae94ae0d8cbf313 100644 (file)
@@ -12,4 +12,5 @@
 source.. = src/
 output.. = bin/
 bin.includes = META-INF/,\
-               .
+               .,\
+               scl/
diff --git a/bundles/org.simantics.threadlog/scl/Simantics/ThreadLog.scl b/bundles/org.simantics.threadlog/scl/Simantics/ThreadLog.scl
new file mode 100644 (file)
index 0000000..fa2c9c5
--- /dev/null
@@ -0,0 +1,4 @@
+
+importJava "org.simantics.threadlog.ui.ThreadLogController" where
+    @JavaName "start"
+    showThreadLog :: <Proc> ()
index 309cab556ed96da05d192596bd56697df36e515d..d58b4abe76547386cbac3b271b063082f8ee28d3 100644 (file)
@@ -40,7 +40,7 @@ public class Activator extends Plugin {
                super.start(context);
                plugin = this;
                
-               ThreadLogController.start();
+               //ThreadLogController.start();
        }
 
        /*
index 81d71572a812c13944124bf453384c1d4d1a634c..79a60110f34e208481ddf7040cdb814dac3dcac7 100644 (file)
          version="0.0.0"
          unpack="false"/>
 
+   <plugin
+         id="org.simantics.threadlog"
+         download-size="0"
+         install-size="0"
+         version="0.0.0"
+         unpack="false"/>
+
 </feature>