1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 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.Resource;
43 import org.simantics.db.ResourceSerializer;
44 import org.simantics.db.Session;
45 import org.simantics.db.SessionManager;
46 import org.simantics.db.SessionVariables;
47 import org.simantics.db.VirtualGraph;
48 import org.simantics.db.WriteGraph;
49 import org.simantics.db.authentication.UserAuthenticationAgent;
50 import org.simantics.db.authentication.UserAuthenticator;
51 import org.simantics.db.common.Indexing;
52 import org.simantics.db.common.TransactionPolicyRelease;
53 import org.simantics.db.common.procedure.adapter.AsyncMultiProcedureAdapter;
54 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
55 import org.simantics.db.common.procedure.wrapper.NoneToAsyncListener;
56 import org.simantics.db.common.procedure.wrapper.NoneToAsyncMultiListener;
57 import org.simantics.db.common.procedure.wrapper.NoneToAsyncMultiProcedure;
58 import org.simantics.db.common.procedure.wrapper.NoneToAsyncProcedure;
59 import org.simantics.db.common.procedure.wrapper.SyncToAsyncListener;
60 import org.simantics.db.common.procedure.wrapper.SyncToAsyncMultiListener;
61 import org.simantics.db.common.procedure.wrapper.SyncToAsyncMultiProcedure;
62 import org.simantics.db.common.procedure.wrapper.SyncToAsyncProcedure;
63 import org.simantics.db.common.service.ServiceActivityMonitorImpl;
64 import org.simantics.db.common.service.ServiceActivityUpdaterForWriteTransactions;
65 import org.simantics.db.common.utils.Logger;
66 import org.simantics.db.event.ChangeEvent;
67 import org.simantics.db.event.ChangeListener;
68 import org.simantics.db.event.SessionEventListener;
69 import org.simantics.db.exception.CancelTransactionException;
70 import org.simantics.db.exception.ClusterSetExistException;
71 import org.simantics.db.exception.DatabaseException;
72 import org.simantics.db.exception.ImmutableException;
73 import org.simantics.db.exception.InvalidResourceReferenceException;
74 import org.simantics.db.exception.ResourceNotFoundException;
75 import org.simantics.db.exception.RuntimeDatabaseException;
76 import org.simantics.db.exception.ServiceException;
77 import org.simantics.db.exception.ServiceNotFoundException;
78 import org.simantics.db.impl.ClusterBase;
79 import org.simantics.db.impl.ClusterI;
80 import org.simantics.db.impl.ClusterTraitsBase;
81 import org.simantics.db.impl.ClusterTranslator;
82 import org.simantics.db.impl.ResourceImpl;
83 import org.simantics.db.impl.TransientGraph;
84 import org.simantics.db.impl.VirtualGraphImpl;
85 import org.simantics.db.impl.graph.DelayedWriteGraph;
86 import org.simantics.db.impl.graph.ReadGraphImpl;
87 import org.simantics.db.impl.graph.WriteGraphImpl;
88 import org.simantics.db.impl.graph.WriteSupport;
89 import org.simantics.db.impl.internal.RandomAccessValueSupport;
90 import org.simantics.db.impl.procedure.ResultCallWrappedQueryProcedure4;
91 import org.simantics.db.impl.procedure.ResultCallWrappedSingleQueryProcedure4;
92 import org.simantics.db.impl.query.QueryProcessor;
93 import org.simantics.db.impl.query.QueryProcessor.SessionRead;
94 import org.simantics.db.impl.query.QueryProcessor.SessionTask;
95 import org.simantics.db.impl.service.QueryDebug;
96 import org.simantics.db.impl.support.VirtualGraphServerSupport;
97 import org.simantics.db.impl.support.WriteRequestScheduleSupport;
98 import org.simantics.db.procedure.AsyncListener;
99 import org.simantics.db.procedure.AsyncMultiListener;
100 import org.simantics.db.procedure.AsyncMultiProcedure;
101 import org.simantics.db.procedure.AsyncProcedure;
102 import org.simantics.db.procedure.Listener;
103 import org.simantics.db.procedure.ListenerBase;
104 import org.simantics.db.procedure.MultiListener;
105 import org.simantics.db.procedure.MultiProcedure;
106 import org.simantics.db.procedure.Procedure;
107 import org.simantics.db.procedure.SyncListener;
108 import org.simantics.db.procedure.SyncMultiListener;
109 import org.simantics.db.procedure.SyncMultiProcedure;
110 import org.simantics.db.procedure.SyncProcedure;
111 import org.simantics.db.procore.cluster.ClusterImpl;
112 import org.simantics.db.procore.cluster.ClusterTraits;
113 import org.simantics.db.procore.protocol.Constants;
114 import org.simantics.db.procore.protocol.DebugPolicy;
115 import org.simantics.db.request.AsyncMultiRead;
116 import org.simantics.db.request.AsyncRead;
117 import org.simantics.db.request.DelayedWrite;
118 import org.simantics.db.request.DelayedWriteResult;
119 import org.simantics.db.request.ExternalRead;
120 import org.simantics.db.request.MultiRead;
121 import org.simantics.db.request.Read;
122 import org.simantics.db.request.ReadInterface;
123 import org.simantics.db.request.Write;
124 import org.simantics.db.request.WriteInterface;
125 import org.simantics.db.request.WriteOnly;
126 import org.simantics.db.request.WriteOnlyResult;
127 import org.simantics.db.request.WriteResult;
128 import org.simantics.db.request.WriteTraits;
129 import org.simantics.db.service.ByteReader;
130 import org.simantics.db.service.ClusterBuilder;
131 import org.simantics.db.service.ClusterBuilderFactory;
132 import org.simantics.db.service.ClusterControl;
133 import org.simantics.db.service.ClusterSetsSupport;
134 import org.simantics.db.service.ClusterUID;
135 import org.simantics.db.service.ClusteringSupport;
136 import org.simantics.db.service.CollectionSupport;
137 import org.simantics.db.service.DebugSupport;
138 import org.simantics.db.service.DirectQuerySupport;
139 import org.simantics.db.service.EventSupport;
140 import org.simantics.db.service.GraphChangeListenerSupport;
141 import org.simantics.db.service.InitSupport;
142 import org.simantics.db.service.LifecycleSupport;
143 import org.simantics.db.service.ManagementSupport;
144 import org.simantics.db.service.QueryControl;
145 import org.simantics.db.service.SerialisationSupport;
146 import org.simantics.db.service.ServerInformation;
147 import org.simantics.db.service.ServiceActivityMonitor;
148 import org.simantics.db.service.SessionEventSupport;
149 import org.simantics.db.service.SessionMonitorSupport;
150 import org.simantics.db.service.SessionUserSupport;
151 import org.simantics.db.service.StatementSupport;
152 import org.simantics.db.service.TransactionPolicySupport;
153 import org.simantics.db.service.TransactionSupport;
154 import org.simantics.db.service.TransferableGraphSupport;
155 import org.simantics.db.service.UndoRedoSupport;
156 import org.simantics.db.service.VirtualGraphSupport;
157 import org.simantics.db.service.XSupport;
158 import org.simantics.layer0.Layer0;
159 import org.simantics.utils.DataContainer;
160 import org.simantics.utils.Development;
161 import org.simantics.utils.threads.logger.ITask;
162 import org.simantics.utils.threads.logger.ThreadLogger;
164 import gnu.trove.procedure.TLongProcedure;
165 import gnu.trove.set.hash.TLongHashSet;
168 public abstract class SessionImplSocket implements Session, WriteRequestScheduleSupport {
170 protected static final boolean DEBUG = false;
172 private static final boolean DIAGNOSTICS = false;
174 private TransactionPolicySupport transactionPolicy;
176 final private ClusterControl clusterControl;
178 final protected BuiltinSupportImpl builtinSupport;
179 final protected VirtualGraphServerSupportImpl virtualGraphServerSupport;
180 final protected ClusterSetsSupport clusterSetsSupport;
181 final protected LifecycleSupportImpl lifecycleSupport;
183 protected QuerySupportImpl querySupport;
184 protected ResourceSupportImpl resourceSupport;
185 protected WriteSupport writeSupport;
186 public ClusterTranslator clusterTranslator;
188 boolean dirtyPrimitives = false;
190 public static final int SERVICE_MODE_CREATE = 2;
191 public static final int SERVICE_MODE_ALLOW = 1;
192 public int serviceMode = 0;
193 public boolean createdImmutableClusters = false;
194 public TLongHashSet createdClusters = new TLongHashSet();
199 * The service locator maintained by the workbench. These services are
200 * initialized during workbench during the <code>init</code> method.
202 final protected ServiceLocatorImpl serviceLocator = new ServiceLocatorImpl();
204 final public ResourceSerializerImpl resourceSerializer = new ResourceSerializerImpl();
206 final CopyOnWriteArrayList<ChangeListener> changeListeners2 = new CopyOnWriteArrayList<ChangeListener>();
208 final CopyOnWriteArrayList<ChangeListener> metadataListeners = new CopyOnWriteArrayList<ChangeListener>();
210 final CopyOnWriteArrayList<SessionEventListener> eventListeners = new CopyOnWriteArrayList<SessionEventListener>();
212 final HashSet<Thread> sessionThreads = new HashSet<Thread>();
214 final BijectionMap<MonitorContext, MonitorHandler> monitorContexts = new BijectionMap<MonitorContext, MonitorHandler>();
216 final protected State state = new State();
218 protected GraphSession graphSession = null;
220 protected SessionManager sessionManagerImpl = null;
222 protected UserAuthenticationAgent authAgent = null;
224 protected UserAuthenticator authenticator = null;
226 protected Resource user = null;
228 protected ClusterStream clusterStream = null;
230 protected SessionRequestManager requestManager = null;
232 public ClusterTable clusterTable = null;
234 public QueryProcessor queryProvider2 = null;
236 ClientChangesImpl clientChanges = null;
238 MonitorHandler[] monitorHandlers = new MonitorHandler[0];
240 // protected long newClusterId = Constants.NullClusterId;
242 protected int flushCounter = 0;
244 protected boolean writeOnly = false;
246 WriteState<?> writeState = null;
247 WriteStateBase<?> delayedWriteState = null;
248 protected Resource defaultClusterSet = null; // If not null then used for newResource().
250 public SessionImplSocket(SessionManager sessionManagerImpl, UserAuthenticationAgent authAgent) {
252 // if (authAgent == null)
253 // throw new IllegalArgumentException("null authentication agent");
255 File t = StaticSessionProperties.virtualGraphStoragePath;
258 this.clusterTable = new ClusterTable(this, t);
259 this.builtinSupport = new BuiltinSupportImpl(this);
260 this.sessionManagerImpl = sessionManagerImpl;
262 // this.authAgent = authAgent;
264 serviceLocator.registerService(Session.class, this);
265 serviceLocator.registerService(InitSupport.class, new InitSupportImpl(this));
266 serviceLocator.registerService(ManagementSupport.class, new ManagementSupportImpl(this));
267 serviceLocator.registerService(QueryControl.class, new QueryControlImpl(this));
268 serviceLocator.registerService(SessionUserSupport.class, new SessionUserSupportImpl(this));
269 serviceLocator.registerService(GraphChangeListenerSupport.class, new GraphChangeListenerSupportImpl(this));
270 serviceLocator.registerService(SessionEventSupport.class, new SessionEventSupportImpl(this));
271 serviceLocator.registerService(SerialisationSupport.class, new SerialisationSupportImpl(this));
272 serviceLocator.registerService(UndoRedoSupport.class, new UndoRedoSupportImpl(this));
273 serviceLocator.registerService(ClusteringSupport.class, new ClusteringSupportImpl(this));
274 serviceLocator.registerService(TransactionSupport.class, new TransactionSupportImpl(this));
275 serviceLocator.registerService(SessionMonitorSupport.class, new SessionMonitorSupportImpl(this));
276 serviceLocator.registerService(TransferableGraphSupport.class, new TransferableGraphSupportImpl(this));
277 serviceLocator.registerService(QueryDebug.class, new QueryDebugImpl(this));
278 serviceLocator.registerService(CollectionSupport.class, new CollectionSupportImpl(this));
279 serviceLocator.registerService(StatementSupport.class, new StatementSupportImpl(this));
280 serviceLocator.registerService(DirectQuerySupport.class, new DirectQuerySupportImpl(this));
281 serviceLocator.registerService(XSupport.class, new XSupportImpl(this));
282 serviceLocator.registerService(DebugSupport.class, new DebugSupportImpl());
283 serviceLocator.registerService(ExternalValueSupport.class, new ExternalValueSupportImpl(this));
284 serviceLocator.registerService(RandomAccessValueSupport.class, new RandomAccessValueSupportImpl());
285 serviceLocator.registerService(ServiceActivityMonitor.class, new ServiceActivityMonitorImpl());
286 serviceLocator.registerService(EventSupport.class, new EventSupportImpl());
287 ServiceActivityUpdaterForWriteTransactions.register(this);
289 this.virtualGraphServerSupport = new VirtualGraphServerSupportImpl(this, t);
290 serviceLocator.registerService(VirtualGraphSupport.class, virtualGraphServerSupport);
291 serviceLocator.registerService(VirtualGraphServerSupport.class, virtualGraphServerSupport);
292 this.lifecycleSupport = new LifecycleSupportImpl(this);
293 serviceLocator.registerService(LifecycleSupport.class, lifecycleSupport);
294 this.transactionPolicy = new TransactionPolicyRelease();
295 serviceLocator.registerService(TransactionPolicySupport.class, transactionPolicy);
296 this.clusterControl = new ClusterControlImpl(this);
297 serviceLocator.registerService(ClusterControl.class, clusterControl);
298 this.clusterSetsSupport = new ClusterSetsSupportImpl2(); // Using same path as virtual graphs.
299 this.clusterSetsSupport.setReadDirectory(t.toPath());
300 this.clusterSetsSupport.updateWriteDirectory(t.toPath());
301 serviceLocator.registerService(ClusterSetsSupport.class, clusterSetsSupport);
311 public Resource getRootLibrary() {
312 return queryProvider2.getRootLibraryResource();
315 void refresh(int thread, ClusterUID[] clusterUID, long csid) throws DatabaseException {
316 if (!graphSession.dbSession.refreshEnabled())
319 getClusterTable().refresh(csid, this, clusterUID);
320 } catch (Throwable t) {
321 Logger.defaultLogError("Refesh failed.", t);
325 static final class TaskHelper {
326 private final String name;
327 private Object result;
328 final Semaphore sema = new Semaphore(0);
329 private Throwable throwable = null;
330 final Consumer<DatabaseException> callback = e -> {
331 synchronized (TaskHelper.this) {
335 final Procedure<Object> proc = new Procedure<Object>() {
337 public void execute(Object result) {
338 callback.accept(null);
341 public void exception(Throwable t) {
342 if (t instanceof DatabaseException)
343 callback.accept((DatabaseException)t);
345 callback.accept(new DatabaseException("" + name + "operation failed.", t));
348 final WriteTraits writeTraits = new WriteTraits() {};
349 TaskHelper(String name) {
352 @SuppressWarnings("unchecked")
356 void setResult(Object result) {
357 this.result = result;
359 // Throwable throwableGet() {
362 synchronized void throwableSet(Throwable t) {
365 // void throwableSet(String t) {
366 // throwable = new InternalException("" + name + " operation failed. " + t);
368 synchronized void throwableCheck()
369 throws DatabaseException {
370 if (null != throwable)
371 if (throwable instanceof DatabaseException)
372 throw (DatabaseException)throwable;
374 throw new DatabaseException("Undo operation failed.", throwable);
376 void throw_(String message)
377 throws DatabaseException {
378 throw new DatabaseException("" + name + " operation failed. " + message);
384 private ListenerBase getListenerBase(Object procedure) {
385 if (procedure instanceof ListenerBase)
386 return (ListenerBase) procedure;
391 public <T> void scheduleRequest(final Write request, final Consumer<DatabaseException> callback, final Semaphore notify) {
392 scheduleRequest(request, callback, notify, null);
396 * @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)
399 public <T> void scheduleRequest(final Write request, final Consumer<DatabaseException> callback, final Semaphore notify, Boolean combine) {
401 assert (request != null);
403 if(Development.DEVELOPMENT) {
405 if(Development.<Boolean>getProperty(DevelopmentKeys.SESSION_LOG_WRITES, Bindings.BOOLEAN))
406 System.err.println("schedule write '" + request + "'");
407 } catch (Throwable t) {
408 Logger.defaultLogError(t);
412 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
414 requestManager.scheduleWrite(new SessionTask(request, thread, thread) {
417 public void run(int thread) {
419 if(Development.DEVELOPMENT) {
421 if(Development.<Boolean>getProperty(DevelopmentKeys.SESSION_LOG_WRITES, Bindings.BOOLEAN))
422 System.err.println("perform write '" + request + "'");
423 } catch (Throwable t) {
424 Logger.defaultLogError(t);
428 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
430 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
435 Disposable.safeDispose(clientChanges);
436 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
438 VirtualGraph vg = getProvider(request.getProvider());
440 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
441 writeState = new WriteState<Object>(writer, request, notify, new Procedure<Object>() {
444 public void execute(Object result) {
445 if(callback != null) callback.accept(null);
449 public void exception(Throwable t) {
450 if(callback != null) callback.accept((DatabaseException)t);
455 assert (null != writer);
456 // writer.state.barrier.inc();
459 request.perform(writer);
460 assert (null != writer);
461 } catch (Throwable t) {
462 if (!(t instanceof CancelTransactionException))
463 Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", t);
464 writeState.except(t);
466 // writer.state.barrier.dec();
467 // writer.waitAsync(request);
471 assert(!queryProvider2.dirty);
473 } catch (Throwable e) {
475 // Log it first, just to be safe that the error is always logged.
476 if (!(e instanceof CancelTransactionException))
477 Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", e);
479 // writeState.getGraph().state.barrier.dec();
480 // writeState.getGraph().waitAsync(request);
482 writeState.except(e);
485 // // Callback is client code, we have to be prepared for it to throw unexpected exceptions.
486 // // All we can do here is to log those, can't really pass them anywhere.
487 // if (callback != null) {
488 // if(e instanceof DatabaseException) callback.run((DatabaseException)e);
489 // else callback.run(new DatabaseException(e));
491 // } catch (Throwable e2) {
492 // Logger.defaultLogError("Write request callback caused an unexpected error, see exception.", e2);
494 // boolean empty = clusterStream.reallyFlush();
495 // int callerThread = -1;
496 // ClientChangesImpl cs = new ClientChangesImpl(SessionImplSocket.this);
497 // SynchronizeContext context = new SynchronizeContext(callerThread, SessionImplSocket.this, cs, 1);
499 // // Send all local changes to server so it can calculate correct reverse change set.
500 // // This will call clusterStream.accept().
501 // state.cancelCommit(context, clusterStream);
503 // if (!context.isOk()) // this is a blocking operation
504 // throw new InternalException("Cancel failed. This should never happen. Contact application support.");
505 // getQueryProvider2().performDirtyUpdates(writeState.getGraph());
507 // state.cancelCommit2(context, clusterStream);
508 // } catch (DatabaseException e3) {
509 // Logger.defaultLogError("Write request cancel caused an unexpected error.", e3);
511 // clusterStream.setOff(false);
512 // clientChanges = new ClientChangesImpl(SessionImplSocket.this);
517 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
523 if(Development.DEVELOPMENT) {
525 if(Development.<Boolean>getProperty(DevelopmentKeys.SESSION_LOG_WRITES, Bindings.BOOLEAN))
526 System.err.println("finish write '" + request + "'");
527 } catch (Throwable t) {
528 Logger.defaultLogError(t);
538 public <T> void scheduleRequest(final WriteResult<T> request, final Procedure<T> procedure, final Semaphore notify) {
539 scheduleRequest(request, procedure, notify, null);
543 * @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)
546 public <T> void scheduleRequest(final WriteResult<T> request, final Procedure<T> procedure, final Semaphore notify, Boolean combine) {
548 assert (request != null);
550 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
552 requestManager.scheduleWrite(new SessionTask(request, thread) {
555 public void run(int thread) {
557 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
559 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
562 Disposable.safeDispose(clientChanges);
563 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
565 VirtualGraph vg = getProvider(request.getProvider());
566 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
569 WriteState<T> writeStateT = new WriteState<T>(writer, request, notify, procedure);
570 writeState = writeStateT;
572 assert (null != writer);
573 // writer.state.barrier.inc();
574 writeStateT.setResult(request.perform(writer));
575 assert (null != writer);
577 // writer.state.barrier.dec();
578 // writer.waitAsync(null);
580 } catch (Throwable e) {
582 // writer.state.barrier.dec();
583 // writer.waitAsync(null);
585 writeState.except(e);
587 // state.stopWriteTransaction(clusterStream);
589 // } catch (Throwable e) {
590 // // Log it first, just to be safe that the error is always logged.
591 // Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", e);
594 // // Callback is client code, we have to be prepared for it to throw unexpected exceptions.
595 // // All we can do here is to log those, can't really pass them anywhere.
596 // if (procedure != null) {
597 // if(e instanceof DatabaseException) procedure.exception((DatabaseException)e);
598 // else procedure.exception(new DatabaseException(e));
600 // } catch (Throwable e2) {
601 // Logger.defaultLogError("Write request callback caused an unexpected error, see exception.", e2);
604 // clientChanges = new ClientChangesImpl(SessionImplSocket.this);
606 // state.stopWriteTransaction(clusterStream);
609 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
612 // if(notify != null) notify.release();
622 public <T> void scheduleRequest(final DelayedWrite request, final Consumer<DatabaseException> callback, final Semaphore notify) {
623 scheduleRequest(request, callback, notify, null);
627 * @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)
630 public <T> void scheduleRequest(final DelayedWrite request, final Consumer<DatabaseException> callback, final Semaphore notify, Boolean combine) {
632 final ITask total = ThreadLogger.getInstance().begin("ScheduleDelayedWrite");
634 assert (request != null);
636 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
638 requestManager.scheduleWrite(new SessionTask(request, thread) {
641 public void run(int thread) {
642 fireSessionVariableChange(SessionVariables.QUEUED_READS);
644 Procedure<Object> stateProcedure = new Procedure<Object>() {
646 public void execute(Object result) {
647 if (callback != null)
648 callback.accept(null);
651 public void exception(Throwable t) {
652 if (callback != null) {
653 if (t instanceof DatabaseException) callback.accept((DatabaseException) t);
654 else callback.accept(new DatabaseException(t));
656 Logger.defaultLogError("Unhandled exception", t);
660 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
661 delayedWriteState = new WriteStateBase<Object>(request, notify, stateProcedure);
662 DelayedWriteGraph dwg = null;
663 // newGraph.state.barrier.inc();
666 dwg = new DelayedWriteGraph(newGraph);
667 request.perform(dwg);
668 } catch (Throwable e) {
669 delayedWriteState.except(e);
674 // newGraph.state.barrier.dec();
675 // newGraph.waitAsync(request);
676 fireSessionVariableChange(SessionVariables.QUEUED_READS);
679 delayedWriteState = null;
681 ITask task2 = ThreadLogger.getInstance().begin("DelayedWriteCommit");
682 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
685 Disposable.safeDispose(clientChanges);
686 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
690 VirtualGraph vg = getProvider(request.getProvider());
691 WriteSupport writeSupport = vg != null ? new VirtualWriteOnlySupport() : new WriteOnlySupport();
693 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
695 writeState = new WriteState<Object>(writer, request, notify, stateProcedure);
697 assert (null != writer);
698 // writer.state.barrier.inc();
702 dwg.commit(writer, request);
704 if(defaultClusterSet != null) {
705 XSupport xs = getService(XSupport.class);
706 defaultClusterSet = xs.convertDelayedResourceToResource(defaultClusterSet);
707 ClusteringSupport cs = getService(ClusteringSupport.class);
708 clusterSetsSupport.put(defaultClusterSet.getResourceId(), cs.getCluster(defaultClusterSet));
711 // This makes clusters available from server
712 clusterStream.reallyFlush();
714 releaseWriteOnly(writer);
715 handleUpdatesAndMetadata(writer);
717 } catch (ServiceException e) {
718 // writer.state.barrier.dec();
719 // writer.waitAsync(null);
721 // These shall be requested from server
722 clusterTable.removeWriteOnlyClusters();
723 // This makes clusters available from server
724 clusterStream.reallyFlush();
726 releaseWriteOnly(writer);
727 writeState.except(e);
729 // Debugging & Profiling
730 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
740 public <T> void scheduleRequest(final DelayedWriteResult<T> request, final Procedure<T> procedure, final Semaphore notify) {
741 scheduleRequest(request, procedure, notify, null);
745 * @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)
748 public <T> void scheduleRequest(final DelayedWriteResult<T> request, final Procedure<T> procedure, final Semaphore notify, Boolean combine) {
749 throw new Error("Not implemented");
752 protected ClusterImpl getNewResourceCluster() throws DatabaseException {
753 ClusterImpl cluster = clusterTable.getNewResourceCluster(clusterTranslator, graphSession, writeOnly);
754 if((serviceMode & SERVICE_MODE_CREATE) > 0) {
755 createdClusters.add(cluster.clusterId);
760 class WriteOnlySupport implements WriteSupport {
762 ClusterStream stream;
763 ClusterImpl currentCluster;
765 public WriteOnlySupport() {
766 this.stream = clusterStream;
770 public void claim(VirtualGraph provider, Resource subject, Resource predicate, Resource object) throws ServiceException {
771 claim(provider, ((ResourceImpl)subject).id, ((ResourceImpl)predicate).id, ((ResourceImpl)object).id );
775 public void claim(VirtualGraph provider, int s, int p, int o) throws ServiceException {
777 ClusterImpl cluster = clusterTable.getClusterByResourceKey(s);
779 if (cluster.getImmutable() && (serviceMode & SessionImplSocket.SERVICE_MODE_ALLOW) == 0)
780 if(s != queryProvider2.getRootLibrary())
781 throw new ImmutableException("Trying to modify immutable resource key=" + s);
784 maintainCluster(cluster, cluster.addRelation(s, p, o, clusterTranslator));
785 } catch (DatabaseException e) {
786 Logger.defaultLogError(e);
790 clientChanges.invalidate(s);
792 if (cluster.isWriteOnly())
794 queryProvider2.updateStatements(s, p);
799 public void claimValue(VirtualGraph provider, Resource resource, byte[] value) throws DatabaseException {
800 claimValue(provider, ((ResourceImpl)resource).id, value, value.length);
804 public void claimValue(VirtualGraph provider, int rid, byte[] value, int length) {
806 ClusterImpl cluster = clusterTable.getClusterByResourceKey(rid);
808 maintainCluster(cluster, cluster.setValue(rid, value, length, clusterTranslator));
809 } catch (DatabaseException e) {
810 Logger.defaultLogError(e);
813 clientChanges.invalidate(rid);
815 if (cluster.isWriteOnly())
817 queryProvider2.updateValue(rid);
822 public void claimValue(VirtualGraph provider, Resource resource, ByteReader reader, int amount) throws DatabaseException {
825 claimValue(provider,resource, reader.readBytes(null, amount));
829 byte[] bytes = new byte[65536];
831 int rid = ((ResourceImpl)resource).id;
832 ClusterImpl cluster = clusterTable.getClusterByResourceKey(rid);
836 int block = Math.min(left, 65536);
837 reader.readBytes(bytes, block);
838 maintainCluster(cluster, cluster.modiValueEx(rid, amount-left, block, bytes, 0, clusterTranslator));
841 } catch (DatabaseException e) {
842 Logger.defaultLogError(e);
845 clientChanges.invalidate(rid);
847 if (cluster.isWriteOnly())
849 queryProvider2.updateValue(rid);
853 private void maintainCluster(ClusterImpl before, ClusterI after_) {
854 if(after_ != null && after_ != before) {
855 ClusterImpl after = (ClusterImpl)after_;
856 if(currentCluster == before) {
857 currentCluster = after;
859 clusterTable.replaceCluster(after);
863 public int createResourceKey(int foreignCounter) throws DatabaseException {
864 if(currentCluster == null) {
865 currentCluster = getNewResourceCluster();
867 if(currentCluster.getNumberOfResources(clusterTranslator) == ClusterTable.CLUSTER_FILL_SIZE) {
868 ClusterWriteOnly newCluster = (ClusterWriteOnly)getNewResourceCluster();
869 newCluster.foreignLookup = new byte[foreignCounter];
870 currentCluster = newCluster;
872 System.err.println("foreignLookup " + currentCluster + " " + foreignCounter);
874 return currentCluster.createResource(clusterTranslator);
878 public Resource createResource(VirtualGraph provider) throws DatabaseException {
879 if(currentCluster == null) {
880 if (null != defaultClusterSet) {
881 ResourceImpl result = getNewResource(defaultClusterSet);
882 currentCluster = clusterTable.getClusterByResourceKey(result.id);
885 currentCluster = getNewResourceCluster();
888 if(currentCluster.getNumberOfResources(clusterTranslator) >= ClusterTable.CLUSTER_FILL_SIZE) {
889 if (null != defaultClusterSet) {
890 ResourceImpl result = getNewResource(defaultClusterSet);
891 currentCluster = clusterTable.getClusterByResourceKey(result.id);
894 currentCluster = getNewResourceCluster();
897 return new ResourceImpl(resourceSupport, currentCluster.createResource(clusterTranslator));
901 public Resource createResource(VirtualGraph provider, long clusterId)
902 throws DatabaseException {
903 return getNewResource(clusterId);
907 public Resource createResource(VirtualGraph provider, Resource clusterSet)
908 throws DatabaseException {
909 return getNewResource(clusterSet);
913 public void createClusterSet(VirtualGraph provider, Resource clusterSet)
914 throws DatabaseException {
915 getNewClusterSet(clusterSet);
919 public boolean hasClusterSet(VirtualGraph dummy, Resource clusterSet)
920 throws ServiceException {
921 return containsClusterSet(clusterSet);
924 public void selectCluster(long cluster) {
925 currentCluster = clusterTable.getClusterByClusterId(cluster);
926 long setResourceId = clusterSetsSupport.getSet(cluster);
927 clusterSetsSupport.put(setResourceId, cluster);
931 public Resource setDefaultClusterSet(Resource clusterSet)
932 throws ServiceException {
933 Resource result = setDefaultClusterSet4NewResource(clusterSet);
934 if(clusterSet != null) {
935 long id = clusterSetsSupport.get(clusterSet.getResourceId());
936 currentCluster = clusterTable.getClusterByClusterId(id);
939 currentCluster = null;
945 public void denyValue(VirtualGraph provider, Resource resource) throws ServiceException {
947 provider = getProvider(provider);
948 if (null == provider) {
949 int key = ((ResourceImpl)resource).id;
953 ClusterI cluster = clusterTable.getClusterProxyByResourceKey(key);
954 // if (cluster.getImmutable() && (serviceMode & SessionImplSocket.SERVICE_MODE_ALLOW) == 0)
955 // if(key != queryProvider2.getRootLibrary())
956 // throw new ImmutableException("Trying to modify immutable resource key=" + key);
959 // cluster.removeValue(key, clusterTranslator);
960 // } catch (DatabaseException e) {
961 // Logger.defaultLogError(e);
965 clusterTable.writeOnlyInvalidate(cluster);
968 int sResourceKey = ClusterTraits.getResourceIndexFromResourceKey(key);
969 clusterTranslator.addStatementIndex(cluster, sResourceKey, cluster.getClusterUID(), ClusterChange.DELETE_OPERATION);
970 clusterTranslator.removeValue(cluster);
971 } catch (DatabaseException e) {
972 Logger.defaultLogError(e);
975 queryProvider2.invalidateResource(key);
976 clientChanges.invalidate(key);
979 ((VirtualGraphImpl)provider).denyValue(((ResourceImpl) resource).id);
980 queryProvider2.updateValue(querySupport.getId(resource));
981 clientChanges.claimValue(resource);
988 public void flush(boolean intermediate) {
989 throw new UnsupportedOperationException();
993 public void flushCluster() {
994 clusterTable.flushCluster(graphSession);
995 if(defaultClusterSet != null) {
996 clusterSetsSupport.put(defaultClusterSet.getResourceId(), Constants.NewClusterId);
998 currentCluster = null;
1002 public void flushCluster(Resource r) {
1003 throw new UnsupportedOperationException("flushCluster resource " + r);
1011 public boolean removeStatement(VirtualGraph provider, Resource subject, Resource predicate,
1014 int s = ((ResourceImpl)subject).id;
1015 int p = ((ResourceImpl)predicate).id;
1016 int o = ((ResourceImpl)object).id;
1018 provider = getProvider(provider);
1019 if (null == provider) {
1021 ClusterI cluster = clusterTable.getClusterProxyByResourceKey(s);
1022 clusterTable.writeOnlyInvalidate(cluster);
1026 int sResourceKey = ClusterTraits.getResourceIndexFromResourceKey(s);
1028 ClusterI pc = clusterTable.getClusterProxyByResourceKey(p);
1029 ClusterI oc = clusterTable.getClusterProxyByResourceKey(o);
1031 clusterTranslator.addStatementIndex(cluster, sResourceKey, cluster.getClusterUID(), ClusterChange.REMOVE_OPERATION);
1032 clusterTranslator.addStatementIndex(cluster, p, pc.getClusterUID(), ClusterStream.NULL_OPERATION);
1033 clusterTranslator.addStatementIndex(cluster, o, oc.getClusterUID(), ClusterStream.NULL_OPERATION);
1034 clusterTranslator.removeStatement(cluster);
1036 queryProvider2.invalidateResource(s);
1037 clientChanges.invalidate(s);
1039 } catch (DatabaseException e) {
1041 Logger.defaultLogError(e);
1049 ((VirtualGraphImpl)provider).deny(s, p, o);
1050 queryProvider2.invalidateResource(s);
1051 clientChanges.invalidate(s);
1060 public void setValue(VirtualGraph provider, Resource resource, byte[] value) {
1061 throw new UnsupportedOperationException();
1065 public boolean writeOnly() {
1070 public void performWriteRequest(WriteGraph graph, Write request) throws DatabaseException {
1071 writeSupport.performWriteRequest(graph, request);
1075 public <T> T performWriteRequest(WriteGraph graph, WriteResult<T> request) throws DatabaseException {
1076 throw new UnsupportedOperationException();
1080 public void performWriteRequest(WriteGraph graph, WriteOnly request) throws DatabaseException {
1081 throw new UnsupportedOperationException();
1085 public <T> void addMetadata(Metadata data) throws ServiceException {
1086 writeSupport.addMetadata(data);
1090 public <T extends Metadata> T getMetadata(Class<T> clazz) throws ServiceException {
1091 return writeSupport.getMetadata(clazz);
1095 public TreeMap<String, byte[]> getMetadata() {
1096 return writeSupport.getMetadata();
1100 public void commitDone(WriteTraits writeTraits, long csid) {
1101 writeSupport.commitDone(writeTraits, csid);
1105 public void clearUndoList(WriteTraits writeTraits) {
1106 writeSupport.clearUndoList(writeTraits);
1109 public int clearMetadata() {
1110 return writeSupport.clearMetadata();
1114 public void startUndo() {
1115 writeSupport.startUndo();
1119 class VirtualWriteOnlySupport implements WriteSupport {
1122 // public void addStatement(VirtualGraph provider, Resource subject, Resource predicate,
1123 // Resource object) {
1124 // throw new UnsupportedOperationException();
1128 public void claim(VirtualGraph provider, Resource subject, Resource predicate, Resource object) {
1130 TransientGraph impl = (TransientGraph)provider;
1131 impl.claim(querySupport.getId(subject), querySupport.getId(predicate), querySupport.getId(object));
1132 getQueryProvider2().updateStatements(querySupport.getId(subject), querySupport.getId(predicate));
1133 clientChanges.claim(subject, predicate, object);
1138 public void claim(VirtualGraph provider, int subject, int predicate, int object) {
1140 TransientGraph impl = (TransientGraph)provider;
1141 impl.claim(subject, predicate, object);
1142 getQueryProvider2().updateStatements(subject, predicate);
1143 clientChanges.claim(subject, predicate, object);
1148 public void claimValue(VirtualGraph provider, Resource resource, byte[] value) throws DatabaseException {
1149 claimValue(provider, ((ResourceImpl)resource).id, value, value.length);
1153 public void claimValue(VirtualGraph provider, int resource, byte[] value, int length) {
1154 ((VirtualGraphImpl)provider).claimValue(resource, value, length);
1155 getQueryProvider2().updateValue(resource);
1156 clientChanges.claimValue(resource);
1160 public void claimValue(VirtualGraph provider, Resource resource, ByteReader reader, int amount) throws DatabaseException {
1161 byte[] value = reader.readBytes(null, amount);
1162 claimValue(provider, resource, value);
1166 public Resource createResource(VirtualGraph provider) {
1167 TransientGraph impl = (TransientGraph)provider;
1168 return impl.getResource(impl.newResource(false));
1172 public Resource createResource(VirtualGraph provider, long clusterId) {
1173 throw new UnsupportedOperationException();
1177 public Resource createResource(VirtualGraph provider, Resource clusterSet)
1178 throws DatabaseException {
1179 throw new UnsupportedOperationException();
1183 public void createClusterSet(VirtualGraph provider, Resource clusterSet)
1184 throws DatabaseException {
1185 throw new UnsupportedOperationException();
1189 public boolean hasClusterSet(VirtualGraph provider, Resource clusterSet)
1190 throws ServiceException {
1191 throw new UnsupportedOperationException();
1195 public Resource setDefaultClusterSet(Resource clusterSet)
1196 throws ServiceException {
1201 public void denyValue(VirtualGraph provider, Resource resource) {
1202 ((VirtualGraphImpl)provider).denyValue(((ResourceImpl) resource).id);
1203 getQueryProvider2().updateValue(querySupport.getId(resource));
1204 // NOTE: this only keeps track of value changes by-resource.
1205 clientChanges.claimValue(resource);
1209 public void flush(boolean intermediate) {
1210 throw new UnsupportedOperationException();
1214 public void flushCluster() {
1215 throw new UnsupportedOperationException();
1219 public void flushCluster(Resource r) {
1220 throw new UnsupportedOperationException("Resource " + r);
1228 public boolean removeStatement(VirtualGraph provider, Resource subject, Resource predicate, Resource object) {
1229 TransientGraph impl = (TransientGraph) provider;
1230 impl.deny(querySupport.getId(subject), querySupport.getId(predicate), querySupport.getId(object));
1231 getQueryProvider2().updateStatements(querySupport.getId(subject), querySupport.getId(predicate));
1232 clientChanges.deny(subject, predicate, object);
1237 public void setValue(VirtualGraph provider, Resource resource, byte[] value) {
1238 throw new UnsupportedOperationException();
1242 public boolean writeOnly() {
1247 public void performWriteRequest(WriteGraph graph, Write request) throws DatabaseException {
1248 throw new UnsupportedOperationException();
1252 public <T> T performWriteRequest(WriteGraph graph, WriteResult<T> request) throws DatabaseException {
1253 throw new UnsupportedOperationException();
1257 public void performWriteRequest(WriteGraph graph, WriteOnly request) throws DatabaseException {
1258 throw new UnsupportedOperationException();
1262 public <T> void addMetadata(Metadata data) throws ServiceException {
1263 throw new UnsupportedOperationException();
1267 public <T extends Metadata> T getMetadata(Class<T> clazz) throws ServiceException {
1268 throw new UnsupportedOperationException();
1272 public TreeMap<String, byte[]> getMetadata() {
1273 throw new UnsupportedOperationException();
1277 public void commitDone(WriteTraits writeTraits, long csid) {
1281 public void clearUndoList(WriteTraits writeTraits) {
1285 public int clearMetadata() {
1290 public void startUndo() {
1294 private <T> void performWriteOnly(WriteOnlyResult<T> request, Semaphore notify, Procedure<T> callback) {
1298 //int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1300 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
1303 Disposable.safeDispose(clientChanges);
1304 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
1308 WriteSupport writeSupport = request.getProvider() != null ? new VirtualWriteOnlySupport() : new WriteOnlySupport();
1310 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, request.getProvider());
1312 WriteState<T> writeStateT = new WriteState<T>(writer, request, notify, callback);
1313 writeState = writeStateT;
1315 assert (null != writer);
1316 // writer.state.barrier.inc();
1317 long start = System.nanoTime();
1318 T result = request.perform(writer);
1319 long duration = System.nanoTime() - start;
1321 System.err.println("################");
1322 System.err.println("WriteOnly duration " + 1e-9*duration);
1324 writeStateT.setResult(result);
1326 // This makes clusters available from server
1327 clusterStream.reallyFlush();
1329 // This will trigger query updates
1330 releaseWriteOnly(writer);
1331 assert (null != writer);
1333 handleUpdatesAndMetadata(writer);
1335 } catch (CancelTransactionException e) {
1337 releaseWriteOnly(writeState.getGraph());
1339 clusterTable.removeWriteOnlyClusters();
1340 state.stopWriteTransaction(clusterStream);
1342 } catch (Throwable e) {
1344 e.printStackTrace();
1346 releaseWriteOnly(writeState.getGraph());
1348 clusterTable.removeWriteOnlyClusters();
1350 if (callback != null)
1351 callback.exception(new DatabaseException(e));
1353 state.stopWriteTransaction(clusterStream);
1354 Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", e);
1358 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
1364 public <T> void scheduleRequest(final WriteOnly request, final Consumer<DatabaseException> callback, final Semaphore notify) {
1365 scheduleRequest(request, callback, notify, null);
1369 public <T> void scheduleRequest(final WriteOnly request, final Consumer<DatabaseException> callback, final Semaphore notify, Boolean combine) {
1373 assert (request != null);
1375 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1377 requestManager.scheduleWrite(new SessionTask(request, thread, thread) {
1380 public void run(int thread) {
1382 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
1386 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
1389 Disposable.safeDispose(clientChanges);
1390 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
1394 VirtualGraph vg = getProvider(request.getProvider());
1395 WriteSupport writeSupport = vg != null ? new VirtualWriteOnlySupport() : new WriteOnlySupport();
1397 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
1399 writeState = new WriteState<Object>(writer, request, notify, new Procedure<Object>() {
1402 public void execute(Object result) {
1403 if(callback != null) callback.accept(null);
1407 public void exception(Throwable t) {
1408 if(callback != null) callback.accept((DatabaseException)t);
1413 assert (null != writer);
1414 // writer.state.barrier.inc();
1418 request.perform(writer);
1420 } catch (Throwable e) {
1422 // writer.state.barrier.dec();
1423 // writer.waitAsync(null);
1425 releaseWriteOnly(writer);
1427 clusterTable.removeWriteOnlyClusters();
1429 if(!(e instanceof CancelTransactionException)) {
1430 if (callback != null)
1431 callback.accept(new DatabaseException(e));
1434 writeState.except(e);
1440 // This makes clusters available from server
1441 boolean empty = clusterStream.reallyFlush();
1442 // This was needed to make WO requests call metadata listeners.
1443 // NOTE: the calling event does not contain clientChanges information.
1444 if (!empty && clientChanges.isEmpty())
1445 clientChanges.setNotEmpty(true);
1446 releaseWriteOnly(writer);
1447 assert (null != writer);
1450 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
1463 public <T> void scheduleRequest(final WriteOnlyResult<T> request, final Procedure<T> callback, final Semaphore notify) {
1464 scheduleRequest(request, callback, notify, null);
1468 * @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)
1471 public <T> void scheduleRequest(final WriteOnlyResult<T> request, final Procedure<T> callback, final Semaphore notify, Boolean combine) {
1473 assert (request != null);
1475 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1477 requestManager.scheduleWrite(new SessionTask(request, thread) {
1480 public void run(int thread) {
1482 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
1484 performWriteOnly(request, notify, callback);
1494 public <T> void scheduleRequest(final Read<T> request, final AsyncProcedure<T> procedure, final Semaphore notify, final DataContainer<Throwable> throwable, final DataContainer<T> result) {
1496 assert (request != null);
1497 assert (procedure != null);
1499 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1501 requestManager.scheduleRead(new SessionRead(request, throwable, notify, thread, thread) {
1504 public void run(int thread) {
1506 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1508 ListenerBase listener = getListenerBase(procedure);
1510 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1514 if (listener != null) {
1517 newGraph.processor.queryRead(newGraph, request, null, new AsyncProcedure<T>() {
1520 public void exception(AsyncReadGraph graph, Throwable t) {
1521 procedure.exception(graph, t);
1522 if(throwable != null) {
1525 // ErrorLogger.defaultLogError("Unhandled exception", t);
1530 public void execute(AsyncReadGraph graph, T t) {
1531 if(result != null) result.set(t);
1532 procedure.execute(graph, t);
1536 } catch (Throwable t) {
1537 // This is handled by the AsyncProcedure
1538 //Logger.defaultLogError("Internal error", t);
1545 // newGraph.state.barrier.inc();
1547 T t = request.perform(newGraph);
1551 if(result != null) result.set(t);
1552 procedure.execute(newGraph, t);
1554 } catch (Throwable th) {
1556 if(throwable != null) {
1559 Logger.defaultLogError("Unhandled exception", th);
1564 } catch (Throwable t) {
1567 t.printStackTrace();
1569 if(throwable != null) {
1572 Logger.defaultLogError("Unhandled exception", t);
1577 procedure.exception(newGraph, t);
1579 } catch (Throwable t2) {
1581 if(throwable != null) {
1584 Logger.defaultLogError("Unhandled exception", t2);
1591 // newGraph.state.barrier.dec();
1592 // newGraph.waitAsync(request);
1598 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1608 public <T> void scheduleRequest(final AsyncRead<T> request, final AsyncProcedure<T> procedure, final ListenerBase listener, final Semaphore notify) {
1610 assert (request != null);
1611 assert (procedure != null);
1613 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1615 requestManager.scheduleRead(new SessionRead(request, null, notify, thread) {
1618 public void run(int thread) {
1620 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1622 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1626 if (listener != null) {
1628 newGraph.processor.query(newGraph, request, null, procedure, listener);
1630 // newGraph.waitAsync(request);
1634 final ResultCallWrappedSingleQueryProcedure4<T> wrapper = new ResultCallWrappedSingleQueryProcedure4<T>(
1635 procedure, "request");
1639 // newGraph.state.barrier.inc();
1641 request.perform(newGraph, wrapper);
1643 // newGraph.waitAsync(request);
1645 } catch (Throwable t) {
1647 wrapper.exception(newGraph, t);
1648 // newGraph.waitAsync(request);
1657 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1667 public <T> void scheduleRequest(final AsyncMultiRead<T> request, final AsyncMultiProcedure<T> procedure, final Semaphore notify) {
1669 assert (request != null);
1670 assert (procedure != null);
1672 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1674 int sync = notify != null ? thread : -1;
1676 requestManager.scheduleRead(new SessionRead(request, null, notify, thread, sync) {
1679 public void run(int thread) {
1681 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1683 ListenerBase listener = getListenerBase(procedure);
1685 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1689 if (listener != null) {
1691 newGraph.processor.query(newGraph, request, null, procedure, listener);
1693 // newGraph.waitAsync(request);
1697 final ResultCallWrappedQueryProcedure4<T> wrapper = new ResultCallWrappedQueryProcedure4<T>(procedure);
1701 request.perform(newGraph, wrapper);
1703 } catch (Throwable t) {
1705 t.printStackTrace();
1713 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1723 public <T> void scheduleRequest(final ExternalRead<T> request, final Procedure<T> procedure, final Semaphore notify, final DataContainer<Throwable> throwable, final DataContainer<T> result) {
1725 assert (request != null);
1726 assert (procedure != null);
1728 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1730 requestManager.scheduleRead(new SessionRead(request, throwable, notify, thread, thread) {
1733 public void run(int thread) {
1735 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1737 ListenerBase listener = getListenerBase(procedure);
1739 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1743 if (listener != null) {
1745 newGraph.processor.query(newGraph, request, null, new Procedure<T>() {
1748 public void exception(Throwable t) {
1749 procedure.exception(t);
1750 if(throwable != null) {
1756 public void execute(T t) {
1757 if(result != null) result.set(t);
1758 procedure.execute(t);
1763 // newGraph.waitAsync(request);
1767 // newGraph.state.barrier.inc();
1769 request.register(newGraph, new Listener<T>() {
1772 public void exception(Throwable t) {
1773 if(throwable != null) throwable.set(t);
1774 procedure.exception(t);
1775 // newGraph.state.barrier.dec();
1779 public void execute(T t) {
1780 if(result != null) result.set(t);
1781 procedure.execute(t);
1782 // newGraph.state.barrier.dec();
1786 public boolean isDisposed() {
1792 // newGraph.waitAsync(request);
1798 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1810 public <T> void asyncRequest(final Read<T> request, final AsyncProcedure<T> procedure) {
1812 scheduleRequest(request, procedure, null, null, null);
1817 public <T> T syncRequest(Read<T> request, AsyncProcedure<T> procedure) throws DatabaseException {
1819 Semaphore notify = new Semaphore(0);
1820 DataContainer<Throwable> container = new DataContainer<Throwable>();
1821 DataContainer<T> result = new DataContainer<T>();
1822 scheduleRequest(request, procedure, notify, container, result);
1823 acquire(notify, request);
1824 Throwable throwable = container.get();
1825 if(throwable != null) {
1826 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1827 else throw new DatabaseException("Unexpected exception", throwable);
1829 return result.get();
1833 public <T> T syncRequest(AsyncRead<T> request, final AsyncProcedure<T> procedure) throws DatabaseException {
1835 Semaphore notify = new Semaphore(0);
1836 final DataContainer<Throwable> exceptionContainer = new DataContainer<Throwable>();
1837 final DataContainer<T> resultContainer = new DataContainer<T>();
1838 scheduleRequest(request, new AsyncProcedure<T>() {
1840 public void exception(AsyncReadGraph graph, Throwable throwable) {
1841 exceptionContainer.set(throwable);
1842 procedure.exception(graph, throwable);
1845 public void execute(AsyncReadGraph graph, T result) {
1846 resultContainer.set(result);
1847 procedure.execute(graph, result);
1849 }, getListenerBase(procedure), notify);
1850 acquire(notify, request, procedure);
1851 Throwable throwable = exceptionContainer.get();
1852 if (throwable != null) {
1853 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1854 else throw new DatabaseException("Unexpected exception", throwable);
1856 return resultContainer.get();
1861 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, final AsyncMultiProcedure<T> procedure) throws DatabaseException {
1863 Semaphore notify = new Semaphore(0);
1864 final DataContainer<Throwable> exceptionContainer = new DataContainer<Throwable>();
1865 scheduleRequest(request, new AsyncMultiProcedure<T>() {
1867 public void exception(AsyncReadGraph graph, Throwable throwable) {
1868 exceptionContainer.set(throwable);
1869 procedure.exception(graph, throwable);
1872 public void execute(AsyncReadGraph graph, T result) {
1873 procedure.execute(graph, result);
1876 public void finished(AsyncReadGraph graph) {
1877 procedure.finished(graph);
1880 acquire(notify, request, procedure);
1881 Throwable throwable = exceptionContainer.get();
1882 if (throwable != null) {
1883 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1884 else throw new DatabaseException("Unexpected exception", throwable);
1886 // TODO: implement return value
1887 System.err.println("TODO: implement return value for syncRequest(AsyncMultiRead, AsyncMultiProcedure)");
1892 public <T> T syncRequest(final ExternalRead<T> request) throws DatabaseException {
1893 return syncRequest(request, new ProcedureAdapter<T>());
1896 // assert(request != null);
1898 // final DataContainer<T> result = new DataContainer<T>();
1899 // final DataContainer<Throwable> exception = new DataContainer<Throwable>();
1901 // syncRequest(request, new Procedure<T>() {
1904 // public void execute(T t) {
1909 // public void exception(Throwable t) {
1910 // exception.set(t);
1915 // Throwable t = exception.get();
1917 // if(t instanceof DatabaseException) throw (DatabaseException)t;
1918 // else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(PrimitiveRead)", t);
1921 // return result.get();
1926 public <T> T syncRequest(ExternalRead<T> request, final Listener<T> procedure) throws DatabaseException {
1927 return syncRequest(request, (Procedure<T>)procedure);
1932 // public <T> T syncRequest(Read<T> request, AsyncProcedure<T> procedure) throws DatabaseException {
1933 // assertNotSession();
1934 // Semaphore notify = new Semaphore(0);
1935 // DataContainer<Throwable> container = new DataContainer<Throwable>();
1936 // DataContainer<T> result = new DataContainer<T>();
1937 // scheduleRequest(request, procedure, notify, container, result);
1938 // acquire(notify, request);
1939 // Throwable throwable = container.get();
1940 // if(throwable != null) {
1941 // if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1942 // else throw new DatabaseException("Unexpected exception", throwable);
1944 // return result.get();
1949 public <T> T syncRequest(ExternalRead<T> request, final Procedure<T> procedure) throws DatabaseException {
1951 Semaphore notify = new Semaphore(0);
1952 final DataContainer<Throwable> container = new DataContainer<Throwable>();
1953 final DataContainer<T> result = new DataContainer<T>();
1954 scheduleRequest(request, procedure, notify, container, result);
1955 acquire(notify, request);
1956 Throwable throwable = container.get();
1957 if (throwable != null) {
1958 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1959 else throw new DatabaseException("Unexpected exception", throwable);
1961 return result.get();
1965 public void syncRequest(Write request) throws DatabaseException {
1968 Semaphore notify = new Semaphore(0);
1969 final DataContainer<DatabaseException> exception = new DataContainer<DatabaseException>();
1970 scheduleRequest(request, e -> exception.set(e), notify);
1971 acquire(notify, request);
1972 if(exception.get() != null) throw exception.get();
1976 public <T> T syncRequest(WriteResult<T> request) throws DatabaseException {
1978 Semaphore notify = new Semaphore(0);
1979 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
1980 final DataContainer<T> result = new DataContainer<T>();
1981 scheduleRequest(request, new Procedure<T>() {
1984 public void exception(Throwable t) {
1989 public void execute(T t) {
1994 acquire(notify, request);
1995 if(exception.get() != null) {
1996 Throwable t = exception.get();
1997 if(t instanceof DatabaseException) throw (DatabaseException)t;
1998 else throw new DatabaseException(t);
2000 return result.get();
2004 public <T> T syncRequest(WriteOnlyResult<T> request) throws DatabaseException {
2006 Semaphore notify = new Semaphore(0);
2007 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2008 final DataContainer<T> result = new DataContainer<T>();
2009 scheduleRequest(request, new Procedure<T>() {
2012 public void exception(Throwable t) {
2017 public void execute(T t) {
2022 acquire(notify, request);
2023 if(exception.get() != null) {
2024 Throwable t = exception.get();
2025 if(t instanceof DatabaseException) throw (DatabaseException)t;
2026 else throw new DatabaseException(t);
2028 return result.get();
2032 public <T> T syncRequest(DelayedWriteResult<T> request) throws DatabaseException {
2034 Semaphore notify = new Semaphore(0);
2035 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2036 final DataContainer<T> result = new DataContainer<T>();
2037 scheduleRequest(request, new Procedure<T>() {
2040 public void exception(Throwable t) {
2045 public void execute(T t) {
2050 acquire(notify, request);
2051 if(exception.get() != null) {
2052 Throwable t = exception.get();
2053 if(t instanceof DatabaseException) throw (DatabaseException)t;
2054 else throw new DatabaseException(t);
2056 return result.get();
2060 public void syncRequest(DelayedWrite request) throws DatabaseException {
2062 Semaphore notify = new Semaphore(0);
2063 final DataContainer<DatabaseException> exception = new DataContainer<DatabaseException>();
2064 scheduleRequest(request, e -> exception.set(e), notify);
2065 acquire(notify, request);
2066 if(exception.get() != null) throw exception.get();
2070 public void syncRequest(WriteOnly request) throws DatabaseException {
2073 Semaphore notify = new Semaphore(0);
2074 final DataContainer<DatabaseException> exception = new DataContainer<DatabaseException>();
2075 scheduleRequest(request, e -> exception.set(e), notify);
2076 acquire(notify, request);
2077 if(exception.get() != null) throw exception.get();
2082 * GraphRequestProcessor interface
2086 public <T> void asyncRequest(final AsyncRead<T> request, final AsyncProcedure<T> procedure) {
2088 scheduleRequest(request, procedure, null, null);
2093 public <T> void asyncRequest(final AsyncMultiRead<T> request, final AsyncMultiProcedure<T> procedure) {
2095 scheduleRequest(request, procedure, null);
2100 public <T> void asyncRequest(final ExternalRead<T> request, final Procedure<T> procedure) {
2102 scheduleRequest(request, procedure, null, null, null);
2107 public void asyncRequest(final Write request, final Consumer<DatabaseException> callback) {
2109 scheduleRequest(request, callback, null);
2114 public <T> void asyncRequest(final WriteResult<T> request, final Procedure<T> procedure) {
2116 scheduleRequest(request, procedure, null);
2121 public <T> void asyncRequest(final WriteOnlyResult<T> request, final Procedure<T> procedure) {
2123 scheduleRequest(request, procedure, null);
2128 public <T> void asyncRequest(final DelayedWriteResult<T> request, final Procedure<T> procedure) {
2130 scheduleRequest(request, procedure, null);
2135 public void asyncRequest(final DelayedWrite request, final Consumer<DatabaseException> callback) {
2137 scheduleRequest(request, callback, null);
2142 public void asyncRequest(final Write r) {
2143 asyncRequest(r, null);
2147 public void asyncRequest(final DelayedWrite r) {
2148 asyncRequest(r, null);
2152 public void asyncRequest(final WriteOnly request, final Consumer<DatabaseException> callback) {
2154 scheduleRequest(request, callback, null);
2159 public void asyncRequest(final WriteOnly request) {
2161 asyncRequest(request, null);
2166 public <T> void async(ReadInterface<T> r, AsyncProcedure<T> procedure) {
2167 r.request(this, procedure);
2171 public <T> void async(ReadInterface<T> r, Procedure<T> procedure) {
2172 r.request(this, procedure);
2176 public <T> void async(ReadInterface<T> r, SyncProcedure<T> procedure) {
2177 r.request(this, procedure);
2181 public <T> void async(ReadInterface<T> r, AsyncListener<T> procedure) {
2182 r.request(this, procedure);
2186 public <T> void async(ReadInterface<T> r, Listener<T> procedure) {
2187 r.request(this, procedure);
2191 public <T> void async(ReadInterface<T> r, SyncListener<T> procedure) {
2192 r.request(this, procedure);
2196 public <T> T sync(ReadInterface<T> r) throws DatabaseException {
2197 return r.request(this);
2201 public <T> T sync(WriteInterface<T> r) throws DatabaseException {
2202 return r.request(this);
2206 public <T> void async(WriteInterface<T> r, Procedure<T> procedure) {
2207 r.request(this, procedure);
2211 public <T> void async(WriteInterface<T> r) {
2212 r.request(this, new ProcedureAdapter<T>());
2216 public void incAsync() {
2221 public void decAsync() {
2225 public long getCluster(ResourceImpl resource) {
2226 ClusterI cluster = clusterTable.getClusterByResourceKey(resource.id);
2227 return cluster.getClusterId();
2230 public long getCluster(int id) {
2231 if (clusterTable == null)
2232 System.out.println("SessionImplSocket.getCluster() clusterTable == null !!!!! how come");
2233 return clusterTable.getClusterIdByResourceKeyNoThrow(id);
2236 public ResourceImpl getResource(int id) {
2237 return new ResourceImpl(resourceSupport, id);
2240 public ResourceImpl getResource(int resourceIndex, long clusterId) {
2241 assert (!ClusterTraitsBase.isIllegalResourceIndex(resourceIndex));
2242 ClusterI proxy = clusterTable.getClusterByClusterId(clusterId);
2243 int key = proxy.getClusterKey();
2244 int resourceKey = ClusterTraitsBase.createResourceKeyNoThrow(key, resourceIndex);
2245 return new ResourceImpl(resourceSupport, resourceKey);
2248 public ResourceImpl getResource2(int id) {
2250 return new ResourceImpl(resourceSupport, id);
2253 final public int getId(ResourceImpl impl) {
2257 public static final Charset UTF8 = Charset.forName("utf-8");
2262 static boolean areVirtualStatementsLoaded(final VirtualGraphServerSupportImpl support, int subject) {
2263 for(TransientGraph g : support.providers) {
2264 if(g.isPending(subject)) return false;
2269 static boolean areVirtualStatementsLoaded(final VirtualGraphServerSupportImpl support, int subject, int predicate) {
2270 for(TransientGraph g : support.providers) {
2271 if(g.isPending(subject, predicate)) return false;
2276 static void loadVirtualStatements(final VirtualGraphServerSupportImpl support, ReadGraphImpl graph, int subject, final Consumer<ReadGraphImpl> runnable) {
2278 Consumer<ReadGraphImpl> composite = new Consumer<ReadGraphImpl>() {
2280 AtomicInteger ready = new AtomicInteger(support.providers.size() + 1);
2283 public void accept(ReadGraphImpl graph) {
2284 if(ready.decrementAndGet() == 0) {
2285 runnable.accept(graph);
2291 for(TransientGraph g : support.providers) {
2292 if(g.isPending(subject)) {
2294 g.load(graph, subject, composite);
2295 } catch (DatabaseException e) {
2296 e.printStackTrace();
2299 composite.accept(graph);
2303 composite.accept(graph);
2307 static void loadVirtualStatements(final VirtualGraphServerSupportImpl support, ReadGraphImpl graph, int subject, int predicate, final Consumer<ReadGraphImpl> runnable) {
2309 Consumer<ReadGraphImpl> composite = new Consumer<ReadGraphImpl>() {
2311 AtomicInteger ready = new AtomicInteger(support.providers.size() + 1);
2314 public void accept(ReadGraphImpl graph) {
2315 if(ready.decrementAndGet() == 0) {
2316 runnable.accept(graph);
2322 for(TransientGraph g : support.providers) {
2323 if(g.isPending(subject, predicate)) {
2325 g.load(graph, subject, predicate, composite);
2326 } catch (DatabaseException e) {
2327 e.printStackTrace();
2330 composite.accept(graph);
2334 composite.accept(graph);
2338 // void dumpHeap() {
2341 // ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
2342 // "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class).dumpHeap(
2343 // "d:/heap" + flushCounter + ".txt", true);
2344 // } catch (IOException e) {
2345 // e.printStackTrace();
2350 void fireReactionsToSynchronize(ChangeSet cs) {
2352 // Do not fire empty events
2356 ReadGraphImpl g = ReadGraphImpl.create(getQueryProvider2());
2357 // g.state.barrier.inc();
2361 if (!cs.isEmpty()) {
2362 ChangeEvent e2 = new ChangeEvent(g.getSession(), g, null, cs);
2363 for (ChangeListener l : changeListeners2) {
2366 } catch (Exception ex) {
2367 ex.printStackTrace();
2374 // g.state.barrier.dec();
2375 // g.waitAsync(null);
2381 void fireReactionsToCommit(ReadGraphImpl graph, ChangeSet cs2) {
2384 // Do not fire empty events
2389 // graph.state.barrier.inc();
2393 if (!cs2.isEmpty()) {
2395 ChangeEvent e2 = new ChangeEvent(graph.getSession(), graph, null, cs2);
2396 for (ChangeListener l : changeListeners2) {
2399 // System.out.println("changelistener " + l);
2400 } catch (Exception ex) {
2401 ex.printStackTrace();
2409 // graph.state.barrier.dec();
2410 // graph.waitAsync(null);
2413 } catch (Throwable t) {
2414 t.printStackTrace();
2418 void fireMetadataListeners(WriteGraphImpl graph, ChangeSet cs2) {
2422 // Do not fire empty events
2426 // Do not fire on virtual requests
2427 if(graph.getProvider() != null)
2430 WriteGraphImpl reactionGraph = WriteGraphImpl.create(graph.processor, writeSupport, null);
2434 ChangeEvent e2 = new ChangeEvent(graph.getSession(), reactionGraph, graph, cs2);
2435 for (ChangeListener l : metadataListeners) {
2438 } catch (Throwable ex) {
2439 ex.printStackTrace();
2447 } catch (Throwable t) {
2448 t.printStackTrace();
2457 * @see org.simantics.db.ServiceLocator#getService(java.lang.Class)
2460 public <T> T getService(Class<T> api) {
2461 T t = peekService(api);
2463 if (state.isClosed())
2464 throw new ServiceNotFoundException(this, api, "Session has been shut down");
2465 throw new ServiceNotFoundException(this, api);
2473 protected abstract ServerInformation getCachedServerInformation();
2475 private Class<?> serviceKey1 = null;
2476 private Class<?> serviceKey2 = null;
2477 private Object service1 = null;
2478 private Object service2 = null;
2484 * fi.vtt.simantics.db.connection.ServiceLocator#peekService(java.lang.Class)
2486 @SuppressWarnings("unchecked")
2488 public synchronized <T> T peekService(Class<T> api) {
2490 if(serviceKey1 == api) {
2492 } else if (serviceKey2 == api) {
2494 Object result = service2;
2495 service2 = service1;
2496 serviceKey2 = serviceKey1;
2502 if (Layer0.class == api)
2504 if (ServerInformation.class == api)
2505 return (T) getCachedServerInformation();
2506 else if (WriteGraphImpl.class == api)
2507 return (T) writeState.getGraph();
2508 else if (ClusterBuilder.class == api)
2509 return (T)new ClusterBuilderImpl(this, (WriteOnlySupport)writeState.getGraph().writeSupport);
2510 else if (ClusterBuilderFactory.class == api)
2511 return (T)new ClusterBuilderFactoryImpl(this);
2513 service2 = service1;
2514 serviceKey2 = serviceKey1;
2516 service1 = serviceLocator.peekService(api);
2527 * fi.vtt.simantics.db.connection.ServiceLocator#hasService(java.lang.Class)
2530 public boolean hasService(Class<?> api) {
2531 return serviceLocator.hasService(api);
2535 * @param api the api that must be implemented by the specified service
2536 * @param service the service implementation
2539 public <T> void registerService(Class<T> api, T service) {
2540 if(Layer0.class == api) {
2541 L0 = (Layer0)service;
2544 serviceLocator.registerService(api, service);
2545 if (TransactionPolicySupport.class == api) {
2546 transactionPolicy = (TransactionPolicySupport)service;
2547 state.resetTransactionPolicy();
2549 if (api == serviceKey1)
2551 else if (api == serviceKey2)
2559 void fireSessionVariableChange(String variable) {
2560 for (MonitorHandler h : monitorHandlers) {
2561 MonitorContext ctx = monitorContexts.getLeft(h);
2563 // SafeRunner functionality repeated here to avoid dependency.
2565 h.valuesChanged(ctx);
2566 } catch (Exception e) {
2567 Logger.defaultLogError("monitor handler notification produced the following exception", e);
2568 } catch (LinkageError e) {
2569 Logger.defaultLogError("monitor handler notification produced a linkage error", e);
2575 class ResourceSerializerImpl implements ResourceSerializer {
2577 public long createRandomAccessId(int id) throws DatabaseException {
2580 int index = ClusterTraitsBase.getResourceIndexFromResourceKey(id);
2581 long cluster = getCluster(id);
2583 return 0; // Better to return 0 then invalid id.
2584 long result = ClusterTraitsBase.createResourceId(cluster, index);
2589 public long getRandomAccessId(Resource resource) throws DatabaseException {
2591 ResourceImpl resourceImpl = (ResourceImpl) resource;
2592 return createRandomAccessId(resourceImpl.id);
2597 public int getTransientId(Resource resource) throws DatabaseException {
2599 ResourceImpl resourceImpl = (ResourceImpl) resource;
2600 return resourceImpl.id;
2605 public String createRandomAccessId(Resource resource)
2606 throws InvalidResourceReferenceException {
2608 if(resource == null) throw new IllegalArgumentException();
2610 ResourceImpl resourceImpl = (ResourceImpl) resource;
2612 if (resourceImpl.id < 0) return String.valueOf(resourceImpl.id) + "_0";
2616 r = ClusterTraits.getResourceIndexFromResourceKey(resourceImpl.id);
2617 } catch (DatabaseException e1) {
2618 throw new InvalidResourceReferenceException(e1);
2621 // Serialize as '<resource index>_<cluster id>'
2622 return "" + r + "_" + getCluster(resourceImpl);
2623 } catch (Throwable e) {
2624 e.printStackTrace();
2625 throw new InvalidResourceReferenceException(e);
2630 public int getTransientId(long serialized) throws DatabaseException {
2631 if (serialized <= 0)
2632 return (int)serialized;
2633 int index = ClusterTraitsBase.getResourceIndexFromResourceId(serialized);
2634 long c = ClusterTraitsBase.getClusterIdFromResourceId(serialized);
2635 ClusterI cluster = clusterTranslator.getClusterByClusterId(c);
2636 if (cluster == null)
2637 throw new DatabaseException("Couldn't load cluster for id " + c + " for resource id " + serialized);
2638 int key = ClusterTraits.createResourceKey(cluster.getClusterKey(), index);
2643 public Resource getResource(long randomAccessId) throws DatabaseException {
2644 return getResourceByKey(getTransientId(randomAccessId));
2648 public Resource getResource(int transientId) throws DatabaseException {
2649 return getResourceByKey(transientId);
2653 public Resource getResource(String randomAccessId)
2654 throws InvalidResourceReferenceException {
2656 int i = randomAccessId.indexOf('_');
2658 throw new InvalidResourceReferenceException("Could not parse resource id + cluster id from '"
2659 + randomAccessId + "'");
2660 int r = Integer.parseInt(randomAccessId.substring(0, i));
2661 if(r < 0) return getResourceByKey(r);
2662 long c = Long.parseLong(randomAccessId.substring(i + 1));
2663 ClusterI cluster = clusterTranslator.getClusterByClusterId(c);
2664 int key = ClusterTraits.createResourceKey(cluster.getClusterKey(), r);
2665 if (cluster.hasResource(key, clusterTranslator))
2666 return getResourceByKey(key);
2667 } catch (InvalidResourceReferenceException e) {
2669 } catch (NumberFormatException e) {
2670 throw new InvalidResourceReferenceException(e);
2671 } catch (Throwable e) {
2672 e.printStackTrace();
2673 throw new InvalidResourceReferenceException(e);
2676 throw new InvalidResourceReferenceException("Resource does not exist " + randomAccessId);
2680 public boolean disposeRandomAccessId(String randomAccessId) throws InvalidResourceReferenceException {
2683 } catch (Throwable e) {
2684 e.printStackTrace();
2685 throw new InvalidResourceReferenceException(e);
2691 // Copied from old SessionImpl
2694 if (state.isClosed())
2695 throw new Error("Session closed.");
2700 public ResourceImpl getNewResource(long clusterId) {
2701 ClusterI cluster = clusterTable.getClusterByClusterIdOrThrow(clusterId);
2704 newId = cluster.createResource(clusterTranslator);
2705 } catch (DatabaseException e) {
2706 Logger.defaultLogError(e);
2709 return new ResourceImpl(resourceSupport, newId);
2712 public ResourceImpl getNewResource(Resource clusterSet)
2713 throws DatabaseException {
2714 long resourceId = clusterSet.getResourceId();
2715 Long clusterId = clusterSetsSupport.get(resourceId);
2716 if (null == clusterId)
2717 throw new ClusterSetExistException("Cluster set does not exist. Resource=" + clusterSet);
2718 if (Constants.NewClusterId == clusterId) {
2719 clusterId = getService(ClusteringSupport.class).createCluster();
2720 if ((serviceMode & SERVICE_MODE_CREATE) > 0)
2721 createdClusters.add(clusterId);
2722 clusterSetsSupport.put(resourceId, clusterId);
2723 return getNewResource(clusterId);
2725 ClusterBase cb = clusterTranslator.getClusterByClusterId(clusterId);
2726 ResourceImpl result;
2727 if (cb.getNumberOfResources(clusterTranslator) >= ClusterTable.CLUSTER_FILL_SIZE) {
2728 clusterId = getService(ClusteringSupport.class).createCluster();
2729 if ((serviceMode & SERVICE_MODE_CREATE) > 0)
2730 createdClusters.add(clusterId);
2731 clusterSetsSupport.put(resourceId, clusterId);
2732 return getNewResource(clusterId);
2734 result = getNewResource(clusterId);
2735 int resultKey = querySupport.getId(result);
2736 long resultCluster = querySupport.getClusterId(resultKey);
2737 if (clusterId != resultCluster)
2738 clusterSetsSupport.put(resourceId, resultCluster);
2744 public void getNewClusterSet(Resource clusterSet)
2745 throws DatabaseException {
2747 System.out.println("new cluster set=" + clusterSet);
2748 long resourceId = clusterSet.getResourceId();
2749 if (clusterSetsSupport.containsKey(resourceId))
2750 throw new ClusterSetExistException("Cluster set exist already. Resource=" + clusterSet);
2751 clusterSetsSupport.put(resourceId, Constants.NewClusterId);
2753 public boolean containsClusterSet(Resource clusterSet)
2754 throws ServiceException {
2755 long resourceId = clusterSet.getResourceId();
2756 return clusterSetsSupport.containsKey(resourceId);
2758 public Resource setDefaultClusterSet4NewResource(Resource clusterSet) {
2759 Resource r = defaultClusterSet;
2760 defaultClusterSet = clusterSet;
2763 void printDiagnostics() {
2767 final DataContainer<Long> totalMem = new DataContainer<Long>(0L);
2768 final DataContainer<Long> residentClusters = new DataContainer<Long>(0L);
2769 for(ClusterI cluster : clusterTable.getClusters()) {
2771 if (cluster.isLoaded() && !cluster.isEmpty()) {
2772 residentClusters.set(residentClusters.get() + 1);
2773 totalMem.set(totalMem.get() + cluster.getUsedSpace());
2775 } catch (DatabaseException e) {
2776 Logger.defaultLogError(e);
2780 System.out.println("--------------------------------");
2781 System.out.println("Cluster information:");
2782 System.out.println("-amount of resident clusters=" + residentClusters.get());
2783 System.out.println("-total memory usage=" + totalMem.get() / 1024 + "kB");
2785 for(ClusterI cluster : clusterTable.getClusters()) {
2786 System.out.print("Cluster " + cluster.getClusterId() + " [");
2788 if (!cluster.isLoaded())
2789 System.out.println("not loaded]");
2790 else if (cluster.isEmpty())
2791 System.out.println("is empty]");
2793 System.out.print("resources=" + cluster.getNumberOfResources(clusterTranslator));
2794 System.out.print(",references=" + cluster.getReferenceCount());
2795 System.out.println(",memory=" + cluster.getUsedSpace() / 1024 + "kB]");
2797 } catch (DatabaseException e) {
2798 Logger.defaultLogError(e);
2799 System.out.println("is corrupted]");
2803 queryProvider2.printDiagnostics();
2804 System.out.println("--------------------------------");
2809 public void fireStartReadTransaction() {
2812 System.out.println("StartReadTransaction");
2814 for (SessionEventListener listener : eventListeners) {
2816 listener.readTransactionStarted();
2817 } catch (Throwable t) {
2818 t.printStackTrace();
2824 public void fireFinishReadTransaction() {
2827 System.out.println("FinishReadTransaction");
2829 for (SessionEventListener listener : eventListeners) {
2831 listener.readTransactionFinished();
2832 } catch (Throwable t) {
2833 t.printStackTrace();
2839 public void fireStartWriteTransaction() {
2842 System.out.println("StartWriteTransaction");
2844 for (SessionEventListener listener : eventListeners) {
2846 listener.writeTransactionStarted();
2847 } catch (Throwable t) {
2848 t.printStackTrace();
2854 public void fireFinishWriteTransaction() {
2857 System.out.println("FinishWriteTransaction");
2859 for (SessionEventListener listener : eventListeners) {
2861 listener.writeTransactionFinished();
2862 } catch (Throwable t) {
2863 t.printStackTrace();
2867 Indexing.resetDependenciesIndexingDisabled();
2871 Resource deserialize(final long resourceId, final long clusterId) throws IOException {
2872 throw new Error("Not supported at the moment.");
2879 ClusterTable getClusterTable() {
2880 return clusterTable;
2883 public GraphSession getGraphSession() {
2884 return graphSession;
2887 public QueryProcessor getQueryProvider2() {
2888 return queryProvider2;
2891 ClientChangesImpl getClientChanges() {
2892 return clientChanges;
2895 boolean getWriteOnly() {
2899 static int counter = 0;
2901 public void onClusterLoaded(long clusterId) {
2903 clusterTable.updateSize();
2911 * Implementation of the interface RequestProcessor
2915 public <T> T syncRequest(final Read<T> request) throws DatabaseException {
2920 assert(request != null);
2922 final DataContainer<T> result = new DataContainer<T>();
2923 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2925 syncRequest(request, new AsyncProcedure<T>() {
2928 public void execute(AsyncReadGraph graph, T t) {
2933 public void exception(AsyncReadGraph graph, Throwable t) {
2939 Throwable t = exception.get();
2941 if(t instanceof DatabaseException) throw (DatabaseException)t;
2942 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
2945 return result.get();
2950 // public <T> T syncRequest(Read<T> request, AsyncListener<T> procedure) throws DatabaseException {
2951 // assertNotSession();
2952 // return syncRequest(request, (AsyncProcedure<T>)procedure);
2956 public <T> T syncRequest(Read<T> request, SyncListener<T> procedure) throws DatabaseException {
2958 return syncRequest(request, new SyncToAsyncListener<T>(procedure));
2962 public <T> T syncRequest(Read<T> request, final Listener<T> procedure) throws DatabaseException {
2964 return syncRequest(request, new NoneToAsyncListener<T>(procedure));
2968 public <T> T syncRequest(final Read<T> request, final SyncProcedure<T> procedure) throws DatabaseException {
2970 return syncRequest(request, new SyncToAsyncProcedure<T>(procedure));
2974 public <T> T syncRequest(Read<T> request, Procedure<T> procedure) throws DatabaseException {
2976 return syncRequest(request, new NoneToAsyncProcedure<T>(procedure));
2980 public <T> T syncRequest(final AsyncRead<T> request) throws DatabaseException {
2984 assert(request != null);
2986 final DataContainer<T> result = new DataContainer<T>();
2987 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2989 syncRequest(request, new AsyncProcedure<T>() {
2992 public void execute(AsyncReadGraph graph, T t) {
2997 public void exception(AsyncReadGraph graph, Throwable t) {
3003 Throwable t = exception.get();
3005 if(t instanceof DatabaseException) throw (DatabaseException)t;
3006 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
3009 return result.get();
3014 public <T> T syncRequest(AsyncRead<T> request, AsyncListener<T> procedure) throws DatabaseException {
3016 return syncRequest(request, (AsyncProcedure<T>)procedure);
3020 public <T> T syncRequest(AsyncRead<T> request, SyncListener<T> procedure) throws DatabaseException {
3022 return syncRequest(request, new SyncToAsyncListener<T>(procedure));
3026 public <T> T syncRequest(AsyncRead<T> request, Listener<T> procedure) throws DatabaseException {
3028 return syncRequest(request, new NoneToAsyncListener<T>(procedure));
3032 public <T> T syncRequest(AsyncRead<T> request, final SyncProcedure<T> procedure) throws DatabaseException {
3034 return syncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3038 final public <T> T syncRequest(final AsyncRead<T> request, final Procedure<T> procedure) throws DatabaseException {
3040 return syncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3044 public <T> Collection<T> syncRequest(MultiRead<T> request) throws DatabaseException {
3048 assert(request != null);
3050 final ArrayList<T> result = new ArrayList<T>();
3051 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
3053 syncRequest(request, new AsyncMultiProcedure<T>() {
3056 public void execute(AsyncReadGraph graph, T t) {
3057 synchronized(result) {
3063 public void finished(AsyncReadGraph graph) {
3067 public void exception(AsyncReadGraph graph, Throwable t) {
3074 Throwable t = exception.get();
3076 if(t instanceof DatabaseException) throw (DatabaseException)t;
3077 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
3085 public <T> Collection<T> syncRequest(MultiRead<T> request, AsyncMultiListener<T> procedure) throws DatabaseException {
3087 return syncRequest(request, (AsyncMultiProcedure<T>)procedure);
3091 public <T> Collection<T> syncRequest(MultiRead<T> request, SyncMultiListener<T> procedure) throws DatabaseException {
3093 return syncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3097 public <T> Collection<T> syncRequest(MultiRead<T> request, MultiListener<T> procedure) throws DatabaseException {
3099 return syncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3103 public <T> Collection<T> syncRequest(MultiRead<T> request, SyncMultiProcedure<T> procedure) throws DatabaseException {
3105 return syncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3109 public <T> Collection<T> syncRequest(MultiRead<T> request, MultiProcedure<T> procedure) throws DatabaseException {
3111 return syncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3115 final public <T> Collection<T> syncRequest(final AsyncMultiRead<T> request) throws DatabaseException {
3119 assert(request != null);
3121 final ArrayList<T> result = new ArrayList<T>();
3122 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
3124 syncRequest(request, new AsyncMultiProcedure<T>() {
3127 public void execute(AsyncReadGraph graph, T t) {
3128 synchronized(result) {
3134 public void finished(AsyncReadGraph graph) {
3138 public void exception(AsyncReadGraph graph, Throwable t) {
3145 Throwable t = exception.get();
3147 if(t instanceof DatabaseException) throw (DatabaseException)t;
3148 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
3156 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, AsyncMultiListener<T> procedure) throws DatabaseException {
3158 return syncRequest(request, (AsyncMultiProcedure<T>)procedure);
3162 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, SyncMultiListener<T> procedure) throws DatabaseException {
3164 return syncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3168 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, MultiListener<T> procedure) throws DatabaseException {
3170 return syncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3174 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, final SyncMultiProcedure<T> procedure) throws DatabaseException {
3176 return syncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3180 final public <T> Collection<T> syncRequest(final AsyncMultiRead<T> request, final MultiProcedure<T> procedure) throws DatabaseException {
3182 return syncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3187 public <T> void asyncRequest(Read<T> request) {
3189 asyncRequest(request, new ProcedureAdapter<T>() {
3191 public void exception(Throwable t) {
3192 t.printStackTrace();
3199 public <T> void asyncRequest(Read<T> request, AsyncListener<T> procedure) {
3200 asyncRequest(request, (AsyncProcedure<T>)procedure);
3204 public <T> void asyncRequest(Read<T> request, final SyncListener<T> procedure) {
3205 asyncRequest(request, new SyncToAsyncListener<T>(procedure));
3209 public <T> void asyncRequest(Read<T> request, final Listener<T> procedure) {
3210 asyncRequest(request, new NoneToAsyncListener<T>(procedure));
3214 public <T> void asyncRequest(Read<T> request, SyncProcedure<T> procedure) {
3215 asyncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3219 public <T> void asyncRequest(Read<T> request, final Procedure<T> procedure) {
3220 asyncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3224 final public <T> void asyncRequest(final AsyncRead<T> request) {
3226 assert(request != null);
3228 asyncRequest(request, new ProcedureAdapter<T>() {
3230 public void exception(Throwable t) {
3231 t.printStackTrace();
3238 public <T> void asyncRequest(AsyncRead<T> request, AsyncListener<T> procedure) {
3239 scheduleRequest(request, procedure, procedure, null);
3243 public <T> void asyncRequest(AsyncRead<T> request, final SyncListener<T> procedure) {
3244 asyncRequest(request, new SyncToAsyncListener<T>(procedure));
3248 public <T> void asyncRequest(AsyncRead<T> request, final Listener<T> procedure) {
3249 asyncRequest(request, new NoneToAsyncListener<T>(procedure));
3253 public <T> void asyncRequest(AsyncRead<T> request, SyncProcedure<T> procedure) {
3254 asyncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3258 final public <T> void asyncRequest(final AsyncRead<T> request, final Procedure<T> procedure) {
3259 asyncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3263 public <T> void asyncRequest(MultiRead<T> request) {
3265 assert(request != null);
3267 asyncRequest(request, new AsyncMultiProcedureAdapter<T>() {
3269 public void exception(AsyncReadGraph graph, Throwable t) {
3270 t.printStackTrace();
3277 public <T> void asyncRequest(MultiRead<T> request, AsyncMultiListener<T> procedure) {
3278 asyncRequest(request, (AsyncMultiProcedure<T>)procedure);
3282 public <T> void asyncRequest(MultiRead<T> request, SyncMultiListener<T> procedure) {
3283 asyncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3287 public <T> void asyncRequest(MultiRead<T> request, MultiListener<T> procedure) {
3288 asyncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3292 public <T> void asyncRequest(MultiRead<T> request, SyncMultiProcedure<T> procedure) {
3293 asyncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3297 public <T> void asyncRequest(MultiRead<T> request, MultiProcedure<T> procedure) {
3298 asyncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3302 final public <T> void asyncRequest(AsyncMultiRead<T> request) {
3304 assert(request != null);
3306 asyncRequest(request, new AsyncMultiProcedureAdapter<T>() {
3308 public void exception(AsyncReadGraph graph, Throwable t) {
3309 t.printStackTrace();
3316 public <T> void asyncRequest(AsyncMultiRead<T> request, AsyncMultiListener<T> procedure) {
3317 asyncRequest(request, (AsyncMultiProcedure<T>)procedure);
3321 public <T> void asyncRequest(AsyncMultiRead<T> request, SyncMultiListener<T> procedure) {
3322 asyncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3326 public <T> void asyncRequest(AsyncMultiRead<T> request, MultiListener<T> procedure) {
3327 asyncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3331 public <T> void asyncRequest(AsyncMultiRead<T> request, SyncMultiProcedure<T> procedure) {
3332 asyncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3336 final public <T> void asyncRequest(AsyncMultiRead<T> request, final MultiProcedure<T> procedure) {
3337 asyncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3341 public <T> Collection<T> syncRequest(MultiRead<T> arg0, AsyncMultiProcedure<T> arg1) throws DatabaseException {
3343 throw new Error("Not implemented!");
3347 public <T> void asyncRequest(MultiRead<T> arg0, AsyncMultiProcedure<T> arg1) {
3348 throw new Error("Not implemented!");
3352 final public <T> void asyncRequest(final ExternalRead<T> request) {
3354 assert(request != null);
3356 asyncRequest(request, new ProcedureAdapter<T>() {
3358 public void exception(Throwable t) {
3359 t.printStackTrace();
3366 public <T> void asyncRequest(ExternalRead<T> request, final Listener<T> procedure) {
3367 asyncRequest(request, (Procedure<T>)procedure);
3372 void check(Throwable t) throws DatabaseException {
3374 if(t instanceof DatabaseException) throw (DatabaseException)t;
3375 else throw new DatabaseException("Unexpected exception", t);
3379 void check(DataContainer<Throwable> container) throws DatabaseException {
3380 Throwable t = container.get();
3382 if(t instanceof DatabaseException) throw (DatabaseException)t;
3383 else throw new DatabaseException("Unexpected exception", t);
3392 boolean sameProvider(Write request) {
3393 if(writeState.getGraph().provider != null) {
3394 return writeState.getGraph().provider.equals(request.getProvider());
3396 return request.getProvider() == null;
3400 boolean plainWrite(WriteGraphImpl graph) {
3401 if(graph == null) return false;
3402 if(graph.writeSupport.writeOnly()) return false;
3407 public static final ThreadGroup SessionThreadGroup = new ThreadGroup("Session Thread Group");
3408 private void assertNotSession() throws DatabaseException {
3409 Thread current = Thread.currentThread();
3410 if(sessionThreads.contains(current)) throw new DatabaseException("Caller is already inside a transaction.");
3413 void assertAlive() {
3414 if (!state.isAlive())
3415 throw new RuntimeDatabaseException("Session has been shut down.");
3418 public InputStream getValueStream(ReadGraphImpl graph, Resource resource) {
3419 return querySupport.getValueStream(graph, querySupport.getId(resource));
3422 public byte[] getValue(ReadGraphImpl graph, Resource resource) {
3423 return querySupport.getValue(graph, querySupport.getId(resource));
3426 <T> void acquire(Semaphore semaphore, T request) throws DatabaseException {
3427 acquire(semaphore, request, null);
3430 private <T,P> void acquire(Semaphore semaphore, T request, P procedure) throws DatabaseException {
3434 // Loop until the semaphore is acquired reporting requests that take a long time.
3437 if (semaphore.tryAcquire(DebugPolicy.LONG_EXECUTION_REPORT_PERIOD, DebugPolicy.LONG_EXECUTION_REPORT_PERIOD_UNIT)) {
3441 if (DebugPolicy.REPORT_TIME_CONSUMING_REQUESTS) {
3443 long waitTime = DebugPolicy.LONG_EXECUTION_REPORT_PERIOD_UNIT
3444 .toMillis(DebugPolicy.LONG_EXECUTION_REPORT_PERIOD)
3446 System.err.println("DB client request '" + request + "' is taking long to execute, so far "
3447 + (waitTime) + " ms. (procedure=" + procedure + ")");
3454 } catch (InterruptedException e) {
3455 e.printStackTrace();
3456 // FIXME: Should perhaps do something else in this case ??
3463 // public boolean holdOnToTransactionAfterCancel() {
3464 // return transactionPolicy.holdOnToTransactionAfterCancel();
3468 // public boolean holdOnToTransactionAfterCommit() {
3469 // return transactionPolicy.holdOnToTransactionAfterCommit();
3473 // public boolean holdOnToTransactionAfterRead() {
3474 // return transactionPolicy.holdOnToTransactionAfterRead();
3478 // public void onRelinquish() {
3479 // transactionPolicy.onRelinquish();
3483 // public void onRelinquishDone() {
3484 // transactionPolicy.onRelinquishDone();
3488 // public void onRelinquishError() {
3489 // transactionPolicy.onRelinquishError();
3494 public Session getSession() {
3499 protected abstract VirtualGraph getProvider(VirtualGraph virtualGraph);
3500 protected abstract ResourceImpl getNewResource() throws DatabaseException;
3502 public void ceased(int thread) {
3504 requestManager.ceased(thread);
3508 public int getAmountOfQueryThreads() {
3509 // This must be a power of two
3511 // return Integer.highestOneBit(Runtime.getRuntime().availableProcessors());
3514 public Resource getResourceByKey(int key) throws ResourceNotFoundException {
3516 return new ResourceImpl(resourceSupport, key);
3520 public void acquireWriteOnly() {
3524 public void releaseWriteOnly(ReadGraphImpl graph) {
3526 queryProvider2.releaseWrite(graph);
3529 public void handleUpdatesAndMetadata(WriteGraphImpl writer) {
3531 long start = System.nanoTime();
3533 while(dirtyPrimitives) {
3534 dirtyPrimitives = false;
3535 getQueryProvider2().performDirtyUpdates(writer);
3536 getQueryProvider2().performScheduledUpdates(writer);
3539 fireMetadataListeners(writer, clientChanges);
3541 if(DebugPolicy.PERFORMANCE_DATA) {
3542 long end = System.nanoTime();
3543 System.err.println("handleUpdatesAndMetadata " + 1e-9*(end-start));
3548 void removeTemporaryData() {
3549 File platform = Platform.getLocation().toFile();
3550 File tempFiles = new File(platform, "tempFiles");
3551 File temp = new File(tempFiles, "db");
3555 Files.walkFileTree(temp.toPath(), new SimpleFileVisitor<Path>() {
3557 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
3560 } catch (IOException e) {
3561 Logger.defaultLogError(e);
3563 return FileVisitResult.CONTINUE;
3566 } catch (IOException e) {
3567 Logger.defaultLogError(e);
3571 public void handleCreatedClusters() {
3572 if ((serviceMode & SERVICE_MODE_CREATE) > 0) {
3573 createdClusters.forEach(new TLongProcedure() {
3576 public boolean execute(long value) {
3577 ClusterImpl cluster = clusterTable.getClusterByClusterId(value);
3578 cluster.setImmutable(true, clusterTranslator);
3583 createdClusters.clear();
3587 public Object getModificationCounter() {
3588 return queryProvider2.modificationCounter;
3592 public void markUndoPoint() {
3593 state.setCombine(false);