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.GraphChangeListenerSupport;
140 import org.simantics.db.service.InitSupport;
141 import org.simantics.db.service.LifecycleSupport;
142 import org.simantics.db.service.ManagementSupport;
143 import org.simantics.db.service.QueryControl;
144 import org.simantics.db.service.SerialisationSupport;
145 import org.simantics.db.service.ServerInformation;
146 import org.simantics.db.service.ServiceActivityMonitor;
147 import org.simantics.db.service.SessionEventSupport;
148 import org.simantics.db.service.SessionMonitorSupport;
149 import org.simantics.db.service.SessionUserSupport;
150 import org.simantics.db.service.StatementSupport;
151 import org.simantics.db.service.TransactionPolicySupport;
152 import org.simantics.db.service.TransactionSupport;
153 import org.simantics.db.service.TransferableGraphSupport;
154 import org.simantics.db.service.UndoRedoSupport;
155 import org.simantics.db.service.VirtualGraphSupport;
156 import org.simantics.db.service.XSupport;
157 import org.simantics.layer0.Layer0;
158 import org.simantics.utils.DataContainer;
159 import org.simantics.utils.Development;
160 import org.simantics.utils.threads.logger.ITask;
161 import org.simantics.utils.threads.logger.ThreadLogger;
163 import gnu.trove.procedure.TLongProcedure;
164 import gnu.trove.set.hash.TLongHashSet;
167 public abstract class SessionImplSocket implements Session, WriteRequestScheduleSupport {
169 protected static final boolean DEBUG = false;
171 private static final boolean DIAGNOSTICS = false;
173 private TransactionPolicySupport transactionPolicy;
175 final private ClusterControl clusterControl;
177 final protected BuiltinSupportImpl builtinSupport;
178 final protected VirtualGraphServerSupportImpl virtualGraphServerSupport;
179 final protected ClusterSetsSupport clusterSetsSupport;
180 final protected LifecycleSupportImpl lifecycleSupport;
182 protected QuerySupportImpl querySupport;
183 protected ResourceSupportImpl resourceSupport;
184 protected WriteSupport writeSupport;
185 public ClusterTranslator clusterTranslator;
187 boolean dirtyPrimitives = false;
189 public static final int SERVICE_MODE_CREATE = 2;
190 public static final int SERVICE_MODE_ALLOW = 1;
191 public int serviceMode = 0;
192 public boolean createdImmutableClusters = false;
193 public TLongHashSet createdClusters = new TLongHashSet();
198 * The service locator maintained by the workbench. These services are
199 * initialized during workbench during the <code>init</code> method.
201 final protected ServiceLocatorImpl serviceLocator = new ServiceLocatorImpl();
203 final public ResourceSerializerImpl resourceSerializer = new ResourceSerializerImpl();
205 final CopyOnWriteArrayList<ChangeListener> changeListeners2 = new CopyOnWriteArrayList<ChangeListener>();
207 final CopyOnWriteArrayList<ChangeListener> metadataListeners = new CopyOnWriteArrayList<ChangeListener>();
209 final CopyOnWriteArrayList<SessionEventListener> eventListeners = new CopyOnWriteArrayList<SessionEventListener>();
211 final HashSet<Thread> sessionThreads = new HashSet<Thread>();
213 final BijectionMap<MonitorContext, MonitorHandler> monitorContexts = new BijectionMap<MonitorContext, MonitorHandler>();
215 final protected State state = new State();
217 protected GraphSession graphSession = null;
219 protected SessionManager sessionManagerImpl = null;
221 protected UserAuthenticationAgent authAgent = null;
223 protected UserAuthenticator authenticator = null;
225 protected Resource user = null;
227 protected ClusterStream clusterStream = null;
229 protected SessionRequestManager requestManager = null;
231 public ClusterTable clusterTable = null;
233 public QueryProcessor queryProvider2 = null;
235 ClientChangesImpl clientChanges = null;
237 MonitorHandler[] monitorHandlers = new MonitorHandler[0];
239 // protected long newClusterId = Constants.NullClusterId;
241 protected int flushCounter = 0;
243 protected boolean writeOnly = false;
245 WriteState<?> writeState = null;
246 WriteStateBase<?> delayedWriteState = null;
247 protected Resource defaultClusterSet = null; // If not null then used for newResource().
249 public SessionImplSocket(SessionManager sessionManagerImpl, UserAuthenticationAgent authAgent) {
251 // if (authAgent == null)
252 // throw new IllegalArgumentException("null authentication agent");
254 File t = StaticSessionProperties.virtualGraphStoragePath;
257 this.clusterTable = new ClusterTable(this, t);
258 this.builtinSupport = new BuiltinSupportImpl(this);
259 this.sessionManagerImpl = sessionManagerImpl;
261 // this.authAgent = authAgent;
263 serviceLocator.registerService(Session.class, this);
264 serviceLocator.registerService(InitSupport.class, new InitSupportImpl(this));
265 serviceLocator.registerService(ManagementSupport.class, new ManagementSupportImpl(this));
266 serviceLocator.registerService(QueryControl.class, new QueryControlImpl(this));
267 serviceLocator.registerService(SessionUserSupport.class, new SessionUserSupportImpl(this));
268 serviceLocator.registerService(GraphChangeListenerSupport.class, new GraphChangeListenerSupportImpl(this));
269 serviceLocator.registerService(SessionEventSupport.class, new SessionEventSupportImpl(this));
270 serviceLocator.registerService(SerialisationSupport.class, new SerialisationSupportImpl(this));
271 serviceLocator.registerService(UndoRedoSupport.class, new UndoRedoSupportImpl(this));
272 serviceLocator.registerService(ClusteringSupport.class, new ClusteringSupportImpl(this));
273 serviceLocator.registerService(TransactionSupport.class, new TransactionSupportImpl(this));
274 serviceLocator.registerService(SessionMonitorSupport.class, new SessionMonitorSupportImpl(this));
275 serviceLocator.registerService(TransferableGraphSupport.class, new TransferableGraphSupportImpl(this));
276 serviceLocator.registerService(QueryDebug.class, new QueryDebugImpl(this));
277 serviceLocator.registerService(CollectionSupport.class, new CollectionSupportImpl(this));
278 serviceLocator.registerService(StatementSupport.class, new StatementSupportImpl(this));
279 serviceLocator.registerService(DirectQuerySupport.class, new DirectQuerySupportImpl(this));
280 serviceLocator.registerService(XSupport.class, new XSupportImpl(this));
281 serviceLocator.registerService(DebugSupport.class, new DebugSupportImpl());
282 serviceLocator.registerService(ExternalValueSupport.class, new ExternalValueSupportImpl(this));
283 serviceLocator.registerService(RandomAccessValueSupport.class, new RandomAccessValueSupportImpl());
284 serviceLocator.registerService(ServiceActivityMonitor.class, new ServiceActivityMonitorImpl());
285 ServiceActivityUpdaterForWriteTransactions.register(this);
287 this.virtualGraphServerSupport = new VirtualGraphServerSupportImpl(this, t);
288 serviceLocator.registerService(VirtualGraphSupport.class, virtualGraphServerSupport);
289 serviceLocator.registerService(VirtualGraphServerSupport.class, virtualGraphServerSupport);
290 this.lifecycleSupport = new LifecycleSupportImpl(this);
291 serviceLocator.registerService(LifecycleSupport.class, lifecycleSupport);
292 this.transactionPolicy = new TransactionPolicyRelease();
293 serviceLocator.registerService(TransactionPolicySupport.class, transactionPolicy);
294 this.clusterControl = new ClusterControlImpl(this);
295 serviceLocator.registerService(ClusterControl.class, clusterControl);
296 this.clusterSetsSupport = new ClusterSetsSupportImpl2(); // Using same path as virtual graphs.
297 this.clusterSetsSupport.setReadDirectory(t.toPath());
298 this.clusterSetsSupport.updateWriteDirectory(t.toPath());
299 serviceLocator.registerService(ClusterSetsSupport.class, clusterSetsSupport);
309 public Resource getRootLibrary() {
310 return queryProvider2.getRootLibraryResource();
313 void refresh(int thread, ClusterUID[] clusterUID, long csid) throws DatabaseException {
314 if (!graphSession.dbSession.refreshEnabled())
317 getClusterTable().refresh(csid, this, clusterUID);
318 } catch (Throwable t) {
319 Logger.defaultLogError("Refesh failed.", t);
323 static final class TaskHelper {
324 private final String name;
325 private Object result;
326 final Semaphore sema = new Semaphore(0);
327 private Throwable throwable = null;
328 final Consumer<DatabaseException> callback = e -> {
329 synchronized (TaskHelper.this) {
333 final Procedure<Object> proc = new Procedure<Object>() {
335 public void execute(Object result) {
336 callback.accept(null);
339 public void exception(Throwable t) {
340 if (t instanceof DatabaseException)
341 callback.accept((DatabaseException)t);
343 callback.accept(new DatabaseException("" + name + "operation failed.", t));
346 final WriteTraits writeTraits = new WriteTraits() {};
347 TaskHelper(String name) {
350 @SuppressWarnings("unchecked")
354 void setResult(Object result) {
355 this.result = result;
357 // Throwable throwableGet() {
360 synchronized void throwableSet(Throwable t) {
363 // void throwableSet(String t) {
364 // throwable = new InternalException("" + name + " operation failed. " + t);
366 synchronized void throwableCheck()
367 throws DatabaseException {
368 if (null != throwable)
369 if (throwable instanceof DatabaseException)
370 throw (DatabaseException)throwable;
372 throw new DatabaseException("Undo operation failed.", throwable);
374 void throw_(String message)
375 throws DatabaseException {
376 throw new DatabaseException("" + name + " operation failed. " + message);
382 private ListenerBase getListenerBase(Object procedure) {
383 if (procedure instanceof ListenerBase)
384 return (ListenerBase) procedure;
389 public <T> void scheduleRequest(final Write request, final Consumer<DatabaseException> callback, final Semaphore notify) {
390 scheduleRequest(request, callback, notify, null);
394 * @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)
397 public <T> void scheduleRequest(final Write request, final Consumer<DatabaseException> callback, final Semaphore notify, Boolean combine) {
399 assert (request != null);
401 if(Development.DEVELOPMENT) {
403 if(Development.<Boolean>getProperty(DevelopmentKeys.SESSION_LOG_WRITES, Bindings.BOOLEAN))
404 System.err.println("schedule write '" + request + "'");
405 } catch (Throwable t) {
406 Logger.defaultLogError(t);
410 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
412 requestManager.scheduleWrite(new SessionTask(request, thread, thread) {
415 public void run(int thread) {
417 if(Development.DEVELOPMENT) {
419 if(Development.<Boolean>getProperty(DevelopmentKeys.SESSION_LOG_WRITES, Bindings.BOOLEAN))
420 System.err.println("perform write '" + request + "'");
421 } catch (Throwable t) {
422 Logger.defaultLogError(t);
426 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
428 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
433 Disposable.safeDispose(clientChanges);
434 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
436 VirtualGraph vg = getProvider(request.getProvider());
438 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
439 writeState = new WriteState<Object>(writer, request, notify, new Procedure<Object>() {
442 public void execute(Object result) {
443 if(callback != null) callback.accept(null);
447 public void exception(Throwable t) {
448 if(callback != null) callback.accept((DatabaseException)t);
453 assert (null != writer);
454 // writer.state.barrier.inc();
457 request.perform(writer);
458 assert (null != writer);
459 } catch (Throwable t) {
460 if (!(t instanceof CancelTransactionException))
461 Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", t);
462 writeState.except(t);
464 // writer.state.barrier.dec();
465 // writer.waitAsync(request);
469 assert(!queryProvider2.cache.dirty);
471 } catch (Throwable e) {
473 // Log it first, just to be safe that the error is always logged.
474 if (!(e instanceof CancelTransactionException))
475 Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", e);
477 // writeState.getGraph().state.barrier.dec();
478 // writeState.getGraph().waitAsync(request);
480 writeState.except(e);
483 // // Callback is client code, we have to be prepared for it to throw unexpected exceptions.
484 // // All we can do here is to log those, can't really pass them anywhere.
485 // if (callback != null) {
486 // if(e instanceof DatabaseException) callback.run((DatabaseException)e);
487 // else callback.run(new DatabaseException(e));
489 // } catch (Throwable e2) {
490 // Logger.defaultLogError("Write request callback caused an unexpected error, see exception.", e2);
492 // boolean empty = clusterStream.reallyFlush();
493 // int callerThread = -1;
494 // ClientChangesImpl cs = new ClientChangesImpl(SessionImplSocket.this);
495 // SynchronizeContext context = new SynchronizeContext(callerThread, SessionImplSocket.this, cs, 1);
497 // // Send all local changes to server so it can calculate correct reverse change set.
498 // // This will call clusterStream.accept().
499 // state.cancelCommit(context, clusterStream);
501 // if (!context.isOk()) // this is a blocking operation
502 // throw new InternalException("Cancel failed. This should never happen. Contact application support.");
503 // getQueryProvider2().performDirtyUpdates(writeState.getGraph());
505 // state.cancelCommit2(context, clusterStream);
506 // } catch (DatabaseException e3) {
507 // Logger.defaultLogError("Write request cancel caused an unexpected error.", e3);
509 // clusterStream.setOff(false);
510 // clientChanges = new ClientChangesImpl(SessionImplSocket.this);
515 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
521 if(Development.DEVELOPMENT) {
523 if(Development.<Boolean>getProperty(DevelopmentKeys.SESSION_LOG_WRITES, Bindings.BOOLEAN))
524 System.err.println("finish write '" + request + "'");
525 } catch (Throwable t) {
526 Logger.defaultLogError(t);
536 public <T> void scheduleRequest(final WriteResult<T> request, final Procedure<T> procedure, final Semaphore notify) {
537 scheduleRequest(request, procedure, notify, null);
541 * @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)
544 public <T> void scheduleRequest(final WriteResult<T> request, final Procedure<T> procedure, final Semaphore notify, Boolean combine) {
546 assert (request != null);
548 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
550 requestManager.scheduleWrite(new SessionTask(request, thread) {
553 public void run(int thread) {
555 ITask task = ThreadLogger.getInstance().begin("WriteRequest " + request);
557 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
560 Disposable.safeDispose(clientChanges);
561 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
563 VirtualGraph vg = getProvider(request.getProvider());
564 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
567 WriteState<T> writeStateT = new WriteState<T>(writer, request, notify, procedure);
568 writeState = writeStateT;
570 assert (null != writer);
571 // writer.state.barrier.inc();
572 writeStateT.setResult(request.perform(writer));
573 assert (null != writer);
575 // writer.state.barrier.dec();
576 // writer.waitAsync(null);
578 } catch (Throwable e) {
580 // writer.state.barrier.dec();
581 // writer.waitAsync(null);
583 writeState.except(e);
585 // state.stopWriteTransaction(clusterStream);
587 // } catch (Throwable e) {
588 // // Log it first, just to be safe that the error is always logged.
589 // Logger.defaultLogError("Write transaction caused an unexpected error, see exception.", e);
592 // // Callback is client code, we have to be prepared for it to throw unexpected exceptions.
593 // // All we can do here is to log those, can't really pass them anywhere.
594 // if (procedure != null) {
595 // if(e instanceof DatabaseException) procedure.exception((DatabaseException)e);
596 // else procedure.exception(new DatabaseException(e));
598 // } catch (Throwable e2) {
599 // Logger.defaultLogError("Write request callback caused an unexpected error, see exception.", e2);
602 // clientChanges = new ClientChangesImpl(SessionImplSocket.this);
604 // state.stopWriteTransaction(clusterStream);
607 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
610 // if(notify != null) notify.release();
620 public <T> void scheduleRequest(final DelayedWrite request, final Consumer<DatabaseException> callback, final Semaphore notify) {
621 scheduleRequest(request, callback, notify, null);
625 * @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)
628 public <T> void scheduleRequest(final DelayedWrite request, final Consumer<DatabaseException> callback, final Semaphore notify, Boolean combine) {
630 final ITask total = ThreadLogger.getInstance().begin("ScheduleDelayedWrite");
632 assert (request != null);
634 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
636 requestManager.scheduleWrite(new SessionTask(request, thread) {
639 public void run(int thread) {
640 fireSessionVariableChange(SessionVariables.QUEUED_READS);
642 Procedure<Object> stateProcedure = new Procedure<Object>() {
644 public void execute(Object result) {
645 if (callback != null)
646 callback.accept(null);
649 public void exception(Throwable t) {
650 if (callback != null) {
651 if (t instanceof DatabaseException) callback.accept((DatabaseException) t);
652 else callback.accept(new DatabaseException(t));
654 Logger.defaultLogError("Unhandled exception", t);
658 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
659 delayedWriteState = new WriteStateBase<Object>(request, notify, stateProcedure);
660 DelayedWriteGraph dwg = null;
661 // newGraph.state.barrier.inc();
664 dwg = new DelayedWriteGraph(newGraph);
665 request.perform(dwg);
666 } catch (Throwable e) {
667 delayedWriteState.except(e);
672 // newGraph.state.barrier.dec();
673 // newGraph.waitAsync(request);
674 fireSessionVariableChange(SessionVariables.QUEUED_READS);
677 delayedWriteState = null;
679 ITask task2 = ThreadLogger.getInstance().begin("DelayedWriteCommit");
680 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
683 Disposable.safeDispose(clientChanges);
684 clientChanges = new ClientChangesImpl(SessionImplSocket.this);
688 VirtualGraph vg = getProvider(request.getProvider());
689 WriteSupport writeSupport = vg != null ? new VirtualWriteOnlySupport() : new WriteOnlySupport();
691 WriteGraphImpl writer = WriteGraphImpl.create(getQueryProvider2(), writeSupport, vg);
693 writeState = new WriteState<Object>(writer, request, notify, stateProcedure);
695 assert (null != writer);
696 // writer.state.barrier.inc();
700 dwg.commit(writer, request);
702 if(defaultClusterSet != null) {
703 XSupport xs = getService(XSupport.class);
704 defaultClusterSet = xs.convertDelayedResourceToResource(defaultClusterSet);
705 ClusteringSupport cs = getService(ClusteringSupport.class);
706 clusterSetsSupport.put(defaultClusterSet.getResourceId(), cs.getCluster(defaultClusterSet));
709 // This makes clusters available from server
710 clusterStream.reallyFlush();
712 releaseWriteOnly(writer);
713 handleUpdatesAndMetadata(writer);
715 } catch (ServiceException e) {
716 // writer.state.barrier.dec();
717 // writer.waitAsync(null);
719 // These shall be requested from server
720 clusterTable.removeWriteOnlyClusters();
721 // This makes clusters available from server
722 clusterStream.reallyFlush();
724 releaseWriteOnly(writer);
725 writeState.except(e);
727 // Debugging & Profiling
728 fireSessionVariableChange(SessionVariables.QUEUED_WRITES);
738 public <T> void scheduleRequest(final DelayedWriteResult<T> request, final Procedure<T> procedure, final Semaphore notify) {
739 scheduleRequest(request, procedure, notify, null);
743 * @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)
746 public <T> void scheduleRequest(final DelayedWriteResult<T> request, final Procedure<T> procedure, final Semaphore notify, Boolean combine) {
747 throw new Error("Not implemented");
750 protected ClusterImpl getNewResourceCluster() throws DatabaseException {
751 ClusterImpl cluster = clusterTable.getNewResourceCluster(clusterTranslator, graphSession, writeOnly);
752 if((serviceMode & SERVICE_MODE_CREATE) > 0) {
753 createdClusters.add(cluster.clusterId);
758 class WriteOnlySupport implements WriteSupport {
760 ClusterStream stream;
761 ClusterImpl currentCluster;
763 public WriteOnlySupport() {
764 this.stream = clusterStream;
768 public void claim(VirtualGraph provider, Resource subject, Resource predicate, Resource object) throws ServiceException {
769 claim(provider, ((ResourceImpl)subject).id, ((ResourceImpl)predicate).id, ((ResourceImpl)object).id );
773 public void claim(VirtualGraph provider, int s, int p, int o) throws ServiceException {
775 ClusterImpl cluster = clusterTable.getClusterByResourceKey(s);
777 if (cluster.getImmutable() && (serviceMode & SessionImplSocket.SERVICE_MODE_ALLOW) == 0)
778 if(s != queryProvider2.getRootLibrary())
779 throw new ImmutableException("Trying to modify immutable resource key=" + s);
782 maintainCluster(cluster, cluster.addRelation(s, p, o, clusterTranslator));
783 } catch (DatabaseException e) {
784 Logger.defaultLogError(e);
788 clientChanges.invalidate(s);
790 if (cluster.isWriteOnly())
792 queryProvider2.updateStatements(s, p);
797 public void claimValue(VirtualGraph provider, Resource resource, byte[] value) throws DatabaseException {
798 claimValue(provider, ((ResourceImpl)resource).id, value, value.length);
802 public void claimValue(VirtualGraph provider, int rid, byte[] value, int length) {
804 ClusterImpl cluster = clusterTable.getClusterByResourceKey(rid);
806 maintainCluster(cluster, cluster.setValue(rid, value, length, clusterTranslator));
807 } catch (DatabaseException e) {
808 Logger.defaultLogError(e);
811 clientChanges.invalidate(rid);
813 if (cluster.isWriteOnly())
815 queryProvider2.updateValue(rid);
820 public void claimValue(VirtualGraph provider, Resource resource, ByteReader reader, int amount) throws DatabaseException {
823 claimValue(provider,resource, reader.readBytes(null, amount));
827 byte[] bytes = new byte[65536];
829 int rid = ((ResourceImpl)resource).id;
830 ClusterImpl cluster = clusterTable.getClusterByResourceKey(rid);
834 int block = Math.min(left, 65536);
835 reader.readBytes(bytes, block);
836 maintainCluster(cluster, cluster.modiValueEx(rid, amount-left, block, bytes, 0, clusterTranslator));
839 } catch (DatabaseException e) {
840 Logger.defaultLogError(e);
843 clientChanges.invalidate(rid);
845 if (cluster.isWriteOnly())
847 queryProvider2.updateValue(rid);
851 private void maintainCluster(ClusterImpl before, ClusterI after_) {
852 if(after_ != null && after_ != before) {
853 ClusterImpl after = (ClusterImpl)after_;
854 if(currentCluster == before) {
855 currentCluster = after;
857 clusterTable.replaceCluster(after);
861 public int createResourceKey(int foreignCounter) throws DatabaseException {
862 if(currentCluster == null) {
863 currentCluster = getNewResourceCluster();
865 if(currentCluster.getNumberOfResources(clusterTranslator) == ClusterTable.CLUSTER_FILL_SIZE) {
866 ClusterWriteOnly newCluster = (ClusterWriteOnly)getNewResourceCluster();
867 newCluster.foreignLookup = new byte[foreignCounter];
868 currentCluster = newCluster;
870 System.err.println("foreignLookup " + currentCluster + " " + foreignCounter);
872 return currentCluster.createResource(clusterTranslator);
876 public Resource createResource(VirtualGraph provider) throws DatabaseException {
877 if(currentCluster == null) {
878 if (null != defaultClusterSet) {
879 ResourceImpl result = getNewResource(defaultClusterSet);
880 currentCluster = clusterTable.getClusterByResourceKey(result.id);
883 currentCluster = getNewResourceCluster();
886 if(currentCluster.getNumberOfResources(clusterTranslator) >= ClusterTable.CLUSTER_FILL_SIZE) {
887 if (null != defaultClusterSet) {
888 ResourceImpl result = getNewResource(defaultClusterSet);
889 currentCluster = clusterTable.getClusterByResourceKey(result.id);
892 currentCluster = getNewResourceCluster();
895 return new ResourceImpl(resourceSupport, currentCluster.createResource(clusterTranslator));
899 public Resource createResource(VirtualGraph provider, long clusterId)
900 throws DatabaseException {
901 return getNewResource(clusterId);
905 public Resource createResource(VirtualGraph provider, Resource clusterSet)
906 throws DatabaseException {
907 return getNewResource(clusterSet);
911 public void createClusterSet(VirtualGraph provider, Resource clusterSet)
912 throws DatabaseException {
913 getNewClusterSet(clusterSet);
917 public boolean hasClusterSet(VirtualGraph dummy, Resource clusterSet)
918 throws ServiceException {
919 return containsClusterSet(clusterSet);
922 public void selectCluster(long cluster) {
923 currentCluster = clusterTable.getClusterByClusterId(cluster);
924 long setResourceId = clusterSetsSupport.getSet(cluster);
925 clusterSetsSupport.put(setResourceId, cluster);
929 public Resource setDefaultClusterSet(Resource clusterSet)
930 throws ServiceException {
931 Resource result = setDefaultClusterSet4NewResource(clusterSet);
932 if(clusterSet != null) {
933 long id = clusterSetsSupport.get(clusterSet.getResourceId());
934 currentCluster = clusterTable.getClusterByClusterId(id);
937 currentCluster = null;
943 public void denyValue(VirtualGraph provider, Resource resource) throws ServiceException {
945 provider = getProvider(provider);
946 if (null == provider) {
947 int key = ((ResourceImpl)resource).id;
951 ClusterI cluster = clusterTable.getClusterProxyByResourceKey(key);
952 // if (cluster.getImmutable() && (serviceMode & SessionImplSocket.SERVICE_MODE_ALLOW) == 0)
953 // if(key != queryProvider2.getRootLibrary())
954 // throw new ImmutableException("Trying to modify immutable resource key=" + key);
957 // cluster.removeValue(key, clusterTranslator);
958 // } catch (DatabaseException e) {
959 // Logger.defaultLogError(e);
963 clusterTable.writeOnlyInvalidate(cluster);
966 int sResourceKey = ClusterTraits.getResourceIndexFromResourceKey(key);
967 clusterTranslator.addStatementIndex(cluster, sResourceKey, cluster.getClusterUID(), ClusterChange.DELETE_OPERATION);
968 clusterTranslator.removeValue(cluster);
969 } catch (DatabaseException e) {
970 Logger.defaultLogError(e);
973 queryProvider2.invalidateResource(key);
974 clientChanges.invalidate(key);
977 ((VirtualGraphImpl)provider).denyValue(((ResourceImpl) resource).id);
978 queryProvider2.updateValue(querySupport.getId(resource));
979 clientChanges.claimValue(resource);
986 public void flush(boolean intermediate) {
987 throw new UnsupportedOperationException();
991 public void flushCluster() {
992 clusterTable.flushCluster(graphSession);
993 if(defaultClusterSet != null) {
994 clusterSetsSupport.put(defaultClusterSet.getResourceId(), Constants.NewClusterId);
996 currentCluster = null;
1000 public void flushCluster(Resource r) {
1001 throw new UnsupportedOperationException("flushCluster resource " + r);
1009 public boolean removeStatement(VirtualGraph provider, Resource subject, Resource predicate,
1012 int s = ((ResourceImpl)subject).id;
1013 int p = ((ResourceImpl)predicate).id;
1014 int o = ((ResourceImpl)object).id;
1016 provider = getProvider(provider);
1017 if (null == provider) {
1019 ClusterI cluster = clusterTable.getClusterProxyByResourceKey(s);
1020 clusterTable.writeOnlyInvalidate(cluster);
1024 int sResourceKey = ClusterTraits.getResourceIndexFromResourceKey(s);
1025 int pResourceKey = ClusterTraits.getResourceIndexFromResourceKey(p);
1026 int oResourceKey = ClusterTraits.getResourceIndexFromResourceKey(o);
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, pResourceKey, pc.getClusterUID(), ClusterStream.NULL_OPERATION);
1033 clusterTranslator.addStatementIndex(cluster, oResourceKey, 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.query(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) {
1629 newGraph.processor.query(newGraph, request, null, procedure, listener);
1630 } catch (DatabaseException e) {
1631 Logger.defaultLogError(e);
1636 final ResultCallWrappedSingleQueryProcedure4<T> wrapper = new ResultCallWrappedSingleQueryProcedure4<T>(
1637 procedure, "request");
1641 // newGraph.state.barrier.inc();
1643 request.perform(newGraph, wrapper);
1645 // newGraph.waitAsync(request);
1647 } catch (Throwable t) {
1649 wrapper.exception(newGraph, t);
1650 // newGraph.waitAsync(request);
1659 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1669 public <T> void scheduleRequest(final AsyncMultiRead<T> request, final AsyncMultiProcedure<T> procedure, final Semaphore notify) {
1671 assert (request != null);
1672 assert (procedure != null);
1674 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1676 int sync = notify != null ? thread : -1;
1678 requestManager.scheduleRead(new SessionRead(request, null, notify, thread, sync) {
1681 public void run(int thread) {
1683 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1685 ListenerBase listener = getListenerBase(procedure);
1687 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1691 if (listener != null) {
1693 newGraph.processor.query(newGraph, request, null, procedure, listener);
1695 // newGraph.waitAsync(request);
1699 final ResultCallWrappedQueryProcedure4<T> wrapper = new ResultCallWrappedQueryProcedure4<T>(procedure);
1703 request.perform(newGraph, wrapper);
1705 } catch (Throwable t) {
1707 t.printStackTrace();
1715 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1725 public <T> void scheduleRequest(final ExternalRead<T> request, final Procedure<T> procedure, final Semaphore notify, final DataContainer<Throwable> throwable, final DataContainer<T> result) {
1727 assert (request != null);
1728 assert (procedure != null);
1730 int thread = request.hashCode() & queryProvider2.THREAD_MASK;
1732 requestManager.scheduleRead(new SessionRead(request, throwable, notify, thread, thread) {
1735 public void run(int thread) {
1737 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1739 ListenerBase listener = getListenerBase(procedure);
1741 final ReadGraphImpl newGraph = ReadGraphImpl.create(getQueryProvider2());
1745 if (listener != null) {
1747 newGraph.processor.query(newGraph, request, null, new Procedure<T>() {
1750 public void exception(Throwable t) {
1751 procedure.exception(t);
1752 if(throwable != null) {
1758 public void execute(T t) {
1759 if(result != null) result.set(t);
1760 procedure.execute(t);
1765 // newGraph.waitAsync(request);
1769 // newGraph.state.barrier.inc();
1771 request.register(newGraph, new Listener<T>() {
1774 public void exception(Throwable t) {
1775 if(throwable != null) throwable.set(t);
1776 procedure.exception(t);
1777 // newGraph.state.barrier.dec();
1781 public void execute(T t) {
1782 if(result != null) result.set(t);
1783 procedure.execute(t);
1784 // newGraph.state.barrier.dec();
1788 public boolean isDisposed() {
1794 // newGraph.waitAsync(request);
1800 fireSessionVariableChange(SessionVariables.QUEUED_READS);
1812 public <T> void asyncRequest(final Read<T> request, final AsyncProcedure<T> procedure) {
1814 scheduleRequest(request, procedure, null, null, null);
1819 public <T> T syncRequest(Read<T> request, AsyncProcedure<T> procedure) throws DatabaseException {
1821 Semaphore notify = new Semaphore(0);
1822 DataContainer<Throwable> container = new DataContainer<Throwable>();
1823 DataContainer<T> result = new DataContainer<T>();
1824 scheduleRequest(request, procedure, notify, container, result);
1825 acquire(notify, request);
1826 Throwable throwable = container.get();
1827 if(throwable != null) {
1828 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1829 else throw new DatabaseException("Unexpected exception", throwable);
1831 return result.get();
1835 public <T> T syncRequest(AsyncRead<T> request, final AsyncProcedure<T> procedure) throws DatabaseException {
1837 Semaphore notify = new Semaphore(0);
1838 final DataContainer<Throwable> exceptionContainer = new DataContainer<Throwable>();
1839 final DataContainer<T> resultContainer = new DataContainer<T>();
1840 scheduleRequest(request, new AsyncProcedure<T>() {
1842 public void exception(AsyncReadGraph graph, Throwable throwable) {
1843 exceptionContainer.set(throwable);
1844 procedure.exception(graph, throwable);
1847 public void execute(AsyncReadGraph graph, T result) {
1848 resultContainer.set(result);
1849 procedure.execute(graph, result);
1851 }, getListenerBase(procedure), notify);
1852 acquire(notify, request, procedure);
1853 Throwable throwable = exceptionContainer.get();
1854 if (throwable != null) {
1855 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1856 else throw new DatabaseException("Unexpected exception", throwable);
1858 return resultContainer.get();
1863 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, final AsyncMultiProcedure<T> procedure) throws DatabaseException {
1865 Semaphore notify = new Semaphore(0);
1866 final DataContainer<Throwable> exceptionContainer = new DataContainer<Throwable>();
1867 scheduleRequest(request, new AsyncMultiProcedure<T>() {
1869 public void exception(AsyncReadGraph graph, Throwable throwable) {
1870 exceptionContainer.set(throwable);
1871 procedure.exception(graph, throwable);
1874 public void execute(AsyncReadGraph graph, T result) {
1875 procedure.execute(graph, result);
1878 public void finished(AsyncReadGraph graph) {
1879 procedure.finished(graph);
1882 acquire(notify, request, procedure);
1883 Throwable throwable = exceptionContainer.get();
1884 if (throwable != null) {
1885 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1886 else throw new DatabaseException("Unexpected exception", throwable);
1888 // TODO: implement return value
1889 System.err.println("TODO: implement return value for syncRequest(AsyncMultiRead, AsyncMultiProcedure)");
1894 public <T> T syncRequest(final ExternalRead<T> request) throws DatabaseException {
1895 return syncRequest(request, new ProcedureAdapter<T>());
1898 // assert(request != null);
1900 // final DataContainer<T> result = new DataContainer<T>();
1901 // final DataContainer<Throwable> exception = new DataContainer<Throwable>();
1903 // syncRequest(request, new Procedure<T>() {
1906 // public void execute(T t) {
1911 // public void exception(Throwable t) {
1912 // exception.set(t);
1917 // Throwable t = exception.get();
1919 // if(t instanceof DatabaseException) throw (DatabaseException)t;
1920 // else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(PrimitiveRead)", t);
1923 // return result.get();
1928 public <T> T syncRequest(ExternalRead<T> request, final Listener<T> procedure) throws DatabaseException {
1929 return syncRequest(request, (Procedure<T>)procedure);
1934 // public <T> T syncRequest(Read<T> request, AsyncProcedure<T> procedure) throws DatabaseException {
1935 // assertNotSession();
1936 // Semaphore notify = new Semaphore(0);
1937 // DataContainer<Throwable> container = new DataContainer<Throwable>();
1938 // DataContainer<T> result = new DataContainer<T>();
1939 // scheduleRequest(request, procedure, notify, container, result);
1940 // acquire(notify, request);
1941 // Throwable throwable = container.get();
1942 // if(throwable != null) {
1943 // if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1944 // else throw new DatabaseException("Unexpected exception", throwable);
1946 // return result.get();
1951 public <T> T syncRequest(ExternalRead<T> request, final Procedure<T> procedure) throws DatabaseException {
1953 Semaphore notify = new Semaphore(0);
1954 final DataContainer<Throwable> container = new DataContainer<Throwable>();
1955 final DataContainer<T> result = new DataContainer<T>();
1956 scheduleRequest(request, procedure, notify, container, result);
1957 acquire(notify, request);
1958 Throwable throwable = container.get();
1959 if (throwable != null) {
1960 if(throwable instanceof DatabaseException) throw (DatabaseException)throwable;
1961 else throw new DatabaseException("Unexpected exception", throwable);
1963 return result.get();
1967 public void syncRequest(Write request) throws DatabaseException {
1970 Semaphore notify = new Semaphore(0);
1971 final DataContainer<DatabaseException> exception = new DataContainer<DatabaseException>();
1972 scheduleRequest(request, e -> exception.set(e), notify);
1973 acquire(notify, request);
1974 if(exception.get() != null) throw exception.get();
1978 public <T> T syncRequest(WriteResult<T> request) throws DatabaseException {
1980 Semaphore notify = new Semaphore(0);
1981 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
1982 final DataContainer<T> result = new DataContainer<T>();
1983 scheduleRequest(request, new Procedure<T>() {
1986 public void exception(Throwable t) {
1991 public void execute(T t) {
1996 acquire(notify, request);
1997 if(exception.get() != null) {
1998 Throwable t = exception.get();
1999 if(t instanceof DatabaseException) throw (DatabaseException)t;
2000 else throw new DatabaseException(t);
2002 return result.get();
2006 public <T> T syncRequest(WriteOnlyResult<T> request) throws DatabaseException {
2008 Semaphore notify = new Semaphore(0);
2009 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2010 final DataContainer<T> result = new DataContainer<T>();
2011 scheduleRequest(request, new Procedure<T>() {
2014 public void exception(Throwable t) {
2019 public void execute(T t) {
2024 acquire(notify, request);
2025 if(exception.get() != null) {
2026 Throwable t = exception.get();
2027 if(t instanceof DatabaseException) throw (DatabaseException)t;
2028 else throw new DatabaseException(t);
2030 return result.get();
2034 public <T> T syncRequest(DelayedWriteResult<T> request) throws DatabaseException {
2036 Semaphore notify = new Semaphore(0);
2037 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2038 final DataContainer<T> result = new DataContainer<T>();
2039 scheduleRequest(request, new Procedure<T>() {
2042 public void exception(Throwable t) {
2047 public void execute(T t) {
2052 acquire(notify, request);
2053 if(exception.get() != null) {
2054 Throwable t = exception.get();
2055 if(t instanceof DatabaseException) throw (DatabaseException)t;
2056 else throw new DatabaseException(t);
2058 return result.get();
2062 public void syncRequest(DelayedWrite request) throws DatabaseException {
2064 Semaphore notify = new Semaphore(0);
2065 final DataContainer<DatabaseException> exception = new DataContainer<DatabaseException>();
2066 scheduleRequest(request, e -> exception.set(e), notify);
2067 acquire(notify, request);
2068 if(exception.get() != null) throw exception.get();
2072 public void syncRequest(WriteOnly request) throws DatabaseException {
2075 Semaphore notify = new Semaphore(0);
2076 final DataContainer<DatabaseException> exception = new DataContainer<DatabaseException>();
2077 scheduleRequest(request, e -> exception.set(e), notify);
2078 acquire(notify, request);
2079 if(exception.get() != null) throw exception.get();
2084 * GraphRequestProcessor interface
2088 public <T> void asyncRequest(final AsyncRead<T> request, final AsyncProcedure<T> procedure) {
2090 scheduleRequest(request, procedure, null, null);
2095 public <T> void asyncRequest(final AsyncMultiRead<T> request, final AsyncMultiProcedure<T> procedure) {
2097 scheduleRequest(request, procedure, null);
2102 public <T> void asyncRequest(final ExternalRead<T> request, final Procedure<T> procedure) {
2104 scheduleRequest(request, procedure, null, null, null);
2109 public void asyncRequest(final Write request, final Consumer<DatabaseException> callback) {
2111 scheduleRequest(request, callback, null);
2116 public <T> void asyncRequest(final WriteResult<T> request, final Procedure<T> procedure) {
2118 scheduleRequest(request, procedure, null);
2123 public <T> void asyncRequest(final WriteOnlyResult<T> request, final Procedure<T> procedure) {
2125 scheduleRequest(request, procedure, null);
2130 public <T> void asyncRequest(final DelayedWriteResult<T> request, final Procedure<T> procedure) {
2132 scheduleRequest(request, procedure, null);
2137 public void asyncRequest(final DelayedWrite request, final Consumer<DatabaseException> callback) {
2139 scheduleRequest(request, callback, null);
2144 public void asyncRequest(final Write r) {
2145 asyncRequest(r, null);
2149 public void asyncRequest(final DelayedWrite r) {
2150 asyncRequest(r, null);
2154 public void asyncRequest(final WriteOnly request, final Consumer<DatabaseException> callback) {
2156 scheduleRequest(request, callback, null);
2161 public void asyncRequest(final WriteOnly request) {
2163 asyncRequest(request, null);
2168 public <T> void async(ReadInterface<T> r, AsyncProcedure<T> procedure) {
2169 r.request(this, procedure);
2173 public <T> void async(ReadInterface<T> r, Procedure<T> procedure) {
2174 r.request(this, procedure);
2178 public <T> void async(ReadInterface<T> r, SyncProcedure<T> procedure) {
2179 r.request(this, procedure);
2183 public <T> void async(ReadInterface<T> r, AsyncListener<T> procedure) {
2184 r.request(this, procedure);
2188 public <T> void async(ReadInterface<T> r, Listener<T> procedure) {
2189 r.request(this, procedure);
2193 public <T> void async(ReadInterface<T> r, SyncListener<T> procedure) {
2194 r.request(this, procedure);
2198 public <T> T sync(ReadInterface<T> r) throws DatabaseException {
2199 return r.request(this);
2203 public <T> T sync(WriteInterface<T> r) throws DatabaseException {
2204 return r.request(this);
2208 public <T> void async(WriteInterface<T> r, Procedure<T> procedure) {
2209 r.request(this, procedure);
2213 public <T> void async(WriteInterface<T> r) {
2214 r.request(this, new ProcedureAdapter<T>());
2218 public void incAsync() {
2223 public void decAsync() {
2227 public long getCluster(ResourceImpl resource) {
2228 ClusterI cluster = clusterTable.getClusterByResourceKey(resource.id);
2229 return cluster.getClusterId();
2232 public long getCluster(int id) {
2233 if (clusterTable == null)
2234 System.out.println("SessionImplSocket.getCluster() clusterTable == null !!!!! how come");
2235 return clusterTable.getClusterIdByResourceKeyNoThrow(id);
2238 public ResourceImpl getResource(int id) {
2239 return new ResourceImpl(resourceSupport, id);
2242 public ResourceImpl getResource(int resourceIndex, long clusterId) {
2243 assert (!ClusterTraitsBase.isIllegalResourceIndex(resourceIndex));
2244 ClusterI proxy = clusterTable.getClusterByClusterId(clusterId);
2245 int key = proxy.getClusterKey();
2246 int resourceKey = ClusterTraitsBase.createResourceKeyNoThrow(key, resourceIndex);
2247 return new ResourceImpl(resourceSupport, resourceKey);
2250 public ResourceImpl getResource2(int id) {
2252 return new ResourceImpl(resourceSupport, id);
2255 final public int getId(ResourceImpl impl) {
2259 public static final Charset UTF8 = Charset.forName("utf-8");
2264 static boolean areVirtualStatementsLoaded(final VirtualGraphServerSupportImpl support, int subject) {
2265 for(TransientGraph g : support.providers) {
2266 if(g.isPending(subject)) return false;
2271 static boolean areVirtualStatementsLoaded(final VirtualGraphServerSupportImpl support, int subject, int predicate) {
2272 for(TransientGraph g : support.providers) {
2273 if(g.isPending(subject, predicate)) return false;
2278 static void loadVirtualStatements(final VirtualGraphServerSupportImpl support, ReadGraphImpl graph, int subject, final Consumer<ReadGraphImpl> runnable) {
2280 Consumer<ReadGraphImpl> composite = new Consumer<ReadGraphImpl>() {
2282 AtomicInteger ready = new AtomicInteger(support.providers.size() + 1);
2285 public void accept(ReadGraphImpl graph) {
2286 if(ready.decrementAndGet() == 0) {
2287 runnable.accept(graph);
2293 for(TransientGraph g : support.providers) {
2294 if(g.isPending(subject)) {
2296 g.load(graph, subject, composite);
2297 } catch (DatabaseException e) {
2298 e.printStackTrace();
2301 composite.accept(graph);
2305 composite.accept(graph);
2309 static void loadVirtualStatements(final VirtualGraphServerSupportImpl support, ReadGraphImpl graph, int subject, int predicate, final Consumer<ReadGraphImpl> runnable) {
2311 Consumer<ReadGraphImpl> composite = new Consumer<ReadGraphImpl>() {
2313 AtomicInteger ready = new AtomicInteger(support.providers.size() + 1);
2316 public void accept(ReadGraphImpl graph) {
2317 if(ready.decrementAndGet() == 0) {
2318 runnable.accept(graph);
2324 for(TransientGraph g : support.providers) {
2325 if(g.isPending(subject, predicate)) {
2327 g.load(graph, subject, predicate, composite);
2328 } catch (DatabaseException e) {
2329 e.printStackTrace();
2332 composite.accept(graph);
2336 composite.accept(graph);
2340 // void dumpHeap() {
2343 // ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
2344 // "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class).dumpHeap(
2345 // "d:/heap" + flushCounter + ".txt", true);
2346 // } catch (IOException e) {
2347 // e.printStackTrace();
2352 void fireReactionsToSynchronize(ChangeSet cs) {
2354 // Do not fire empty events
2358 ReadGraphImpl g = ReadGraphImpl.create(getQueryProvider2());
2359 // g.state.barrier.inc();
2363 if (!cs.isEmpty()) {
2364 ChangeEvent e2 = new ChangeEvent(g.getSession(), g, null, cs);
2365 for (ChangeListener l : changeListeners2) {
2368 } catch (Exception ex) {
2369 ex.printStackTrace();
2376 // g.state.barrier.dec();
2377 // g.waitAsync(null);
2383 void fireReactionsToCommit(ReadGraphImpl graph, ChangeSet cs2) {
2386 // Do not fire empty events
2391 // graph.state.barrier.inc();
2395 if (!cs2.isEmpty()) {
2397 ChangeEvent e2 = new ChangeEvent(graph.getSession(), graph, null, cs2);
2398 for (ChangeListener l : changeListeners2) {
2401 // System.out.println("changelistener " + l);
2402 } catch (Exception ex) {
2403 ex.printStackTrace();
2411 // graph.state.barrier.dec();
2412 // graph.waitAsync(null);
2415 } catch (Throwable t) {
2416 t.printStackTrace();
2420 void fireMetadataListeners(WriteGraphImpl graph, ChangeSet cs2) {
2424 // Do not fire empty events
2428 // Do not fire on virtual requests
2429 if(graph.getProvider() != null)
2432 WriteGraphImpl reactionGraph = WriteGraphImpl.create(graph.processor, writeSupport, null);
2436 ChangeEvent e2 = new ChangeEvent(graph.getSession(), reactionGraph, graph, cs2);
2437 for (ChangeListener l : metadataListeners) {
2440 } catch (Throwable ex) {
2441 ex.printStackTrace();
2449 } catch (Throwable t) {
2450 t.printStackTrace();
2459 * @see org.simantics.db.ServiceLocator#getService(java.lang.Class)
2462 public <T> T getService(Class<T> api) {
2463 T t = peekService(api);
2465 if (state.isClosed())
2466 throw new ServiceNotFoundException(this, api, "Session has been shut down");
2467 throw new ServiceNotFoundException(this, api);
2475 protected abstract ServerInformation getCachedServerInformation();
2477 private Class<?> serviceKey1 = null;
2478 private Class<?> serviceKey2 = null;
2479 private Object service1 = null;
2480 private Object service2 = null;
2486 * fi.vtt.simantics.db.connection.ServiceLocator#peekService(java.lang.Class)
2488 @SuppressWarnings("unchecked")
2490 public synchronized <T> T peekService(Class<T> api) {
2492 if(serviceKey1 == api) {
2494 } else if (serviceKey2 == api) {
2496 Object result = service2;
2497 service2 = service1;
2498 serviceKey2 = serviceKey1;
2504 if (Layer0.class == api)
2506 if (ServerInformation.class == api)
2507 return (T) getCachedServerInformation();
2508 else if (WriteGraphImpl.class == api)
2509 return (T) writeState.getGraph();
2510 else if (ClusterBuilder.class == api)
2511 return (T)new ClusterBuilderImpl(this, (WriteOnlySupport)writeState.getGraph().writeSupport);
2512 else if (ClusterBuilderFactory.class == api)
2513 return (T)new ClusterBuilderFactoryImpl(this);
2515 service2 = service1;
2516 serviceKey2 = serviceKey1;
2518 service1 = serviceLocator.peekService(api);
2529 * fi.vtt.simantics.db.connection.ServiceLocator#hasService(java.lang.Class)
2532 public boolean hasService(Class<?> api) {
2533 return serviceLocator.hasService(api);
2537 * @param api the api that must be implemented by the specified service
2538 * @param service the service implementation
2541 public <T> void registerService(Class<T> api, T service) {
2542 if(Layer0.class == api) {
2543 L0 = (Layer0)service;
2546 serviceLocator.registerService(api, service);
2547 if (TransactionPolicySupport.class == api) {
2548 transactionPolicy = (TransactionPolicySupport)service;
2549 state.resetTransactionPolicy();
2551 if (api == serviceKey1)
2553 else if (api == serviceKey2)
2561 void fireSessionVariableChange(String variable) {
2562 for (MonitorHandler h : monitorHandlers) {
2563 MonitorContext ctx = monitorContexts.getLeft(h);
2565 // SafeRunner functionality repeated here to avoid dependency.
2567 h.valuesChanged(ctx);
2568 } catch (Exception e) {
2569 Logger.defaultLogError("monitor handler notification produced the following exception", e);
2570 } catch (LinkageError e) {
2571 Logger.defaultLogError("monitor handler notification produced a linkage error", e);
2577 class ResourceSerializerImpl implements ResourceSerializer {
2579 public long createRandomAccessId(int id) throws DatabaseException {
2582 int index = ClusterTraitsBase.getResourceIndexFromResourceKey(id);
2583 long cluster = getCluster(id);
2585 return 0; // Better to return 0 then invalid id.
2586 long result = ClusterTraitsBase.createResourceId(cluster, index);
2591 public long getRandomAccessId(Resource resource) throws DatabaseException {
2593 ResourceImpl resourceImpl = (ResourceImpl) resource;
2594 return createRandomAccessId(resourceImpl.id);
2599 public int getTransientId(Resource resource) throws DatabaseException {
2601 ResourceImpl resourceImpl = (ResourceImpl) resource;
2602 return resourceImpl.id;
2607 public String createRandomAccessId(Resource resource)
2608 throws InvalidResourceReferenceException {
2610 if(resource == null) throw new IllegalArgumentException();
2612 ResourceImpl resourceImpl = (ResourceImpl) resource;
2614 if (resourceImpl.id < 0) return String.valueOf(resourceImpl.id) + "_0";
2618 r = ClusterTraits.getResourceIndexFromResourceKey(resourceImpl.id);
2619 } catch (DatabaseException e1) {
2620 throw new InvalidResourceReferenceException(e1);
2623 // Serialize as '<resource index>_<cluster id>'
2624 return "" + r + "_" + getCluster(resourceImpl);
2625 } catch (Throwable e) {
2626 e.printStackTrace();
2627 throw new InvalidResourceReferenceException(e);
2632 public int getTransientId(long serialized) throws DatabaseException {
2633 if (serialized <= 0)
2634 return (int)serialized;
2635 int index = ClusterTraitsBase.getResourceIndexFromResourceId(serialized);
2636 long c = ClusterTraitsBase.getClusterIdFromResourceId(serialized);
2637 ClusterI cluster = clusterTranslator.getClusterByClusterId(c);
2638 if (cluster == null)
2639 throw new DatabaseException("Couldn't load cluster for id " + c + " for resource id " + serialized);
2640 int key = ClusterTraits.createResourceKey(cluster.getClusterKey(), index);
2645 public Resource getResource(long randomAccessId) throws DatabaseException {
2646 return getResourceByKey(getTransientId(randomAccessId));
2650 public Resource getResource(int transientId) throws DatabaseException {
2651 return getResourceByKey(transientId);
2655 public Resource getResource(String randomAccessId)
2656 throws InvalidResourceReferenceException {
2658 int i = randomAccessId.indexOf('_');
2660 throw new InvalidResourceReferenceException("Could not parse resource id + cluster id from '"
2661 + randomAccessId + "'");
2662 int r = Integer.parseInt(randomAccessId.substring(0, i));
2663 if(r < 0) return getResourceByKey(r);
2664 long c = Long.parseLong(randomAccessId.substring(i + 1));
2665 ClusterI cluster = clusterTranslator.getClusterByClusterId(c);
2666 int key = ClusterTraits.createResourceKey(cluster.getClusterKey(), r);
2667 if (cluster.hasResource(key, clusterTranslator))
2668 return getResourceByKey(key);
2669 } catch (InvalidResourceReferenceException e) {
2671 } catch (NumberFormatException e) {
2672 throw new InvalidResourceReferenceException(e);
2673 } catch (Throwable e) {
2674 e.printStackTrace();
2675 throw new InvalidResourceReferenceException(e);
2678 throw new InvalidResourceReferenceException("Resource does not exist " + randomAccessId);
2682 public boolean disposeRandomAccessId(String randomAccessId) throws InvalidResourceReferenceException {
2685 } catch (Throwable e) {
2686 e.printStackTrace();
2687 throw new InvalidResourceReferenceException(e);
2693 // Copied from old SessionImpl
2696 if (state.isClosed())
2697 throw new Error("Session closed.");
2702 public ResourceImpl getNewResource(long clusterId) {
2703 ClusterI cluster = clusterTable.getClusterByClusterIdOrThrow(clusterId);
2706 newId = cluster.createResource(clusterTranslator);
2707 } catch (DatabaseException e) {
2708 Logger.defaultLogError(e);
2711 return new ResourceImpl(resourceSupport, newId);
2714 public ResourceImpl getNewResource(Resource clusterSet)
2715 throws DatabaseException {
2716 long resourceId = clusterSet.getResourceId();
2717 Long clusterId = clusterSetsSupport.get(resourceId);
2718 if (null == clusterId)
2719 throw new ClusterSetExistException("Cluster set does not exist. Resource=" + clusterSet);
2720 if (Constants.NewClusterId == clusterId) {
2721 clusterId = getService(ClusteringSupport.class).createCluster();
2722 if ((serviceMode & SERVICE_MODE_CREATE) > 0)
2723 createdClusters.add(clusterId);
2724 clusterSetsSupport.put(resourceId, clusterId);
2725 return getNewResource(clusterId);
2727 ClusterBase cb = clusterTranslator.getClusterByClusterId(clusterId);
2728 ResourceImpl result;
2729 if (cb.getNumberOfResources(clusterTranslator) >= ClusterTable.CLUSTER_FILL_SIZE) {
2730 clusterId = getService(ClusteringSupport.class).createCluster();
2731 if ((serviceMode & SERVICE_MODE_CREATE) > 0)
2732 createdClusters.add(clusterId);
2733 clusterSetsSupport.put(resourceId, clusterId);
2734 return getNewResource(clusterId);
2736 result = getNewResource(clusterId);
2737 int resultKey = querySupport.getId(result);
2738 long resultCluster = querySupport.getClusterId(resultKey);
2739 if (clusterId != resultCluster)
2740 clusterSetsSupport.put(resourceId, resultCluster);
2746 public void getNewClusterSet(Resource clusterSet)
2747 throws DatabaseException {
2749 System.out.println("new cluster set=" + clusterSet);
2750 long resourceId = clusterSet.getResourceId();
2751 if (clusterSetsSupport.containsKey(resourceId))
2752 throw new ClusterSetExistException("Cluster set exist already. Resource=" + clusterSet);
2753 clusterSetsSupport.put(resourceId, Constants.NewClusterId);
2755 public boolean containsClusterSet(Resource clusterSet)
2756 throws ServiceException {
2757 long resourceId = clusterSet.getResourceId();
2758 return clusterSetsSupport.containsKey(resourceId);
2760 public Resource setDefaultClusterSet4NewResource(Resource clusterSet) {
2761 Resource r = defaultClusterSet;
2762 defaultClusterSet = clusterSet;
2765 void printDiagnostics() {
2769 final DataContainer<Long> totalMem = new DataContainer<Long>(0L);
2770 final DataContainer<Long> residentClusters = new DataContainer<Long>(0L);
2771 for(ClusterI cluster : clusterTable.getClusters()) {
2773 if (cluster.isLoaded() && !cluster.isEmpty()) {
2774 residentClusters.set(residentClusters.get() + 1);
2775 totalMem.set(totalMem.get() + cluster.getUsedSpace());
2777 } catch (DatabaseException e) {
2778 Logger.defaultLogError(e);
2782 System.out.println("--------------------------------");
2783 System.out.println("Cluster information:");
2784 System.out.println("-amount of resident clusters=" + residentClusters.get());
2785 System.out.println("-total memory usage=" + totalMem.get() / 1024 + "kB");
2787 for(ClusterI cluster : clusterTable.getClusters()) {
2788 System.out.print("Cluster " + cluster.getClusterId() + " [");
2790 if (!cluster.isLoaded())
2791 System.out.println("not loaded]");
2792 else if (cluster.isEmpty())
2793 System.out.println("is empty]");
2795 System.out.print("resources=" + cluster.getNumberOfResources(clusterTranslator));
2796 System.out.print(",references=" + cluster.getReferenceCount());
2797 System.out.println(",memory=" + cluster.getUsedSpace() / 1024 + "kB]");
2799 } catch (DatabaseException e) {
2800 Logger.defaultLogError(e);
2801 System.out.println("is corrupted]");
2805 queryProvider2.printDiagnostics();
2806 System.out.println("--------------------------------");
2811 public void fireStartReadTransaction() {
2814 System.out.println("StartReadTransaction");
2816 for (SessionEventListener listener : eventListeners) {
2818 listener.readTransactionStarted();
2819 } catch (Throwable t) {
2820 t.printStackTrace();
2826 public void fireFinishReadTransaction() {
2829 System.out.println("FinishReadTransaction");
2831 for (SessionEventListener listener : eventListeners) {
2833 listener.readTransactionFinished();
2834 } catch (Throwable t) {
2835 t.printStackTrace();
2841 public void fireStartWriteTransaction() {
2844 System.out.println("StartWriteTransaction");
2846 for (SessionEventListener listener : eventListeners) {
2848 listener.writeTransactionStarted();
2849 } catch (Throwable t) {
2850 t.printStackTrace();
2856 public void fireFinishWriteTransaction() {
2859 System.out.println("FinishWriteTransaction");
2861 for (SessionEventListener listener : eventListeners) {
2863 listener.writeTransactionFinished();
2864 } catch (Throwable t) {
2865 t.printStackTrace();
2869 Indexing.resetDependenciesIndexingDisabled();
2873 Resource deserialize(final long resourceId, final long clusterId) throws IOException {
2874 throw new Error("Not supported at the moment.");
2881 ClusterTable getClusterTable() {
2882 return clusterTable;
2885 public GraphSession getGraphSession() {
2886 return graphSession;
2889 public QueryProcessor getQueryProvider2() {
2890 return queryProvider2;
2893 ClientChangesImpl getClientChanges() {
2894 return clientChanges;
2897 boolean getWriteOnly() {
2901 static int counter = 0;
2903 public void onClusterLoaded(long clusterId) {
2905 clusterTable.updateSize();
2913 * Implementation of the interface RequestProcessor
2917 public <T> T syncRequest(final Read<T> request) throws DatabaseException {
2922 assert(request != null);
2924 final DataContainer<T> result = new DataContainer<T>();
2925 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2927 syncRequest(request, new AsyncProcedure<T>() {
2930 public void execute(AsyncReadGraph graph, T t) {
2935 public void exception(AsyncReadGraph graph, Throwable t) {
2941 Throwable t = exception.get();
2943 if(t instanceof DatabaseException) throw (DatabaseException)t;
2944 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
2947 return result.get();
2952 // public <T> T syncRequest(Read<T> request, AsyncListener<T> procedure) throws DatabaseException {
2953 // assertNotSession();
2954 // return syncRequest(request, (AsyncProcedure<T>)procedure);
2958 public <T> T syncRequest(Read<T> request, SyncListener<T> procedure) throws DatabaseException {
2960 return syncRequest(request, new SyncToAsyncListener<T>(procedure));
2964 public <T> T syncRequest(Read<T> request, final Listener<T> procedure) throws DatabaseException {
2966 return syncRequest(request, new NoneToAsyncListener<T>(procedure));
2970 public <T> T syncRequest(final Read<T> request, final SyncProcedure<T> procedure) throws DatabaseException {
2972 return syncRequest(request, new SyncToAsyncProcedure<T>(procedure));
2976 public <T> T syncRequest(Read<T> request, Procedure<T> procedure) throws DatabaseException {
2978 return syncRequest(request, new NoneToAsyncProcedure<T>(procedure));
2982 public <T> T syncRequest(final AsyncRead<T> request) throws DatabaseException {
2986 assert(request != null);
2988 final DataContainer<T> result = new DataContainer<T>();
2989 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2991 syncRequest(request, new AsyncProcedure<T>() {
2994 public void execute(AsyncReadGraph graph, T t) {
2999 public void exception(AsyncReadGraph graph, Throwable t) {
3005 Throwable t = exception.get();
3007 if(t instanceof DatabaseException) throw (DatabaseException)t;
3008 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
3011 return result.get();
3016 public <T> T syncRequest(AsyncRead<T> request, AsyncListener<T> procedure) throws DatabaseException {
3018 return syncRequest(request, (AsyncProcedure<T>)procedure);
3022 public <T> T syncRequest(AsyncRead<T> request, SyncListener<T> procedure) throws DatabaseException {
3024 return syncRequest(request, new SyncToAsyncListener<T>(procedure));
3028 public <T> T syncRequest(AsyncRead<T> request, Listener<T> procedure) throws DatabaseException {
3030 return syncRequest(request, new NoneToAsyncListener<T>(procedure));
3034 public <T> T syncRequest(AsyncRead<T> request, final SyncProcedure<T> procedure) throws DatabaseException {
3036 return syncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3040 final public <T> T syncRequest(final AsyncRead<T> request, final Procedure<T> procedure) throws DatabaseException {
3042 return syncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3046 public <T> Collection<T> syncRequest(MultiRead<T> request) throws DatabaseException {
3050 assert(request != null);
3052 final ArrayList<T> result = new ArrayList<T>();
3053 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
3055 syncRequest(request, new AsyncMultiProcedure<T>() {
3058 public void execute(AsyncReadGraph graph, T t) {
3059 synchronized(result) {
3065 public void finished(AsyncReadGraph graph) {
3069 public void exception(AsyncReadGraph graph, Throwable t) {
3076 Throwable t = exception.get();
3078 if(t instanceof DatabaseException) throw (DatabaseException)t;
3079 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
3087 public <T> Collection<T> syncRequest(MultiRead<T> request, AsyncMultiListener<T> procedure) throws DatabaseException {
3089 return syncRequest(request, (AsyncMultiProcedure<T>)procedure);
3093 public <T> Collection<T> syncRequest(MultiRead<T> request, SyncMultiListener<T> procedure) throws DatabaseException {
3095 return syncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3099 public <T> Collection<T> syncRequest(MultiRead<T> request, MultiListener<T> procedure) throws DatabaseException {
3101 return syncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3105 public <T> Collection<T> syncRequest(MultiRead<T> request, SyncMultiProcedure<T> procedure) throws DatabaseException {
3107 return syncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3111 public <T> Collection<T> syncRequest(MultiRead<T> request, MultiProcedure<T> procedure) throws DatabaseException {
3113 return syncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3117 final public <T> Collection<T> syncRequest(final AsyncMultiRead<T> request) throws DatabaseException {
3121 assert(request != null);
3123 final ArrayList<T> result = new ArrayList<T>();
3124 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
3126 syncRequest(request, new AsyncMultiProcedure<T>() {
3129 public void execute(AsyncReadGraph graph, T t) {
3130 synchronized(result) {
3136 public void finished(AsyncReadGraph graph) {
3140 public void exception(AsyncReadGraph graph, Throwable t) {
3147 Throwable t = exception.get();
3149 if(t instanceof DatabaseException) throw (DatabaseException)t;
3150 else throw new DatabaseException("Unexpected exception in ReadGraph.syncRequest(Read)", t);
3158 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, AsyncMultiListener<T> procedure) throws DatabaseException {
3160 return syncRequest(request, (AsyncMultiProcedure<T>)procedure);
3164 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, SyncMultiListener<T> procedure) throws DatabaseException {
3166 return syncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3170 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, MultiListener<T> procedure) throws DatabaseException {
3172 return syncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3176 public <T> Collection<T> syncRequest(AsyncMultiRead<T> request, final SyncMultiProcedure<T> procedure) throws DatabaseException {
3178 return syncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3182 final public <T> Collection<T> syncRequest(final AsyncMultiRead<T> request, final MultiProcedure<T> procedure) throws DatabaseException {
3184 return syncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3189 public <T> void asyncRequest(Read<T> request) {
3191 asyncRequest(request, new ProcedureAdapter<T>() {
3193 public void exception(Throwable t) {
3194 t.printStackTrace();
3201 public <T> void asyncRequest(Read<T> request, AsyncListener<T> procedure) {
3202 asyncRequest(request, (AsyncProcedure<T>)procedure);
3206 public <T> void asyncRequest(Read<T> request, final SyncListener<T> procedure) {
3207 asyncRequest(request, new SyncToAsyncListener<T>(procedure));
3211 public <T> void asyncRequest(Read<T> request, final Listener<T> procedure) {
3212 asyncRequest(request, new NoneToAsyncListener<T>(procedure));
3216 public <T> void asyncRequest(Read<T> request, SyncProcedure<T> procedure) {
3217 asyncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3221 public <T> void asyncRequest(Read<T> request, final Procedure<T> procedure) {
3222 asyncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3226 final public <T> void asyncRequest(final AsyncRead<T> request) {
3228 assert(request != null);
3230 asyncRequest(request, new ProcedureAdapter<T>() {
3232 public void exception(Throwable t) {
3233 t.printStackTrace();
3240 public <T> void asyncRequest(AsyncRead<T> request, AsyncListener<T> procedure) {
3241 scheduleRequest(request, procedure, procedure, null);
3245 public <T> void asyncRequest(AsyncRead<T> request, final SyncListener<T> procedure) {
3246 asyncRequest(request, new SyncToAsyncListener<T>(procedure));
3250 public <T> void asyncRequest(AsyncRead<T> request, final Listener<T> procedure) {
3251 asyncRequest(request, new NoneToAsyncListener<T>(procedure));
3255 public <T> void asyncRequest(AsyncRead<T> request, SyncProcedure<T> procedure) {
3256 asyncRequest(request, new SyncToAsyncProcedure<T>(procedure));
3260 final public <T> void asyncRequest(final AsyncRead<T> request, final Procedure<T> procedure) {
3261 asyncRequest(request, new NoneToAsyncProcedure<T>(procedure));
3265 public <T> void asyncRequest(MultiRead<T> request) {
3267 assert(request != null);
3269 asyncRequest(request, new AsyncMultiProcedureAdapter<T>() {
3271 public void exception(AsyncReadGraph graph, Throwable t) {
3272 t.printStackTrace();
3279 public <T> void asyncRequest(MultiRead<T> request, AsyncMultiListener<T> procedure) {
3280 asyncRequest(request, (AsyncMultiProcedure<T>)procedure);
3284 public <T> void asyncRequest(MultiRead<T> request, SyncMultiListener<T> procedure) {
3285 asyncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3289 public <T> void asyncRequest(MultiRead<T> request, MultiListener<T> procedure) {
3290 asyncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3294 public <T> void asyncRequest(MultiRead<T> request, SyncMultiProcedure<T> procedure) {
3295 asyncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3299 public <T> void asyncRequest(MultiRead<T> request, MultiProcedure<T> procedure) {
3300 asyncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3304 final public <T> void asyncRequest(AsyncMultiRead<T> request) {
3306 assert(request != null);
3308 asyncRequest(request, new AsyncMultiProcedureAdapter<T>() {
3310 public void exception(AsyncReadGraph graph, Throwable t) {
3311 t.printStackTrace();
3318 public <T> void asyncRequest(AsyncMultiRead<T> request, AsyncMultiListener<T> procedure) {
3319 asyncRequest(request, (AsyncMultiProcedure<T>)procedure);
3323 public <T> void asyncRequest(AsyncMultiRead<T> request, SyncMultiListener<T> procedure) {
3324 asyncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
3328 public <T> void asyncRequest(AsyncMultiRead<T> request, MultiListener<T> procedure) {
3329 asyncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
3333 public <T> void asyncRequest(AsyncMultiRead<T> request, SyncMultiProcedure<T> procedure) {
3334 asyncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
3338 final public <T> void asyncRequest(AsyncMultiRead<T> request, final MultiProcedure<T> procedure) {
3339 asyncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
3343 public <T> Collection<T> syncRequest(MultiRead<T> arg0, AsyncMultiProcedure<T> arg1) throws DatabaseException {
3345 throw new Error("Not implemented!");
3349 public <T> void asyncRequest(MultiRead<T> arg0, AsyncMultiProcedure<T> arg1) {
3350 throw new Error("Not implemented!");
3354 final public <T> void asyncRequest(final ExternalRead<T> request) {
3356 assert(request != null);
3358 asyncRequest(request, new ProcedureAdapter<T>() {
3360 public void exception(Throwable t) {
3361 t.printStackTrace();
3368 public <T> void asyncRequest(ExternalRead<T> request, final Listener<T> procedure) {
3369 asyncRequest(request, (Procedure<T>)procedure);
3374 void check(Throwable t) throws DatabaseException {
3376 if(t instanceof DatabaseException) throw (DatabaseException)t;
3377 else throw new DatabaseException("Unexpected exception", t);
3381 void check(DataContainer<Throwable> container) throws DatabaseException {
3382 Throwable t = container.get();
3384 if(t instanceof DatabaseException) throw (DatabaseException)t;
3385 else throw new DatabaseException("Unexpected exception", t);
3394 boolean sameProvider(Write request) {
3395 if(writeState.getGraph().provider != null) {
3396 return writeState.getGraph().provider.equals(request.getProvider());
3398 return request.getProvider() == null;
3402 boolean plainWrite(WriteGraphImpl graph) {
3403 if(graph == null) return false;
3404 if(graph.writeSupport.writeOnly()) return false;
3409 public static final ThreadGroup SessionThreadGroup = new ThreadGroup("Session Thread Group");
3410 private void assertNotSession() throws DatabaseException {
3411 Thread current = Thread.currentThread();
3412 if(sessionThreads.contains(current)) throw new DatabaseException("Caller is already inside a transaction.");
3415 void assertAlive() {
3416 if (!state.isAlive())
3417 throw new RuntimeDatabaseException("Session has been shut down.");
3420 public InputStream getValueStream(ReadGraphImpl graph, Resource resource) {
3421 return querySupport.getValueStream(graph, querySupport.getId(resource));
3424 public byte[] getValue(ReadGraphImpl graph, Resource resource) {
3425 return querySupport.getValue(graph, querySupport.getId(resource));
3428 <T> void acquire(Semaphore semaphore, T request) throws DatabaseException {
3429 acquire(semaphore, request, null);
3432 private <T,P> void acquire(Semaphore semaphore, T request, P procedure) throws DatabaseException {
3436 // Loop until the semaphore is acquired reporting requests that take a long time.
3439 if (semaphore.tryAcquire(DebugPolicy.LONG_EXECUTION_REPORT_PERIOD, DebugPolicy.LONG_EXECUTION_REPORT_PERIOD_UNIT)) {
3443 if (DebugPolicy.REPORT_TIME_CONSUMING_REQUESTS) {
3445 long waitTime = DebugPolicy.LONG_EXECUTION_REPORT_PERIOD_UNIT
3446 .toMillis(DebugPolicy.LONG_EXECUTION_REPORT_PERIOD)
3448 System.err.println("DB client request '" + request + "' is taking long to execute, so far "
3449 + (waitTime) + " ms. (procedure=" + procedure + ")");
3456 } catch (InterruptedException e) {
3457 e.printStackTrace();
3458 // FIXME: Should perhaps do something else in this case ??
3465 // public boolean holdOnToTransactionAfterCancel() {
3466 // return transactionPolicy.holdOnToTransactionAfterCancel();
3470 // public boolean holdOnToTransactionAfterCommit() {
3471 // return transactionPolicy.holdOnToTransactionAfterCommit();
3475 // public boolean holdOnToTransactionAfterRead() {
3476 // return transactionPolicy.holdOnToTransactionAfterRead();
3480 // public void onRelinquish() {
3481 // transactionPolicy.onRelinquish();
3485 // public void onRelinquishDone() {
3486 // transactionPolicy.onRelinquishDone();
3490 // public void onRelinquishError() {
3491 // transactionPolicy.onRelinquishError();
3496 public Session getSession() {
3501 protected abstract VirtualGraph getProvider(VirtualGraph virtualGraph);
3502 protected abstract ResourceImpl getNewResource() throws DatabaseException;
3504 public void ceased(int thread) {
3506 requestManager.ceased(thread);
3510 public int getAmountOfQueryThreads() {
3511 // This must be a power of two
3513 // return Integer.highestOneBit(Runtime.getRuntime().availableProcessors());
3516 public Resource getResourceByKey(int key) throws ResourceNotFoundException {
3518 return new ResourceImpl(resourceSupport, key);
3522 public void acquireWriteOnly() {
3526 public void releaseWriteOnly(ReadGraphImpl graph) {
3528 queryProvider2.releaseWrite(graph);
3531 public void handleUpdatesAndMetadata(WriteGraphImpl writer) {
3533 long start = System.nanoTime();
3535 while(dirtyPrimitives) {
3536 dirtyPrimitives = false;
3537 getQueryProvider2().performDirtyUpdates(writer);
3538 getQueryProvider2().performScheduledUpdates(writer);
3541 fireMetadataListeners(writer, clientChanges);
3543 if(DebugPolicy.PERFORMANCE_DATA) {
3544 long end = System.nanoTime();
3545 System.err.println("handleUpdatesAndMetadata " + 1e-9*(end-start));
3550 void removeTemporaryData() {
3551 File platform = Platform.getLocation().toFile();
3552 File tempFiles = new File(platform, "tempFiles");
3553 File temp = new File(tempFiles, "db");
3557 Files.walkFileTree(temp.toPath(), new SimpleFileVisitor<Path>() {
3559 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
3562 } catch (IOException e) {
3563 Logger.defaultLogError(e);
3565 return FileVisitResult.CONTINUE;
3568 } catch (IOException e) {
3569 Logger.defaultLogError(e);
3573 public void handleCreatedClusters() {
3574 if ((serviceMode & SERVICE_MODE_CREATE) > 0) {
3575 createdClusters.forEach(new TLongProcedure() {
3578 public boolean execute(long value) {
3579 ClusterImpl cluster = clusterTable.getClusterByClusterId(value);
3580 cluster.setImmutable(true, clusterTranslator);
3585 createdClusters.clear();
3589 public Object getModificationCounter() {
3590 return queryProvider2.modificationCounter;
3594 public void markUndoPoint() {
3595 state.setCombine(false);