1 /*******************************************************************************
2 * Copyright (c) 2007, 2018 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package fi.vtt.simantics.procore.internal;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.nio.charset.Charset;
18 import java.nio.file.FileVisitResult;
19 import java.nio.file.Files;
20 import java.nio.file.Path;
21 import java.nio.file.SimpleFileVisitor;
22 import java.nio.file.attribute.BasicFileAttributes;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.HashSet;
26 import java.util.TreeMap;
27 import java.util.concurrent.CopyOnWriteArrayList;
28 import java.util.concurrent.Semaphore;
29 import java.util.concurrent.atomic.AtomicInteger;
30 import java.util.function.Consumer;
32 import org.eclipse.core.runtime.Platform;
33 import org.simantics.databoard.Bindings;
34 import org.simantics.db.AsyncReadGraph;
35 import org.simantics.db.ChangeSet;
36 import org.simantics.db.DevelopmentKeys;
37 import org.simantics.db.Disposable;
38 import org.simantics.db.ExternalValueSupport;
39 import org.simantics.db.Metadata;
40 import org.simantics.db.MonitorContext;
41 import org.simantics.db.MonitorHandler;
42 import org.simantics.db.ReadGraph;
43 import org.simantics.db.Resource;
44 import org.simantics.db.ResourceSerializer;
45 import org.simantics.db.Session;
46 import org.simantics.db.SessionManager;
47 import org.simantics.db.SessionVariables;
48 import org.simantics.db.VirtualGraph;
49 import org.simantics.db.WriteGraph;
50 import org.simantics.db.authentication.UserAuthenticationAgent;
51 import org.simantics.db.authentication.UserAuthenticator;
52 import org.simantics.db.common.Indexing;
53 import org.simantics.db.common.TransactionPolicyRelease;
54 import org.simantics.db.common.procedure.adapter.AsyncMultiProcedureAdapter;
55 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
56 import org.simantics.db.common.procedure.adapter.SyncMultiProcedureAdapter;
57 import org.simantics.db.common.procedure.wrapper.NoneToAsyncListener;
58 import org.simantics.db.common.procedure.wrapper.NoneToAsyncMultiListener;
59 import org.simantics.db.common.procedure.wrapper.NoneToAsyncMultiProcedure;
60 import org.simantics.db.common.procedure.wrapper.NoneToAsyncProcedure;
61 import org.simantics.db.common.procedure.wrapper.NoneToSyncMultiListener;
62 import org.simantics.db.common.procedure.wrapper.NoneToSyncMultiProcedure;
63 import org.simantics.db.common.procedure.wrapper.SyncToAsyncListener;
64 import org.simantics.db.common.procedure.wrapper.SyncToAsyncMultiListener;
65 import org.simantics.db.common.procedure.wrapper.SyncToAsyncMultiProcedure;
66 import org.simantics.db.common.procedure.wrapper.SyncToAsyncProcedure;
67 import org.simantics.db.common.service.ServiceActivityMonitorImpl;
68 import org.simantics.db.common.service.ServiceActivityUpdaterForWriteTransactions;
69 import org.simantics.db.common.utils.Logger;
70 import org.simantics.db.event.ChangeEvent;
71 import org.simantics.db.event.ChangeListener;
72 import org.simantics.db.event.SessionEventListener;
73 import org.simantics.db.exception.CancelTransactionException;
74 import org.simantics.db.exception.ClusterSetExistException;
75 import org.simantics.db.exception.DatabaseException;
76 import org.simantics.db.exception.ImmutableException;
77 import org.simantics.db.exception.InvalidResourceReferenceException;
78 import org.simantics.db.exception.ResourceNotFoundException;
79 import org.simantics.db.exception.RuntimeDatabaseException;
80 import org.simantics.db.exception.ServiceException;
81 import org.simantics.db.exception.ServiceNotFoundException;
82 import org.simantics.db.impl.BlockingAsyncProcedure;
83 import org.simantics.db.impl.ClusterBase;
84 import org.simantics.db.impl.ClusterI;
85 import org.simantics.db.impl.ClusterTraitsBase;
86 import org.simantics.db.impl.ClusterTranslator;
87 import org.simantics.db.impl.ResourceImpl;
88 import org.simantics.db.impl.TransientGraph;
89 import org.simantics.db.impl.VirtualGraphImpl;
90 import org.simantics.db.impl.graph.DelayedWriteGraph;
91 import org.simantics.db.impl.graph.ReadGraphImpl;
92 import org.simantics.db.impl.graph.WriteGraphImpl;
93 import org.simantics.db.impl.graph.WriteSupport;
94 import org.simantics.db.impl.internal.RandomAccessValueSupport;
95 import org.simantics.db.impl.procedure.ResultCallWrappedQueryProcedure4;
96 import org.simantics.db.impl.procedure.ResultCallWrappedSyncQueryProcedure;
97 import org.simantics.db.impl.query.QueryCache;
98 import org.simantics.db.impl.query.QueryCacheBase;
99 import org.simantics.db.impl.query.QueryProcessor;
100 import org.simantics.db.impl.query.QueryProcessor.SessionRead;
101 import org.simantics.db.impl.query.QueryProcessor.SessionTask;
102 import org.simantics.db.impl.service.QueryDebug;
103 import org.simantics.db.impl.support.VirtualGraphServerSupport;
104 import org.simantics.db.impl.support.WriteRequestScheduleSupport;
105 import org.simantics.db.procedure.AsyncListener;
106 import org.simantics.db.procedure.AsyncMultiListener;
107 import org.simantics.db.procedure.AsyncMultiProcedure;
108 import org.simantics.db.procedure.AsyncProcedure;
109 import org.simantics.db.procedure.Listener;
110 import org.simantics.db.procedure.ListenerBase;
111 import org.simantics.db.procedure.MultiListener;
112 import org.simantics.db.procedure.MultiProcedure;
113 import org.simantics.db.procedure.Procedure;
114 import org.simantics.db.procedure.SyncListener;
115 import org.simantics.db.procedure.SyncMultiListener;
116 import org.simantics.db.procedure.SyncMultiProcedure;
117 import org.simantics.db.procedure.SyncProcedure;
118 import org.simantics.db.procore.cluster.ClusterImpl;
119 import org.simantics.db.procore.cluster.ClusterTraits;
120 import org.simantics.db.procore.protocol.Constants;
121 import org.simantics.db.procore.protocol.DebugPolicy;
122 import org.simantics.db.request.AsyncMultiRead;
123 import org.simantics.db.request.AsyncRead;
124 import org.simantics.db.request.DelayedWrite;
125 import org.simantics.db.request.DelayedWriteResult;
126 import org.simantics.db.request.ExternalRead;
127 import org.simantics.db.request.MultiRead;
128 import org.simantics.db.request.Read;
129 import org.simantics.db.request.ReadInterface;
130 import org.simantics.db.request.Write;
131 import org.simantics.db.request.WriteInterface;
132 import org.simantics.db.request.WriteOnly;
133 import org.simantics.db.request.WriteOnlyResult;
134 import org.simantics.db.request.WriteResult;
135 import org.simantics.db.request.WriteTraits;
136 import org.simantics.db.service.ByteReader;
137 import org.simantics.db.service.ClusterBuilder;
138 import org.simantics.db.service.ClusterBuilderFactory;
139 import org.simantics.db.service.ClusterControl;
140 import org.simantics.db.service.ClusterSetsSupport;
141 import org.simantics.db.service.ClusterUID;
142 import org.simantics.db.service.ClusteringSupport;
143 import org.simantics.db.service.CollectionSupport;
144 import org.simantics.db.service.DebugSupport;
145 import org.simantics.db.service.DirectQuerySupport;
146 import org.simantics.db.service.GraphChangeListenerSupport;
147 import org.simantics.db.service.InitSupport;
148 import org.simantics.db.service.LifecycleSupport;
149 import org.simantics.db.service.ManagementSupport;
150 import org.simantics.db.service.QueryControl;
151 import org.simantics.db.service.SerialisationSupport;
152 import org.simantics.db.service.ServerInformation;
153 import org.simantics.db.service.ServiceActivityMonitor;
154 import org.simantics.db.service.SessionEventSupport;
155 import org.simantics.db.service.SessionMonitorSupport;
156 import org.simantics.db.service.SessionUserSupport;
157 import org.simantics.db.service.StatementSupport;
158 import org.simantics.db.service.TransactionPolicySupport;
159 import org.simantics.db.service.TransactionSupport;
160 import org.simantics.db.service.TransferableGraphSupport;
161 import org.simantics.db.service.UndoRedoSupport;
162 import org.simantics.db.service.VirtualGraphSupport;
163 import org.simantics.db.service.XSupport;
164 import org.simantics.layer0.Layer0;
165 import org.simantics.utils.DataContainer;
166 import org.simantics.utils.Development;
167 import org.simantics.utils.threads.logger.ITask;
168 import org.simantics.utils.threads.logger.ThreadLogger;
170 import gnu.trove.procedure.TLongProcedure;
171 import gnu.trove.set.hash.TLongHashSet;
174 public abstract class SessionImplSocket implements Session, WriteRequestScheduleSupport {
176 protected static final boolean DEBUG = false;
178 private static final boolean DIAGNOSTICS = false;
180 private TransactionPolicySupport transactionPolicy;
182 final private ClusterControl clusterControl;
184 final protected BuiltinSupportImpl builtinSupport;
185 final protected VirtualGraphServerSupportImpl virtualGraphServerSupport;
186 final protected ClusterSetsSupport clusterSetsSupport;
187 final protected LifecycleSupportImpl lifecycleSupport;
189 protected QuerySupportImpl querySupport;
190 protected ResourceSupportImpl resourceSupport;
191 protected WriteSupport writeSupport;
192 public ClusterTranslator clusterTranslator;
194 boolean dirtyPrimitives = false;
196 public static final int SERVICE_MODE_CREATE = 2;
197 public static final int SERVICE_MODE_ALLOW = 1;
198 public int serviceMode = 0;
199 public boolean createdImmutableClusters = false;
200 public TLongHashSet createdClusters = new TLongHashSet();
205 * The service locator maintained by the workbench. These services are
206 * initialized during workbench during the <code>init</code> method.
208 final protected ServiceLocatorImpl serviceLocator = new ServiceLocatorImpl();
210 final public ResourceSerializerImpl resourceSerializer = new ResourceSerializerImpl();
212 final CopyOnWriteArrayList<ChangeListener> changeListeners2 = new CopyOnWriteArrayList<ChangeListener>();
214 final CopyOnWriteArrayList<ChangeListener> metadataListeners = new CopyOnWriteArrayList<ChangeListener>();
216 final CopyOnWriteArrayList<SessionEventListener> eventListeners = new CopyOnWriteArrayList<SessionEventListener>();
218 final HashSet<Thread> sessionThreads = new HashSet<Thread>();
220 final BijectionMap<MonitorContext, MonitorHandler> monitorContexts = new BijectionMap<MonitorContext, MonitorHandler>();
222 final protected State state = new State();
224 protected GraphSession graphSession = null;
226 protected SessionManager sessionManagerImpl = null;
228 protected UserAuthenticationAgent authAgent = null;
230 protected UserAuthenticator authenticator = null;
232 protected Resource user = null;
234 protected ClusterStream clusterStream = null;
236 protected SessionRequestManager requestManager = null;
238 public ClusterTable clusterTable = null;
240 public QueryProcessor queryProvider2 = null;
242 ClientChangesImpl clientChanges = null;
244 MonitorHandler[] monitorHandlers = new MonitorHandler[0];
246 // protected long newClusterId = Constants.NullClusterId;
248 protected int flushCounter = 0;
250 protected boolean writeOnly = false;
252 WriteState<?> writeState = null;
253 WriteStateBase<?> delayedWriteState = null;
254 protected Resource defaultClusterSet = null; // If not null then used for newResource().
256 public SessionImplSocket(SessionManager sessionManagerImpl, UserAuthenticationAgent authAgent) {
258 // if (authAgent == null)
259 // throw new IllegalArgumentException("null authentication agent");
261 File t = StaticSessionProperties.virtualGraphStoragePath;
264 this.clusterTable = new ClusterTable(this, t);
265 this.builtinSupport = new BuiltinSupportImpl(this);
266 this.sessionManagerImpl = sessionManagerImpl;
268 // this.authAgent = authAgent;
270 serviceLocator.registerService(Session.class, this);
271 serviceLocator.registerService(InitSupport.class, new InitSupportImpl(this));
272 serviceLocator.registerService(ManagementSupport.class, new ManagementSupportImpl(this));
273 serviceLocator.registerService(QueryControl.class, new QueryControlImpl(this));
274 serviceLocator.registerService(SessionUserSupport.class, new SessionUserSupportImpl(this));
275 serviceLocator.registerService(GraphChangeListenerSupport.class, new GraphChangeListenerSupportImpl(this));
276 serviceLocator.registerService(SessionEventSupport.class, new SessionEventSupportImpl(this));
277 serviceLocator.registerService(SerialisationSupport.class, new SerialisationSupportImpl(this));
278 serviceLocator.registerService(UndoRedoSupport.class, new UndoRedoSupportImpl(this));
279 serviceLocator.registerService(ClusteringSupport.class, new ClusteringSupportImpl(this));
280 serviceLocator.registerService(TransactionSupport.class, new TransactionSupportImpl(this));
281 serviceLocator.registerService(SessionMonitorSupport.class, new SessionMonitorSupportImpl(this));
282 serviceLocator.registerService(TransferableGraphSupport.class, new TransferableGraphSupportImpl(this));
283 serviceLocator.registerService(QueryDebug.class, new QueryDebugImpl(this));
284 serviceLocator.registerService(CollectionSupport.class, new CollectionSupportImpl(this));
285 serviceLocator.registerService(StatementSupport.class, new StatementSupportImpl(this));
286 serviceLocator.registerService(DirectQuerySupport.class, new DirectQuerySupportImpl(this));
287 serviceLocator.registerService(XSupport.class, new XSupportImpl(this));
288 serviceLocator.registerService(DebugSupport.class, new DebugSupportImpl());
289 serviceLocator.registerService(ExternalValueSupport.class, new ExternalValueSupportImpl(this));
290 serviceLocator.registerService(RandomAccessValueSupport.class, new RandomAccessValueSupportImpl());
291 serviceLocator.registerService(ServiceActivityMonitor.class, new ServiceActivityMonitorImpl());
292 ServiceActivityUpdaterForWriteTransactions.register(this);
294 this.virtualGraphServerSupport = new VirtualGraphServerSupportImpl(this, t);
295 serviceLocator.registerService(VirtualGraphSupport.class, virtualGraphServerSupport);
296 serviceLocator.registerService(VirtualGraphServerSupport.class, virtualGraphServerSupport);
297 this.lifecycleSupport = new LifecycleSupportImpl(this);
298 serviceLocator.registerService(LifecycleSupport.class, lifecycleSupport);
299 this.transactionPolicy = new TransactionPolicyRelease();
300 serviceLocator.registerService(TransactionPolicySupport.class, transactionPolicy);
301 this.clusterControl = new ClusterControlImpl(this);
302 serviceLocator.registerService(ClusterControl.class, clusterControl);
303 this.clusterSetsSupport = new ClusterSetsSupportImpl2(); // Using same path as virtual graphs.
304 this.clusterSetsSupport.setReadDirectory(t.toPath());
305 this.clusterSetsSupport.updateWriteDirectory(t.toPath());
306 serviceLocator.registerService(ClusterSetsSupport.class, clusterSetsSupport);
316 public Resource getRootLibrary() {
317 return queryProvider2.getRootLibraryResource();
320 void refresh(int thread, ClusterUID[] clusterUID, long csid) throws DatabaseException {
321 if (!graphSession.dbSession.refreshEnabled())
324 getClusterTable().refresh(csid, this, clusterUID);
325 } catch (Throwable t) {
326 Logger.defaultLogError("Refesh failed.", t);
330 static final class TaskHelper {
331 private final String name;
332 private Object result;
333 final Semaphore sema = new Semaphore(0);
334 private Throwable throwable = null;
335 final Consumer<DatabaseException> callback = e -> {
336 synchronized (TaskHelper.this) {
340 final Procedure<Object> proc = new Procedure<Object>() {
342 public void execute(Object result) {
343 callback.accept(null);
346 public void exception(Throwable t) {
347 if (t instanceof DatabaseException)
348 callback.accept((DatabaseException)t);
350 callback.accept(new DatabaseException("" + name + "operation failed.", t));
353 final WriteTraits writeTraits = new WriteTraits() {};
354 TaskHelper(String name) {
357 @SuppressWarnings("unchecked")
361 void setResult(Object result) {
362 this.result = result;
364 // Throwable throwableGet() {
367 synchronized void throwableSet(Throwable t) {
370 // void throwableSet(String t) {
371 // throwable = new InternalException("" + name + " operation failed. " + t);
373 synchronized void throwableCheck()
374 throws DatabaseException {
375 if (null != throwable)
376 if (throwable instanceof DatabaseException)
377 throw (DatabaseException)throwable;
379 throw new DatabaseException("Undo operation failed.", throwable);
381 void throw_(String message)
382 throws DatabaseException {
383 throw new DatabaseException("" + name + " operation failed. " + message);
389 private ListenerBase getListenerBase(Object procedure) {
390 if (procedure instanceof ListenerBase)
391 return (ListenerBase) procedure;
396 public <T> void scheduleRequest(final Write request, final Consumer<DatabaseException> callback, final Semaphore notify) {
397 scheduleRequest(request, callback, notify, null);
401 * @see fi.vtt.simantics.procore.internal.WriteRequestScheduler#scheduleRequest(org.simantics.db.request.Write, org.simantics.utils.datastructures.Callback, java.util.concurrent.Semaphore, java.lang.Boolean)
404 public <T> void scheduleRequest(final Write request, final Consumer<DatabaseException> callback, final Semaphore notify, Boolean combine) {
406 assert (request != null);
408 if(Development.DEVELOPMENT) {
410 if(Development.<Boolean>getProperty(DevelopmentKeys.SESSION_LOG_WRITES, Bindings.BOOLEAN))
411 System.err.println("schedule write '" + request + "'");
412 } catch (Throwable t) {
413 Logger.defaultLogError(t);
417 requestManager.scheduleWrite(new SessionTask(null) {
420 public void run0(int thread) {
422 if(Development.DEVELOPMENT) {
424 if(Development.<Boolean>getProperty(DevelopmentKeys.SESSION_LOG_WRITES, Bindings.BOOLEAN))
425 System.err.println("perform write '" + request + "'");
426 } catch (Throwable t) {
427 Logger.defaultLogError(t);
431 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
433 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
438 Disposable.safeDispose(clientChanges);
439 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
441 VirtualGraph vg = getProvider(request.getProvider());
443 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
444 writeState = new WriteState<Object>(writer, request, notify, new Procedure<Object>() {
447 public void execute(Object result) {
448 if(callback != null) callback.accept(null);
452 public void exception(Throwable t) {
453 if(callback != null) callback.accept((DatabaseException)t);
458 assert (null != writer);
459 // writer.state.barrier.inc();
462 request.perform(writer);
463 assert (null != writer);
464 } catch (Throwable t) {
465 if (!(t instanceof CancelTransactionException))
466 Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", t);
467 writeState.except(t);
469 // writer.state.barrier.dec();
470 // writer.waitAsync(request);
474 assert(!queryProvider2.cache.dirty);
476 } catch (Throwable e) {
478 // Log it first, just to be safe that the error is always logged.
479 if (!(e instanceof CancelTransactionException))
480 Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", e);
482 // writeState.getGraph().state.barrier.dec();
483 // writeState.getGraph().waitAsync(request);
485 writeState.except(e);
488 // // Callback is client code, we have to be prepared for it to throw unexpected exceptions.
489 // // All we can do here is to log those, can't really pass them anywhere.
490 // if (callback != null) {
491 // if(e instanceof DatabaseException) callback.run((DatabaseException)e);
492 // else callback.run(new DatabaseException(e));
494 // } catch (Throwable e2) {
495 // Logger.defaultLogError("Write request callback caused an unexpected error, see exception.", e2);
497 // boolean empty = clusterStream.reallyFlush();
498 // int callerThread = -1;
499 // ClientChangesImpl cs = new ClientChangesImpl(SessionImplSocket.this);
500 // SynchronizeContext context = new SynchronizeContext(callerThread, SessionImplSocket.this, cs, 1);
502 // // Send all local changes to server so it can calculate correct reverse change set.
503 // // This will call clusterStream.accept().
504 // state.cancelCommit(context, clusterStream);
506 // if (!context.isOk()) // this is a blocking operation
507 // throw new InternalException("Cancel failed. This should never happen.");
508 // getQueryProvider2().performDirtyUpdates(writeState.getGraph());
510 // state.cancelCommit2(context, clusterStream);
511 // } catch (DatabaseException e3) {
512 // Logger.defaultLogError("Write request cancel caused an unexpected error.", e3);
514 // clusterStream.setOff(false);
515 // clientChanges = new ClientChangesImpl(SessionImplSocket.this);
520 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
526 if(Development.DEVELOPMENT) {
528 if(Development.<Boolean>getProperty(DevelopmentKeys.SESSION_LOG_WRITES, Bindings.BOOLEAN))
529 System.err.println("finish write '" + request + "'");
530 } catch (Throwable t) {
531 Logger.defaultLogError(t);
541 public <T> void scheduleRequest(final WriteResult<T> request, final Procedure<T> procedure, final Semaphore notify) {
542 scheduleRequest(request, procedure, notify, null);
546 * @see fi.vtt.simantics.procore.internal.WriteRequestScheduler#scheduleRequest(org.simantics.db.request.WriteResult, org.simantics.db.procedure.Procedure, java.util.concurrent.Semaphore, java.lang.Boolean)
549 public <T> void scheduleRequest(final WriteResult<T> request, final Procedure<T> procedure, final Semaphore notify, Boolean combine) {
551 assert (request != null);
553 requestManager.scheduleWrite(new SessionTask(null) {
556 public void run0(int thread) {
558 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
560 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
563 Disposable.safeDispose(clientChanges);
564 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
566 VirtualGraph vg = getProvider(request.getProvider());
567 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
570 WriteState<T> writeStateT = new WriteState<T>(writer, request, notify, procedure);
571 writeState = writeStateT;
573 assert (null != writer);
574 // writer.state.barrier.inc();
575 writeStateT.setResult(request.perform(writer));
576 assert (null != writer);
578 // writer.state.barrier.dec();
579 // writer.waitAsync(null);
581 } catch (Throwable e) {
583 // writer.state.barrier.dec();
584 // writer.waitAsync(null);
586 writeState.except(e);
588 // state.stopWriteTransaction(clusterStream);
590 // } catch (Throwable e) {
591 // // Log it first, just to be safe that the error is always logged.
592 // Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", e);
595 // // Callback is client code, we have to be prepared for it to throw unexpected exceptions.
596 // // All we can do here is to log those, can't really pass them anywhere.
597 // if (procedure != null) {
598 // if(e instanceof DatabaseException) procedure.exception((DatabaseException)e);
599 // else procedure.exception(new DatabaseException(e));
601 // } catch (Throwable e2) {
602 // Logger.defaultLogError("Write request callback caused an unexpected error, see exception.", e2);
605 // clientChanges = new ClientChangesImpl(SessionImplSocket.this);
607 // state.stopWriteTransaction(clusterStream);
610 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
613 // if(notify != null) notify.release();
623 public <T> void scheduleRequest(final DelayedWrite request, final Consumer<DatabaseException> callback, final Semaphore notify) {
624 scheduleRequest(request, callback, notify, null);
628 * @see fi.vtt.simantics.procore.internal.WriteRequestScheduler#scheduleRequest(org.simantics.db.request.DelayedWrite, org.simantics.utils.datastructures.Callback, java.util.concurrent.Semaphore, java.lang.Boolean)
631 public <T> void scheduleRequest(final DelayedWrite request, final Consumer<DatabaseException> callback, final Semaphore notify, Boolean combine) {
633 final ITask total = ThreadLogger.getInstance().begin("ScheduleDelayedWrite");
635 assert (request != null);
637 requestManager.scheduleWrite(new SessionTask(null) {
640 public void run0(int thread) {
641 fireSessionVariableChange(SessionVariables.QUEUED_READS);
643 Procedure<Object> stateProcedure = new Procedure<Object>() {
645 public void execute(Object result) {
646 if (callback != null)
647 callback.accept(null);
650 public void exception(Throwable t) {
651 if (callback != null) {
652 if (t instanceof DatabaseException) callback.accept((DatabaseException) t);
653 else callback.accept(new DatabaseException(t));
655 Logger.defaultLogError("Unhandled exception", t);
659 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
660 delayedWriteState = new WriteStateBase<Object>(request, notify, stateProcedure);
661 DelayedWriteGraph dwg = null;
662 // newGraph.state.barrier.inc();
665 dwg = new DelayedWriteGraph(newGraph);
666 request.perform(dwg);
667 } catch (Throwable e) {
668 delayedWriteState.except(e);
673 // newGraph.state.barrier.dec();
674 // newGraph.waitAsync(request);
675 fireSessionVariableChange(SessionVariables.QUEUED_READS);
678 delayedWriteState = null;
680 ITask task2 = ThreadLogger.getInstance().begin("DelayedWriteCommit");
681 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
684 Disposable.safeDispose(clientChanges);
685 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
689 VirtualGraph vg = getProvider(request.getProvider());
690 WriteSupport writeSupport = vg != null ? new VirtualWriteOnlySupport() : new WriteOnlySupport();
692 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
694 writeState = new WriteState<Object>(writer, request, notify, stateProcedure);
696 assert (null != writer);
697 // writer.state.barrier.inc();
701 dwg.commit(writer, request);
703 if(defaultClusterSet != null) {
704 XSupport xs = getService(XSupport.class);
705 defaultClusterSet = xs.convertDelayedResourceToResource(defaultClusterSet);
706 ClusteringSupport cs = getService(ClusteringSupport.class);
707 clusterSetsSupport.put(defaultClusterSet.getResourceId(), cs.getCluster(defaultClusterSet));
710 // This makes clusters available from server
711 clusterStream.reallyFlush();
713 releaseWriteOnly(writer);
714 handleUpdatesAndMetadata(writer);
716 } catch (ServiceException e) {
717 // writer.state.barrier.dec();
718 // writer.waitAsync(null);
720 // These shall be requested from server
721 clusterTable.removeWriteOnlyClusters();
722 // This makes clusters available from server
723 clusterStream.reallyFlush();
725 releaseWriteOnly(writer);
726 writeState.except(e);
728 // Debugging & Profiling
729 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
739 public <T> void scheduleRequest(final DelayedWriteResult<T> request, final Procedure<T> procedure, final Semaphore notify) {
740 scheduleRequest(request, procedure, notify, null);
744 * @see fi.vtt.simantics.procore.internal.WriteRequestScheduler#scheduleRequest(org.simantics.db.request.DelayedWriteResult, org.simantics.db.procedure.Procedure, java.util.concurrent.Semaphore, java.lang.Boolean)
747 public <T> void scheduleRequest(final DelayedWriteResult<T> request, final Procedure<T> procedure, final Semaphore notify, Boolean combine) {
748 throw new Error("Not implemented");
751 protected ClusterImpl getNewResourceCluster() throws DatabaseException {
752 ClusterImpl cluster = clusterTable.getNewResourceCluster(clusterTranslator, graphSession, writeOnly);
753 if((serviceMode & SERVICE_MODE_CREATE) > 0) {
754 createdClusters.add(cluster.clusterId);
759 class WriteOnlySupport implements WriteSupport {
761 ClusterStream stream;
762 ClusterImpl currentCluster;
764 public WriteOnlySupport() {
765 this.stream = clusterStream;
769 public void claim(VirtualGraph provider, Resource subject, Resource predicate, Resource object) throws ServiceException {
770 claim(provider, ((ResourceImpl)subject).id, ((ResourceImpl)predicate).id, ((ResourceImpl)object).id );
774 public void claim(VirtualGraph provider, int s, int p, int o) throws ServiceException {
776 ClusterImpl cluster = clusterTable.getClusterByResourceKey(s);
778 if (cluster.getImmutable() && (serviceMode & SessionImplSocket.SERVICE_MODE_ALLOW) == 0)
779 if(s != queryProvider2.getRootLibrary())
780 throw new ImmutableException("Trying to modify immutable resource key=" + s);
783 maintainCluster(cluster, cluster.addRelation(s, p, o, clusterTranslator));
784 } catch (DatabaseException e) {
785 Logger.defaultLogError(e);
789 clientChanges.invalidate(s);
791 if (cluster.isWriteOnly())
793 queryProvider2.updateStatements(s, p);
798 public void claimValue(VirtualGraph provider, Resource resource, byte[] value) throws DatabaseException {
799 claimValue(provider, ((ResourceImpl)resource).id, value, value.length);
803 public void claimValue(VirtualGraph provider, int rid, byte[] value, int length) {
805 ClusterImpl cluster = clusterTable.getClusterByResourceKey(rid);
807 maintainCluster(cluster, cluster.setValue(rid, value, length, clusterTranslator));
808 } catch (DatabaseException e) {
809 Logger.defaultLogError(e);
812 clientChanges.invalidate(rid);
814 if (cluster.isWriteOnly())
816 queryProvider2.updateValue(rid);
821 public void claimValue(VirtualGraph provider, Resource resource, ByteReader reader, int amount) throws DatabaseException {
824 claimValue(provider,resource, reader.readBytes(null, amount));
828 byte[] bytes = new byte[65536];
830 int rid = ((ResourceImpl)resource).id;
831 ClusterImpl cluster = clusterTable.getClusterByResourceKey(rid);
835 int block = Math.min(left, 65536);
836 reader.readBytes(bytes, block);
837 maintainCluster(cluster, cluster.modiValueEx(rid, amount-left, block, bytes, 0, clusterTranslator));
840 } catch (DatabaseException e) {
841 Logger.defaultLogError(e);
844 clientChanges.invalidate(rid);
846 if (cluster.isWriteOnly())
848 queryProvider2.updateValue(rid);
852 private void maintainCluster(ClusterImpl before, ClusterI after_) {
853 if(after_ != null && after_ != before) {
854 ClusterImpl after = (ClusterImpl)after_;
855 if(currentCluster == before) {
856 currentCluster = after;
858 clusterTable.replaceCluster(after);
862 public int createResourceKey(int foreignCounter) throws DatabaseException {
863 if(currentCluster == null) {
864 currentCluster = getNewResourceCluster();
866 if(currentCluster.getNumberOfResources(clusterTranslator) == ClusterTable.CLUSTER_FILL_SIZE) {
867 ClusterWriteOnly newCluster = (ClusterWriteOnly)getNewResourceCluster();
868 newCluster.foreignLookup = new byte[foreignCounter];
869 currentCluster = newCluster;
871 System.err.println("foreignLookup " + currentCluster + " " + foreignCounter);
873 return currentCluster.createResource(clusterTranslator);
877 public Resource createResource(VirtualGraph provider) throws DatabaseException {
878 if(currentCluster == null) {
879 if (null != defaultClusterSet) {
880 ResourceImpl result = getNewResource(defaultClusterSet);
881 currentCluster = clusterTable.getClusterByResourceKey(result.id);
884 currentCluster = getNewResourceCluster();
887 if(currentCluster.getNumberOfResources(clusterTranslator) >= ClusterTable.CLUSTER_FILL_SIZE) {
888 if (null != defaultClusterSet) {
889 ResourceImpl result = getNewResource(defaultClusterSet);
890 currentCluster = clusterTable.getClusterByResourceKey(result.id);
893 currentCluster = getNewResourceCluster();
896 return new ResourceImpl(resourceSupport, currentCluster.createResource(clusterTranslator));
900 public Resource createResource(VirtualGraph provider, long clusterId)
901 throws DatabaseException {
902 return getNewResource(clusterId);
906 public Resource createResource(VirtualGraph provider, Resource clusterSet)
907 throws DatabaseException {
908 return getNewResource(clusterSet);
912 public void createClusterSet(VirtualGraph provider, Resource clusterSet)
913 throws DatabaseException {
914 getNewClusterSet(clusterSet);
918 public boolean hasClusterSet(VirtualGraph dummy, Resource clusterSet)
919 throws ServiceException {
920 return containsClusterSet(clusterSet);
923 public void selectCluster(long cluster) {
924 currentCluster = clusterTable.getClusterByClusterId(cluster);
925 long setResourceId = clusterSetsSupport.getSet(cluster);
926 clusterSetsSupport.put(setResourceId, cluster);
930 public Resource setDefaultClusterSet(Resource clusterSet)
931 throws ServiceException {
932 Resource result = setDefaultClusterSet4NewResource(clusterSet);
933 if(clusterSet != null) {
934 long id = clusterSetsSupport.get(clusterSet.getResourceId());
935 currentCluster = clusterTable.getClusterByClusterId(id);
938 currentCluster = null;
944 public void denyValue(VirtualGraph provider, Resource resource) throws ServiceException {
946 provider = getProvider(provider);
947 if (null == provider) {
948 int key = ((ResourceImpl)resource).id;
952 ClusterI cluster = clusterTable.getClusterProxyByResourceKey(key);
953 // if (cluster.getImmutable() && (serviceMode & SessionImplSocket.SERVICE_MODE_ALLOW) == 0)
954 // if(key != queryProvider2.getRootLibrary())
955 // throw new ImmutableException("Trying to modify immutable resource key=" + key);
958 // cluster.removeValue(key, clusterTranslator);
959 // } catch (DatabaseException e) {
960 // Logger.defaultLogError(e);
964 clusterTable.writeOnlyInvalidate(cluster);
967 int sResourceKey = ClusterTraits.getResourceIndexFromResourceKey(key);
968 clusterTranslator.addStatementIndex(cluster, sResourceKey, cluster.getClusterUID(), ClusterChange.DELETE_OPERATION);
969 clusterTranslator.removeValue(cluster);
970 } catch (DatabaseException e) {
971 Logger.defaultLogError(e);
974 queryProvider2.invalidateResource(key);
975 clientChanges.invalidate(key);
978 ((VirtualGraphImpl)provider).denyValue(((ResourceImpl) resource).id);
979 queryProvider2.updateValue(querySupport.getId(resource));
980 clientChanges.claimValue(resource);
987 public void flush(boolean intermediate) {
988 throw new UnsupportedOperationException();
992 public void flushCluster() {
993 clusterTable.flushCluster(graphSession);
994 if(defaultClusterSet != null) {
995 clusterSetsSupport.put(defaultClusterSet.getResourceId(), Constants.NewClusterId);
997 currentCluster = null;
1001 public void flushCluster(Resource r) {
1002 throw new UnsupportedOperationException("flushCluster resource " + r);
1010 public boolean removeStatement(VirtualGraph provider, Resource subject, Resource predicate,
1013 int s = ((ResourceImpl)subject).id;
1014 int p = ((ResourceImpl)predicate).id;
1015 int o = ((ResourceImpl)object).id;
1017 provider = getProvider(provider);
1018 if (null == provider) {
1020 ClusterI cluster = clusterTable.getClusterProxyByResourceKey(s);
1021 clusterTable.writeOnlyInvalidate(cluster);
1025 int sResourceKey = ClusterTraits.getResourceIndexFromResourceKey(s);
1027 ClusterI pc = clusterTable.getClusterProxyByResourceKey(p);
1028 ClusterI oc = clusterTable.getClusterProxyByResourceKey(o);
1030 clusterTranslator.addStatementIndex(cluster, sResourceKey, cluster.getClusterUID(), ClusterChange.REMOVE_OPERATION);
1031 clusterTranslator.addStatementIndex(cluster, p, pc.getClusterUID(), ClusterStream.NULL_OPERATION);
1032 clusterTranslator.addStatementIndex(cluster, o, oc.getClusterUID(), ClusterStream.NULL_OPERATION);
1033 clusterTranslator.removeStatement(cluster);
1035 queryProvider2.invalidateResource(s);
1036 clientChanges.invalidate(s);
1038 } catch (DatabaseException e) {
1040 Logger.defaultLogError(e);
1048 ((VirtualGraphImpl)provider).deny(s, p, o);
1049 queryProvider2.invalidateResource(s);
1050 clientChanges.invalidate(s);
1059 public void setValue(VirtualGraph provider, Resource resource, byte[] value) {
1060 throw new UnsupportedOperationException();
1064 public boolean writeOnly() {
1069 public void performWriteRequest(WriteGraph graph, Write request) throws DatabaseException {
1070 writeSupport.performWriteRequest(graph, request);
1074 public <T> T performWriteRequest(WriteGraph graph, WriteResult<T> request) throws DatabaseException {
1075 throw new UnsupportedOperationException();
1079 public void performWriteRequest(WriteGraph graph, WriteOnly request) throws DatabaseException {
1080 throw new UnsupportedOperationException();
1084 public <T> void addMetadata(Metadata data) throws ServiceException {
1085 writeSupport.addMetadata(data);
1089 public <T extends Metadata> T getMetadata(Class<T> clazz) throws ServiceException {
1090 return writeSupport.getMetadata(clazz);
1094 public TreeMap<String, byte[]> getMetadata() {
1095 return writeSupport.getMetadata();
1099 public void commitDone(WriteTraits writeTraits, long csid) {
1100 writeSupport.commitDone(writeTraits, csid);
1104 public void clearUndoList(WriteTraits writeTraits) {
1105 writeSupport.clearUndoList(writeTraits);
1108 public int clearMetadata() {
1109 return writeSupport.clearMetadata();
1113 public void startUndo() {
1114 writeSupport.startUndo();
1118 class VirtualWriteOnlySupport implements WriteSupport {
1121 // public void addStatement(VirtualGraph provider, Resource subject, Resource predicate,
1122 // Resource object) {
1123 // throw new UnsupportedOperationException();
1127 public void claim(VirtualGraph provider, Resource subject, Resource predicate, Resource object) {
1129 TransientGraph impl = (TransientGraph)provider;
1130 impl.claim(querySupport.getId(subject), querySupport.getId(predicate), querySupport.getId(object));
1131 getQueryProvider2().updateStatements(querySupport.getId(subject), querySupport.getId(predicate));
1132 clientChanges.claim(subject, predicate, object);
1137 public void claim(VirtualGraph provider, int subject, int predicate, int object) {
1139 TransientGraph impl = (TransientGraph)provider;
1140 impl.claim(subject, predicate, object);
1141 getQueryProvider2().updateStatements(subject, predicate);
1142 clientChanges.claim(subject, predicate, object);
1147 public void claimValue(VirtualGraph provider, Resource resource, byte[] value) throws DatabaseException {
1148 claimValue(provider, ((ResourceImpl)resource).id, value, value.length);
1152 public void claimValue(VirtualGraph provider, int resource, byte[] value, int length) {
1153 ((VirtualGraphImpl)provider).claimValue(resource, value, length);
1154 getQueryProvider2().updateValue(resource);
1155 clientChanges.claimValue(resource);
1159 public void claimValue(VirtualGraph provider, Resource resource, ByteReader reader, int amount) throws DatabaseException {
1160 byte[] value = reader.readBytes(null, amount);
1161 claimValue(provider, resource, value);
1165 public Resource createResource(VirtualGraph provider) {
1166 TransientGraph impl = (TransientGraph)provider;
1167 return impl.getResource(impl.newResource(false));
1171 public Resource createResource(VirtualGraph provider, long clusterId) {
1172 throw new UnsupportedOperationException();
1176 public Resource createResource(VirtualGraph provider, Resource clusterSet)
1177 throws DatabaseException {
1178 throw new UnsupportedOperationException();
1182 public void createClusterSet(VirtualGraph provider, Resource clusterSet)
1183 throws DatabaseException {
1184 throw new UnsupportedOperationException();
1188 public boolean hasClusterSet(VirtualGraph provider, Resource clusterSet)
1189 throws ServiceException {
1190 throw new UnsupportedOperationException();
1194 public Resource setDefaultClusterSet(Resource clusterSet)
1195 throws ServiceException {
1200 public void denyValue(VirtualGraph provider, Resource resource) {
1201 ((VirtualGraphImpl)provider).denyValue(((ResourceImpl) resource).id);
1202 getQueryProvider2().updateValue(querySupport.getId(resource));
1203 // NOTE: this only keeps track of value changes by-resource.
1204 clientChanges.claimValue(resource);
1208 public void flush(boolean intermediate) {
1209 throw new UnsupportedOperationException();
1213 public void flushCluster() {
1214 throw new UnsupportedOperationException();
1218 public void flushCluster(Resource r) {
1219 throw new UnsupportedOperationException("Resource " + r);
1227 public boolean removeStatement(VirtualGraph provider, Resource subject, Resource predicate, Resource object) {
1228 TransientGraph impl = (TransientGraph) provider;
1229 impl.deny(querySupport.getId(subject), querySupport.getId(predicate), querySupport.getId(object));
1230 getQueryProvider2().updateStatements(querySupport.getId(subject), querySupport.getId(predicate));
1231 clientChanges.deny(subject, predicate, object);
1236 public void setValue(VirtualGraph provider, Resource resource, byte[] value) {
1237 throw new UnsupportedOperationException();
1241 public boolean writeOnly() {
1246 public void performWriteRequest(WriteGraph graph, Write request) throws DatabaseException {
1247 throw new UnsupportedOperationException();
1251 public <T> T performWriteRequest(WriteGraph graph, WriteResult<T> request) throws DatabaseException {
1252 throw new UnsupportedOperationException();
1256 public void performWriteRequest(WriteGraph graph, WriteOnly request) throws DatabaseException {
1257 throw new UnsupportedOperationException();
1261 public <T> void addMetadata(Metadata data) throws ServiceException {
1262 throw new UnsupportedOperationException();
1266 public <T extends Metadata> T getMetadata(Class<T> clazz) throws ServiceException {
1267 throw new UnsupportedOperationException();
1271 public TreeMap<String, byte[]> getMetadata() {
1272 throw new UnsupportedOperationException();
1276 public void commitDone(WriteTraits writeTraits, long csid) {
1280 public void clearUndoList(WriteTraits writeTraits) {
1284 public int clearMetadata() {
1289 public void startUndo() {
1293 private <T> void performWriteOnly(WriteOnlyResult<T> request, Semaphore notify, Procedure<T> callback) {
1297 //int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1299 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
1302 Disposable.safeDispose(clientChanges);
1303 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
1307 WriteSupport writeSupport = request.getProvider() != null ? new VirtualWriteOnlySupport() : new WriteOnlySupport();
1309 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, request.getProvider());
1311 WriteState<T> writeStateT = new WriteState<T>(writer, request, notify, callback);
1312 writeState = writeStateT;
1314 assert (null != writer);
1315 // writer.state.barrier.inc();
1316 long start = System.nanoTime();
1317 T result = request.perform(writer);
1318 long duration = System.nanoTime() - start;
1320 System.err.println("################");
1321 System.err.println("WriteOnly duration " + 1e-9*duration);
1323 writeStateT.setResult(result);
1325 // This makes clusters available from server
1326 clusterStream.reallyFlush();
1328 // This will trigger query updates
1329 releaseWriteOnly(writer);
1330 assert (null != writer);
1332 handleUpdatesAndMetadata(writer);
1334 } catch (CancelTransactionException e) {
1336 releaseWriteOnly(writeState.getGraph());
1338 clusterTable.removeWriteOnlyClusters();
1339 state.stopWriteTransaction(clusterStream);
1341 } catch (Throwable e) {
1343 e.printStackTrace();
1345 releaseWriteOnly(writeState.getGraph());
1347 clusterTable.removeWriteOnlyClusters();
1349 if (callback != null)
1350 callback.exception(new DatabaseException(e));
1352 state.stopWriteTransaction(clusterStream);
1353 Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", e);
1357 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
1363 public <T> void scheduleRequest(final WriteOnly request, final Consumer<DatabaseException> callback, final Semaphore notify) {
1364 scheduleRequest(request, callback, notify, null);
1368 public <T> void scheduleRequest(final WriteOnly request, final Consumer<DatabaseException> callback, final Semaphore notify, Boolean combine) {
1372 assert (request != null);
1374 requestManager.scheduleWrite(new SessionTask(null) {
1377 public void run0(int thread) {
1379 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
1383 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
1386 Disposable.safeDispose(clientChanges);
1387 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
1391 VirtualGraph vg = getProvider(request.getProvider());
1392 WriteSupport writeSupport = vg != null ? new VirtualWriteOnlySupport() : new WriteOnlySupport();
1394 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
1396 writeState = new WriteState<Object>(writer, request, notify, new Procedure<Object>() {
1399 public void execute(Object result) {
1400 if(callback != null) callback.accept(null);
1404 public void exception(Throwable t) {
1405 if(callback != null) callback.accept((DatabaseException)t);
1410 assert (null != writer);
1411 // writer.state.barrier.inc();
1415 request.perform(writer);
1417 } catch (Throwable e) {
1419 // writer.state.barrier.dec();
1420 // writer.waitAsync(null);
1422 releaseWriteOnly(writer);
1424 clusterTable.removeWriteOnlyClusters();
1426 if(!(e instanceof CancelTransactionException)) {
1427 if (callback != null)
1428 callback.accept(new DatabaseException(e));
1431 writeState.except(e);
1437 // This makes clusters available from server
1438 boolean empty = clusterStream.reallyFlush();
1439 // This was needed to make WO requests call metadata listeners.
1440 // NOTE: the calling event does not contain clientChanges information.
1441 if (!empty && clientChanges.isEmpty())
1442 clientChanges.setNotEmpty(true);
1443 releaseWriteOnly(writer);
1444 assert (null != writer);
1447 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
1460 public <T> void scheduleRequest(final WriteOnlyResult<T> request, final Procedure<T> callback, final Semaphore notify) {
1461 scheduleRequest(request, callback, notify, null);
1465 * @see org.simantics.db.impl.support.WriteRequestScheduleSupport#scheduleRequest(org.simantics.db.request.WriteOnlyResult, org.simantics.db.procedure.Procedure, java.util.concurrent.Semaphore, java.lang.Boolean)
1468 public <T> void scheduleRequest(final WriteOnlyResult<T> request, final Procedure<T> callback, final Semaphore notify, Boolean combine) {
1470 assert (request != null);
1472 requestManager.scheduleWrite(new SessionTask(null) {
1475 public void run0(int thread) {
1477 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
1479 performWriteOnly(request, notify, callback);
1489 public <T> void scheduleRequest(final Read<T> request, final AsyncProcedure<T> procedure, final Semaphore notify, final DataContainer<Throwable> throwable, final DataContainer<T> result) {
1491 assert (request != null);
1492 assert (procedure != null);
1494 //int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1496 requestManager.scheduleRead(new SessionRead(throwable, notify) {
1499 public void run0(int thread) {
1501 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1503 ListenerBase listener = getListenerBase(procedure);
1505 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1507 // This is never synced but increase to prevent it from visiting 0
1508 newGraph.asyncBarrier.inc();
1512 if (listener != null) {
1516 AsyncProcedure ap = new AsyncProcedure<T>() {
1519 public void exception(AsyncReadGraph graph, Throwable t) {
1520 procedure.exception(graph, t);
1521 if(throwable != null) {
1524 // ErrorLogger.defaultLogError("Unhandled exception", t);
1529 public void execute(AsyncReadGraph graph, T t) {
1530 if(result != null) result.set(t);
1531 procedure.execute(graph, t);
1536 QueryCache.runnerReadEntry(newGraph, request, null, listener, ap, true);
1538 } catch (Throwable t) {
1539 // This is handled by the AsyncProcedure
1540 //Logger.defaultLogError("Internal error", t);
1547 // newGraph.state.barrier.inc();
1549 T t = request.perform(newGraph);
1553 if(result != null) result.set(t);
1554 procedure.execute(newGraph, t);
1556 } catch (Throwable th) {
1558 if(throwable != null) {
1561 Logger.defaultLogError("Unhandled exception", th);
1566 } catch (Throwable t) {
1569 t.printStackTrace();
1571 if(throwable != null) {
1574 Logger.defaultLogError("Unhandled exception", t);
1579 procedure.exception(newGraph, t);
1581 } catch (Throwable t2) {
1583 if(throwable != null) {
1586 Logger.defaultLogError("Unhandled exception", t2);
1593 // newGraph.state.barrier.dec();
1594 // newGraph.waitAsync(request);
1600 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1610 public <T> void scheduleRequest(final AsyncRead<T> request, final AsyncProcedure<T> procedure, final ListenerBase listener, final Semaphore notify) {
1612 assert (request != null);
1613 assert (procedure != null);
1615 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1617 requestManager.scheduleRead(new SessionRead(null, notify) {
1620 public void run0(int thread) {
1622 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1624 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1628 if (listener != null) {
1631 QueryCacheBase.resultAsyncReadEntry(newGraph, request, null, listener, procedure);
1632 //QueryCache.runnerAsyncReadEntry(newGraph, request, null, listener, procedure, true);
1633 //newGraph.processor.query(newGraph, request, null, procedure, listener);
1634 } catch (DatabaseException e) {
1635 Logger.defaultLogError(e);
1640 // final ResultCallWrappedSingleQueryProcedure4<T> wrapper = new ResultCallWrappedSingleQueryProcedure4<T>(
1641 // procedure, "request");
1643 BlockingAsyncProcedure<T> wrap = new BlockingAsyncProcedure<T>(newGraph.asyncBarrier, newGraph, procedure, request);
1647 request.perform(newGraph, wrap);
1650 } catch (DatabaseException e) {
1652 Logger.defaultLogError(e);
1660 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1670 public <T> void scheduleRequest(final MultiRead<T> request, final SyncMultiProcedure<T> procedure, final Semaphore notify) {
1672 assert (request != null);
1673 assert (procedure != null);
1675 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1677 int sync = notify != null ? thread : -1;
1679 requestManager.scheduleRead(new SessionRead(null, notify) {
1682 public void run0(int thread) {
1684 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1686 ListenerBase listener = getListenerBase(procedure);
1688 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1692 if (listener != null) {
1694 newGraph.processor.query(newGraph, request, null, procedure, listener);
1696 // newGraph.waitAsync(request);
1700 final ResultCallWrappedSyncQueryProcedure<T> wrapper = new ResultCallWrappedSyncQueryProcedure<T>(procedure);
1704 request.perform(newGraph, wrapper);
1706 } catch (Throwable t) {
1708 t.printStackTrace();
1716 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1726 public <T> void scheduleRequest(final AsyncMultiRead<T> request, final AsyncMultiProcedure<T> procedure, final Semaphore notify) {
1728 assert (request != null);
1729 assert (procedure != null);
1731 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1733 int sync = notify != null ? thread : -1;
1735 requestManager.scheduleRead(new SessionRead(null, notify) {
1738 public void run0(int thread) {
1740 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1742 ListenerBase listener = getListenerBase(procedure);
1744 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1748 if (listener != null) {
1750 newGraph.processor.query(newGraph, request, null, procedure, listener);
1752 // newGraph.waitAsync(request);
1756 final ResultCallWrappedQueryProcedure4<T> wrapper = new ResultCallWrappedQueryProcedure4<T>(procedure);
1760 request.perform(newGraph, wrapper);
1762 } catch (Throwable t) {
1764 t.printStackTrace();
1772 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1782 public <T> void scheduleRequest(final ExternalRead<T> request, final Procedure<T> procedure, final Semaphore notify, final DataContainer<Throwable> throwable, final DataContainer<T> result) {
1784 assert (request != null);
1785 assert (procedure != null);
1787 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1789 requestManager.scheduleRead(new SessionRead(throwable, notify) {
1792 public void run0(int thread) {
1794 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1796 ListenerBase listener = getListenerBase(procedure);
1798 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1802 if (listener != null) {
1805 QueryCacheBase.resultExternalReadEntry(newGraph, request, null, listener, procedure);
1806 } catch (DatabaseException e) {
1807 Logger.defaultLogError(e);
1812 // newGraph.state.barrier.inc();
1814 request.register(newGraph, new Listener<T>() {
1817 public void exception(Throwable t) {
1818 if(throwable != null) throwable.set(t);
1819 procedure.exception(t);
1820 // newGraph.state.barrier.dec();
1824 public void execute(T t) {
1825 if(result != null) result.set(t);
1826 procedure.execute(t);
1827 // newGraph.state.barrier.dec();
1831 public boolean isDisposed() {
1837 // newGraph.waitAsync(request);
1843 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1855 public <T> void asyncRequest(final Read<T> request, final AsyncProcedure<T> procedure) {
1857 scheduleRequest(request, procedure, null, null, null);
1862 public <T> T syncRequest(Read<T> request, AsyncProcedure<T> procedure) throws DatabaseException {
1864 Semaphore notify = new Semaphore(0);
1865 DataContainer<Throwable> container = new DataContainer<Throwable>();
1866 DataContainer<T> result = new DataContainer<T>();
1867 scheduleRequest(request, procedure, notify, container, result);
1868 acquire(notify, request);
1869 Throwable throwable = container.get();
1870 if(throwable != null) {
1871 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1872 else throw new DatabaseException("Unexpected exception", throwable);
1874 return result.get();
1878 public <T> T syncRequest(AsyncRead<T> request, final AsyncProcedure<T> procedure) throws DatabaseException {
1880 Semaphore notify = new Semaphore(0);
1881 final DataContainer<Throwable> exceptionContainer = new DataContainer<Throwable>();
1882 final DataContainer<T> resultContainer = new DataContainer<T>();
1883 scheduleRequest(request, new AsyncProcedure<T>() {
1885 public void exception(AsyncReadGraph graph, Throwable throwable) {
1886 exceptionContainer.set(throwable);
1887 procedure.exception(graph, throwable);
1890 public void execute(AsyncReadGraph graph, T result) {
1891 resultContainer.set(result);
1892 procedure.execute(graph, result);
1894 }, getListenerBase(procedure), notify);
1895 acquire(notify, request, procedure);
1896 Throwable throwable = exceptionContainer.get();
1897 if (throwable != null) {
1898 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1899 else throw new DatabaseException("Unexpected exception", throwable);
1901 return resultContainer.get();
1906 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, final AsyncMultiProcedure<T> procedure) throws DatabaseException {
1908 Semaphore notify = new Semaphore(0);
1909 final DataContainer<Throwable> exceptionContainer = new DataContainer<Throwable>();
1910 scheduleRequest(request, new AsyncMultiProcedure<T>() {
1912 public void exception(AsyncReadGraph graph, Throwable throwable) {
1913 exceptionContainer.set(throwable);
1914 procedure.exception(graph, throwable);
1917 public void execute(AsyncReadGraph graph, T result) {
1918 procedure.execute(graph, result);
1921 public void finished(AsyncReadGraph graph) {
1922 procedure.finished(graph);
1925 acquire(notify, request, procedure);
1926 Throwable throwable = exceptionContainer.get();
1927 if (throwable != null) {
1928 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1929 else throw new DatabaseException("Unexpected exception", throwable);
1931 // TODO: implement return value
1932 System.err.println("TODO: implement return value for syncRequest(AsyncMultiRead, AsyncMultiProcedure)");
1937 public <T> T syncRequest(final ExternalRead<T> request) throws DatabaseException {
1938 return syncRequest(request, new ProcedureAdapter<T>());
1941 // assert(request != null);
1943 // final DataContainer<T> result = new DataContainer<T>();
1944 // final DataContainer<Throwable> exception = new DataContainer<Throwable>();
1946 // syncRequest(request, new Procedure<T>() {
1949 // public void execute(T t) {
1954 // public void exception(Throwable t) {
1955 // exception.set(t);
1960 // Throwable t = exception.get();
1962 // if(t instanceof DatabaseException) throw (DatabaseException)t;
1963 // else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(PrimitiveRead)", t);
1966 // return result.get();
1971 public <T> T syncRequest(ExternalRead<T> request, final Listener<T> procedure) throws DatabaseException {
1972 return syncRequest(request, (Procedure<T>)procedure);
1977 // public <T> T syncRequest(Read<T> request, AsyncProcedure<T> procedure) throws DatabaseException {
1978 // assertNotSession();
1979 // Semaphore notify = new Semaphore(0);
1980 // DataContainer<Throwable> container = new DataContainer<Throwable>();
1981 // DataContainer<T> result = new DataContainer<T>();
1982 // scheduleRequest(request, procedure, notify, container, result);
1983 // acquire(notify, request);
1984 // Throwable throwable = container.get();
1985 // if(throwable != null) {
1986 // if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1987 // else throw new DatabaseException("Unexpected exception", throwable);
1989 // return result.get();
1994 public <T> T syncRequest(ExternalRead<T> request, final Procedure<T> procedure) throws DatabaseException {
1996 Semaphore notify = new Semaphore(0);
1997 final DataContainer<Throwable> container = new DataContainer<Throwable>();
1998 final DataContainer<T> result = new DataContainer<T>();
1999 scheduleRequest(request, procedure, notify, container, result);
2000 acquire(notify, request);
2001 Throwable throwable = container.get();
2002 if (throwable != null) {
2003 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
2004 else throw new DatabaseException("Unexpected exception", throwable);
2006 return result.get();
2010 public void syncRequest(Write request) throws DatabaseException {
2013 Semaphore notify = new Semaphore(0);
2014 final DataContainer<DatabaseException> exception = new DataContainer<DatabaseException>();
2015 scheduleRequest(request, e -> exception.set(e), notify);
2016 acquire(notify, request);
2017 if(exception.get() != null) throw exception.get();
2021 public <T> T syncRequest(WriteResult<T> request) throws DatabaseException {
2023 Semaphore notify = new Semaphore(0);
2024 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2025 final DataContainer<T> result = new DataContainer<T>();
2026 scheduleRequest(request, new Procedure<T>() {
2029 public void exception(Throwable t) {
2034 public void execute(T t) {
2039 acquire(notify, request);
2040 if(exception.get() != null) {
2041 Throwable t = exception.get();
2042 if(t instanceof DatabaseException) throw (DatabaseException)t;
2043 else throw new DatabaseException(t);
2045 return result.get();
2049 public <T> T syncRequest(WriteOnlyResult<T> request) throws DatabaseException {
2051 Semaphore notify = new Semaphore(0);
2052 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2053 final DataContainer<T> result = new DataContainer<T>();
2054 scheduleRequest(request, new Procedure<T>() {
2057 public void exception(Throwable t) {
2062 public void execute(T t) {
2067 acquire(notify, request);
2068 if(exception.get() != null) {
2069 Throwable t = exception.get();
2070 if(t instanceof DatabaseException) throw (DatabaseException)t;
2071 else throw new DatabaseException(t);
2073 return result.get();
2077 public <T> T syncRequest(DelayedWriteResult<T> request) throws DatabaseException {
2079 Semaphore notify = new Semaphore(0);
2080 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2081 final DataContainer<T> result = new DataContainer<T>();
2082 scheduleRequest(request, new Procedure<T>() {
2085 public void exception(Throwable t) {
2090 public void execute(T t) {
2095 acquire(notify, request);
2096 if(exception.get() != null) {
2097 Throwable t = exception.get();
2098 if(t instanceof DatabaseException) throw (DatabaseException)t;
2099 else throw new DatabaseException(t);
2101 return result.get();
2105 public void syncRequest(DelayedWrite request) throws DatabaseException {
2107 Semaphore notify = new Semaphore(0);
2108 final DataContainer<DatabaseException> exception = new DataContainer<DatabaseException>();
2109 scheduleRequest(request, e -> exception.set(e), notify);
2110 acquire(notify, request);
2111 if(exception.get() != null) throw exception.get();
2115 public void syncRequest(WriteOnly request) throws DatabaseException {
2118 Semaphore notify = new Semaphore(0);
2119 final DataContainer<DatabaseException> exception = new DataContainer<DatabaseException>();
2120 scheduleRequest(request, e -> exception.set(e), notify);
2121 acquire(notify, request);
2122 if(exception.get() != null) throw exception.get();
2127 * GraphRequestProcessor interface
2131 public <T> void asyncRequest(final AsyncRead<T> request, final AsyncProcedure<T> procedure) {
2133 scheduleRequest(request, procedure, null, null);
2138 public <T> void asyncRequest(final AsyncMultiRead<T> request, final AsyncMultiProcedure<T> procedure) {
2140 scheduleRequest(request, procedure, null);
2145 public <T> void asyncRequest(final ExternalRead<T> request, final Procedure<T> procedure) {
2147 scheduleRequest(request, procedure, null, null, null);
2152 public void asyncRequest(final Write request, final Consumer<DatabaseException> callback) {
2154 scheduleRequest(request, callback, null);
2159 public <T> void asyncRequest(final WriteResult<T> request, final Procedure<T> procedure) {
2161 scheduleRequest(request, procedure, null);
2166 public <T> void asyncRequest(final WriteOnlyResult<T> request, final Procedure<T> procedure) {
2168 scheduleRequest(request, procedure, null);
2173 public <T> void asyncRequest(final DelayedWriteResult<T> request, final Procedure<T> procedure) {
2175 scheduleRequest(request, procedure, null);
2180 public void asyncRequest(final DelayedWrite request, final Consumer<DatabaseException> callback) {
2182 scheduleRequest(request, callback, null);
2187 public void asyncRequest(final Write r) {
2188 asyncRequest(r, null);
2192 public void asyncRequest(final DelayedWrite r) {
2193 asyncRequest(r, null);
2197 public void asyncRequest(final WriteOnly request, final Consumer<DatabaseException> callback) {
2199 scheduleRequest(request, callback, null);
2204 public void asyncRequest(final WriteOnly request) {
2206 asyncRequest(request, null);
2211 public <T> void async(ReadInterface<T> r, AsyncProcedure<T> procedure) {
2212 r.request(this, procedure);
2216 public <T> void async(ReadInterface<T> r, Procedure<T> procedure) {
2217 r.request(this, procedure);
2221 public <T> void async(ReadInterface<T> r, SyncProcedure<T> procedure) {
2222 r.request(this, procedure);
2226 public <T> void async(ReadInterface<T> r, AsyncListener<T> procedure) {
2227 r.request(this, procedure);
2231 public <T> void async(ReadInterface<T> r, Listener<T> procedure) {
2232 r.request(this, procedure);
2236 public <T> void async(ReadInterface<T> r, SyncListener<T> procedure) {
2237 r.request(this, procedure);
2241 public <T> T sync(ReadInterface<T> r) throws DatabaseException {
2242 return r.request(this);
2246 public <T> T sync(WriteInterface<T> r) throws DatabaseException {
2247 return r.request(this);
2251 public <T> void async(WriteInterface<T> r, Procedure<T> procedure) {
2252 r.request(this, procedure);
2256 public <T> void async(WriteInterface<T> r) {
2257 r.request(this, new ProcedureAdapter<T>());
2261 public void incAsync() {
2266 public void decAsync() {
2270 public long getCluster(ResourceImpl resource) {
2271 ClusterI cluster = clusterTable.getClusterByResourceKey(resource.id);
2272 return cluster.getClusterId();
2275 public long getCluster(int id) {
2276 if (clusterTable == null)
2277 System.out.println("SessionImplSocket.getCluster() clusterTable == null !!!!! how come");
2278 return clusterTable.getClusterIdByResourceKeyNoThrow(id);
2281 public ResourceImpl getResource(int id) {
2282 return new ResourceImpl(resourceSupport, id);
2285 public ResourceImpl getResource(int resourceIndex, long clusterId) {
2286 assert (!ClusterTraitsBase.isIllegalResourceIndex(resourceIndex));
2287 ClusterI proxy = clusterTable.getClusterByClusterId(clusterId);
2288 int key = proxy.getClusterKey();
2289 int resourceKey = ClusterTraitsBase.createResourceKeyNoThrow(key, resourceIndex);
2290 return new ResourceImpl(resourceSupport, resourceKey);
2293 public ResourceImpl getResource2(int id) {
2295 return new ResourceImpl(resourceSupport, id);
2298 final public int getId(ResourceImpl impl) {
2302 public static final Charset UTF8 = Charset.forName("utf-8");
2307 static boolean areVirtualStatementsLoaded(final VirtualGraphServerSupportImpl support, int subject) {
2308 for(TransientGraph g : support.providers) {
2309 if(g.isPending(subject)) return false;
2314 static boolean areVirtualStatementsLoaded(final VirtualGraphServerSupportImpl support, int subject, int predicate) {
2315 for(TransientGraph g : support.providers) {
2316 if(g.isPending(subject, predicate)) return false;
2321 static void loadVirtualStatements(final VirtualGraphServerSupportImpl support, ReadGraphImpl graph, int subject, final Consumer<ReadGraphImpl> runnable) {
2323 Consumer<ReadGraphImpl> composite = new Consumer<ReadGraphImpl>() {
2325 AtomicInteger ready = new AtomicInteger(support.providers.size() + 1);
2328 public void accept(ReadGraphImpl graph) {
2329 if(ready.decrementAndGet() == 0) {
2330 runnable.accept(graph);
2336 for(TransientGraph g : support.providers) {
2337 if(g.isPending(subject)) {
2339 g.load(graph, subject, composite);
2340 } catch (DatabaseException e) {
2341 e.printStackTrace();
2344 composite.accept(graph);
2348 composite.accept(graph);
2352 static void loadVirtualStatements(final VirtualGraphServerSupportImpl support, ReadGraphImpl graph, int subject, int predicate, final Consumer<ReadGraphImpl> runnable) {
2354 Consumer<ReadGraphImpl> composite = new Consumer<ReadGraphImpl>() {
2356 AtomicInteger ready = new AtomicInteger(support.providers.size() + 1);
2359 public void accept(ReadGraphImpl graph) {
2360 if(ready.decrementAndGet() == 0) {
2361 runnable.accept(graph);
2367 for(TransientGraph g : support.providers) {
2368 if(g.isPending(subject, predicate)) {
2370 g.load(graph, subject, predicate, composite);
2371 } catch (DatabaseException e) {
2372 e.printStackTrace();
2375 composite.accept(graph);
2379 composite.accept(graph);
2383 // void dumpHeap() {
2386 // ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
2387 // "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class).dumpHeap(
2388 // "d:/heap" + flushCounter + ".txt", true);
2389 // } catch (IOException e) {
2390 // e.printStackTrace();
2395 void fireReactionsToSynchronize(ChangeSet cs) {
2397 // Do not fire empty events
2401 ReadGraphImpl g = ReadGraphImpl.create(getQueryProvider2());
2402 // g.state.barrier.inc();
2406 if (!cs.isEmpty()) {
2407 ChangeEvent e2 = new ChangeEvent(g.getSession(), g, null, cs);
2408 for (ChangeListener l : changeListeners2) {
2411 } catch (Exception ex) {
2412 ex.printStackTrace();
2419 // g.state.barrier.dec();
2420 // g.waitAsync(null);
2426 void fireReactionsToCommit(ReadGraphImpl graph, ChangeSet cs2) {
2429 // Do not fire empty events
2434 // graph.state.barrier.inc();
2438 if (!cs2.isEmpty()) {
2440 ChangeEvent e2 = new ChangeEvent(graph.getSession(), graph, null, cs2);
2441 for (ChangeListener l : changeListeners2) {
2444 // System.out.println("changelistener " + l);
2445 } catch (Exception ex) {
2446 ex.printStackTrace();
2454 // graph.state.barrier.dec();
2455 // graph.waitAsync(null);
2458 } catch (Throwable t) {
2459 t.printStackTrace();
2463 void fireMetadataListeners(WriteGraphImpl graph, ChangeSet cs2) {
2467 // Do not fire empty events
2471 // Do not fire on virtual requests
2472 if(graph.getProvider() != null)
2475 WriteGraphImpl reactionGraph = WriteGraphImpl.create(graph.processor, writeSupport, null);
2479 ChangeEvent e2 = new ChangeEvent(graph.getSession(), reactionGraph, graph, cs2);
2480 for (ChangeListener l : metadataListeners) {
2483 } catch (Throwable ex) {
2484 ex.printStackTrace();
2492 } catch (Throwable t) {
2493 t.printStackTrace();
2502 * @see org.simantics.db.ServiceLocator#getService(java.lang.Class)
2505 public <T> T getService(Class<T> api) {
2506 T t = peekService(api);
2508 if (state.isClosed())
2509 throw new ServiceNotFoundException(this, api, "Session has been shut down");
2510 throw new ServiceNotFoundException(this, api);
2518 protected abstract ServerInformation getCachedServerInformation();
2520 private Class<?> serviceKey1 = null;
2521 private Class<?> serviceKey2 = null;
2522 private Object service1 = null;
2523 private Object service2 = null;
2529 * fi.vtt.simantics.db.connection.ServiceLocator#peekService(java.lang.Class)
2531 @SuppressWarnings("unchecked")
2533 public synchronized <T> T peekService(Class<T> api) {
2535 if(serviceKey1 == api) {
2537 } else if (serviceKey2 == api) {
2539 Object result = service2;
2540 service2 = service1;
2541 serviceKey2 = serviceKey1;
2547 if (Layer0.class == api)
2549 if (ServerInformation.class == api)
2550 return (T) getCachedServerInformation();
2551 else if (WriteGraphImpl.class == api)
2552 return (T) writeState.getGraph();
2553 else if (ClusterBuilder.class == api)
2554 return (T)new ClusterBuilderImpl(this, (WriteOnlySupport)writeState.getGraph().writeSupport);
2555 else if (ClusterBuilderFactory.class == api)
2556 return (T)new ClusterBuilderFactoryImpl(this);
2558 service2 = service1;
2559 serviceKey2 = serviceKey1;
2561 service1 = serviceLocator.peekService(api);
2572 * fi.vtt.simantics.db.connection.ServiceLocator#hasService(java.lang.Class)
2575 public boolean hasService(Class<?> api) {
2576 return serviceLocator.hasService(api);
2580 * @param api the api that must be implemented by the specified service
2581 * @param service the service implementation
2584 public <T> void registerService(Class<T> api, T service) {
2585 if(Layer0.class == api) {
2586 L0 = (Layer0)service;
2589 serviceLocator.registerService(api, service);
2590 if (TransactionPolicySupport.class == api) {
2591 transactionPolicy = (TransactionPolicySupport)service;
2592 state.resetTransactionPolicy();
2594 if (api == serviceKey1)
2596 else if (api == serviceKey2)
2604 void fireSessionVariableChange(String variable) {
2605 for (MonitorHandler h : monitorHandlers) {
2606 MonitorContext ctx = monitorContexts.getLeft(h);
2608 // SafeRunner functionality repeated here to avoid dependency.
2610 h.valuesChanged(ctx);
2611 } catch (Exception e) {
2612 Logger.defaultLogError("monitor handler notification produced the following exception", e);
2613 } catch (LinkageError e) {
2614 Logger.defaultLogError("monitor handler notification produced a linkage error", e);
2620 class ResourceSerializerImpl implements ResourceSerializer {
2622 public long createRandomAccessId(int id) throws DatabaseException {
2625 int index = ClusterTraitsBase.getResourceIndexFromResourceKey(id);
2626 long cluster = getCluster(id);
2628 return 0; // Better to return 0 then invalid id.
2629 long result = ClusterTraitsBase.createResourceId(cluster, index);
2634 public long getRandomAccessId(Resource resource) throws DatabaseException {
2636 ResourceImpl resourceImpl = (ResourceImpl) resource;
2637 return createRandomAccessId(resourceImpl.id);
2642 public int getTransientId(Resource resource) throws DatabaseException {
2644 ResourceImpl resourceImpl = (ResourceImpl) resource;
2645 return resourceImpl.id;
2650 public String createRandomAccessId(Resource resource)
2651 throws InvalidResourceReferenceException {
2653 if(resource == null) throw new IllegalArgumentException();
2655 ResourceImpl resourceImpl = (ResourceImpl) resource;
2657 if (resourceImpl.id < 0) return String.valueOf(resourceImpl.id) + "_0";
2661 r = ClusterTraits.getResourceIndexFromResourceKey(resourceImpl.id);
2662 } catch (DatabaseException e1) {
2663 throw new InvalidResourceReferenceException(e1);
2666 // Serialize as '<resource index>_<cluster id>'
2667 return "" + r + "_" + getCluster(resourceImpl);
2668 } catch (Throwable e) {
2669 e.printStackTrace();
2670 throw new InvalidResourceReferenceException(e);
2675 public int getTransientId(long serialized) throws DatabaseException {
2676 if (serialized <= 0)
2677 return (int)serialized;
2678 int index = ClusterTraitsBase.getResourceIndexFromResourceId(serialized);
2679 long c = ClusterTraitsBase.getClusterIdFromResourceId(serialized);
2680 ClusterI cluster = clusterTranslator.getClusterByClusterId(c);
2681 if (cluster == null)
2682 throw new DatabaseException("Couldn't load cluster for id " + c + " for resource id " + serialized);
2683 int key = ClusterTraits.createResourceKey(cluster.getClusterKey(), index);
2688 public Resource getResource(long randomAccessId) throws DatabaseException {
2689 return getResourceByKey(getTransientId(randomAccessId));
2693 public Resource getResource(int transientId) throws DatabaseException {
2694 return getResourceByKey(transientId);
2698 public Resource getResource(String randomAccessId)
2699 throws InvalidResourceReferenceException {
2701 int i = randomAccessId.indexOf('_');
2703 throw new InvalidResourceReferenceException("Could not parse resource id + cluster id from '"
2704 + randomAccessId + "'");
2705 int r = Integer.parseInt(randomAccessId.substring(0, i));
2706 if(r < 0) return getResourceByKey(r);
2707 long c = Long.parseLong(randomAccessId.substring(i + 1));
2708 ClusterI cluster = clusterTranslator.getClusterByClusterId(c);
2709 int key = ClusterTraits.createResourceKey(cluster.getClusterKey(), r);
2710 if (cluster.hasResource(key, clusterTranslator))
2711 return getResourceByKey(key);
2712 } catch (InvalidResourceReferenceException e) {
2714 } catch (NumberFormatException e) {
2715 throw new InvalidResourceReferenceException(e);
2716 } catch (Throwable e) {
2717 e.printStackTrace();
2718 throw new InvalidResourceReferenceException(e);
2721 throw new InvalidResourceReferenceException("Resource does not exist " + randomAccessId);
2725 public boolean disposeRandomAccessId(String randomAccessId) throws InvalidResourceReferenceException {
2728 } catch (Throwable e) {
2729 e.printStackTrace();
2730 throw new InvalidResourceReferenceException(e);
2736 // Copied from old SessionImpl
2739 if (state.isClosed())
2740 throw new Error("Session closed.");
2745 public ResourceImpl getNewResource(long clusterId) {
2746 ClusterI cluster = clusterTable.getClusterByClusterIdOrThrow(clusterId);
2749 newId = cluster.createResource(clusterTranslator);
2750 } catch (DatabaseException e) {
2751 Logger.defaultLogError(e);
2754 return new ResourceImpl(resourceSupport, newId);
2757 public ResourceImpl getNewResource(Resource clusterSet)
2758 throws DatabaseException {
2759 long resourceId = clusterSet.getResourceId();
2760 Long clusterId = clusterSetsSupport.get(resourceId);
2761 if (null == clusterId)
2762 throw new ClusterSetExistException("Cluster set does not exist. Resource=" + clusterSet);
2763 if (Constants.NewClusterId == clusterId) {
2764 clusterId = getService(ClusteringSupport.class).createCluster();
2765 if ((serviceMode & SERVICE_MODE_CREATE) > 0)
2766 createdClusters.add(clusterId);
2767 clusterSetsSupport.put(resourceId, clusterId);
2768 return getNewResource(clusterId);
2770 ClusterBase cb = clusterTranslator.getClusterByClusterId(clusterId);
2771 ResourceImpl result;
2772 if (cb.getNumberOfResources(clusterTranslator) >= ClusterTable.CLUSTER_FILL_SIZE) {
2773 clusterId = getService(ClusteringSupport.class).createCluster();
2774 if ((serviceMode & SERVICE_MODE_CREATE) > 0)
2775 createdClusters.add(clusterId);
2776 clusterSetsSupport.put(resourceId, clusterId);
2777 return getNewResource(clusterId);
2779 result = getNewResource(clusterId);
2780 int resultKey = querySupport.getId(result);
2781 long resultCluster = querySupport.getClusterId(resultKey);
2782 if (clusterId != resultCluster)
2783 clusterSetsSupport.put(resourceId, resultCluster);
2789 public void getNewClusterSet(Resource clusterSet)
2790 throws DatabaseException {
2792 System.out.println("new cluster set=" + clusterSet);
2793 long resourceId = clusterSet.getResourceId();
2794 if (clusterSetsSupport.containsKey(resourceId))
2795 throw new ClusterSetExistException("Cluster set exist already. Resource=" + clusterSet);
2796 clusterSetsSupport.put(resourceId, Constants.NewClusterId);
2798 public boolean containsClusterSet(Resource clusterSet)
2799 throws ServiceException {
2800 long resourceId = clusterSet.getResourceId();
2801 return clusterSetsSupport.containsKey(resourceId);
2803 public Resource setDefaultClusterSet4NewResource(Resource clusterSet) {
2804 Resource r = defaultClusterSet;
2805 defaultClusterSet = clusterSet;
2808 void printDiagnostics() {
2812 final DataContainer<Long> totalMem = new DataContainer<Long>(0L);
2813 final DataContainer<Long> residentClusters = new DataContainer<Long>(0L);
2814 for(ClusterI cluster : clusterTable.getClusters()) {
2816 if (cluster.isLoaded() && !cluster.isEmpty()) {
2817 residentClusters.set(residentClusters.get() + 1);
2818 totalMem.set(totalMem.get() + cluster.getUsedSpace());
2820 } catch (DatabaseException e) {
2821 Logger.defaultLogError(e);
2825 System.out.println("--------------------------------");
2826 System.out.println("Cluster information:");
2827 System.out.println("-amount of resident clusters=" + residentClusters.get());
2828 System.out.println("-total memory usage=" + totalMem.get() / 1024 + "kB");
2830 for(ClusterI cluster : clusterTable.getClusters()) {
2831 System.out.print("Cluster " + cluster.getClusterId() + " [");
2833 if (!cluster.isLoaded())
2834 System.out.println("not loaded]");
2835 else if (cluster.isEmpty())
2836 System.out.println("is empty]");
2838 System.out.print("resources=" + cluster.getNumberOfResources(clusterTranslator));
2839 System.out.print(",references=" + cluster.getReferenceCount());
2840 System.out.println(",memory=" + cluster.getUsedSpace() / 1024 + "kB]");
2842 } catch (DatabaseException e) {
2843 Logger.defaultLogError(e);
2844 System.out.println("is corrupted]");
2848 queryProvider2.printDiagnostics();
2849 System.out.println("--------------------------------");
2854 public void fireStartReadTransaction() {
2857 System.out.println("StartReadTransaction");
2859 for (SessionEventListener listener : eventListeners) {
2861 listener.readTransactionStarted();
2862 } catch (Throwable t) {
2863 t.printStackTrace();
2869 public void fireFinishReadTransaction() {
2872 System.out.println("FinishReadTransaction");
2874 for (SessionEventListener listener : eventListeners) {
2876 listener.readTransactionFinished();
2877 } catch (Throwable t) {
2878 t.printStackTrace();
2884 public void fireStartWriteTransaction() {
2887 System.out.println("StartWriteTransaction");
2889 for (SessionEventListener listener : eventListeners) {
2891 listener.writeTransactionStarted();
2892 } catch (Throwable t) {
2893 t.printStackTrace();
2899 public void fireFinishWriteTransaction() {
2902 System.out.println("FinishWriteTransaction");
2904 for (SessionEventListener listener : eventListeners) {
2906 listener.writeTransactionFinished();
2907 } catch (Throwable t) {
2908 t.printStackTrace();
2912 Indexing.resetDependenciesIndexingDisabled();
2916 Resource deserialize(final long resourceId, final long clusterId) throws IOException {
2917 throw new Error("Not supported at the moment.");
2924 ClusterTable getClusterTable() {
2925 return clusterTable;
2928 public GraphSession getGraphSession() {
2929 return graphSession;
2932 public QueryProcessor getQueryProvider2() {
2933 return queryProvider2;
2936 ClientChangesImpl getClientChanges() {
2937 return clientChanges;
2940 boolean getWriteOnly() {
2944 static int counter = 0;
2946 public void onClusterLoaded(long clusterId) {
2948 clusterTable.updateSize();
2956 * Implementation of the interface RequestProcessor
2960 public <T> T syncRequest(final Read<T> request) throws DatabaseException {
2965 assert(request != null);
2967 final DataContainer<T> result = new DataContainer<T>();
2968 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2970 syncRequest(request, new AsyncProcedure<T>() {
2973 public void execute(AsyncReadGraph graph, T t) {
2978 public void exception(AsyncReadGraph graph, Throwable t) {
2984 Throwable t = exception.get();
2986 if(t instanceof DatabaseException) throw (DatabaseException)t;
2987 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
2990 return result.get();
2995 // public <T> T syncRequest(Read<T> request, AsyncListener<T> procedure) throws DatabaseException {
2996 // assertNotSession();
2997 // return syncRequest(request, (AsyncProcedure<T>)procedure);
3001 public <T> T syncRequest(Read<T> request, SyncListener<T> procedure) throws DatabaseException {
3003 return syncRequest(request, new SyncToAsyncListener<T>(procedure));
3007 public <T> T syncRequest(Read<T> request, final Listener<T> procedure) throws DatabaseException {
3009 return syncRequest(request, new NoneToAsyncListener<T>(procedure));
3013 public <T> T syncRequest(final Read<T> request, final SyncProcedure<T> procedure) throws DatabaseException {
3015 return syncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3019 public <T> T syncRequest(Read<T> request, Procedure<T> procedure) throws DatabaseException {
3021 return syncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3025 public <T> T syncRequest(final AsyncRead<T> request) throws DatabaseException {
3029 assert(request != null);
3031 final DataContainer<T> result = new DataContainer<T>();
3032 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
3034 syncRequest(request, new AsyncProcedure<T>() {
3037 public void execute(AsyncReadGraph graph, T t) {
3042 public void exception(AsyncReadGraph graph, Throwable t) {
3048 Throwable t = exception.get();
3050 if(t instanceof DatabaseException) throw (DatabaseException)t;
3051 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
3054 return result.get();
3059 public <T> T syncRequest(AsyncRead<T> request, AsyncListener<T> procedure) throws DatabaseException {
3061 return syncRequest(request, (AsyncProcedure<T>)procedure);
3065 public <T> T syncRequest(AsyncRead<T> request, SyncListener<T> procedure) throws DatabaseException {
3067 return syncRequest(request, new SyncToAsyncListener<T>(procedure));
3071 public <T> T syncRequest(AsyncRead<T> request, Listener<T> procedure) throws DatabaseException {
3073 return syncRequest(request, new NoneToAsyncListener<T>(procedure));
3077 public <T> T syncRequest(AsyncRead<T> request, final SyncProcedure<T> procedure) throws DatabaseException {
3079 return syncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3083 final public <T> T syncRequest(final AsyncRead<T> request, final Procedure<T> procedure) throws DatabaseException {
3085 return syncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3089 public <T> Collection<T> syncRequest(MultiRead<T> request) throws DatabaseException {
3093 assert(request != null);
3095 final ArrayList<T> result = new ArrayList<T>();
3096 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
3098 syncRequest(request, new SyncMultiProcedure<T>() {
3101 public void execute(ReadGraph graph, T t) {
3102 synchronized(result) {
3108 public void finished(ReadGraph graph) {
3112 public void exception(ReadGraph graph, Throwable t) {
3119 Throwable t = exception.get();
3121 if(t instanceof DatabaseException) throw (DatabaseException)t;
3122 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
3130 public <T> Collection<T> syncRequest(MultiRead<T> arg0, SyncMultiProcedure<T> arg1) throws DatabaseException {
3132 throw new Error("Not implemented!");
3136 public <T> Collection<T> syncRequest(MultiRead<T> request, SyncMultiListener<T> procedure) throws DatabaseException {
3138 return syncRequest(request, (SyncMultiProcedure<T>)procedure);
3142 public <T> Collection<T> syncRequest(MultiRead<T> request, MultiListener<T> procedure) throws DatabaseException {
3144 return syncRequest(request, new NoneToSyncMultiListener<T>(procedure));
3148 public <T> Collection<T> syncRequest(MultiRead<T> request, MultiProcedure<T> procedure) throws DatabaseException {
3150 return syncRequest(request, new NoneToSyncMultiProcedure<T>(procedure));
3154 final public <T> Collection<T> syncRequest(final AsyncMultiRead<T> request) throws DatabaseException {
3158 assert(request != null);
3160 final ArrayList<T> result = new ArrayList<T>();
3161 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
3163 syncRequest(request, new AsyncMultiProcedure<T>() {
3166 public void execute(AsyncReadGraph graph, T t) {
3167 synchronized(result) {
3173 public void finished(AsyncReadGraph graph) {
3177 public void exception(AsyncReadGraph graph, Throwable t) {
3184 Throwable t = exception.get();
3186 if (t instanceof DatabaseException)
3187 throw (DatabaseException) t;
3189 throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
3197 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, AsyncMultiListener<T> procedure) throws DatabaseException {
3199 return syncRequest(request, (AsyncMultiProcedure<T>)procedure);
3203 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, SyncMultiListener<T> procedure) throws DatabaseException {
3205 return syncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3209 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, MultiListener<T> procedure) throws DatabaseException {
3211 return syncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3215 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, final SyncMultiProcedure<T> procedure) throws DatabaseException {
3217 return syncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3221 final public <T> Collection<T> syncRequest(final AsyncMultiRead<T> request, final MultiProcedure<T> procedure) throws DatabaseException {
3223 return syncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3228 public <T> void asyncRequest(Read<T> request) {
3230 asyncRequest(request, new ProcedureAdapter<T>() {
3232 public void exception(Throwable t) {
3233 t.printStackTrace();
3240 public <T> void asyncRequest(Read<T> request, AsyncListener<T> procedure) {
3241 asyncRequest(request, (AsyncProcedure<T>)procedure);
3245 public <T> void asyncRequest(Read<T> request, final SyncListener<T> procedure) {
3246 asyncRequest(request, new SyncToAsyncListener<T>(procedure));
3250 public <T> void asyncRequest(Read<T> request, final Listener<T> procedure) {
3251 asyncRequest(request, new NoneToAsyncListener<T>(procedure));
3255 public <T> void asyncRequest(Read<T> request, SyncProcedure<T> procedure) {
3256 asyncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3260 public <T> void asyncRequest(Read<T> request, final Procedure<T> procedure) {
3261 asyncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3265 final public <T> void asyncRequest(final AsyncRead<T> request) {
3267 assert(request != null);
3269 asyncRequest(request, new ProcedureAdapter<T>() {
3271 public void exception(Throwable t) {
3272 t.printStackTrace();
3279 public <T> void asyncRequest(AsyncRead<T> request, AsyncListener<T> procedure) {
3280 scheduleRequest(request, procedure, procedure, null);
3284 public <T> void asyncRequest(AsyncRead<T> request, final SyncListener<T> procedure) {
3285 asyncRequest(request, new SyncToAsyncListener<T>(procedure));
3289 public <T> void asyncRequest(AsyncRead<T> request, final Listener<T> procedure) {
3290 asyncRequest(request, new NoneToAsyncListener<T>(procedure));
3294 public <T> void asyncRequest(AsyncRead<T> request, SyncProcedure<T> procedure) {
3295 asyncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3299 final public <T> void asyncRequest(final AsyncRead<T> request, final Procedure<T> procedure) {
3300 asyncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3304 public <T> void asyncRequest(MultiRead<T> request) {
3306 assert(request != null);
3308 asyncRequest(request, new SyncMultiProcedureAdapter<T>() {
3310 public void exception(ReadGraph graph, Throwable t) {
3311 t.printStackTrace();
3318 public <T> void asyncRequest(MultiRead<T> request, SyncMultiListener<T> procedure) {
3319 asyncRequest(request, (SyncMultiProcedure<T>)procedure);
3323 public <T> void asyncRequest(MultiRead<T> request, MultiListener<T> procedure) {
3324 asyncRequest(request, new NoneToSyncMultiListener<T>(procedure));
3328 public <T> void asyncRequest(MultiRead<T> request, SyncMultiProcedure<T> procedure) {
3329 scheduleRequest(request, procedure, null);
3333 public <T> void asyncRequest(MultiRead<T> request, MultiProcedure<T> procedure) {
3334 asyncRequest(request, new NoneToSyncMultiProcedure<T>(procedure));
3338 final public <T> void asyncRequest(AsyncMultiRead<T> request) {
3340 assert(request != null);
3342 asyncRequest(request, new AsyncMultiProcedureAdapter<T>() {
3344 public void exception(AsyncReadGraph graph, Throwable t) {
3345 t.printStackTrace();
3352 public <T> void asyncRequest(AsyncMultiRead<T> request, AsyncMultiListener<T> procedure) {
3353 asyncRequest(request, (AsyncMultiProcedure<T>)procedure);
3357 public <T> void asyncRequest(AsyncMultiRead<T> request, SyncMultiListener<T> procedure) {
3358 asyncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3362 public <T> void asyncRequest(AsyncMultiRead<T> request, MultiListener<T> procedure) {
3363 asyncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3367 public <T> void asyncRequest(AsyncMultiRead<T> request, SyncMultiProcedure<T> procedure) {
3368 asyncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3372 final public <T> void asyncRequest(AsyncMultiRead<T> request, final MultiProcedure<T> procedure) {
3373 asyncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3377 final public <T> void asyncRequest(final ExternalRead<T> request) {
3379 assert(request != null);
3381 asyncRequest(request, new ProcedureAdapter<T>() {
3383 public void exception(Throwable t) {
3384 t.printStackTrace();
3391 public <T> void asyncRequest(ExternalRead<T> request, final Listener<T> procedure) {
3392 asyncRequest(request, (Procedure<T>)procedure);
3395 boolean sameProvider(Write request) {
3396 if(writeState.getGraph().provider != null) {
3397 return writeState.getGraph().provider.equals(request.getProvider());
3399 return request.getProvider() == null;
3403 boolean plainWrite(WriteGraphImpl graph) {
3404 if(graph == null) return false;
3405 if(graph.writeSupport.writeOnly()) return false;
3410 public static final ThreadGroup SessionThreadGroup = new ThreadGroup("Session Thread Group");
3412 private void assertNotSession() throws DatabaseException {
3413 Thread current = Thread.currentThread();
3414 if (sessionThreads.contains(current))
3415 throw new ServiceException("Caller is already inside a transaction.");
3418 void assertAlive() {
3419 if (!state.isAlive())
3420 throw new RuntimeDatabaseException("Session has been shut down.");
3423 public InputStream getValueStream(ReadGraphImpl graph, Resource resource) {
3424 return querySupport.getValueStream(graph, querySupport.getId(resource));
3427 public byte[] getValue(ReadGraphImpl graph, Resource resource) {
3428 return querySupport.getValue(graph, querySupport.getId(resource));
3431 <T> void acquire(Semaphore semaphore, T request) throws DatabaseException {
3432 acquire(semaphore, request, null);
3435 private <T,P> void acquire(Semaphore semaphore, T request, P procedure) throws DatabaseException {
3439 // Loop until the semaphore is acquired reporting requests that take a long time.
3442 if (semaphore.tryAcquire(DebugPolicy.LONG_EXECUTION_REPORT_PERIOD, DebugPolicy.LONG_EXECUTION_REPORT_PERIOD_UNIT)) {
3446 if (DebugPolicy.REPORT_TIME_CONSUMING_REQUESTS) {
3448 long waitTime = DebugPolicy.LONG_EXECUTION_REPORT_PERIOD_UNIT
3449 .toMillis(DebugPolicy.LONG_EXECUTION_REPORT_PERIOD)
3451 System.err.println("DB client request '" + request + "' is taking long to execute, so far "
3452 + (waitTime) + " ms. (procedure=" + procedure + ")");
3459 } catch (InterruptedException e) {
3460 e.printStackTrace();
3461 // FIXME: Should perhaps do something else in this case ??
3468 // public boolean holdOnToTransactionAfterCancel() {
3469 // return transactionPolicy.holdOnToTransactionAfterCancel();
3473 // public boolean holdOnToTransactionAfterCommit() {
3474 // return transactionPolicy.holdOnToTransactionAfterCommit();
3478 // public boolean holdOnToTransactionAfterRead() {
3479 // return transactionPolicy.holdOnToTransactionAfterRead();
3483 // public void onRelinquish() {
3484 // transactionPolicy.onRelinquish();
3488 // public void onRelinquishDone() {
3489 // transactionPolicy.onRelinquishDone();
3493 // public void onRelinquishError() {
3494 // transactionPolicy.onRelinquishError();
3499 public Session getSession() {
3504 protected abstract VirtualGraph getProvider(VirtualGraph virtualGraph);
3505 protected abstract ResourceImpl getNewResource() throws DatabaseException;
3507 public void ceased(int thread) {
3509 requestManager.ceased(thread);
3513 public int getAmountOfQueryThreads() {
3514 // This must be a power of two
3516 // return Integer.highestOneBit(Runtime.getRuntime().availableProcessors());
3519 public Resource getResourceByKey(int key) throws ResourceNotFoundException {
3521 return new ResourceImpl(resourceSupport, key);
3525 public void acquireWriteOnly() {
3529 public void releaseWriteOnly(ReadGraphImpl graph) {
3531 queryProvider2.releaseWrite(graph);
3534 public void handleUpdatesAndMetadata(WriteGraphImpl writer) {
3536 long start = System.nanoTime();
3538 while(dirtyPrimitives) {
3539 dirtyPrimitives = false;
3540 getQueryProvider2().performDirtyUpdates(writer);
3541 getQueryProvider2().performScheduledUpdates(writer);
3544 fireMetadataListeners(writer, clientChanges);
3546 if(DebugPolicy.PERFORMANCE_DATA) {
3547 long end = System.nanoTime();
3548 System.err.println("handleUpdatesAndMetadata " + 1e-9*(end-start));
3553 void removeTemporaryData() {
3554 File platform = Platform.getLocation().toFile();
3555 File tempFiles = new File(platform, "tempFiles");
3556 File temp = new File(tempFiles, "db");
3560 Files.walkFileTree(temp.toPath(), new SimpleFileVisitor<Path>() {
3562 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
3565 } catch (IOException e) {
3566 Logger.defaultLogError(e);
3568 return FileVisitResult.CONTINUE;
3571 } catch (IOException e) {
3572 Logger.defaultLogError(e);
3576 public void handleCreatedClusters() {
3577 if ((serviceMode & SERVICE_MODE_CREATE) > 0) {
3578 createdClusters.forEach(new TLongProcedure() {
3581 public boolean execute(long value) {
3582 ClusterImpl cluster = clusterTable.getClusterByClusterId(value);
3583 cluster.setImmutable(true, clusterTranslator);
3588 createdClusters.clear();
3592 public Object getModificationCounter() {
3593 return queryProvider2.modificationCounter;
3597 public void markUndoPoint() {
3598 state.setCombine(false);