]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.impl/src/org/simantics/db/impl/graph/ReadGraphImpl.java
5d4852c0d7822efe1f88ef70a1a7eb6a941cb272
[simantics/platform.git] / bundles / org.simantics.db.impl / src / org / simantics / db / impl / graph / ReadGraphImpl.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2018 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.impl.graph;
13
14 import java.io.BufferedOutputStream;
15 import java.io.File;
16 import java.io.FileOutputStream;
17 import java.io.IOException;
18 import java.io.PrintStream;
19 import java.lang.reflect.Array;
20 import java.lang.reflect.InvocationTargetException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashSet;
25 import java.util.IdentityHashMap;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.ListIterator;
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.function.Consumer;
32
33 import org.eclipse.core.runtime.Platform;
34 import org.simantics.databoard.Accessors;
35 import org.simantics.databoard.Bindings;
36 import org.simantics.databoard.accessor.Accessor;
37 import org.simantics.databoard.accessor.error.AccessorConstructionException;
38 import org.simantics.databoard.adapter.AdaptException;
39 import org.simantics.databoard.binding.Binding;
40 import org.simantics.databoard.binding.error.RuntimeBindingConstructionException;
41 import org.simantics.databoard.binding.impl.ObjectVariantBinding;
42 import org.simantics.databoard.binding.mutable.Variant;
43 import org.simantics.databoard.serialization.Serializer;
44 import org.simantics.databoard.type.Datatype;
45 import org.simantics.databoard.util.binary.BinaryFile;
46 import org.simantics.databoard.util.binary.RandomAccessBinary;
47 import org.simantics.db.AsyncReadGraph;
48 import org.simantics.db.ComputationalValue;
49 import org.simantics.db.DevelopmentKeys;
50 import org.simantics.db.ExternalValueSupport;
51 import org.simantics.db.ReadGraph;
52 import org.simantics.db.RelationContext;
53 import org.simantics.db.RelationInfo;
54 import org.simantics.db.Resource;
55 import org.simantics.db.Session;
56 import org.simantics.db.Statement;
57 import org.simantics.db.adaption.AdaptionService;
58 import org.simantics.db.common.primitiverequest.Adapter;
59 import org.simantics.db.common.primitiverequest.Builtin;
60 import org.simantics.db.common.primitiverequest.DatatypeBinding;
61 import org.simantics.db.common.primitiverequest.ForEachAssertedObject;
62 import org.simantics.db.common.primitiverequest.ForEachAssertedStatement;
63 import org.simantics.db.common.primitiverequest.HasStatement;
64 import org.simantics.db.common.primitiverequest.HasStatementSubject;
65 import org.simantics.db.common.primitiverequest.HasStatementSubjectObject;
66 import org.simantics.db.common.primitiverequest.HasValue;
67 import org.simantics.db.common.primitiverequest.Inverse;
68 import org.simantics.db.common.primitiverequest.IsInheritedFrom;
69 import org.simantics.db.common.primitiverequest.IsInstanceOf;
70 import org.simantics.db.common.primitiverequest.IsSubrelationOf;
71 import org.simantics.db.common.primitiverequest.OrderedSet;
72 import org.simantics.db.common.primitiverequest.PossibleAdapter;
73 import org.simantics.db.common.primitiverequest.PossibleInverse;
74 import org.simantics.db.common.primitiverequest.PossibleObject;
75 import org.simantics.db.common.primitiverequest.PossibleRelatedValue;
76 import org.simantics.db.common.primitiverequest.PossibleRelatedValueImplied;
77 import org.simantics.db.common.primitiverequest.PossibleStatement;
78 import org.simantics.db.common.primitiverequest.PossibleType;
79 import org.simantics.db.common.primitiverequest.PossibleUniqueAdapter;
80 import org.simantics.db.common.primitiverequest.PossibleValue;
81 import org.simantics.db.common.primitiverequest.PossibleValueImplied;
82 import org.simantics.db.common.primitiverequest.RelatedValue;
83 import org.simantics.db.common.primitiverequest.RelatedValueImplied;
84 import org.simantics.db.common.primitiverequest.SingleObject;
85 import org.simantics.db.common.primitiverequest.SingleStatement;
86 import org.simantics.db.common.primitiverequest.SingleType;
87 import org.simantics.db.common.primitiverequest.SingleTypeAny;
88 import org.simantics.db.common.primitiverequest.Types;
89 import org.simantics.db.common.primitiverequest.UniqueAdapter;
90 import org.simantics.db.common.primitiverequest.Value;
91 import org.simantics.db.common.primitiverequest.ValueImplied;
92 import org.simantics.db.common.primitiverequest.VariantValueImplied;
93 import org.simantics.db.common.procedure.adapter.AsyncMultiProcedureAdapter;
94 import org.simantics.db.common.procedure.adapter.AsyncProcedureAdapter;
95 import org.simantics.db.common.procedure.adapter.ProcedureAdapter;
96 import org.simantics.db.common.procedure.adapter.SyncMultiProcedureAdapter;
97 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
98 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
99 import org.simantics.db.common.procedure.single.SyncReadProcedure;
100 import org.simantics.db.common.procedure.single.wrapper.DeepSingleOrErrorProcedure;
101 import org.simantics.db.common.procedure.single.wrapper.DeepSingleOrNullProcedure;
102 import org.simantics.db.common.procedure.single.wrapper.ExceptionToNullProcedure;
103 import org.simantics.db.common.procedure.single.wrapper.NullSingleOrNullProcedure;
104 import org.simantics.db.common.procedure.single.wrapper.SingleFunctionalOrNullProcedure;
105 import org.simantics.db.common.procedure.single.wrapper.SingleOrErrorProcedure;
106 import org.simantics.db.common.procedure.single.wrapper.SingleOrNullProcedure;
107 import org.simantics.db.common.procedure.wrapper.NoneToAsyncListener;
108 import org.simantics.db.common.procedure.wrapper.NoneToAsyncMultiListener;
109 import org.simantics.db.common.procedure.wrapper.NoneToAsyncMultiProcedure;
110 import org.simantics.db.common.procedure.wrapper.NoneToAsyncProcedure;
111 import org.simantics.db.common.procedure.wrapper.NoneToAsyncSetProcedure;
112 import org.simantics.db.common.procedure.wrapper.NoneToSyncMultiListener;
113 import org.simantics.db.common.procedure.wrapper.NoneToSyncMultiProcedure;
114 import org.simantics.db.common.procedure.wrapper.SyncToAsyncListener;
115 import org.simantics.db.common.procedure.wrapper.SyncToAsyncMultiListener;
116 import org.simantics.db.common.procedure.wrapper.SyncToAsyncMultiProcedure;
117 import org.simantics.db.common.procedure.wrapper.SyncToAsyncProcedure;
118 import org.simantics.db.common.procedure.wrapper.SyncToAsyncSetProcedure;
119 import org.simantics.db.common.request.AdaptValue;
120 import org.simantics.db.common.request.ResourceRead;
121 import org.simantics.db.common.utils.Logger;
122 import org.simantics.db.common.utils.NameUtils;
123 import org.simantics.db.common.validation.L0Validations;
124 import org.simantics.db.exception.AdaptionException;
125 import org.simantics.db.exception.ArgumentException;
126 import org.simantics.db.exception.AssumptionException;
127 import org.simantics.db.exception.BindingException;
128 import org.simantics.db.exception.DatabaseException;
129 import org.simantics.db.exception.DoesNotContainValueException;
130 import org.simantics.db.exception.EmptyResourceException;
131 import org.simantics.db.exception.InternalException;
132 import org.simantics.db.exception.InvalidLiteralException;
133 import org.simantics.db.exception.ManyObjectsForFunctionalRelationException;
134 import org.simantics.db.exception.NoInverseException;
135 import org.simantics.db.exception.NoSingleResultException;
136 import org.simantics.db.exception.ResourceNotFoundException;
137 import org.simantics.db.exception.ServiceException;
138 import org.simantics.db.exception.ValidationException;
139 import org.simantics.db.impl.RelationContextImpl;
140 import org.simantics.db.impl.ResourceImpl;
141 import org.simantics.db.impl.internal.RandomAccessValueSupport;
142 import org.simantics.db.impl.internal.ResourceData;
143 import org.simantics.db.impl.procedure.ResultCallWrappedSyncQueryProcedure;
144 import org.simantics.db.impl.query.CacheEntry;
145 import org.simantics.db.impl.query.QueryCache;
146 import org.simantics.db.impl.query.QueryCacheBase;
147 import org.simantics.db.impl.query.QueryProcessor;
148 import org.simantics.db.impl.query.QueryProcessor.SessionTask;
149 import org.simantics.db.impl.query.QuerySupport;
150 import org.simantics.db.impl.query.TripleIntProcedure;
151 import org.simantics.db.impl.support.ResourceSupport;
152 import org.simantics.db.procedure.AsyncListener;
153 import org.simantics.db.procedure.AsyncMultiListener;
154 import org.simantics.db.procedure.AsyncMultiProcedure;
155 import org.simantics.db.procedure.AsyncProcedure;
156 import org.simantics.db.procedure.AsyncSetListener;
157 import org.simantics.db.procedure.Listener;
158 import org.simantics.db.procedure.ListenerBase;
159 import org.simantics.db.procedure.MultiListener;
160 import org.simantics.db.procedure.MultiProcedure;
161 import org.simantics.db.procedure.Procedure;
162 import org.simantics.db.procedure.SetListener;
163 import org.simantics.db.procedure.StatementProcedure;
164 import org.simantics.db.procedure.SyncListener;
165 import org.simantics.db.procedure.SyncMultiListener;
166 import org.simantics.db.procedure.SyncMultiProcedure;
167 import org.simantics.db.procedure.SyncProcedure;
168 import org.simantics.db.procedure.SyncSetListener;
169 import org.simantics.db.request.AsyncMultiRead;
170 import org.simantics.db.request.AsyncRead;
171 import org.simantics.db.request.DelayedWrite;
172 import org.simantics.db.request.DelayedWriteResult;
173 import org.simantics.db.request.ExternalRead;
174 import org.simantics.db.request.MultiRead;
175 import org.simantics.db.request.Read;
176 import org.simantics.db.request.ReadInterface;
177 import org.simantics.db.request.Write;
178 import org.simantics.db.request.WriteInterface;
179 import org.simantics.db.request.WriteOnly;
180 import org.simantics.db.request.WriteOnlyResult;
181 import org.simantics.db.request.WriteResult;
182 import org.simantics.layer0.Layer0;
183 import org.simantics.scl.compiler.types.Type;
184 import org.simantics.scl.compiler.types.exceptions.SCLTypeParseException;
185 import org.simantics.scl.reflection.ReflectionUtils;
186 import org.simantics.scl.reflection.ValueNotFoundException;
187 import org.simantics.scl.runtime.function.Function3;
188 import org.simantics.utils.DataContainer;
189 import org.simantics.utils.Development;
190 import org.simantics.utils.datastructures.Pair;
191 import org.simantics.utils.datastructures.collections.CollectionUtils;
192 import org.slf4j.LoggerFactory;
193
194 import gnu.trove.map.hash.TObjectIntHashMap;
195
196 public class ReadGraphImpl implements AsyncReadGraph {
197
198     private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ReadGraphImpl.class);
199
200     final static boolean EMPTY_RESOURCE_CHECK = false;
201     
202         final public CacheEntry parent;
203         public final ReadGraphImpl parentGraph;
204         final public QueryProcessor processor;
205         
206         public final AsyncBarrierImpl asyncBarrier;
207         
208         final static Binding DATA_TYPE_BINDING_INTERNAL = Bindings.getBindingUnchecked(Datatype.class);
209         final static Serializer DATA_TYPE_SERIALIZER = Bindings.getSerializerUnchecked(DATA_TYPE_BINDING_INTERNAL);
210
211         final public static TObjectIntHashMap<String> counters = new TObjectIntHashMap<String>(); 
212         
213         public static void resetCounters() {
214                 counters.clear();
215         }
216         
217         public static String listCounters(File file) throws IOException {
218                 
219                 PrintStream b = new PrintStream(new BufferedOutputStream(new FileOutputStream(file)));
220
221                 for(Pair<String,Integer> p : CollectionUtils.valueSortedEntries(counters)) {
222                         b.print(-p.second + " " + p.first + "\n");
223                 }
224
225                 b.close();
226
227                 return "Dumped " + counters.size() + " queries.";
228                 
229         }
230         
231         /*
232          * Implementation of the interface ReadGraph
233          */
234         final public String getURI(final Resource resource)     throws AssumptionException, ValidationException, ServiceException {
235                 
236                 assert (resource != null);
237
238                 try {
239
240                         return syncRequest(new org.simantics.db.common.uri.ResourceToURI(resource));
241
242                 } catch (AssumptionException e) {
243
244                         throw new AssumptionException(e);
245
246                 } catch (ValidationException e) {
247
248                         throw new ValidationException(e);
249
250                 } catch (ServiceException e) {
251
252                         throw new ServiceException(e);
253
254                 } catch (DatabaseException e) {
255
256                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
257
258                 }
259
260         }
261         
262         final public String getPossibleURI(final Resource resource)     throws ValidationException,     ServiceException {
263
264                 assert (resource != null);
265
266                 try {
267
268                         return syncRequest(new org.simantics.db.common.uri.ResourceToPossibleURI(resource));
269
270                 } catch (ValidationException e) {
271
272                         throw new ValidationException(e);
273
274                 } catch (ServiceException e) {
275
276                         throw new ServiceException(e);
277
278                 } catch (DatabaseException e) {
279
280                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
281
282                 }
283
284         }
285
286         final public Resource getResource(final String id)
287                         throws ResourceNotFoundException, ValidationException,
288                         ServiceException {
289
290                 assert (id != null);
291
292                 try {
293
294                         Integer rid = QueryCache.resultURIToResource(this, id, parent, null);
295                         // FIXME: stupid to throw this here and catch and wrap it right away
296                         if(rid == 0) throw new ResourceNotFoundException(id);
297                         return processor.querySupport.getResource(rid);
298
299                 } catch (ResourceNotFoundException e) {
300
301                         throw new ResourceNotFoundException(id, e);
302
303                 } catch (ValidationException e) {
304
305                         throw new ValidationException(e);
306
307                 } catch (ServiceException e) {
308
309                         throw new ServiceException(e);
310
311                 } catch (DatabaseException e) {
312
313                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
314
315                 }
316
317         }
318
319         final public Resource getPossibleResource(final String id)
320         throws ResourceNotFoundException, ValidationException,
321         ServiceException {
322
323                 assert (id != null);
324
325                 try {
326
327                         return getResource(id);
328
329                 } catch (ResourceNotFoundException e) {
330                         
331                         return null;
332
333                 } catch (ValidationException e) {
334
335                         throw new ValidationException(e);
336
337                 } catch (ServiceException e) {
338
339                         throw new ServiceException(e);
340
341                 } catch (DatabaseException e) {
342
343                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
344
345                 }
346
347         }
348         
349         @Override
350         public Map<String, Resource> getChildren(Resource resource) throws ValidationException, ServiceException {
351                 
352                 assert (resource != null);
353
354                 try {
355
356                         int rId = processor.querySupport.getId(resource);
357                         return QueryCache.resultChildMap(this, rId, parent, null);
358
359                 } catch (ValidationException e) {
360
361                         throw new ValidationException(e);
362
363                 } catch (ServiceException e) {
364
365                         throw new ServiceException(e);
366
367                 } catch (DatabaseException e) {
368
369                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
370
371                 }
372                 
373         }
374
375         final public Resource getRootLibrary() {
376                 return processor.getRootLibraryResource();
377         }
378         
379         final public Resource getBuiltin(final String id)
380                         throws ResourceNotFoundException, ServiceException {
381
382                 assert (id != null);
383
384                 try {
385
386                         return syncRequest(new Builtin(id));
387
388                 } catch (ResourceNotFoundException e) {
389
390                         throw new ResourceNotFoundException(id, e);
391
392                 } catch (ServiceException e) {
393
394                         throw new ServiceException(e);
395
396                 } catch (DatabaseException e) {
397
398                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
399
400                 }
401
402         }
403
404         static class StatementReadProcedure extends TIntArrayListInternal implements StatementProcedure {
405
406                 private static Throwable DONE = new Throwable();
407                 
408                 Throwable exception = null;
409                 
410                 final ResourceSupport support;
411                 
412                 public StatementReadProcedure(ResourceSupport support) {
413                         this.support = support;
414                 }
415                 
416                 @Override
417                 public synchronized void execute(AsyncReadGraph graph, int s, int p, int o) {
418                         add(s);
419                         add(p);
420                         add(o);
421                 }
422                 
423                 @Override
424                 public void finished(AsyncReadGraph graph) {
425                         exception = DONE;
426                 }
427
428                 @Override
429                 public void exception(AsyncReadGraph graph, Throwable t) {
430                         exception = t;
431                 }
432                 
433                 public void checkAndThrow() throws DatabaseException {
434                         if(exception != DONE) {
435                                 if (exception instanceof DatabaseException)
436                                         throw (DatabaseException) exception;
437                                 else
438                                         throw new DatabaseException(
439                                                         "Unexpected exception in ReadGraph.syncRequest(AsyncMultiRead)",
440                                                         exception);
441                         }
442                 }
443                 
444                 public boolean done() {
445                         return exception != null;
446                 }
447
448                 @Override
449                 public boolean contains(Object obj) {
450                     if(!(obj instanceof InternalStatement))
451                         return false;
452                     InternalStatement statement = (InternalStatement)obj;
453                     int s = statement.s;
454                     int p = statement.p;
455                     int o = statement.o;
456                     for(int i=0;i<sizeInternal();i+=3)
457                 if(s==getQuick(i) && p==getQuick(i+1) && o==getQuick(i+2))
458                     return true;
459                     return false;
460                 }
461
462                 @SuppressWarnings("unchecked")
463         @Override
464                 public <T> T[] toArray(T[] a) {
465                     int length = sizeInternal() / 3;
466                     if(length > a.length) {
467                         Class<?> arrayType = a.getClass();
468                         a = (arrayType == Object[].class) 
469                                 ? (T[]) new Object[length]
470                                 : (T[]) Array.newInstance(arrayType.getComponentType(), length);
471                     }
472                     else {
473                         for(int i=length;i<a.length;++i)
474                             a[i] = null;
475                     }
476             for(int i=0,j=0;i<sizeInternal();i+=3,++j)
477                 a[j] = (T)new InternalStatement(support, getQuick(i), getQuick(i+1), getQuick(i+2));
478             return a;
479                 }
480
481                 @Override
482                 public boolean add(Statement e) {
483                         throw new UnsupportedOperationException();
484                 }
485
486                 @Override
487                 public boolean remove(Object o) {
488                         throw new UnsupportedOperationException();
489                 }
490
491                 @Override
492                 public boolean addAll(Collection<? extends Statement> c) {
493                         throw new UnsupportedOperationException();
494                 }
495
496                 class IteratorImpl implements ListIterator<Statement> {
497             
498             int index;
499             
500             public IteratorImpl(int index) {
501                 this.index = index;
502             }
503
504             @Override
505             public boolean hasNext() {
506                 return index < sizeInternal(); 
507             }
508
509             @Override
510             public Statement next() {
511                 Statement result = new InternalStatement(support, getQuick(index), getQuick(index+1), getQuick(index+2)); 
512                 index += 3;
513                 return result;
514             }
515
516             @Override
517             public void remove() {
518                 throw new Error("Not supported");
519             }
520
521             @Override
522             public boolean hasPrevious() {
523                 return index > 0;
524             }
525
526             @Override
527             public Statement previous() {
528                 index -= 3;
529                 Statement result = new InternalStatement(support, getQuick(index), getQuick(index+1), getQuick(index+2)); 
530                 return result;
531             }
532
533             @Override
534             public int nextIndex() {
535                 return index/3;
536             }
537
538             @Override
539             public int previousIndex() {
540                 return index/3-1;
541             }
542
543             @Override
544             public void set(Statement e) {
545                 throw new UnsupportedOperationException();
546             }
547
548             @Override
549             public void add(Statement e) {
550                 throw new UnsupportedOperationException();
551             }
552             
553         };
554         
555                 @Override
556                 public Iterator<Statement> iterator() {
557                         return new IteratorImpl(0);
558                 }
559                 
560                 @Override
561                 public int size() {
562                         return sizeInternal() / 3;
563                 }
564
565                 @Override
566                 public Object[] toArray() {
567                     Object[] result = new Object[sizeInternal() / 3];
568                     for(int i=0,j=0;j<sizeInternal();i++,j+=3)
569                         result[i] = new InternalStatement(support, getQuick(j), getQuick(j+1), getQuick(j+2));
570                         return result;
571                 }
572
573         @Override
574         public boolean addAll(int index, Collection<? extends Statement> c) {
575             throw new UnsupportedOperationException();
576         }
577
578         @Override
579         public Statement get(int index) {
580             index += 3;
581             if(index < 0 || index >= sizeInternal())
582                 throw new IndexOutOfBoundsException();
583             return new InternalStatement(support, getQuick(index), getQuick(index+1), getQuick(index+2));
584         }
585
586         @Override
587         public Statement set(int index, Statement element) {
588             throw new UnsupportedOperationException();
589         }
590
591         @Override
592         public void add(int index, Statement element) {
593             throw new UnsupportedOperationException();
594         }
595
596         @Override
597         public Statement remove(int index) {
598             throw new UnsupportedOperationException();
599         }
600
601         @Override
602         public int indexOf(Object obj) {
603             if(!(obj instanceof InternalStatement))
604                 return -1;
605             InternalStatement statement = (InternalStatement)obj;
606             int s = statement.s;
607             int p = statement.p;
608             int o = statement.o;
609             for(int i=0;i<sizeInternal();i+=3)
610                 if(s==getQuick(i) && p==getQuick(i+1) && o==getQuick(i+2))
611                     return i/3;
612             return -1;
613         }
614
615         @Override
616         public int lastIndexOf(Object obj) {
617             if(!(obj instanceof InternalStatement))
618                 return -1;
619             InternalStatement statement = (InternalStatement)obj;
620             int s = statement.s;
621             int p = statement.p;
622             int o = statement.o;
623             for(int i=sizeInternal()-3;i>=0;i-=3)
624                 if(s==getQuick(i) && p==getQuick(i+1) && o==getQuick(i+2))
625                     return i/3;
626             return -1;
627         }
628
629         @Override
630         public ListIterator<Statement> listIterator() {
631             return new IteratorImpl(0);
632         }
633
634         @Override
635         public ListIterator<Statement> listIterator(int index) {
636             return new IteratorImpl(index*3);
637         }
638
639         @Override
640         public List<Statement> subList(int fromIndex, int toIndex) {
641             if(fromIndex < 0 || toIndex*3 >= sizeInternal() || fromIndex > toIndex)
642                 throw new IndexOutOfBoundsException();
643             return new RandomAccessSubList<Statement>(this, fromIndex, toIndex-fromIndex);
644         }
645         }
646         
647         @Override
648         final public Collection<Statement> getStatements(final Resource subject,
649                         final Resource relation)
650                         throws ManyObjectsForFunctionalRelationException, ServiceException {
651
652                 assert (subject != null);
653                 assert (relation != null);
654
655                 try {
656
657                         StatementReadProcedure procedure = new StatementReadProcedure(getResourceSupport());
658                         processor.forEachStatement(this, subject, relation, procedure);
659                         procedure.checkAndThrow();
660                         return procedure;
661                         
662                 } catch (DatabaseException e) {
663
664                         System.err.println(INTERNAL_ERROR_STRING + " getStatements " + subject + " " + relation);
665
666                         StatementReadProcedure procedure = new StatementReadProcedure(getResourceSupport());
667                         processor.forEachStatement(this, subject, relation, procedure);
668                         
669                         return Collections.emptyList();
670                 
671 //                      throw new ServiceException(INTERNAL_ERROR_STRING + " getStatements " + subject + " " + relation, e);
672
673                 }
674
675         }
676
677         @Override
678         final public Collection<Statement> getAssertedStatements(final Resource subject, final Resource relation)
679                         throws ManyObjectsForFunctionalRelationException, ServiceException {
680
681                 assert (subject != null);
682                 assert (relation != null);
683
684                 try {
685
686                         return syncRequest(new ForEachAssertedStatement(subject, relation));
687
688                 } catch (ManyObjectsForFunctionalRelationException e) {
689
690                         throw new ManyObjectsForFunctionalRelationException(e);
691
692                 } catch (ServiceException e) {
693
694                         throw new ServiceException(e);
695
696                 } catch (DatabaseException e) {
697
698                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
699
700                 }
701
702         }
703
704         @Override
705         final public Collection<Resource> getPredicates(final Resource subject) throws ServiceException {
706
707                 assert (subject != null);
708
709                 try {
710
711                         return processor.getPredicates(this, subject);
712
713 //                      AsyncMultiReadProcedure<Resource> procedure = new AsyncMultiReadProcedure<Resource>();
714 //                      processor.forEachPredicate(this, subject, procedure);
715 //                      procedure.checkAndThrow();
716 //                      return procedure;
717
718                 } catch (ServiceException e) {
719
720                         throw new ServiceException(e);
721
722                 } catch (DatabaseException e) {
723
724                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
725
726                 }  catch (Throwable e) {
727
728             throw new ServiceException(e);
729
730                 }
731
732         }
733
734         @Override
735         final public Collection<Resource> getPrincipalTypes(final Resource subject)
736                         throws ServiceException {
737
738                 assert (subject != null);
739
740                 try {
741
742                         AsyncMultiReadProcedure<Resource> procedure = new AsyncMultiReadProcedure<Resource>();
743                         processor.forEachPrincipalType(this, subject, procedure);
744                         procedure.checkAndThrow();
745                         return procedure;
746                         
747                 } catch (ServiceException e) {
748
749                         throw new ServiceException(e);
750
751                 } catch (DatabaseException e) {
752
753                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
754
755                 }
756
757         }
758
759         @Override
760         final public Set<Resource> getTypes(final Resource subject) throws ServiceException {
761
762                 assert (subject != null);
763
764                 try {
765                         
766                         return processor.getTypes(this, subject);
767                         
768                 } catch (ServiceException e) {
769
770                         throw new ServiceException(e);
771                         
772                 } catch (DatabaseException e) {
773
774                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
775
776         } catch (Throwable e) {
777
778             throw new ServiceException(e);
779
780                 }
781
782         }
783
784         @Override
785         final public Set<Resource> getSupertypes(final Resource subject)
786                         throws ServiceException {
787
788                 assert (subject != null);
789
790                 try {
791
792                         SyncReadProcedure<Set<Resource>> procedure = new SyncReadProcedure<Set<Resource>>();
793                         processor.forSupertypes(this, subject, procedure);
794                         procedure.checkAndThrow();
795                         return procedure.result;
796
797                 } catch (ServiceException e) {
798
799                         throw new ServiceException(e);
800
801                 } catch (DatabaseException e) {
802
803                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
804
805                 }
806
807         }
808
809         @Override
810         final public Set<Resource> getSuperrelations(final Resource subject)
811                         throws ServiceException {
812
813                 assert (subject != null);
814
815                 try {
816
817                         SyncReadProcedure<Set<Resource>> procedure = new SyncReadProcedure<Set<Resource>>();
818                         processor.forSuperrelations(this, subject, procedure);
819                         procedure.checkAndThrow();
820                         return procedure.result;
821
822                 } catch (ServiceException e) {
823
824                         throw new ServiceException(e);
825
826                 } catch (DatabaseException e) {
827
828                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
829
830                 }
831
832         }
833         
834         @Override
835         public Resource getPossibleSuperrelation(Resource subject) throws ServiceException {
836                 
837                 try {
838
839                         SyncReadProcedure<Resource> procedure = new SyncReadProcedure<Resource>();
840                         processor.forPossibleSuperrelation(this, subject, procedure);
841                         procedure.checkAndThrow();
842                         return procedure.result;
843
844                 } catch (ServiceException e) {
845
846                         throw new ServiceException(e);
847
848                 } catch (DatabaseException e) {
849
850                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
851
852                 }
853
854         }
855
856         @Override
857         final public Collection<Resource> getObjects(final Resource subject, final Resource relation)
858                         throws ServiceException {
859
860                 assert (subject != null);
861                 assert (relation != null);
862
863                 if(Development.DEVELOPMENT) {
864             if(Development.isTrue(DevelopmentKeys.READGRAPH_COUNT)) {
865                 counters.adjustOrPutValue("objects $" + subject.getResourceId() + " $" + relation.getResourceId(), 1, 1);
866             }
867             //if(subject.getResourceId()==xx && relation.getResourceId()==xx) new Exception().printStackTrace();
868                 }
869                 
870                 try {
871
872                         AsyncMultiReadProcedure<Resource> procedure = new AsyncMultiReadProcedure<Resource>();
873                         processor.forEachObject(this, subject, relation, procedure);
874                         procedure.checkAndThrow();
875                         return procedure;
876                         
877                 } catch (DatabaseException e) {
878
879                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
880
881                 }
882
883         }
884
885         @Override
886         final public Collection<Resource> getAssertedObjects(
887                         final Resource subject, final Resource relation)
888                         throws ManyObjectsForFunctionalRelationException, ServiceException {
889
890         if (subject == null)
891             throw new ArgumentException("Subject must not be null.");
892         if (relation == null)
893             throw new ArgumentException("Relation must not be null. Subject=" + subject);
894
895                 try {
896
897                         return syncRequest(new ForEachAssertedObject(subject, relation));
898
899                 } catch (ManyObjectsForFunctionalRelationException e) {
900
901                         throw new ManyObjectsForFunctionalRelationException(e);
902
903                 } catch (ServiceException e) {
904
905                         throw new ServiceException(e);
906
907                 } catch (DatabaseException e) {
908
909                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
910
911                 }
912
913         }
914
915         @Override
916         final public Resource getInverse(final Resource relation) throws NoInverseException, ServiceException {
917
918                 assert (relation != null);
919
920                 try {
921
922                         return getSingleObject(relation, processor.querySupport.getResource(processor.getInverseOf()));
923
924                 } catch (NoSingleResultException e) {
925
926                         throw new NoInverseException(e);
927
928                 } catch (ServiceException e) {
929
930                         throw new ServiceException(e);
931
932                 }
933
934         }
935
936         @Override
937         final public Resource getSingleObject(final Resource subject, final Resource relation) throws NoSingleResultException, ServiceException {
938
939                 if( subject == null) throw new IllegalArgumentException("subject can not be null");
940                 if( relation == null) throw new IllegalArgumentException("relation can not be null");
941
942                 try {
943                         int single = processor.getSingleObject(this, subject, relation);
944                         if (single == 0) {
945                                 if (EMPTY_RESOURCE_CHECK) {
946                                         if (!hasStatement(subject)) {
947                                                 throw new EmptyResourceException("Resource " + debugString(subject));
948                                         }
949                                 }
950                                 throw new NoSingleResultException("No single object for subject " + debugString(subject)
951                                                 + " and relation " + debugString(relation), single);
952                         }
953                         return processor.querySupport.getResource(single);
954                 } catch (NoSingleResultException e) {
955                         throw e;
956                 } catch (DatabaseException e) {
957                         throw new ServiceException(e);
958                 } 
959         }
960
961         @Override
962         final public Statement getSingleStatement(final Resource subject, final Resource relation) throws NoSingleResultException, ManyObjectsForFunctionalRelationException, ServiceException {
963                 assert (subject != null);
964                 assert (relation != null);
965                 try {
966                         Collection<Statement> statements = getStatements(subject, relation);
967                         if (statements.size() == 1) {
968                                 return statements.iterator().next();
969                         } else {
970                                 if (EMPTY_RESOURCE_CHECK)
971                                         if (!hasStatement(subject))
972                                                 throw new EmptyResourceException("Resource " + debugString(subject));
973                                 throw new NoSingleResultException("No single statement for subject " + debugString(subject)
974                                                 + " and relation " + debugString(relation), statements.size());
975                         }
976                 } catch (ServiceException e) {
977                         throw new ServiceException(e);
978                 } 
979         }
980
981         @Override
982         final public Resource getSingleType(final Resource subject) throws NoSingleResultException, ServiceException {
983                 assert (subject != null);
984                 try {
985                         ArrayList<Resource> principalTypes = (ArrayList<Resource>)getPrincipalTypes(subject);
986                         if (principalTypes.size() == 1) {
987                             return principalTypes.get(0);
988                         } else {
989                             throw new NoSingleResultException("No single type for subject " + debugString(subject), principalTypes.size());
990                         }
991                 } catch (ServiceException e) {
992                         throw new ServiceException(e);
993                 } 
994         }
995
996         @Override
997         final public Resource getSingleType(final Resource subject,
998                         final Resource baseType) throws NoSingleResultException,
999                         ServiceException {
1000
1001                 assert (subject != null);
1002                 assert (baseType != null);
1003
1004                 try {
1005                         return syncRequest(new SingleType(subject, baseType));
1006                 } catch (DatabaseException e) {
1007                     throw new NoSingleResultException("subject=" + subject + ", baseType=" + baseType, 0, e);
1008                 }
1009         }
1010
1011         @Override
1012         final public <T> T getValue(final Resource subject) throws DoesNotContainValueException, ServiceException {
1013
1014                 assert (subject != null);
1015
1016                 try {
1017
1018                         Layer0 L0 = processor.getL0(this);
1019             int object = processor.getSingleObject(this, subject, L0.HasDataType);
1020             if(object == 0) throw new DoesNotContainValueException("No data type for " + subject);
1021             
1022             if(processor.isImmutable(object)) {
1023                 Binding binding = syncRequest(new DatatypeBinding(processor.querySupport.getResource(object)), TransientCacheListener.<Binding>instance()); 
1024                         return getValue(subject, binding);
1025             } else {
1026                     byte[] dt = processor.getValue(this, object);
1027                     if(dt == null) throw new ServiceException("No data type for " + subject);
1028                     Datatype datatype = (Datatype)DATA_TYPE_SERIALIZER.deserialize(dt);
1029                     Binding binding = Bindings.getBinding(datatype);
1030                     return getValue(subject, binding);
1031             }
1032                         
1033         } catch (IOException e) {
1034
1035             throw new ServiceException(e);
1036
1037                 } catch (DoesNotContainValueException e) {
1038
1039                         throw new DoesNotContainValueException(e, subject);
1040
1041                 } catch (ServiceException e) {
1042
1043                         throw new ServiceException(e);
1044
1045                 } catch (DatabaseException e) {
1046
1047                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1048
1049         }
1050
1051         }
1052
1053     @Override
1054     final public Variant getVariantValue(final Resource subject) throws DoesNotContainValueException, ServiceException {
1055
1056         assert (subject != null);
1057
1058         try {
1059
1060             Layer0 L0 = processor.getL0(this);
1061             int object = processor.getSingleObject(this, subject, L0.HasDataType);
1062             if(object == 0) throw new DoesNotContainValueException("No data type for " + subject);
1063             
1064             if(processor.isImmutable(object)) {
1065                 Binding binding = syncRequest(new DatatypeBinding(processor.querySupport.getResource(object)), TransientCacheListener.<Binding>instance()); 
1066                 return new Variant(binding, getValue(subject, binding));
1067             } else {
1068                 byte[] dt = processor.getValue(this, object);
1069                 if(dt == null) throw new ServiceException("No data type for " + subject);
1070                 Datatype datatype = (Datatype)DATA_TYPE_SERIALIZER.deserialize(dt);
1071                 Binding binding = Bindings.getBinding(datatype);
1072                 return new Variant(binding, getValue(subject, binding));
1073             }
1074             
1075         } catch (IOException e) {
1076
1077             throw new ServiceException(e);
1078
1079         } catch (DoesNotContainValueException e) {
1080
1081             throw new DoesNotContainValueException(e, subject);
1082
1083         } catch (ServiceException e) {
1084
1085             throw new ServiceException(e);
1086
1087         } catch (DatabaseException e) {
1088
1089             throw new ServiceException(INTERNAL_ERROR_STRING, e);
1090
1091         }               
1092         }
1093
1094         static final IdentityHashMap<Binding,Serializer> serializers = new IdentityHashMap<Binding,Serializer>();
1095         
1096         static {
1097                 serializers.put(Bindings.STRING, Bindings.STRING.serializer());
1098         }
1099         
1100         final protected Serializer getSerializer(Binding binding) {
1101             return binding.serializer();
1102         }
1103         
1104         @Override
1105         final public <T> T getValue(final Resource subject, final Binding binding) throws DoesNotContainValueException, BindingException,
1106                         ServiceException {
1107
1108                 assert (subject != null);
1109
1110                 byte[] bytes = null;
1111                 try {
1112                         
1113                         bytes = processor.getValue(this, subject);
1114                         if (bytes == null) throw new DoesNotContainValueException("No value for resource " + subject);
1115
1116                         Serializer serializer = getSerializer(binding);
1117                         return (T)serializer.deserialize(bytes);
1118
1119                 } catch (DoesNotContainValueException e) {
1120
1121                         throw new DoesNotContainValueException(e);
1122
1123                 } catch (Throwable t) {
1124                         throw new ServiceException("Could not getValue for subject " + debugString(subject) + " and binding " + String.valueOf(binding) + " with bytes " + safeArrayToString(bytes), t);
1125                 }
1126         }
1127
1128         @Override
1129         final public <T> T getRelatedValue(final Resource subject, final Resource relation) throws NoSingleResultException,
1130                         DoesNotContainValueException, ServiceException {
1131
1132                 assert (subject != null);
1133                 assert (relation != null);
1134
1135                 try {
1136                         Resource object = getSingleObject(subject, relation);
1137                         return getValue(object);
1138                 } catch (NoSingleResultException e) {
1139                         throw new NoSingleResultException("No single value found for subject " + debugString(subject) + " and relation " + debugString(relation), e.getResultCount(), e);
1140                 } catch (DoesNotContainValueException e) {
1141                         try {
1142                                 Layer0 L0 = processor.getL0(this);
1143                                 Resource object = getPossibleObject(subject, relation);
1144                                 if(isInstanceOf(object, L0.Value)) {
1145                                         if(isInstanceOf(object, L0.Literal)) {
1146                                                 throw new DoesNotContainValueException(e);
1147                                         } else {
1148                                                 throw new InvalidLiteralException("The object " + object + " is not an instance of L0.Literal (use getRelatedValue2 instead)", e);
1149                                         }
1150                                 } else {
1151                                         throw new DoesNotContainValueException("The object " + object + " is not an instance of L0.Value", e);
1152                                 }
1153                         } catch (DoesNotContainValueException e2) {
1154                                 throw e2;
1155                         } catch (DatabaseException e2) {
1156                                 throw new InternalException("The client failed to analyse the cause of the following exception", e);
1157                         }
1158                 } catch (ServiceException e) {
1159                         throw new ServiceException(e);
1160                 }
1161         }
1162
1163     @Override
1164     final public Variant getRelatedVariantValue(final Resource subject, final Resource relation) throws NoSingleResultException,
1165             DoesNotContainValueException, ServiceException {
1166
1167         assert (subject != null);
1168         assert (relation != null);
1169
1170         try {
1171             Resource object = getSingleObject(subject, relation);
1172             return getVariantValue(object);
1173         } catch (NoSingleResultException e) {
1174             throw new NoSingleResultException("No single object for subject " + debugString(subject) + " and relation " + debugString(relation), e.getResultCount(), e);
1175         } catch (DoesNotContainValueException e) {
1176             try {
1177                 Layer0 L0 = processor.getL0(this);
1178                 Resource object = getPossibleObject(subject, relation);
1179                 if(isInstanceOf(object, L0.Value)) {
1180                     if(isInstanceOf(object, L0.Literal)) {
1181                         throw new DoesNotContainValueException(e);
1182                     } else {
1183                         throw new InvalidLiteralException("The object " + object + " is not an instance of L0.Literal (use getRelatedValue2 instead)", e);
1184                     }
1185                 } else {
1186                     throw new DoesNotContainValueException("The object " + object + " is not an instance of L0.Value", e);
1187                 }
1188             } catch (DoesNotContainValueException e2) {
1189                 throw e2;
1190             } catch (DatabaseException e2) {
1191                 throw new InternalException("The client failed to analyse the cause of the following exception", e);
1192             }
1193         } catch (ServiceException e) {
1194             throw new ServiceException(e);
1195         } 
1196     }
1197     
1198         @Override
1199         final public <T> T getRelatedValue(final Resource subject, final Resource relation, final Binding binding)
1200                         throws NoSingleResultException, DoesNotContainValueException, BindingException, ServiceException {
1201
1202                 assert (subject != null);
1203                 assert (relation != null);
1204
1205                 try {
1206                         Resource object = getSingleObject(subject, relation);
1207                         return getValue(object, binding);
1208                 } catch (NoSingleResultException e) {
1209                     String message = "";
1210                     try {
1211                     String subjectName = NameUtils.getSafeName(this, subject, true);
1212                     String relationName = NameUtils.getSafeName(this, relation, true);
1213                     message = "Subject: " + subjectName + ", Relation: " + relationName;
1214                     } catch (DatabaseException e2) {
1215                         
1216                     }
1217             throw new NoSingleResultException(message, e.getResultCount(), e);
1218                 } catch (DoesNotContainValueException e) {
1219                         throw new DoesNotContainValueException(e);
1220                 } catch (ServiceException e) {
1221                         throw new ServiceException(e);
1222                 }
1223         }
1224
1225         @Override
1226         final public <T> T adapt(final Resource resource, final Class<T> clazz)
1227                         throws AdaptionException, ValidationException, ServiceException {
1228
1229                 assert (resource != null);
1230                 assert (clazz != null);
1231
1232                 try {
1233
1234                         return syncRequest(new Adapter<T>(resource, clazz));
1235
1236                 } catch (AdaptionException e) {
1237
1238                         throw new AdaptionException(e);
1239
1240                 } catch (ValidationException e) {
1241
1242                         throw new ValidationException(e);
1243
1244                 } catch (ServiceException e) {
1245
1246                         throw new ServiceException(e);
1247
1248                 } catch (DatabaseException e) {
1249
1250                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1251
1252                 }
1253
1254         }
1255
1256         @Override
1257         final public <T,C> T adaptContextual(final Resource resource, final C context, final Class<C> contextClass, final Class<T> clazz)
1258                         throws AdaptionException, ValidationException, ServiceException {
1259
1260                 assert (resource != null);
1261                 assert (context != null);
1262
1263                 class ContextualAdapter implements AsyncRead<T> {
1264
1265                         final private Resource resource;
1266                         final private C context;
1267                     final private Class<T> clazz;
1268                     
1269                     @Override
1270                     public int hashCode() {
1271                         return resource.hashCode() + 31 * (clazz.hashCode() + 41 * context.hashCode());
1272                     }
1273                     
1274                     @Override
1275                     final public int threadHash() {
1276                         return resource.getThreadHash();
1277                     }
1278                     
1279                     @Override
1280                     public boolean equals(Object object) {
1281                         if (this == object)
1282                             return true;
1283                         else if (object == null)
1284                             return false;
1285                         else if (getClass() != object.getClass())
1286                             return false;
1287                         ContextualAdapter r = (ContextualAdapter)object;
1288                         return resource.equals(r.resource) && context.equals(r.context) && clazz.equals(r.clazz);
1289                     }
1290
1291                     @Override
1292                     public int getFlags() {
1293                         return 0;
1294                     }
1295                     
1296                     public ContextualAdapter(Resource resource, C context, Class<T> clazz) {
1297                         this.resource = resource;
1298                         this.context = context;
1299                         this.clazz = clazz;
1300                     }
1301
1302                     @Override
1303                     public void perform(AsyncReadGraph graph, AsyncProcedure<T> procedure) {
1304                         
1305                                 final AdaptionService service = getSession().peekService(AdaptionService.class);
1306                                 if (service == null)
1307                                         procedure.exception(graph, new ServiceException("No AdaptionService available")); 
1308                                 else
1309                                         service.adapt(graph, resource, context, contextClass, clazz, false, procedure); 
1310                         
1311                     }
1312
1313                     @Override
1314                     public String toString() {
1315                         return "Adapter for (" + resource + "," + context + ") as " + clazz.getName();
1316                     }
1317                     
1318                 }
1319                 
1320                 try {
1321
1322                         return syncRequest(new ContextualAdapter(resource, context, clazz));
1323
1324                 } catch (AdaptionException e) {
1325
1326                         throw new AdaptionException(e);
1327
1328                 } catch (ValidationException e) {
1329
1330                         throw new ValidationException(e);
1331
1332                 } catch (ServiceException e) {
1333
1334                         throw new ServiceException(e);
1335
1336                 } catch (DatabaseException e) {
1337
1338                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1339
1340                 }
1341
1342         }
1343         
1344         @Override
1345         final public <T> T adaptRelated(final Resource resource, final Resource relation, final Class<T> clazz)
1346                         throws AdaptionException, NoSingleResultException, ValidationException, ServiceException {
1347
1348                 assert (resource != null);
1349                 assert (clazz != null);
1350
1351                 Statement stm = getSingleStatement(resource, relation);
1352                 
1353                 Object o = adaptContextual(stm.getObject(), new RelationContextImpl(resource, stm), RelationContext.class, clazz);
1354                 if (clazz.isInstance(o))
1355                         return (T)o;
1356                 throw new AdaptionException("Returned value is not expected class , got " + o.getClass().getName()+ " , expected " + clazz.getName());
1357                 
1358         }
1359
1360         @Override
1361         final public <T> T getPossibleRelatedAdapter(final Resource resource, final Resource relation, final Class<T> clazz)
1362                         throws ValidationException, ServiceException {
1363
1364                 try {
1365                         return adaptRelated(resource, relation, clazz);
1366                 } catch (DatabaseException e) {
1367                         return null;
1368                 }
1369                 
1370         }
1371
1372         @Override
1373         final public <T,C> T getPossibleContextualAdapter(final Resource resource, final C context, final Class<C> contextClass, final Class<T> clazz)
1374                         throws ValidationException, ServiceException {
1375
1376                 assert (resource != null);
1377                 assert (context != null);
1378
1379                 class PossibleContextualAdapter implements AsyncRead<T> {
1380
1381                         final private Resource resource;
1382                         final private C context;
1383                     final private Class<T> clazz;
1384                     
1385                     @Override
1386                     public int hashCode() {
1387                         return resource.hashCode() + 31 * (clazz.hashCode() + 41 * context.hashCode());
1388                     }
1389                     
1390                     @Override
1391                     final public int threadHash() {
1392                         return resource.getThreadHash();
1393                     }
1394                     
1395                     @Override
1396                     public boolean equals(Object object) {
1397                         if (this == object)
1398                             return true;
1399                         else if (object == null)
1400                             return false;
1401                         else if (getClass() != object.getClass())
1402                             return false;
1403                         PossibleContextualAdapter r = (PossibleContextualAdapter)object;
1404                         return resource.equals(r.resource) && context.equals(r.context) && clazz.equals(r.clazz);
1405                     }
1406
1407                     @Override
1408                     public int getFlags() {
1409                         return 0;
1410                     }
1411                     
1412                     public PossibleContextualAdapter(Resource resource, C context, Class<T> clazz) {
1413                         this.resource = resource;
1414                         this.context = context;
1415                         this.clazz = clazz;
1416                     }
1417
1418                     @Override
1419                     public void perform(AsyncReadGraph graph, AsyncProcedure<T> procedure) {
1420                         
1421                                 final AdaptionService service = getSession().peekService(AdaptionService.class);
1422                                 if (service == null)
1423                                         procedure.exception(graph, new ServiceException("No AdaptionService available")); 
1424                                 else
1425                                         service.adapt(graph, resource, context, contextClass, clazz, true, procedure); 
1426                         
1427                     }
1428
1429                     @Override
1430                     public String toString() {
1431                         return "Possible adapter for (" + resource + "," + context + ") as " + clazz.getName();
1432                     }
1433                     
1434                 }
1435                 
1436                 try {
1437
1438                         return syncRequest(new PossibleContextualAdapter(resource, context, clazz));
1439
1440                 } catch (ValidationException e) {
1441
1442                         throw new ValidationException(e);
1443
1444                 } catch (ServiceException e) {
1445
1446                         throw new ServiceException(e);
1447
1448                 } catch (DatabaseException e) {
1449
1450                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1451
1452                 }
1453                 
1454         }
1455
1456         @Override
1457         final public <T> T adaptUnique(final Resource resource, final Class<T> clazz)
1458                         throws AdaptionException, ValidationException, ServiceException {
1459
1460                 assert (resource != null);
1461                 assert (clazz != null);
1462
1463                 try {
1464
1465                         return syncRequest(new UniqueAdapter<T>(resource, clazz));
1466
1467                 } catch (AdaptionException e) {
1468
1469                         throw new AdaptionException(e);
1470
1471                 } catch (ValidationException e) {
1472
1473                         throw new ValidationException(e);
1474
1475                 } catch (ServiceException e) {
1476
1477                         throw new ServiceException(e);
1478
1479                 } catch (DatabaseException e) {
1480
1481                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1482
1483                 }
1484
1485         }
1486
1487         @Override
1488         final public Resource getPossibleInverse(final Resource relation)
1489                         throws ServiceException {
1490
1491                 assert (relation != null);
1492
1493                 try {
1494
1495                         return getPossibleObject(relation, processor.querySupport.getResource(processor.getInverseOf()));
1496
1497                 } catch (ServiceException e) {
1498
1499                         throw new ServiceException(e);
1500
1501                 } catch (DatabaseException e) {
1502
1503                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1504
1505                 }
1506
1507         }
1508
1509         @Override
1510         public Resource getPossibleObject(final Resource subject, final Resource relation)
1511                         throws ManyObjectsForFunctionalRelationException, ServiceException {
1512
1513                 assert (subject != null);
1514                 assert (relation != null);
1515
1516                 try {
1517
1518                         int result = processor.getSingleObject(this, subject, relation);
1519                         if(result == 0) return null;
1520
1521                         return processor.querySupport.getResource(result);
1522
1523                 } catch (ManyObjectsForFunctionalRelationException e) {
1524
1525                         throw new ManyObjectsForFunctionalRelationException("Many objects in " + subject + " for functional relation " + relation);
1526
1527                 } catch (DatabaseException e) {
1528
1529                         throw new ServiceException(e);
1530
1531                 }
1532                 
1533         }
1534
1535         @Override
1536         final public Statement getPossibleStatement(final Resource subject, final Resource relation)
1537                         throws ManyObjectsForFunctionalRelationException, ServiceException {
1538
1539                 assert (subject != null);
1540                 assert (relation != null);
1541
1542                 try {
1543
1544                         Collection<Statement> statements = getStatements(subject, relation);
1545                         if(statements.size() == 1) return statements.iterator().next();
1546                         else return null;
1547
1548                 } catch (ManyObjectsForFunctionalRelationException e) {
1549
1550                         throw new ManyObjectsForFunctionalRelationException("Many objects in " + subject + " for functional relation " + relation);
1551
1552                 } catch (ServiceException e) {
1553
1554                         throw new ServiceException(e);
1555
1556                 } 
1557
1558         }
1559
1560         @Override
1561         final public Resource getPossibleType(final Resource subject, final Resource baseType) throws ServiceException {
1562
1563                 assert (subject != null);
1564                 assert (baseType != null);
1565
1566                 try {
1567
1568                         AsyncReadProcedure<Resource> procedure = new AsyncReadProcedure<Resource>();
1569                         forPossibleType(subject, baseType, procedure);
1570                         procedure.checkAndThrow();
1571                         return procedure.result;                        
1572
1573                 } catch (ServiceException e) {
1574
1575                         throw new ServiceException(e);
1576
1577                 } catch (DatabaseException e) {
1578
1579                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1580
1581                 }
1582
1583         }
1584
1585         @Override
1586         final public <T> T getPossibleValue(final Resource subject) throws ServiceException {
1587
1588                 assert (subject != null);
1589
1590                 try {
1591                     
1592                     int object = processor.getSingleObject(this, subject, processor.getL0(this).HasDataType);
1593                     if(object == 0) return null;
1594                     
1595             if(processor.isImmutable(object)) {
1596                 Binding binding = syncRequest(new DatatypeBinding(processor.querySupport.getResource(object)), TransientCacheListener.<Binding>instance()); 
1597                         return getPossibleValue(subject, binding);
1598             } else {
1599                     byte[] dt = processor.getValue(this, object);
1600                     if(dt == null) return null;
1601                     Datatype datatype = (Datatype)DATA_TYPE_SERIALIZER.deserialize(dt);
1602                     Binding binding = Bindings.getBinding(datatype);
1603                     return getPossibleValue(subject, binding);
1604             }
1605                     
1606         } catch (IOException e) {
1607             
1608             throw new ServiceException(e);
1609             
1610                 } catch (ServiceException e) {
1611
1612                         throw new ServiceException(e);
1613
1614                 } catch (DatabaseException e) {
1615
1616                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1617
1618         }
1619
1620         }
1621
1622         @Override
1623         final public <T> T getPossibleValue(final Resource subject, final Binding binding) throws BindingException, ServiceException {
1624
1625                 assert (subject != null);
1626                 assert (binding != null);
1627
1628                 try {
1629
1630             byte[] dt = processor.getValue(this, subject);
1631             if(dt == null) return null;
1632                         Serializer serializer = getSerializer(binding);
1633             return (T)serializer.deserialize(dt);
1634
1635         } catch (IOException e) {
1636
1637             throw new ServiceException(e);
1638             
1639                 } catch (BindingException e) {
1640
1641                         throw new BindingException(e);
1642
1643                 } catch (ServiceException e) {
1644
1645                         throw new ServiceException(e);
1646
1647                 } catch (DatabaseException e) {
1648                         e.printStackTrace();
1649                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1650         }
1651
1652         }
1653
1654         @Override
1655         public <T> T getPossibleRelatedValue(final Resource subject, final Resource relation)
1656                         throws ManyObjectsForFunctionalRelationException, ServiceException {
1657
1658                 assert (subject != null);
1659                 assert (relation != null);
1660
1661                 try {
1662
1663                         Resource object = getPossibleObject(subject, relation);
1664                         if(object == null) return null;
1665                         else return getPossibleValue(object);
1666
1667                 } catch (ManyObjectsForFunctionalRelationException e) {
1668
1669                         throw new ManyObjectsForFunctionalRelationException(e);
1670
1671                 } catch (ServiceException e) {
1672
1673                         throw new ServiceException(e);
1674
1675                 } 
1676
1677         }
1678
1679         @Override
1680         public <T> T getPossibleRelatedValue(final Resource subject, final Resource relation, final Binding binding)
1681                         throws ManyObjectsForFunctionalRelationException, BindingException, ServiceException {
1682
1683                 assert (subject != null);
1684                 assert (relation != null);
1685                 assert (binding != null);
1686
1687                 try {
1688
1689                         Resource object = getPossibleObject(subject, relation);
1690                         if(object == null) return null;
1691                         else return getPossibleValue(object, binding);
1692
1693                 } catch (ManyObjectsForFunctionalRelationException e) {
1694
1695                         throw new ManyObjectsForFunctionalRelationException(e);
1696
1697                 } catch (BindingException e) {
1698
1699                         throw new BindingException(e);
1700
1701                 } catch (ServiceException e) {
1702
1703                         throw new ServiceException(e);
1704
1705                 }
1706
1707         }
1708
1709         @Override
1710         public <T> T getPossibleAdapter(Resource resource, Class<T> clazz) throws ValidationException, ServiceException {
1711
1712                 assert (resource != null);
1713                 assert (clazz != null);
1714
1715                 try {
1716
1717                         return syncRequest(new PossibleAdapter<T>(resource, clazz));
1718
1719                 } catch (ValidationException e) {
1720
1721                         throw new ValidationException(e);
1722
1723                 } catch (AdaptionException e) {
1724
1725                         return null;
1726
1727                 } catch (DatabaseException e) {
1728
1729                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1730
1731                 }
1732         }
1733
1734         @Override
1735         public <T> T getPossibleUniqueAdapter(Resource resource, Class<T> clazz) throws ValidationException, ServiceException {
1736
1737                 assert (resource != null);
1738                 assert (clazz != null);
1739
1740                 try {
1741
1742                         return syncRequest(new PossibleUniqueAdapter<T>(resource, clazz));
1743
1744                 } catch (AdaptionException e) {
1745
1746                         return null;
1747
1748                 } catch (ValidationException e) {
1749
1750                         throw new ValidationException(e);
1751
1752                 } catch (DatabaseException e) {
1753
1754                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1755
1756                 }
1757
1758         }
1759
1760     @Override
1761     final public boolean isInstanceOf(final Resource resource, final Resource type) throws ServiceException {
1762
1763         assert (resource != null);
1764         assert (type != null);
1765
1766         Set<Resource> resources = getTypes(resource);
1767         // This check was necessary because some of the callers of this method got stuck when the NPE was thrown from here.
1768         if (null == resources)
1769             return false;
1770         
1771         if(EMPTY_RESOURCE_CHECK) {
1772             if (resources.isEmpty()) {
1773                 if(!hasStatement(resource)) throw new EmptyResourceException("Resource " + debugString(resource));
1774             }
1775         }
1776         
1777         return resources.contains(type);
1778
1779     }
1780
1781         @Override
1782         final public boolean isInheritedFrom(final Resource resource, final Resource type) throws ServiceException {
1783
1784                 assert (resource != null);
1785                 assert (type != null);
1786
1787                 try {
1788
1789                         if(resource.equals(type)) return true;
1790                         
1791                         return getSupertypes(resource).contains(type);
1792
1793                 } catch (ServiceException e) {
1794
1795                         throw new ServiceException(e);
1796
1797                 } 
1798                 
1799         }
1800
1801         @Override
1802         final public boolean isSubrelationOf(final Resource resource, final Resource type) throws ServiceException {
1803
1804                 assert (resource != null);
1805                 assert (type != null);
1806
1807                 try {
1808
1809                         if(resource.equals(type)) return true;
1810                         
1811                         return getSuperrelations(resource).contains(type);
1812
1813                 } catch (ServiceException e) {
1814
1815                         throw new ServiceException(e);
1816
1817                 } 
1818
1819         }
1820
1821         @Override
1822         final public boolean hasStatement(final Resource subject) throws ServiceException {
1823
1824                 assert (subject != null);
1825
1826                 try {
1827
1828                         SyncReadProcedure<Boolean> procedure = new SyncReadProcedure<Boolean>();
1829                         processor.forHasStatement(this, subject, procedure);
1830                         procedure.checkAndThrow();
1831                         return procedure.result;
1832
1833                 } catch (ServiceException e) {
1834
1835                         throw new ServiceException(e);
1836
1837                 } catch (DatabaseException e) {
1838
1839                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1840
1841                 }
1842
1843         }
1844
1845         @Override
1846         final public boolean hasStatement(final Resource subject, final Resource relation) throws ServiceException {
1847
1848                 assert (subject != null);
1849                 assert (relation != null);
1850
1851                 try {
1852
1853                         SyncReadProcedure<RelationInfo> procedure = new SyncReadProcedure<RelationInfo>();
1854                         processor.forRelationInfo(this, relation, procedure);
1855                         Collection<Resource> predicates = getPredicates(subject);
1856                         
1857                         if(procedure.result.isFinal) {
1858                                 
1859                                 return predicates.contains(relation);
1860                                 
1861                         } else if (procedure.result.isFunctional) {
1862
1863                                 try {
1864                                         int result = processor.getSingleObject(this, subject, relation);
1865                                         return result != 0;
1866                                 } catch (ManyObjectsForFunctionalRelationException e) {
1867                                         return true;
1868                                 } catch (DatabaseException e) {
1869                                         throw new ServiceException(e);
1870                                 }
1871                                 
1872                         } else {
1873
1874                                 for(Resource predicate : getPredicates(subject)) {
1875                                         if(isSubrelationOf(predicate, relation))
1876                                                 return true;
1877                                 }
1878                                 
1879                         }
1880                         
1881                         return false;
1882
1883                 } catch (ServiceException e) {
1884
1885                         throw new ServiceException(e);
1886
1887                 } 
1888                 
1889         }
1890
1891         @Override
1892         final public boolean hasStatement(final Resource subject, final Resource relation, final Resource object) throws ServiceException {
1893
1894                 assert (subject != null);
1895                 assert (relation != null);
1896                 assert (object != null);
1897
1898                 try {
1899
1900                         for(Resource o : getObjects(subject, relation)) {
1901                                 if(object.equals(o)) return true;
1902                         }
1903                         
1904                         return false;
1905
1906                 } catch (ServiceException e) {
1907
1908                         throw new ServiceException(e);
1909
1910                 }
1911
1912         }
1913
1914         @Override
1915         final public boolean hasValue(final Resource subject) throws ServiceException {
1916
1917                 assert (subject != null);
1918
1919                 try {
1920
1921                         SyncReadProcedure<Boolean> procedure = new SyncReadProcedure<Boolean>();
1922                         processor.forHasValue(this, subject, procedure);
1923                         procedure.checkAndThrow();
1924                         return procedure.result;
1925
1926                 } catch (ServiceException e) {
1927
1928                         throw new ServiceException(e);
1929
1930                 } catch (DatabaseException e) {
1931
1932                         throw new ServiceException(INTERNAL_ERROR_STRING, e);
1933
1934                 }
1935
1936         }
1937
1938         final AsyncProcedure<?> NONE = new AsyncProcedure<Object>() {
1939
1940                 @Override
1941                 public void execute(AsyncReadGraph graph, Object result) {
1942                 }
1943
1944                 @Override
1945                 public void exception(AsyncReadGraph graph, Throwable throwable) {
1946                 }
1947                 
1948         };
1949         
1950         /*
1951          * Implementation of the interface RequestProcessor
1952          */
1953
1954     @Override
1955     public <T> T syncRequest(final Read<T> request) throws DatabaseException {
1956         assert (request != null);
1957         return (T)QueryCache.runnerReadEntry(this, request, parent, null, null, true);
1958     }
1959
1960         @Override
1961         public <T> T syncRequest(Read<T> request, SyncListener<T> procedure)
1962                         throws DatabaseException {
1963                 return syncRequest(request, new SyncToAsyncListener<T>(procedure));
1964         }
1965
1966         @Override
1967         public <T> T syncRequest(Read<T> request, final Listener<T> procedure)
1968                         throws DatabaseException {
1969                 return syncRequest(request, new NoneToAsyncListener<T>(procedure));
1970         }
1971
1972     @Override
1973     public <T> T syncRequest(final Read<T> request, final AsyncProcedure<T> procedure) throws DatabaseException {
1974         assert (request != null);
1975         ListenerBase listener = procedure != null ? getListenerBase(procedure) : null;
1976         return (T)QueryCache.runnerReadEntry(this, request, parent, listener, procedure, true);
1977     }
1978
1979         @Override
1980         public <T> T syncRequest(final Read<T> request,
1981                         final SyncProcedure<T> procedure) throws DatabaseException {
1982                 return syncRequest(request, new SyncToAsyncProcedure<T>(procedure));
1983         }
1984
1985         @Override
1986         public <T> T syncRequest(Read<T> request, Procedure<T> procedure)
1987                         throws DatabaseException {
1988                 return syncRequest(request, new NoneToAsyncProcedure<T>(procedure));
1989         }
1990
1991         static class AsyncReadProcedure<T> implements AsyncProcedure<T> {
1992
1993                 private static Throwable DONE = new Throwable();
1994                 
1995                 T result = null;
1996                 Throwable exception = null;
1997                 
1998                 @Override
1999                 public void execute(AsyncReadGraph graph, T t) {
2000                         result = t;
2001                         exception = DONE;
2002                 }
2003
2004                 @Override
2005                 public void exception(AsyncReadGraph graph, Throwable t) {
2006                         exception = t;
2007                 }
2008                 
2009                 public void checkAndThrow() throws DatabaseException {
2010                         if(exception != DONE) {
2011                                 if (exception instanceof DatabaseException)
2012                                         throw (DatabaseException) exception;
2013                                 else
2014                                         throw new DatabaseException(
2015                                                         "Unexpected exception in ReadGraph.syncRequest(AsyncRead)",
2016                                                         exception);
2017                         }
2018                 }
2019                 
2020                 public boolean done() {
2021                         return exception != null;
2022                 }
2023                 
2024         }
2025         
2026         @Override
2027         public <T> T syncRequest(final AsyncRead<T> request)
2028                         throws DatabaseException {
2029
2030                 assert (request != null);
2031                 return syncRequest(request, new AsyncProcedureAdapter<>() );
2032
2033         }
2034
2035         @Override
2036         public <T> T syncRequest(AsyncRead<T> request, AsyncListener<T> procedure)
2037                         throws DatabaseException {
2038                 return syncRequest(request, (AsyncProcedure<T>) procedure);
2039         }
2040
2041         @Override
2042         public <T> T syncRequest(AsyncRead<T> request, SyncListener<T> procedure)
2043                         throws DatabaseException {
2044                 return syncRequest(request, new SyncToAsyncListener<T>(procedure));
2045         }
2046
2047         @Override
2048         public <T> T syncRequest(AsyncRead<T> request, Listener<T> procedure)
2049                         throws DatabaseException {
2050                 return syncRequest(request, new NoneToAsyncListener<T>(procedure));
2051         }
2052
2053     @Override
2054     final public <T> T syncRequest(final AsyncRead<T> request,
2055             final AsyncProcedure<T> procedure) throws DatabaseException {
2056         assert (request != null);
2057         ListenerBase listener = getListenerBase(procedure);
2058         return (T)QueryCache.runnerAsyncReadEntry(this, request, parent, listener, procedure, true); 
2059     }
2060
2061         @Override
2062         public <T> T syncRequest(AsyncRead<T> request,
2063                         final SyncProcedure<T> procedure) throws DatabaseException {
2064                 return syncRequest(request, new SyncToAsyncProcedure<T>(procedure));
2065         }
2066
2067         @Override
2068         final public <T> T syncRequest(final AsyncRead<T> request,
2069                         final Procedure<T> procedure) throws DatabaseException {
2070                 return syncRequest(request, new NoneToAsyncProcedure<T>(procedure));
2071         }
2072
2073         @Override
2074         public <T> Collection<T> syncRequest(final MultiRead<T> request)
2075                         throws DatabaseException {
2076
2077                 assert (request != null);
2078
2079                 final ArrayList<T> result = new ArrayList<T>();
2080                 final DataContainer<Throwable> exception = new DataContainer<Throwable>();
2081
2082                 syncRequest(request, new SyncMultiProcedure<T>() {
2083
2084                         @Override
2085                         public void execute(ReadGraph graph, T t) {
2086                                 synchronized (result) {
2087                                         result.add(t);
2088                                 }
2089                         }
2090
2091                         @Override
2092                         public void finished(ReadGraph graph) {
2093                         }
2094
2095                         @Override
2096                         public void exception(ReadGraph graph, Throwable t) {
2097                                 exception.set(t);
2098                         }
2099
2100                         @Override
2101                         public String toString() {
2102                                 return "syncRequest(MultiRead) -> " + request;
2103                         }
2104
2105                 });
2106
2107                 Throwable t = exception.get();
2108                 if (t != null) {
2109                         if (t instanceof DatabaseException)
2110                                 throw (DatabaseException) t;
2111                         else
2112                                 throw new DatabaseException(
2113                                                 "Unexpected exception in ReadGraph.syncRequest(Read)",
2114                                                 t);
2115                 }
2116
2117                 return result;
2118
2119         }
2120
2121         @Override
2122         public <T> Collection<T> syncRequest(MultiRead<T> request,
2123                         SyncMultiListener<T> procedure) {
2124                 return syncRequest(request, (SyncMultiProcedure<T>)procedure);
2125         }
2126
2127         @Override
2128         public <T> Collection<T> syncRequest(MultiRead<T> request,
2129                         MultiListener<T> procedure) {
2130                 return syncRequest(request, new NoneToSyncMultiListener<T>(procedure));
2131         }
2132
2133         @Override
2134         public <T> Collection<T> syncRequest(MultiRead<T> request,
2135                         SyncMultiProcedure<T> procedure) {
2136
2137                 assert (request != null);
2138
2139                 ListenerBase listener = getListenerBase(procedure);
2140
2141                 final ResultCallWrappedSyncQueryProcedure<T> wrapper = new ResultCallWrappedSyncQueryProcedure<T>(procedure);
2142
2143                 if (parent != null || listener != null) {
2144
2145 //                      Object syncParent = request;
2146
2147 //                      final ReadGraphImpl newGraph = newSync();
2148
2149                         processor.query(this, request, parent, wrapper, listener);
2150
2151 //                      newGraph.waitAsync(syncParent);
2152
2153                 } else {
2154
2155 //                      Object syncParent = request;
2156
2157 //                      final ReadGraphImpl newGraph = newSync();
2158
2159                         try {
2160                                 request.perform(this, wrapper);
2161                         } catch (Throwable t) {
2162                                 wrapper.exception(this, t);
2163                         }
2164
2165                 }
2166
2167                 return wrapper.get();
2168
2169         }
2170
2171         @Override
2172         public <T> Collection<T> syncRequest(MultiRead<T> request,
2173                         MultiProcedure<T> procedure) {
2174                 return syncRequest(request, new NoneToSyncMultiProcedure<T>(procedure));
2175         }
2176
2177         static class AsyncMultiReadProcedure<T> extends ArrayList<T> implements AsyncMultiProcedure<T> {
2178
2179                 private static Throwable DONE = new Throwable();
2180                 
2181                 private static final long serialVersionUID = -6494230465108115812L;
2182                 
2183                 Throwable exception = null;
2184                 
2185                 @Override
2186                 public synchronized void execute(AsyncReadGraph graph, T t) {
2187                         add(t);
2188                 }
2189
2190                 @Override
2191                 public void finished(AsyncReadGraph graph) {
2192                         exception = DONE;
2193                 }
2194
2195                 @Override
2196                 public void exception(AsyncReadGraph graph, Throwable t) {
2197                         exception = t;
2198                 }
2199                 
2200                 public void checkAndThrow() throws DatabaseException {
2201                         if(exception != DONE) {
2202                                 if (exception instanceof DatabaseException)
2203                                         throw (DatabaseException) exception;
2204                                 else
2205                                         throw new DatabaseException(
2206                                                         "Unexpected exception in ReadGraph.syncRequest(AsyncMultiRead)",
2207                                                         exception);
2208                         }
2209                 }
2210                 
2211                 public boolean done() {
2212                         return exception != null;
2213                 }
2214                 
2215         }
2216
2217         @Override
2218         final public <T> Collection<T> syncRequest(AsyncMultiRead<T> request)
2219                         throws DatabaseException {
2220
2221                 assert (request != null);
2222
2223                 final AsyncMultiReadProcedure<T> procedure = new AsyncMultiReadProcedure<T>();
2224                 
2225                 syncRequest(request, procedure);
2226                 
2227                 procedure.checkAndThrow();
2228                 return procedure;
2229
2230         }
2231
2232         @Override
2233         public <T> Collection<T> syncRequest(AsyncMultiRead<T> request,
2234                         AsyncMultiListener<T> procedure) {
2235                 return syncRequest(request, (AsyncMultiProcedure<T>) procedure);
2236         }
2237
2238         @Override
2239         public <T> Collection<T> syncRequest(AsyncMultiRead<T> request,
2240                         SyncMultiListener<T> procedure) {
2241                 return syncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
2242         }
2243
2244         @Override
2245         public <T> Collection<T> syncRequest(AsyncMultiRead<T> request,
2246                         MultiListener<T> procedure) {
2247                 return syncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
2248         }
2249
2250         final private <T> void syncRequest(final AsyncMultiRead<T> request,
2251                         final AsyncMultiReadProcedure<T> procedure) {
2252
2253                 assert (request != null);
2254                 assert (procedure != null);
2255
2256                 ListenerBase listener = getListenerBase(procedure);
2257
2258                 if (parent != null || listener != null) {
2259
2260 //                      Object syncParent = request;
2261
2262 //                      final ReadGraphImpl newGraph = newSync();
2263
2264                         processor.query(this, request, parent, procedure, listener);
2265
2266 //                      newGraph.waitAsync(syncParent);
2267                         waitAsyncProcedure(procedure);
2268
2269                 } else {
2270
2271 //                      Object syncParent = callerThread == Integer.MIN_VALUE ? null
2272 //                                      : request;
2273 //
2274 //                      final ReadGraphImpl newGraph = newSyncAsync(syncParent);
2275
2276                         try {
2277
2278 //                              inc();
2279 //                              ReadGraphImpl sync = newSync();
2280                                 request.perform(this, procedure);
2281 //                              sync.waitAsync(null);
2282                                 waitAsyncProcedure(procedure);
2283 //                              dec();
2284
2285                         } catch (Throwable t) {
2286
2287                                 waitAsyncProcedure(procedure);
2288 //                              dec();
2289
2290                         }
2291
2292                 }
2293
2294         }
2295         
2296         
2297         @Override
2298         final public <T> Collection<T> syncRequest(final AsyncMultiRead<T> request,
2299                         final AsyncMultiProcedure<T> procedure) {
2300
2301                 assert (request != null);
2302                 assert (procedure != null);
2303
2304                 ListenerBase listener = getListenerBase(procedure);
2305
2306                 if (parent != null || listener != null) {
2307
2308 //                      Object syncParent = request;
2309
2310 //                      final ReadGraphImpl newGraph = newSync();
2311
2312                         processor.query(this, request, parent, procedure, listener);
2313
2314 //                      newGraph.waitAsync(syncParent);
2315
2316                 } else {
2317
2318 //                      Object syncParent = request;
2319
2320 //                      final ReadGraphImpl newGraph = newSync();
2321
2322                         try {
2323
2324                                 request.perform(this, new AsyncMultiProcedure<T>() {
2325
2326                                         @Override
2327                                         public void execute(AsyncReadGraph graph, T result) {
2328                                                 procedure.execute(graph, result);
2329                                         }
2330
2331                                         @Override
2332                                         public void finished(AsyncReadGraph graph) {
2333                                                 procedure.finished(graph);
2334                                         }
2335
2336                                         @Override
2337                                         public void exception(AsyncReadGraph graph, Throwable t) {
2338                                                 procedure.exception(graph, t);
2339                                         }
2340
2341                                         @Override
2342                                         public String toString() {
2343                                                 return "syncRequest(AsyncMultiRead) -> " + procedure;
2344                                         }
2345
2346                                 });
2347
2348                         } catch (Throwable t) {
2349
2350                         }
2351
2352                 }
2353
2354                 // TODO!!
2355                 return null;
2356
2357         }
2358
2359         @Override
2360         public <T> Collection<T> syncRequest(AsyncMultiRead<T> request,
2361                         final SyncMultiProcedure<T> procedure) {
2362                 return syncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
2363         }
2364
2365         @Override
2366         final public <T> Collection<T> syncRequest(final AsyncMultiRead<T> request,
2367                         final MultiProcedure<T> procedure) {
2368                 return syncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
2369         }
2370
2371         @Override
2372         public <T> T syncRequest(final ExternalRead<T> request)
2373                         throws DatabaseException {
2374
2375                 assert (request != null);
2376
2377                 return syncRequest(request, new Procedure<T>() {
2378
2379                         @Override
2380                         public void execute(T t) {
2381                         }
2382
2383                         @Override
2384                         public void exception(Throwable t) {
2385                         }
2386
2387                         @Override
2388                         public String toString() {
2389                                 return "syncRequest(AsyncRead) -> " + request;
2390                         }
2391
2392                 });
2393
2394         }
2395
2396         @Override
2397         public <T> T syncRequest(ExternalRead<T> request, Listener<T> procedure) throws DatabaseException {
2398                 return syncRequest(request, (Procedure<T>) procedure);
2399         }
2400
2401         @Override
2402         final public <T> T syncRequest(final ExternalRead<T> request,
2403                         final Procedure<T> procedure) throws DatabaseException {
2404
2405         assert (request != null);
2406
2407         ListenerBase listener = procedure != null ? getListenerBase(procedure) : null;
2408         return QueryCache.resultExternalReadEntry(this, request, parent, listener, procedure);
2409
2410         }
2411
2412         @Override
2413         public void syncRequest(final Write request) throws DatabaseException {
2414
2415                 assert (request != null);
2416
2417                 throw new DatabaseException(
2418                                 "Write operations are not supported during read transactions!");
2419
2420         }
2421
2422         @Override
2423         public <T> T syncRequest(final WriteResult<T> request) throws DatabaseException {
2424
2425                 assert (request != null);
2426
2427                 throw new DatabaseException(
2428                                 "Write operations are not supported during read transactions!");
2429
2430         }
2431
2432         @Override
2433         public void syncRequest(final DelayedWrite request)
2434                         throws DatabaseException {
2435
2436                 assert (request != null);
2437
2438                 throw new DatabaseException(
2439                                 "Write operations are not supported during read transactions!");
2440
2441         }
2442
2443         @Override
2444         public <T> T syncRequest(final DelayedWriteResult<T> request) throws DatabaseException {
2445
2446                 assert (request != null);
2447
2448                 throw new DatabaseException(
2449                                 "Write operations are not supported during read transactions!");
2450
2451         }
2452         
2453         @Override
2454         public void syncRequest(final WriteOnly request) throws DatabaseException {
2455
2456                 assert (request != null);
2457
2458                 throw new DatabaseException(
2459                                 "Write operations are not supported during read transactions!");
2460
2461         }
2462
2463         @Override
2464         public <T> T syncRequest(final WriteOnlyResult<T> request) throws DatabaseException {
2465
2466                 assert (request != null);
2467
2468                 throw new DatabaseException(
2469                                 "Write operations are not supported during read transactions!");
2470
2471         }
2472         
2473         @Override
2474         public <T> void async(ReadInterface<T> r, AsyncProcedure<T> procedure) {
2475                 r.request(this, procedure);
2476         }
2477         
2478         @Override
2479         public <T> void async(ReadInterface<T> r, Procedure<T> procedure) {
2480                 r.request(this, procedure);
2481         }
2482         
2483         @Override
2484         public <T> void async(ReadInterface<T> r, SyncProcedure<T> procedure) {
2485                 r.request(this, procedure);
2486         }
2487         
2488         @Override
2489         public <T> void async(ReadInterface<T> r, AsyncListener<T> procedure) {
2490                 r.request(this, procedure);
2491         }
2492         
2493         @Override
2494         public <T> void async(ReadInterface<T> r, Listener<T> procedure) {
2495                 r.request(this, procedure);
2496         }
2497         
2498         @Override
2499         public <T> void async(ReadInterface<T> r, SyncListener<T> procedure) {
2500                 r.request(this, procedure);
2501         }
2502
2503         @Override
2504         public <T> T sync(ReadInterface<T> r) throws DatabaseException {
2505                 return r.request(this);
2506         }
2507         
2508         @Override
2509         public <T> T sync(WriteInterface<T> r) throws DatabaseException {
2510                 return r.request(this);
2511         }
2512         
2513         @Override
2514         public <T> void async(WriteInterface<T> r, Procedure<T> procedure) {
2515                 r.request(this, procedure);
2516         }
2517
2518         @Override
2519         public <T> void async(WriteInterface<T> r) {
2520                 r.request(this, new ProcedureAdapter<T>());
2521         }
2522
2523         /*
2524          * Implementation of the interface AsyncReadGraph
2525          */
2526
2527         @Override
2528         public void forURI(Resource resource, AsyncListener<String> listener) {
2529                 asyncRequest(new org.simantics.db.common.uri.ResourceToURI(resource),
2530                                 listener);
2531         }
2532
2533         @Override
2534         public void forURI(Resource resource, SyncListener<String> listener) {
2535                 asyncRequest(new org.simantics.db.common.uri.ResourceToURI(resource),
2536                                 listener);
2537         }
2538
2539         @Override
2540         public void forURI(Resource resource, Listener<String> listener) {
2541                 asyncRequest(new org.simantics.db.common.uri.ResourceToURI(resource),
2542                                 listener);
2543         }
2544
2545         @Override
2546         final public void forURI(final Resource resource,
2547                         final AsyncProcedure<String> procedure) {
2548
2549                 assert (resource != null);
2550                 assert (procedure != null);
2551
2552                 asyncRequest(new org.simantics.db.common.uri.ResourceToURI(resource),
2553                                 procedure);
2554
2555         }
2556
2557         @Override
2558         public void forURI(Resource resource, SyncProcedure<String> procedure) {
2559                 forURI(resource, new SyncToAsyncProcedure<String>(procedure));
2560         }
2561
2562         @Override
2563         public void forURI(Resource resource, Procedure<String> procedure) {
2564                 forURI(resource, new NoneToAsyncProcedure<String>(procedure));
2565         }
2566         
2567         @Override
2568         public void forResource(String id, AsyncListener<Resource> listener) {
2569                 asyncRequest(new org.simantics.db.common.primitiverequest.Resource(id),
2570                                 listener);
2571         }
2572
2573         @Override
2574         public void forResource(String id, SyncListener<Resource> listener) {
2575                 asyncRequest(new org.simantics.db.common.primitiverequest.Resource(id),
2576                                 listener);
2577         }
2578
2579         @Override
2580         public void forResource(String id, Listener<Resource> listener) {
2581                 asyncRequest(new org.simantics.db.common.primitiverequest.Resource(id),
2582                                 listener);
2583         }
2584
2585         @Override
2586         final public void forResource(final String id,
2587                         final AsyncProcedure<Resource> procedure) {
2588
2589                 assert (id != null);
2590                 assert (procedure != null);
2591
2592                 processor.forResource(this, id, procedure);
2593
2594         }
2595
2596         @Override
2597         public void forResource(String id, SyncProcedure<Resource> procedure) {
2598                 forResource(id, new SyncToAsyncProcedure<Resource>(procedure));
2599         }
2600
2601         @Override
2602         public void forResource(String id, Procedure<Resource> procedure) {
2603                 forResource(id, new NoneToAsyncProcedure<Resource>(procedure));
2604         }
2605
2606         @Override
2607         public void forBuiltin(String id, AsyncListener<Resource> listener) {
2608                 asyncRequest(new Builtin(id), listener);
2609         }
2610
2611         @Override
2612         public void forBuiltin(String id, SyncListener<Resource> listener) {
2613                 asyncRequest(new Builtin(id), listener);
2614         }
2615
2616         @Override
2617         public void forBuiltin(String id, Listener<Resource> listener) {
2618                 asyncRequest(new Builtin(id), listener);
2619         }
2620
2621         @Override
2622         final public void forBuiltin(final String id,
2623                         final AsyncProcedure<Resource> procedure) {
2624
2625                 assert (id != null);
2626                 assert (procedure != null);
2627
2628                 processor.forBuiltin(this, id, procedure);
2629
2630         }
2631
2632         @Override
2633         public void forBuiltin(String id, SyncProcedure<Resource> procedure) {
2634                 forBuiltin(id, new SyncToAsyncProcedure<Resource>(procedure));
2635         }
2636
2637         @Override
2638         public void forBuiltin(String id, Procedure<Resource> procedure) {
2639                 forBuiltin(id, new NoneToAsyncProcedure<Resource>(procedure));
2640         }
2641
2642         @Override
2643         final public void forEachStatement(Resource subject, Resource relation,
2644                         AsyncMultiProcedure<Statement> procedure) {
2645
2646                 assert (subject != null);
2647                 assert (relation != null);
2648                 assert (procedure != null);
2649
2650                 processor.forEachStatement(this, subject, relation, procedure);
2651
2652         }
2653
2654         @Override
2655         public void forEachStatement(Resource subject, Resource relation,
2656                         SyncMultiProcedure<Statement> procedure) {
2657                 forEachStatement(subject, relation,
2658                                 new SyncToAsyncMultiProcedure<Statement>(procedure));
2659         }
2660
2661         @Override
2662         final public void forEachStatement(Resource subject, Resource relation,
2663                         MultiProcedure<Statement> procedure) {
2664
2665                 assert (subject != null);
2666                 assert (relation != null);
2667                 assert (procedure != null);
2668
2669                 processor.forEachStatement(this, subject, relation, procedure);
2670
2671         }
2672
2673         @Override
2674         final public void forStatementSet(Resource subject, Resource relation,
2675                         AsyncSetListener<Statement> procedure) {
2676
2677                 assert (subject != null);
2678                 assert (relation != null);
2679                 assert (procedure != null);
2680
2681                 processor.forStatementSet(this, subject, relation, procedure);
2682
2683         }
2684
2685         @Override
2686         final public void forStatementSet(Resource subject, Resource relation,
2687                         SyncSetListener<Statement> procedure) {
2688                 forStatementSet(subject, relation,
2689                                 new SyncToAsyncSetProcedure<Statement>(procedure));
2690         }
2691
2692         @Override
2693         public void forStatementSet(Resource subject, Resource relation,
2694                         SetListener<Statement> listener) {
2695                 forStatementSet(subject, relation,
2696                                 new NoneToAsyncSetProcedure<Statement>(listener));
2697         }
2698
2699         @Override
2700         final public void forEachAssertedStatement(final Resource subject,
2701                         final Resource relation,
2702                         final AsyncMultiProcedure<Statement> procedure) {
2703
2704                 assert (subject != null);
2705                 assert (relation != null);
2706                 assert (procedure != null);
2707
2708                 processor.forEachAssertedStatement(this, subject, relation, procedure);
2709
2710         }
2711
2712         @Override
2713         public void forEachAssertedStatement(Resource subject, Resource relation,
2714                         SyncMultiProcedure<Statement> procedure) {
2715                 forEachAssertedStatement(subject, relation,
2716                                 new SyncToAsyncMultiProcedure<Statement>(procedure));
2717         }
2718
2719         @Override
2720         public void forEachAssertedStatement(Resource subject, Resource relation,
2721                         MultiProcedure<Statement> procedure) {
2722                 forEachAssertedStatement(subject, relation,
2723                                 new NoneToAsyncMultiProcedure<Statement>(procedure));
2724         }
2725
2726         @Override
2727         public void forAssertedStatementSet(Resource subject, Resource relation,
2728                         AsyncSetListener<Statement> procedure) {
2729
2730                 assert (subject != null);
2731                 assert (relation != null);
2732                 assert (procedure != null);
2733
2734                 processor.forAssertedStatementSet(this, subject, relation, procedure);
2735
2736         }
2737
2738         @Override
2739         public void forAssertedStatementSet(Resource subject, Resource relation,
2740                         SyncSetListener<Statement> procedure) {
2741
2742                 assert (subject != null);
2743                 assert (relation != null);
2744                 assert (procedure != null);
2745
2746                 forAssertedStatementSet(subject, relation,
2747                                 new SyncToAsyncSetProcedure<Statement>(procedure));
2748
2749         }
2750
2751         @Override
2752         public void forAssertedStatementSet(Resource subject, Resource relation,
2753                         SetListener<Statement> procedure) {
2754
2755                 assert (subject != null);
2756                 assert (relation != null);
2757                 assert (procedure != null);
2758
2759                 forAssertedStatementSet(subject, relation,
2760                                 new NoneToAsyncSetProcedure<Statement>(procedure));
2761
2762         }
2763
2764         @Override
2765         final public void forEachPredicate(final Resource subject,
2766                         final AsyncMultiProcedure<Resource> procedure) {
2767
2768                 assert (subject != null);
2769                 assert (procedure != null);
2770
2771                 processor.forEachPredicate(this, subject, procedure);
2772
2773         }
2774
2775         @Override
2776         public void forEachPredicate(Resource subject,
2777                         SyncMultiProcedure<Resource> procedure) {
2778                 forEachPredicate(subject, new SyncToAsyncMultiProcedure<Resource>(
2779                                 procedure));
2780         }
2781
2782         @Override
2783         final public void forEachPredicate(final Resource subject,
2784                         final MultiProcedure<Resource> procedure) {
2785
2786                 assert (subject != null);
2787                 assert (procedure != null);
2788
2789                 processor.forEachPredicate(this, subject, procedure);
2790
2791         }
2792
2793         @Override
2794         final public void forPredicateSet(final Resource subject,
2795                         final AsyncSetListener<Resource> procedure) {
2796
2797                 assert (subject != null);
2798                 assert (procedure != null);
2799
2800                 processor.forPredicateSet(this, subject, procedure);
2801
2802         }
2803
2804         @Override
2805         final public void forPredicateSet(final Resource subject,
2806                         final SyncSetListener<Resource> procedure) {
2807
2808                 assert (subject != null);
2809                 assert (procedure != null);
2810
2811                 forPredicateSet(subject, new SyncToAsyncSetProcedure<Resource>(
2812                                 procedure));
2813
2814         }
2815
2816         @Override
2817         final public void forPredicateSet(final Resource subject,
2818                         final SetListener<Resource> procedure) {
2819
2820                 assert (subject != null);
2821                 assert (procedure != null);
2822
2823                 forPredicateSet(subject, new NoneToAsyncSetProcedure<Resource>(
2824                                 procedure));
2825
2826         }
2827
2828         @Override
2829         final public void forEachPrincipalType(final Resource subject,
2830                         final AsyncMultiProcedure<Resource> procedure) {
2831
2832                 assert (subject != null);
2833                 assert (procedure != null);
2834
2835                 processor.forEachPrincipalType(this, subject, procedure);
2836
2837         }
2838
2839         @Override
2840         public void forEachPrincipalType(Resource subject,
2841                         SyncMultiProcedure<Resource> procedure) {
2842                 forEachPrincipalType(subject, new SyncToAsyncMultiProcedure<Resource>(
2843                                 procedure));
2844         }
2845
2846         @Override
2847         final public void forEachPrincipalType(final Resource subject,
2848                         final MultiProcedure<Resource> procedure) {
2849
2850                 assert (subject != null);
2851                 assert (procedure != null);
2852
2853                 processor.forEachPrincipalType(this, subject, procedure);
2854
2855         }
2856
2857         @Override
2858         final public void forPrincipalTypeSet(final Resource subject,
2859                         final AsyncSetListener<Resource> procedure) {
2860
2861                 assert (subject != null);
2862                 assert (procedure != null);
2863
2864                 processor.forPrincipalTypeSet(this, subject, procedure);
2865
2866         }
2867
2868         @Override
2869         final public void forPrincipalTypeSet(final Resource subject,
2870                         final SyncSetListener<Resource> procedure) {
2871
2872                 assert (subject != null);
2873                 assert (procedure != null);
2874
2875                 forPrincipalTypeSet(subject, new SyncToAsyncSetProcedure<Resource>(
2876                                 procedure));
2877
2878         }
2879
2880         @Override
2881         final public void forPrincipalTypeSet(final Resource subject,
2882                         final SetListener<Resource> procedure) {
2883
2884                 assert (subject != null);
2885                 assert (procedure != null);
2886
2887                 forPrincipalTypeSet(subject, new NoneToAsyncSetProcedure<Resource>(
2888                                 procedure));
2889
2890         }
2891
2892         @Override
2893         public void forTypes(Resource subject, AsyncListener<Set<Resource>> listener) {
2894                 asyncRequest(new Types(subject), listener);
2895         }
2896
2897         @Override
2898         public void forTypes(Resource subject, SyncListener<Set<Resource>> listener) {
2899                 asyncRequest(new Types(subject), listener);
2900         }
2901
2902         @Override
2903         public void forTypes(Resource subject, Listener<Set<Resource>> listener) {
2904                 asyncRequest(new Types(subject), listener);
2905         }
2906
2907         @Override
2908         final public void forTypes(final Resource subject,
2909                         final AsyncProcedure<Set<Resource>> procedure) {
2910
2911                 assert (subject != null);
2912                 assert (procedure != null);
2913
2914                 processor.forTypes(this, subject, procedure);
2915
2916         }
2917
2918         @Override
2919         public void forTypes(Resource subject,
2920                         SyncProcedure<Set<Resource>> procedure) {
2921                 forTypes(subject, new SyncToAsyncProcedure<Set<Resource>>(procedure));
2922         }
2923
2924         @Override
2925         public void forTypes(Resource subject, Procedure<Set<Resource>> procedure) {
2926                 forTypes(subject, new NoneToAsyncProcedure<Set<Resource>>(procedure));
2927         }
2928
2929         @Override
2930         public void forSupertypes(Resource subject,
2931                         AsyncListener<Set<Resource>> listener) {
2932                 asyncRequest(new Types(subject), listener);
2933         }
2934
2935         @Override
2936         public void forSupertypes(Resource subject,
2937                         SyncListener<Set<Resource>> listener) {
2938                 asyncRequest(new Types(subject), listener);
2939         }
2940
2941         @Override
2942         public void forSupertypes(Resource subject, Listener<Set<Resource>> listener) {
2943                 asyncRequest(new Types(subject), listener);
2944         }
2945
2946         @Override
2947         final public void forSupertypes(final Resource subject,
2948                         final AsyncProcedure<Set<Resource>> procedure) {
2949
2950                 assert (subject != null);
2951                 assert (procedure != null);
2952
2953                 processor.forSupertypes(this, subject, procedure);
2954
2955         }
2956
2957         @Override
2958         public void forSupertypes(Resource subject,
2959                         SyncProcedure<Set<Resource>> procedure) {
2960                 forSupertypes(subject, new SyncToAsyncProcedure<Set<Resource>>(
2961                                 procedure));
2962         }
2963
2964         @Override
2965         public void forSupertypes(Resource subject,
2966                         Procedure<Set<Resource>> procedure) {
2967                 forSupertypes(subject, new NoneToAsyncProcedure<Set<Resource>>(
2968                                 procedure));
2969         }
2970
2971         @Override
2972         public void forDirectSuperrelations(Resource subject,
2973                         AsyncMultiProcedure<Resource> procedure) {
2974                 
2975                 assert (subject != null);
2976                 assert (procedure != null);
2977
2978                 processor.forDirectSuperrelations(this, subject, procedure);
2979                 
2980         }
2981
2982         @Override
2983         public void forPossibleSuperrelation(Resource subject, AsyncProcedure<Resource> procedure) {
2984                 
2985                 assert (subject != null);
2986                 assert (procedure != null);
2987
2988                 processor.forPossibleSuperrelation(this, subject, procedure);
2989                 
2990         }
2991
2992         @Override
2993         public void forSuperrelations(Resource subject,
2994                         AsyncListener<Set<Resource>> listener) {
2995                 asyncRequest(new Types(subject), listener);
2996         }
2997
2998         @Override
2999         public void forSuperrelations(Resource subject,
3000                         SyncListener<Set<Resource>> listener) {
3001                 asyncRequest(new Types(subject), listener);
3002         }
3003
3004         @Override
3005         public void forSuperrelations(Resource subject,
3006                         Listener<Set<Resource>> listener) {
3007                 asyncRequest(new Types(subject), listener);
3008         }
3009
3010         @Override
3011         final public void forSuperrelations(final Resource subject,
3012                         final AsyncProcedure<Set<Resource>> procedure) {
3013
3014                 assert (subject != null);
3015                 assert (procedure != null);
3016
3017                 processor.forSuperrelations(this, subject, procedure);
3018
3019         }
3020
3021         @Override
3022         public void forSuperrelations(Resource subject,
3023                         SyncProcedure<Set<Resource>> procedure) {
3024                 forSuperrelations(subject, new SyncToAsyncProcedure<Set<Resource>>(
3025                                 procedure));
3026         }
3027
3028         @Override
3029         public void forSuperrelations(Resource subject,
3030                         Procedure<Set<Resource>> procedure) {
3031                 forSuperrelations(subject, new NoneToAsyncProcedure<Set<Resource>>(
3032                                 procedure));
3033         }
3034
3035         @Override
3036         final public void forEachObject(final Resource subject, final Resource relation, final AsyncMultiProcedure<Resource> procedure) {
3037                 processor.forEachObject(this, subject, relation, procedure);
3038         }
3039
3040         @Override
3041         public void forEachObject(Resource subject, Resource relation,
3042                         SyncMultiProcedure<Resource> procedure) {
3043                 forEachObject(subject, relation,
3044                                 new SyncToAsyncMultiProcedure<Resource>(procedure));
3045         }
3046
3047         @Override
3048         public void forEachObject(Resource subject, Resource relation,
3049                         MultiProcedure<Resource> procedure) {
3050
3051                 processor.forEachObject(this, subject, relation, procedure);
3052
3053         }
3054
3055         @Override
3056         final public void forEachDirectPredicate(final Resource subject, final AsyncProcedure<Set<Resource>> procedure) {
3057                 processor.forEachDirectPredicate(this, subject, procedure);
3058         }
3059
3060         @Override
3061         final public void forEachDirectPredicate(final Resource subject, final SyncProcedure<Set<Resource>> procedure) {
3062                 forEachDirectPredicate(subject, new SyncToAsyncProcedure<Set<Resource>>(procedure));
3063         }
3064
3065         @Override
3066         public void forEachDirectPredicate(Resource subject, Procedure<Set<Resource>> procedure) {
3067                 forEachDirectPredicate(subject, new NoneToAsyncProcedure<Set<Resource>>(procedure));
3068         }
3069
3070         @Override
3071         final public void forObjectSet(final Resource subject,
3072                         final Resource relation, final AsyncSetListener<Resource> procedure) {
3073
3074                 assert (subject != null);
3075                 assert (relation != null);
3076                 assert (procedure != null);
3077
3078                 processor.forObjectSet(this, subject, relation, procedure);
3079
3080         }
3081
3082         @Override
3083         final public void forObjectSet(final Resource subject,
3084                         final Resource relation, final SyncSetListener<Resource> procedure) {
3085
3086                 assert (subject != null);
3087                 assert (relation != null);
3088                 assert (procedure != null);
3089
3090                 forObjectSet(subject, relation, new SyncToAsyncSetProcedure<Resource>(
3091                                 procedure));
3092
3093         }
3094
3095         @Override
3096         final public void forObjectSet(final Resource subject,
3097                         final Resource relation, final SetListener<Resource> procedure) {
3098
3099                 assert (subject != null);
3100                 assert (relation != null);
3101                 assert (procedure != null);
3102
3103                 forObjectSet(subject, relation, new NoneToAsyncSetProcedure<Resource>(
3104                                 procedure));
3105
3106         }
3107
3108         @Override
3109         final public void forEachAssertedObject(final Resource subject,
3110                         final Resource relation,
3111                         final AsyncMultiProcedure<Resource> procedure) {
3112
3113                 assert (subject != null);
3114                 assert (relation != null);
3115                 assert (procedure != null);
3116
3117                 processor.forEachAssertedObject(this, subject, relation, procedure);
3118
3119         }
3120
3121         @Override
3122         public void forEachAssertedObject(Resource subject, Resource relation,
3123                         SyncMultiProcedure<Resource> procedure) {
3124
3125                 assert (subject != null);
3126                 assert (relation != null);
3127                 assert (procedure != null);
3128
3129                 forEachAssertedObject(subject, relation,
3130                                 new SyncToAsyncMultiProcedure<Resource>(procedure));
3131
3132         }
3133
3134         @Override
3135         public void forEachAssertedObject(Resource subject, Resource relation,
3136                         MultiProcedure<Resource> procedure) {
3137
3138                 assert (subject != null);
3139                 assert (relation != null);
3140                 assert (procedure != null);
3141
3142                 forEachAssertedObject(subject, relation,
3143                                 new NoneToAsyncMultiProcedure<Resource>(procedure));
3144
3145         }
3146
3147         @Override
3148         public void forAssertedObjectSet(Resource subject, Resource relation,
3149                         AsyncSetListener<Resource> procedure) {
3150
3151                 assert (subject != null);
3152                 assert (relation != null);
3153                 assert (procedure != null);
3154
3155                 processor.forAssertedObjectSet(this, subject, relation, procedure);
3156
3157         }
3158
3159         @Override
3160         public void forAssertedObjectSet(Resource subject, Resource relation,
3161                         SyncSetListener<Resource> procedure) {
3162
3163                 assert (subject != null);
3164                 assert (relation != null);
3165                 assert (procedure != null);
3166
3167                 forAssertedObjectSet(subject, relation,
3168                                 new SyncToAsyncSetProcedure<Resource>(procedure));
3169
3170         }
3171
3172         @Override
3173         public void forAssertedObjectSet(Resource subject, Resource relation,
3174                         SetListener<Resource> procedure) {
3175
3176                 assert (subject != null);
3177                 assert (relation != null);
3178                 assert (procedure != null);
3179
3180                 forAssertedObjectSet(subject, relation,
3181                                 new NoneToAsyncSetProcedure<Resource>(procedure));
3182
3183         }
3184
3185         @Override
3186         public void forInverse(Resource relation, AsyncListener<Resource> listener) {
3187                 asyncRequest(new Inverse(relation), listener);
3188         }
3189
3190         @Override
3191         public void forInverse(Resource relation, SyncListener<Resource> listener) {
3192                 asyncRequest(new Inverse(relation), listener);
3193         }
3194
3195         @Override
3196         public void forInverse(Resource relation, Listener<Resource> listener) {
3197                 asyncRequest(new Inverse(relation), listener);
3198         }
3199
3200         @Override
3201         final public void forInverse(final Resource relation,
3202                         final AsyncProcedure<Resource> procedure) {
3203
3204                 assert (relation != null);
3205                 assert (procedure != null);
3206
3207                 processor.forInverse(this, relation, new AsyncProcedure<Resource>() {
3208
3209                         @Override
3210                         public void execute(AsyncReadGraph graph, Resource result) {
3211                                 if (result != null)
3212                                         procedure.execute(graph, result);
3213                                 else {
3214                                         procedure.exception(graph, new NoInverseException(relation
3215                                                         .toString()));
3216                                 }
3217                         }
3218
3219                         @Override
3220                         public void exception(AsyncReadGraph graph, Throwable throwable) {
3221                                 procedure.exception(graph, throwable);
3222                         }
3223
3224                         @Override
3225                         public String toString() {
3226                                 return "forInverse -> " + procedure;
3227                         }
3228
3229                 });
3230
3231         }
3232
3233         @Override
3234         public void forInverse(Resource relation, SyncProcedure<Resource> procedure) {
3235                 forInverse(relation, new SyncToAsyncProcedure<Resource>(procedure));
3236         }
3237
3238         @Override
3239         public void forInverse(Resource relation, Procedure<Resource> procedure) {
3240                 forInverse(relation, new NoneToAsyncProcedure<Resource>(procedure));
3241         }
3242
3243         @Override
3244         public void forSingleObject(Resource subject, Resource relation,
3245                         AsyncListener<Resource> listener) {
3246                 asyncRequest(new SingleObject(subject, relation), listener);
3247         }
3248
3249         @Override
3250         public void forSingleObject(Resource subject, Resource relation,
3251                         SyncListener<Resource> listener) {
3252                 asyncRequest(new SingleObject(subject, relation), listener);
3253         }
3254
3255         @Override
3256         public void forSingleObject(Resource subject, Resource relation,
3257                         Listener<Resource> listener) {
3258                 asyncRequest(new SingleObject(subject, relation), listener);
3259         }
3260
3261         @Override
3262         final public void forSingleObject(final Resource subject,
3263                         final Resource relation, final AsyncProcedure<Resource> procedure) {
3264
3265                 assert (subject != null);
3266                 assert (relation != null);
3267                 assert (procedure != null);
3268
3269                 processor.forEachObject(this, subject, relation,
3270                                 new SingleOrErrorProcedure<Resource>(procedure));
3271
3272         }
3273
3274         @Override
3275         public void forSingleObject(Resource subject, Resource relation,
3276                         SyncProcedure<Resource> procedure) {
3277                 forSingleObject(subject, relation, new SyncToAsyncProcedure<Resource>(
3278                                 procedure));
3279         }
3280
3281         @Override
3282         public void forSingleObject(Resource subject, Resource relation,
3283                         Procedure<Resource> procedure) {
3284                 forSingleObject(subject, relation, new NoneToAsyncProcedure<Resource>(
3285                                 procedure));
3286         }
3287
3288         @Override
3289         public void forSingleStatement(Resource subject, Resource relation,
3290                         AsyncListener<Statement> listener) {
3291                 asyncRequest(new SingleStatement(subject, relation), listener);
3292         }
3293
3294         @Override
3295         public void forSingleStatement(Resource subject, Resource relation,
3296                         SyncListener<Statement> listener) {
3297                 asyncRequest(new SingleStatement(subject, relation), listener);
3298         }
3299
3300         @Override
3301         public void forSingleStatement(Resource subject, Resource relation,
3302                         Listener<Statement> listener) {
3303                 asyncRequest(new SingleStatement(subject, relation), listener);
3304         }
3305
3306         @Override
3307         final public void forSingleStatement(final Resource subject,
3308                         final Resource relation, final AsyncProcedure<Statement> procedure) {
3309
3310                 assert (subject != null);
3311                 assert (relation != null);
3312                 assert (procedure != null);
3313
3314                 processor.forEachStatement(this, subject, relation,
3315                                 new SingleOrErrorProcedure<Statement>(procedure));
3316
3317         }
3318
3319         @Override
3320         public void forSingleStatement(Resource subject, Resource relation,
3321                         SyncProcedure<Statement> procedure) {
3322                 forSingleStatement(subject, relation,
3323                                 new SyncToAsyncProcedure<Statement>(procedure));
3324         }
3325
3326         @Override
3327         public void forSingleStatement(Resource subject, Resource relation,
3328                         Procedure<Statement> procedure) {
3329                 forSingleStatement(subject, relation,
3330                                 new NoneToAsyncProcedure<Statement>(procedure));
3331         }
3332
3333         @Override
3334         public void forSingleType(Resource subject,
3335                         AsyncListener<Resource> listener) {
3336                 asyncRequest(new SingleTypeAny(subject), listener);
3337         }
3338
3339         @Override
3340         public void forSingleType(Resource subject,
3341                         SyncListener<Resource> listener) {
3342                 asyncRequest(new SingleTypeAny(subject), listener);
3343         }
3344
3345         @Override
3346         public void forSingleType(Resource subject,
3347                         Listener<Resource> listener) {
3348                 asyncRequest(new SingleTypeAny(subject), listener);
3349         }
3350
3351         @Override
3352         final public void forSingleType(final Resource subject, final AsyncProcedure<Resource> procedure) {
3353
3354                 assert (subject != null);
3355                 assert (procedure != null);
3356
3357                 final DeepSingleOrErrorProcedure<Resource> checkedProcedure = new DeepSingleOrErrorProcedure<Resource>(procedure);
3358
3359                 processor.forEachPrincipalType(this, subject, new AsyncMultiProcedureAdapter<Resource>() {
3360
3361                         @Override
3362                         public void execute(AsyncReadGraph graph, final Resource principalType) {
3363                                 checkedProcedure.offer(graph, principalType);
3364                         }
3365
3366                         @Override
3367                         public void finished(AsyncReadGraph graph) {
3368                                 checkedProcedure.dec(graph);
3369                         }
3370
3371                         @Override
3372                         public void exception(AsyncReadGraph graph, Throwable t) {
3373                                 checkedProcedure.exception(graph, t);
3374                         }
3375
3376                         @Override
3377                         public String toString() {
3378                                 return "forSingleType -> " + procedure;
3379                         }
3380
3381                 });
3382
3383         }
3384
3385         @Override
3386         public void forSingleType(Resource subject, SyncProcedure<Resource> procedure) {
3387                 forSingleType(subject, new SyncToAsyncProcedure<Resource>(
3388                                 procedure));
3389         }
3390
3391         @Override
3392         public void forSingleType(Resource subject, Procedure<Resource> procedure) {
3393                 forSingleType(subject, new NoneToAsyncProcedure<Resource>(
3394                                 procedure));
3395         }
3396
3397         @Override
3398         public void forSingleType(Resource subject, Resource relation,
3399                         AsyncListener<Resource> listener) {
3400                 asyncRequest(new SingleType(subject, relation), listener);
3401         }
3402
3403         @Override
3404         public void forSingleType(Resource subject, Resource relation,
3405                         SyncListener<Resource> listener) {
3406                 asyncRequest(new SingleType(subject, relation), listener);
3407         }
3408
3409         @Override
3410         public void forSingleType(Resource subject, Resource relation,
3411                         Listener<Resource> listener) {
3412                 asyncRequest(new SingleType(subject, relation), listener);
3413         }
3414
3415         @Override
3416         final public void forSingleType(final Resource subject,
3417                         final Resource baseType, final AsyncProcedure<Resource> procedure) {
3418
3419                 assert (subject != null);
3420                 assert (procedure != null);
3421
3422                 final DeepSingleOrErrorProcedure<Resource> checkedProcedure = new DeepSingleOrErrorProcedure<Resource>(procedure);
3423
3424                 processor.forEachPrincipalType(this, subject,
3425                                 new AsyncMultiProcedureAdapter<Resource>() {
3426
3427                                         @Override
3428                                         public void execute(AsyncReadGraph graph,
3429                                                         final Resource principalType) {
3430
3431                                                 checkedProcedure.inc();
3432
3433                                                 if(baseType == null) {
3434
3435                                                         checkedProcedure.offer(graph, principalType);
3436                                                         checkedProcedure.dec(graph);
3437
3438                                                 } else if(principalType.equals(baseType)) {
3439
3440                                                         checkedProcedure.offer(graph, principalType);
3441                                                         checkedProcedure.dec(graph);
3442
3443                                                 } else {
3444
3445                                                         processor.forSupertypes((ReadGraphImpl)graph, principalType,
3446                                                                         new AsyncProcedure<Set<Resource>>() {
3447
3448                                                                                 @Override
3449                                                                                 public void execute(
3450                                                                                                 AsyncReadGraph graph,
3451                                                                                                 Set<Resource> result) {
3452
3453                                                                                         if (result.contains(baseType))
3454                                                                                                 checkedProcedure.offer(graph,
3455                                                                                                                 principalType);
3456                                                                                         checkedProcedure.dec(graph);
3457
3458                                                                                 }
3459
3460                                                                                 @Override
3461                                                                                 public void exception(
3462                                                                                                 AsyncReadGraph graph,
3463                                                                                                 Throwable t) {
3464                                                                                         checkedProcedure
3465                                                                                                         .exception(graph, t);
3466                                                                                 }
3467
3468                                                                         });
3469
3470                                                 }
3471
3472                                         }
3473
3474                                         @Override
3475                                         public void finished(AsyncReadGraph graph) {
3476                                                 checkedProcedure.dec(graph);
3477                                         }
3478
3479                                         @Override
3480                                         public void exception(AsyncReadGraph graph, Throwable t) {
3481                                                 checkedProcedure.exception(graph, t);
3482                                         }
3483
3484                                         @Override
3485                                         public String toString() {
3486                                                 return "forSingleType -> " + procedure;
3487                                         }
3488
3489                                 });
3490
3491         }
3492
3493         @Override
3494         public void forSingleType(Resource subject, Resource relation,
3495                         SyncProcedure<Resource> procedure) {
3496                 forSingleType(subject, relation, new SyncToAsyncProcedure<Resource>(
3497                                 procedure));
3498         }
3499
3500         @Override
3501         public void forSingleType(Resource subject, Resource relation,
3502                         Procedure<Resource> procedure) {
3503                 forSingleType(subject, relation, new NoneToAsyncProcedure<Resource>(
3504                                 procedure));
3505         }
3506
3507         @Override
3508         public <T> void forValue(Resource subject, Binding binding,
3509                         AsyncListener<T> listener) {
3510                 asyncRequest(new Value<T>(subject, binding), listener);
3511         }
3512
3513         @Override
3514         public <T> void forValue(Resource subject, Binding binding,
3515                         SyncListener<T> listener) {
3516                 asyncRequest(new Value<T>(subject, binding), listener);
3517         }
3518
3519         @Override
3520         public <T> void forValue(Resource subject, Binding binding,
3521                         Listener<T> listener) {
3522                 asyncRequest(new Value<T>(subject, binding), listener);
3523         }
3524
3525         @Override
3526         public <T> void forValue(final Resource resource, final Binding binding,
3527                         final AsyncProcedure<T> procedure) {
3528
3529                 assert (resource != null);
3530                 assert (binding != null);
3531                 assert (procedure != null);
3532                 
3533                 processor.forValue(this, resource, new AsyncProcedure<byte[]>() {
3534
3535                         @Override
3536                         public void execute(AsyncReadGraph graph, byte[] result) {
3537                                 
3538                                 try {
3539
3540                                         if (result == null) {
3541                                                 procedure.exception(graph,
3542                                                                 new DoesNotContainValueException(
3543                                                                                 "No value for resource " + resource));
3544                                                 return;
3545                                         }
3546
3547                                         Serializer serializer = binding.serializer();
3548 //                                      Serializer serializer = Bindings.getSerializer( binding );
3549                                         Object obj = serializer.deserialize(result);
3550 //                                      if (!binding.isInstance(obj))
3551 //                                              procedure.exception(graph, new ClassCastException(
3552 //                                                              "Cannot get value " + obj + " with binding "
3553 //                                                                              + binding));
3554 //                                      else
3555                                                 procedure.execute(graph, (T) obj);
3556
3557                                 } catch (Throwable t) {
3558                                     procedure.exception(graph, new ServiceException("Could not forValue for subject " + debugString(resource) + " and binding " + String.valueOf(binding) + " with bytes " + safeArrayToString(result), t));
3559                                 }
3560                         }
3561
3562                         @Override
3563                         public void exception(AsyncReadGraph graph, Throwable t) {
3564                                 try {
3565                                         procedure.exception(graph, t);
3566                                 } catch (Throwable t2) {
3567                                 Logger.defaultLogError(t2);
3568                                 }
3569                         }
3570
3571                         @Override
3572                         public String toString() {
3573                                 return "forValue -> " + procedure;
3574                         }
3575
3576                 });
3577
3578         }
3579         
3580     private static String safeArrayToString(byte[] a) {
3581         if (a == null)
3582             return "null";
3583         int iMax = a.length - 1;
3584         if (iMax == -1)
3585             return "[]";
3586
3587         StringBuilder b = new StringBuilder();
3588         b.append('[');
3589         for (int i = 0; i < 100; i++) { // limit to first 100 items 
3590             b.append(a[i]);
3591             if (i == iMax)
3592                 return b.append(']').toString();
3593             b.append(", ");
3594         }
3595         return b.append(", ... (" + a.length + ")]").toString();
3596     }
3597
3598         @Override
3599         public <T> void forValue(Resource subject, Binding binding,
3600                         SyncProcedure<T> procedure) {
3601                 forValue(subject, binding, new SyncToAsyncProcedure<T>(procedure));
3602         }
3603
3604         @Override
3605         public <T> void forValue(Resource subject, Binding binding,
3606                         Procedure<T> procedure) {
3607                 forValue(subject, binding, new NoneToAsyncProcedure<T>(procedure));
3608         }
3609
3610         @Override
3611         public <T> void forValue(Resource subject, AsyncListener<T> listener) {
3612                 asyncRequest(new ValueImplied<T>(subject), listener);
3613         }
3614
3615         @Override
3616         public <T> void forValue(Resource subject, SyncListener<T> listener) {
3617                 asyncRequest(new ValueImplied<T>(subject), listener);
3618         }
3619
3620         @Override
3621         public <T> void forValue(Resource subject, Listener<T> listener) {
3622                 asyncRequest(new ValueImplied<T>(subject), listener);
3623         }
3624
3625         @Override
3626         final public <T> void forValue(final Resource subject, final AsyncProcedure<T> procedure) {
3627
3628                 assert (subject != null);
3629                 assert (procedure != null);
3630                 
3631                 forRelatedValue(subject, processor.getL0(this).HasDataType, DATA_TYPE_BINDING_INTERNAL, new AsyncProcedure<Datatype>() {
3632
3633                         @Override
3634                         public void execute(AsyncReadGraph graph, Datatype type) {
3635                                 // TODO: consider trying Bindings.getBeanBinding(type);
3636                                 Binding binding = Bindings.getBinding(type);
3637                                 graph.forValue(subject, binding, procedure);
3638                         }
3639
3640                         @Override
3641                         public void exception(AsyncReadGraph graph, Throwable throwable) {
3642                                 procedure.exception(graph, new DoesNotContainValueException("Invalid data type", throwable));
3643                         }
3644                         
3645                 });
3646
3647         }
3648
3649         @Override
3650         public <T> void forValue(Resource subject, SyncProcedure<T> procedure) {
3651                 forValue(subject, new SyncToAsyncProcedure<T>(procedure));
3652         }
3653
3654         @Override
3655         public <T> void forValue(Resource subject, Procedure<T> procedure) {
3656                 forValue(subject, new NoneToAsyncProcedure<T>(procedure));
3657         }
3658
3659         @Override
3660         public <T> void forRelatedValue(Resource subject, Resource relation,
3661                         AsyncListener<T> listener) {
3662                 asyncRequest(new RelatedValueImplied<T>(subject, relation), listener);
3663         }
3664
3665         @Override
3666         public <T> void forRelatedValue(Resource subject, Resource relation,
3667                         SyncListener<T> listener) {
3668                 asyncRequest(new RelatedValueImplied<T>(subject, relation), listener);
3669         }
3670
3671         @Override
3672         public <T> void forRelatedValue(Resource subject, Resource relation,
3673                         Listener<T> listener) {
3674                 asyncRequest(new RelatedValueImplied<T>(subject, relation), listener);
3675         }
3676
3677         @Override
3678         final public <T> void forRelatedValue(final Resource subject,
3679                         final Resource relation, final AsyncProcedure<T> procedure) {
3680
3681                 assert (subject != null);
3682                 assert (relation != null);
3683                 assert (procedure != null);
3684
3685                 final DeepSingleOrErrorProcedure<T> checkedProcedure = new DeepSingleOrErrorProcedure<T>(procedure);
3686
3687                 processor.forEachObject(this, subject, relation,
3688                                 new AsyncMultiProcedureAdapter<Resource>() {
3689
3690                                         @Override
3691                                         public void execute(AsyncReadGraph graph,
3692                                                         final Resource object) {
3693
3694                                                 checkedProcedure.inc();
3695
3696                                                 graph.forValue(object, new AsyncProcedure<Object>() {
3697
3698                                                         @Override
3699                                                         public void execute(AsyncReadGraph graph,
3700                                                                         Object result) {
3701                                                                 checkedProcedure.offer(graph, (T) result);
3702                                                                 checkedProcedure.dec(graph);
3703                                                         }
3704
3705                                                         @Override
3706                                                         public void exception(AsyncReadGraph graph,
3707                                                                         Throwable t) {
3708                                                                 checkedProcedure.exception(graph, t);
3709                                                         }
3710
3711                                                         @Override
3712                                                         public String toString() {
3713                                                                 return "forRelatedValue -> " + procedure;
3714                                                         }
3715
3716                                                 });
3717
3718                                         }
3719
3720                                         @Override
3721                                         public void finished(AsyncReadGraph graph) {
3722                                                 checkedProcedure.dec(graph);
3723                                         }
3724
3725                                         @Override
3726                                         public void exception(AsyncReadGraph graph, Throwable t) {
3727                                                 checkedProcedure.exception(graph, t);
3728                                         }
3729
3730                                 });
3731
3732         }
3733
3734         @Override
3735         public <T> void forRelatedValue(Resource subject, Resource relation,
3736                         SyncProcedure<T> procedure) {
3737                 forRelatedValue(subject, relation, new SyncToAsyncProcedure<T>(
3738                                 procedure));
3739         }
3740
3741         @Override
3742         public <T> void forRelatedValue(Resource subject, Resource relation,
3743                         Procedure<T> procedure) {
3744                 forRelatedValue(subject, relation, new NoneToAsyncProcedure<T>(
3745                                 procedure));
3746         }
3747
3748         @Override
3749         public <T> void forRelatedValue(Resource subject, Resource relation,
3750                         Binding binding, AsyncListener<T> listener) {
3751                 asyncRequest(new RelatedValue<T>(subject, relation, binding), listener);
3752         }
3753
3754         @Override
3755         public <T> void forRelatedValue(Resource subject, Resource relation,
3756                         Binding binding, SyncListener<T> listener) {
3757                 asyncRequest(new RelatedValue<T>(subject, relation, binding), listener);
3758         }
3759
3760         @Override
3761         public <T> void forRelatedValue(Resource subject, Resource relation,
3762                         Binding binding, Listener<T> listener) {
3763                 asyncRequest(new RelatedValue<T>(subject, relation, binding), listener);
3764         }
3765
3766         @Override
3767         final public <T> void forRelatedValue(final Resource subject,
3768                         final Resource relation, final Binding binding,
3769                         final AsyncProcedure<T> procedure) {
3770
3771                 assert (subject != null);
3772                 assert (relation != null);
3773                 assert (binding != null);
3774                 assert (procedure != null);
3775
3776                 final DeepSingleOrErrorProcedure<T> checkedProcedure = new DeepSingleOrErrorProcedure<T>(procedure);
3777                 
3778                 processor.forEachObject(this, subject, relation,
3779                                 new AsyncMultiProcedureAdapter<Resource>() {
3780
3781                                         @Override
3782                                         public void execute(AsyncReadGraph graph,
3783                                                         final Resource object) {
3784
3785                                                 checkedProcedure.inc();
3786
3787                                                 graph.forValue(object, binding, new AsyncProcedure<Object>() {
3788
3789                                                                         @Override
3790                                                                         public void execute(AsyncReadGraph graph,
3791                                                                                         Object result) {
3792                                                                                 
3793                                                                                 checkedProcedure.offer(graph,
3794                                                                                                 (T) result);
3795                                                                                 checkedProcedure.dec(graph);
3796                                                                         }
3797
3798                                                                         @Override
3799                                                                         public void exception(AsyncReadGraph graph,
3800                                                                                         Throwable t) {
3801                                                                                 checkedProcedure.exception(graph, t);
3802                                                                         }
3803
3804                                                                         @Override
3805                                                                         public String toString() {
3806                                                                                 return "forRelatedValue -> "
3807                                                                                                 + procedure;
3808                                                                         }
3809
3810                                                                 });
3811
3812                                         }
3813
3814                                         @Override
3815                                         public void finished(AsyncReadGraph graph) {
3816                                                 checkedProcedure.dec(graph);
3817                                         }
3818
3819                                         @Override
3820                                         public void exception(AsyncReadGraph graph, Throwable t) {
3821                                                 checkedProcedure.exception(graph, t);
3822                                         }
3823
3824                                 });
3825
3826         }
3827
3828         @Override
3829         public <T> void forRelatedValue(Resource subject, Resource relation,
3830                         Binding binding, SyncProcedure<T> procedure) {
3831                 forRelatedValue(subject, relation, binding,
3832                                 new SyncToAsyncProcedure<T>(procedure));
3833         }
3834
3835         @Override
3836         public <T> void forRelatedValue(Resource subject, Resource relation,
3837                         Binding binding, Procedure<T> procedure) {
3838                 forRelatedValue(subject, relation, binding,
3839                                 new NoneToAsyncProcedure<T>(procedure));
3840         }
3841
3842         @Override
3843         public <T> void forAdapted(Resource resource, Class<T> clazz,
3844                         AsyncListener<T> listener) {
3845                 asyncRequest(new Adapter<T>(resource, clazz), listener);
3846         }
3847
3848         @Override
3849         public <T> void forAdapted(Resource resource, Class<T> clazz,
3850                         SyncListener<T> listener) {
3851                 asyncRequest(new Adapter<T>(resource, clazz), listener);
3852         }
3853
3854         @Override
3855         public <T> void forAdapted(Resource resource, Class<T> clazz,
3856                         Listener<T> listener) {
3857                 asyncRequest(new Adapter<T>(resource, clazz), listener);
3858         }
3859
3860         @Override
3861         final public <T> void forAdapted(final Resource resource,
3862                         final Class<T> clazz, final AsyncProcedure<T> procedure) {
3863
3864                 assert (resource != null);
3865                 assert (clazz != null);
3866                 assert (procedure != null);
3867
3868                 final AdaptionService service = getSession().peekService(AdaptionService.class);
3869                 if (service == null)
3870                         procedure.exception(this, new ServiceException("No AdaptionService available")); 
3871                 else
3872                         service.adapt(this, resource, resource, Resource.class, clazz, false, procedure); 
3873
3874         }
3875
3876         @Override
3877         public <T> void forAdapted(Resource resource, Class<T> clazz,
3878                         SyncProcedure<T> procedure) {
3879                 forAdapted(resource, clazz, new SyncToAsyncProcedure<T>(procedure));
3880         }
3881
3882         @Override
3883         public <T> void forAdapted(Resource resource, Class<T> clazz,
3884                         Procedure<T> procedure) {
3885                 forAdapted(resource, clazz, new NoneToAsyncProcedure<T>(procedure));
3886         }
3887
3888         @Override
3889         public <T> void forUniqueAdapted(Resource resource, Class<T> clazz,
3890                         AsyncListener<T> listener) {
3891                 asyncRequest(new UniqueAdapter<T>(resource, clazz), listener);
3892         }
3893
3894         @Override
3895         public <T> void forUniqueAdapted(Resource resource, Class<T> clazz,
3896                         SyncListener<T> listener) {
3897                 asyncRequest(new UniqueAdapter<T>(resource, clazz), listener);
3898         }
3899
3900         @Override
3901         public <T> void forUniqueAdapted(Resource resource, Class<T> clazz,
3902                         Listener<T> listener) {
3903                 asyncRequest(new UniqueAdapter<T>(resource, clazz), listener);
3904         }
3905
3906         @Override
3907         final public <T> void forUniqueAdapted(final Resource resource,
3908                         final Class<T> clazz, final AsyncProcedure<T> procedure) {
3909
3910                 assert (resource != null);
3911                 assert (clazz != null);
3912                 assert (procedure != null);
3913
3914                 final AdaptionService service = getSession().peekService(AdaptionService.class);
3915                 if (service == null)
3916                         procedure.exception(this, new ServiceException("No AdaptionService available")); 
3917                 else
3918                         service.adaptNew(this, resource, clazz, false, procedure);
3919
3920         }
3921
3922         @Override
3923         public <T> void forUniqueAdapted(Resource resource, Class<T> clazz,
3924                         SyncProcedure<T> procedure) {
3925                 forUniqueAdapted(resource, clazz,
3926                                 new SyncToAsyncProcedure<T>(procedure));
3927         }
3928
3929         @Override
3930         public <T> void forUniqueAdapted(Resource resource, Class<T> clazz,
3931                         Procedure<T> procedure) {
3932                 forUniqueAdapted(resource, clazz,
3933                                 new NoneToAsyncProcedure<T>(procedure));
3934         }
3935
3936         @Override
3937         public void forPossibleInverse(Resource subject,
3938                         AsyncListener<Resource> listener) {
3939                 asyncRequest(new PossibleInverse(subject), listener);
3940         }
3941
3942         @Override
3943         public void forPossibleInverse(Resource subject,
3944                         SyncListener<Resource> listener) {
3945                 asyncRequest(new PossibleInverse(subject), listener);
3946         }
3947
3948         @Override
3949         public void forPossibleInverse(Resource subject, Listener<Resource> listener) {
3950                 asyncRequest(new PossibleInverse(subject), listener);
3951         }
3952
3953         @Override
3954         final public void forPossibleInverse(final Resource relation,
3955                         final AsyncProcedure<Resource> procedure) {
3956
3957                 assert (relation != null);
3958                 assert (procedure != null);
3959
3960                 processor.forInverse(this, relation, new ExceptionToNullProcedure<Resource>(procedure));
3961
3962         }
3963
3964         @Override
3965         public void forPossibleInverse(Resource subject,
3966                         SyncProcedure<Resource> procedure) {
3967                 forPossibleInverse(subject, new SyncToAsyncProcedure<Resource>(
3968                                 procedure));
3969         }
3970
3971         @Override
3972         public void forPossibleInverse(Resource subject,
3973                         Procedure<Resource> procedure) {
3974                 forPossibleInverse(subject, new NoneToAsyncProcedure<Resource>(
3975                                 procedure));
3976         }
3977
3978         @Override
3979         public void forPossibleObject(Resource subject, Resource relation,
3980                         AsyncListener<Resource> listener) {
3981                 asyncRequest(new PossibleObject(subject, relation), listener);
3982         }
3983
3984         @Override
3985         public void forPossibleObject(Resource subject, Resource relation,
3986                         SyncListener<Resource> listener) {
3987                 asyncRequest(new PossibleObject(subject, relation), listener);
3988         }
3989
3990         @Override
3991         public void forPossibleObject(Resource subject, Resource relation,
3992                         Listener<Resource> listener) {
3993                 asyncRequest(new PossibleObject(subject, relation), listener);
3994         }
3995
3996         @Override
3997         final public void forPossibleObject(final Resource subject,
3998                         final Resource relation, final AsyncProcedure<Resource> procedure) {
3999
4000                 assert (subject != null);
4001                 assert (relation != null);
4002                 assert (procedure != null);
4003
4004                 processor.forEachObject(this, subject, relation,
4005                                 new SingleOrNullProcedure<Resource>(procedure));
4006
4007         }
4008
4009         @Override
4010         public void forPossibleObject(Resource subject, Resource relation,
4011                         SyncProcedure<Resource> procedure) {
4012                 forPossibleObject(subject, relation,
4013                                 new SyncToAsyncProcedure<Resource>(procedure));
4014         }
4015
4016         @Override
4017         public void forPossibleObject(Resource subject, Resource relation,
4018                         Procedure<Resource> procedure) {
4019                 forPossibleObject(subject, relation,
4020                                 new NoneToAsyncProcedure<Resource>(procedure));
4021         }
4022
4023         @Override
4024         public void forPossibleStatement(Resource subject, Resource relation,
4025                         AsyncListener<Statement> listener) {
4026                 asyncRequest(new PossibleStatement(subject, relation), listener);
4027         }
4028
4029         @Override
4030         public void forPossibleStatement(Resource subject, Resource relation,
4031                         SyncListener<Statement> listener) {
4032                 asyncRequest(new PossibleStatement(subject, relation), listener);
4033         }
4034
4035         @Override
4036         public void forPossibleStatement(Resource subject, Resource relation,
4037                         Listener<Statement> listener) {
4038                 asyncRequest(new PossibleStatement(subject, relation), listener);
4039         }
4040
4041         @Override
4042         final public void forPossibleStatement(final Resource subject,
4043                         final Resource relation, final AsyncProcedure<Statement> procedure) {
4044
4045                 assert (subject != null);
4046                 assert (relation != null);
4047                 assert (procedure != null);
4048
4049                 processor.forEachStatement(this, subject, relation,
4050                                 new SingleFunctionalOrNullProcedure<Statement>(
4051                                                 "forPossibleStatement", procedure));
4052
4053         }
4054
4055         @Override
4056         public void forPossibleStatement(Resource subject, Resource relation,
4057                         SyncProcedure<Statement> procedure) {
4058                 forPossibleStatement(subject, relation,
4059                                 new SyncToAsyncProcedure<Statement>(procedure));
4060         }
4061
4062         @Override
4063         public void forPossibleStatement(Resource subject, Resource relation,
4064                         Procedure<Statement> procedure) {
4065                 forPossibleStatement(subject, relation,
4066                                 new NoneToAsyncProcedure<Statement>(procedure));
4067         }
4068
4069         @Override
4070         public void forPossibleType(Resource subject, Resource relation,
4071                         AsyncListener<Resource> listener) {
4072                 asyncRequest(new PossibleType(subject, relation), listener);
4073         }
4074
4075         @Override
4076         public void forPossibleType(Resource subject, Resource relation,
4077                         SyncListener<Resource> listener) {
4078                 asyncRequest(new PossibleType(subject, relation), listener);
4079         }
4080
4081         @Override
4082         public void forPossibleType(Resource subject, Resource relation,
4083                         Listener<Resource> listener) {
4084                 asyncRequest(new PossibleType(subject, relation), listener);
4085         }
4086
4087         @Override
4088         final public void forPossibleType(final Resource subject,
4089                         final Resource baseType, final AsyncProcedure<Resource> procedure) {
4090
4091                 assert (subject != null);
4092                 assert (procedure != null);
4093
4094                 final NullSingleOrNullProcedure<Resource> checkedProcedure = new NullSingleOrNullProcedure<Resource>(procedure);
4095
4096                 processor.forEachPrincipalType(this, subject, new AsyncMultiProcedureAdapter<Resource>() {
4097
4098                                         @Override
4099                                         public void execute(AsyncReadGraph graph,
4100                                                         final Resource principalType) {
4101
4102                                                 if (baseType == null) {
4103
4104                                                         checkedProcedure.offer(graph, principalType);
4105
4106                                                 } else if (principalType.equals(baseType)) {
4107
4108                                                         checkedProcedure.offer(graph, principalType);
4109
4110                                                 } else {
4111
4112                                                         checkedProcedure.inc();
4113
4114                                                         processor.forSupertypes((ReadGraphImpl)graph, principalType,
4115                                                                         new AsyncProcedure<Set<Resource>>() {
4116
4117                                                                                 @Override
4118                                                                                 public void execute(
4119                                                                                                 AsyncReadGraph graph,
4120                                                                                                 Set<Resource> result) {
4121
4122                                                                                         if (result.contains(baseType)) {
4123                                                                                                 checkedProcedure.offer(graph,
4124                                                                                                                 principalType);
4125                                                                                         }
4126
4127                                                                                         checkedProcedure.dec(graph);
4128
4129                                                                                 }
4130
4131                                                                                 @Override
4132                                                                                 public void exception(
4133                                                                                                 AsyncReadGraph graph,
4134                                                                                                 Throwable t) {
4135                                                                                         checkedProcedure.exception(graph, t);
4136                                                                                         checkedProcedure.dec(graph);
4137                                                                                 }
4138
4139                                                                                 @Override
4140                                                                                 public String toString() {
4141                                                                                         return "forPossibleType -> "
4142                                                                                                         + procedure;
4143                                                                                 }
4144
4145                                                                         });
4146
4147                                                 }
4148
4149                                         }
4150
4151                                         @Override
4152                                         public void finished(AsyncReadGraph graph) {
4153                                                 checkedProcedure.dec(graph);
4154                                         }
4155
4156                                         @Override
4157                                         public void exception(AsyncReadGraph graph, Throwable t) {
4158                                                 checkedProcedure.exception(graph, t);
4159                                                 checkedProcedure.dec(graph);
4160                                         }
4161
4162                                 });
4163
4164         }
4165
4166         @Override
4167         public void forPossibleType(Resource subject, Resource relation,
4168                         SyncProcedure<Resource> procedure) {
4169                 forPossibleType(subject, relation, new SyncToAsyncProcedure<Resource>(
4170                                 procedure));
4171         }
4172
4173         @Override
4174         public void forPossibleType(Resource subject, Resource relation,
4175                         Procedure<Resource> procedure) {
4176                 forPossibleType(subject, relation, new NoneToAsyncProcedure<Resource>(
4177                                 procedure));
4178         }
4179
4180         @Override
4181         public <T> void forPossibleValue(Resource subject, AsyncListener<T> listener) {
4182                 asyncRequest(new PossibleValueImplied<T>(subject), listener);
4183         }
4184
4185         @Override
4186         public <T> void forPossibleValue(Resource subject, SyncListener<T> listener) {
4187                 asyncRequest(new PossibleValueImplied<T>(subject), listener);
4188         }
4189
4190         @Override
4191         public <T> void forPossibleValue(Resource subject, Listener<T> listener) {
4192                 asyncRequest(new PossibleValueImplied<T>(subject), listener);
4193         }
4194
4195         @Override
4196         final public <T> void forPossibleValue(final Resource subject,
4197                         final AsyncProcedure<T> procedure) {
4198
4199                 assert (subject != null);
4200                 assert (procedure != null);
4201                 
4202                 forPossibleRelatedValue(subject, processor.getL0(this).HasDataType, DATA_TYPE_BINDING_INTERNAL, new AsyncProcedure<Datatype>() {
4203
4204                         @Override
4205                         public void execute(AsyncReadGraph graph, final Datatype type) {
4206                                 if (type == null) {
4207                                         procedure.execute(graph, null);
4208                                 } else {
4209                                         try {
4210                                                 // TODO: consider trying Bindings.getBeanBinding(type);
4211                                                 Binding binding = Bindings.getBinding(type);
4212                                                 graph.forPossibleValue(subject, binding, procedure);
4213                                         } catch (RuntimeBindingConstructionException e) {
4214                                                 procedure.exception(graph, e);
4215                                         }
4216                                 }
4217                         }
4218
4219                         @Override
4220                         public void exception(AsyncReadGraph graph, Throwable t) {
4221                                 procedure.exception(graph, t);
4222                         }
4223
4224                         @Override
4225                         public String toString() {
4226                                 return "forPossibleValue -> " + procedure;
4227                         }
4228
4229                 });
4230
4231         }
4232
4233         @Override
4234         public <T> void forPossibleValue(Resource subject,
4235                         SyncProcedure<T> procedure) {
4236                 forPossibleValue(subject, new SyncToAsyncProcedure<T>(procedure));
4237         }
4238
4239         @Override
4240         public <T> void forPossibleValue(Resource subject, Procedure<T> procedure) {
4241                 forPossibleValue(subject, new NoneToAsyncProcedure<T>(procedure));
4242         }
4243
4244         @Override
4245         public <T> void forPossibleValue(Resource subject, Binding binding,
4246                         AsyncListener<T> listener) {
4247                 asyncRequest(new PossibleValue<T>(subject, binding), listener);
4248         }
4249
4250         @Override
4251         public <T> void forPossibleValue(Resource subject, Binding binding,
4252                         SyncListener<T> listener) {
4253                 asyncRequest(new PossibleValue<T>(subject, binding), listener);
4254         }
4255
4256         @Override
4257         public <T> void forPossibleValue(Resource subject, Binding binding,
4258                         Listener<T> listener) {
4259                 asyncRequest(new PossibleValue<T>(subject, binding), listener);
4260         }
4261
4262         @Override
4263         final public <T> void forPossibleValue(final Resource resource,
4264                         final Binding binding, final AsyncProcedure<T> procedure) {
4265
4266                 assert (resource != null);
4267                 assert (binding != null);
4268                 assert (procedure != null);
4269
4270                 processor.forValue(this, resource, new AsyncProcedure<byte[]>() {
4271
4272                         @Override
4273                         public void execute(AsyncReadGraph graph, byte[] result) {
4274
4275                                 try {
4276
4277                                         if (result == null) {
4278                                                 procedure.execute(graph, null);
4279                                                 return;
4280                                         }
4281
4282                                         Serializer serializer = Bindings.getSerializer( binding );
4283                                         Object obj = serializer.deserialize(result);
4284                                         if (!binding.isInstance(obj))
4285                                                 procedure.exception(graph, new ClassCastException(
4286                                                                 "Cannot get value " + obj + " with binding "
4287                                                                                 + binding));
4288                                         else
4289                                                 procedure.execute(graph, (T) obj);
4290
4291                                 } catch (Throwable t) {
4292                                         procedure.exception(graph, new ServiceException("Could not forValue for subject " + debugString(resource) + " and binding " + String.valueOf(binding) + " with bytes " + safeArrayToString(result), t));
4293                                 }
4294                         }
4295
4296                         @Override
4297                         public void exception(AsyncReadGraph graph, Throwable t) {
4298                                 try {
4299                                         procedure.exception(graph, t);
4300                                 } catch (Throwable t2) {
4301                                 Logger.defaultLogError(t2);
4302                                 }
4303                         }
4304
4305                         @Override
4306                         public String toString() {
4307                                 return "forPossibleValue -> " + procedure;
4308                         }
4309
4310                 });
4311
4312         }
4313
4314         @Override
4315         public <T> void forPossibleValue(Resource subject, Binding binding,
4316                         SyncProcedure<T> procedure) {
4317                 forPossibleValue(subject, binding, new SyncToAsyncProcedure<T>(
4318                                 procedure));
4319         }
4320
4321         @Override
4322         public <T> void forPossibleValue(Resource subject, Binding binding,
4323                         Procedure<T> procedure) {
4324                 forPossibleValue(subject, binding, new NoneToAsyncProcedure<T>(
4325                                 procedure));
4326         }
4327
4328         @Override
4329         public <T> void forPossibleRelatedValue(Resource subject,
4330                         Resource relation, AsyncListener<T> listener) {
4331                 asyncRequest(new PossibleRelatedValueImplied<T>(subject, relation),
4332                                 listener);
4333         }
4334
4335         @Override
4336         public <T> void forPossibleRelatedValue(Resource subject,
4337                         Resource relation, SyncListener<T> listener) {
4338                 asyncRequest(new PossibleRelatedValueImplied<T>(subject, relation),
4339                                 listener);
4340         }
4341
4342         @Override
4343         public <T> void forPossibleRelatedValue(Resource subject,
4344                         Resource relation, Listener<T> listener) {
4345                 asyncRequest(new PossibleRelatedValueImplied<T>(subject, relation),
4346                                 listener);
4347         }
4348
4349         @Override
4350         final public <T> void forPossibleRelatedValue(final Resource subject,
4351                         final Resource relation, final AsyncProcedure<T> procedure) {
4352
4353                 assert (subject != null);
4354                 assert (relation != null);
4355                 assert (procedure != null);
4356
4357                 final DeepSingleOrNullProcedure<T> checkedProcedure = new DeepSingleOrNullProcedure<T>(procedure);
4358                 
4359                 processor.forEachObject(this, subject, relation,
4360                                 new AsyncMultiProcedureAdapter<Resource>() {
4361
4362                                         @Override
4363                                         public void execute(AsyncReadGraph graph,
4364                                                         final Resource object) {
4365
4366                                                 checkedProcedure.inc();
4367
4368                                                 graph.forValue(object, new AsyncProcedure<Object>() {
4369
4370                                                         @Override
4371                                                         public void execute(AsyncReadGraph graph,
4372                                                                         Object result) {
4373                                                                 checkedProcedure.offer(graph, (T) result);
4374                                                                 checkedProcedure.dec(graph);
4375                                                         }
4376
4377                                                         @Override
4378                                                         public void exception(AsyncReadGraph graph,
4379                                                                         Throwable t) {
4380                                                                 checkedProcedure.exception(graph, t);
4381                                                                 checkedProcedure.dec(graph);
4382                                                         }
4383
4384                                                 });
4385
4386                                         }
4387
4388                                         @Override
4389                                         public void finished(AsyncReadGraph graph) {
4390
4391                                                 checkedProcedure.dec(graph);
4392                                         }
4393
4394                                         @Override
4395                                         public void exception(AsyncReadGraph graph, Throwable t) {
4396                                                 checkedProcedure.exception(graph, t);
4397                                                 checkedProcedure.dec(graph);
4398                                         }
4399
4400                                         @Override
4401                                         public String toString() {
4402                                                 return "forPossibleRelatedValue -> " + procedure;
4403                                         }
4404                                 });
4405
4406         }
4407
4408         @Override
4409         public <T> void forPossibleRelatedValue(Resource subject,
4410                         Resource relation, SyncProcedure<T> procedure) {
4411                 forPossibleRelatedValue(subject, relation, new SyncToAsyncProcedure<T>(
4412                                 procedure));
4413         }
4414
4415         @Override
4416         public <T> void forPossibleRelatedValue(Resource subject,
4417                         Resource relation, Procedure<T> procedure) {
4418                 forPossibleRelatedValue(subject, relation, new NoneToAsyncProcedure<T>(
4419                                 procedure));
4420         }
4421
4422         @Override
4423         public <T> void forPossibleRelatedValue(Resource subject,
4424                         Resource relation, Binding binding, AsyncListener<T> listener) {
4425                 asyncRequest(new PossibleRelatedValue<T>(subject, relation, binding),
4426                                 listener);
4427         }
4428
4429         @Override
4430         public <T> void forPossibleRelatedValue(Resource subject,
4431                         Resource relation, Binding binding, SyncListener<T> listener) {
4432                 asyncRequest(new PossibleRelatedValue<T>(subject, relation, binding),
4433                                 listener);
4434         }
4435
4436         @Override
4437         public <T> void forPossibleRelatedValue(Resource subject,
4438                         Resource relation, Binding binding, Listener<T> listener) {
4439                 asyncRequest(new PossibleRelatedValue<T>(subject, relation, binding),
4440                                 listener);
4441         }
4442
4443         final public <T> void forPossibleRelatedValue(final Resource subject, final Resource relation, final Binding binding,
4444                         final AsyncProcedure<T> procedure) {
4445
4446                 assert (subject != null);
4447                 assert (relation != null);
4448                 assert (procedure != null);
4449
4450                 processor.forPossibleObject(this, subject, relation, new AsyncProcedure<Resource>() {
4451                         
4452                         @Override
4453                         public void execute(AsyncReadGraph graph, Resource object) {
4454                                 
4455                                 if(object == null) {
4456                                         procedure.execute(graph, null);
4457                                         return;
4458                                 }
4459
4460                                 processor.forPossibleValue((ReadGraphImpl)graph, object, new AsyncProcedure<byte[]>() {
4461
4462                                         @Override
4463                                         public void execute(AsyncReadGraph graph, byte[] bytes) {
4464
4465                                                 if(bytes != null) {
4466
4467                                                         try {
4468                                                         
4469                                                                 Serializer serializer = binding.serializer();
4470                                                                 Object obj = serializer.deserialize(bytes);
4471                                                                 if (!binding.isInstance(obj)) {
4472                                                                         procedure.exception(graph, new ClassCastException("Cannot get value " + obj + " with binding " + binding));
4473                                                                 } else {
4474                                                                         procedure.execute(graph, (T) obj);
4475                                                                 }
4476
4477                                                         } catch (Throwable t) {
4478                                                                 
4479                                                                 procedure.exception(graph, t);
4480                                                                 
4481                                                         }
4482                                                         
4483                                                 } else {
4484                                                         
4485                                                         procedure.execute(graph, null);
4486                                                         
4487                                                 }
4488                                                 
4489                                         }
4490
4491                                         @Override
4492                                         public void exception(AsyncReadGraph graph, Throwable t) {
4493                                                 procedure.exception(graph, t);
4494                                         }
4495
4496                                 });
4497                                 
4498                         }
4499                         
4500                         @Override
4501                         public void exception(AsyncReadGraph graph, Throwable throwable) {
4502                                 throwable.printStackTrace();
4503                                 procedure.exception(graph, throwable);
4504                         }
4505                         
4506                 });
4507
4508         }
4509
4510         @Override
4511         public <T> void forPossibleRelatedValue(Resource subject,
4512                         Resource relation, Binding binding, SyncProcedure<T> procedure) {
4513                 forPossibleRelatedValue(subject, relation, binding,
4514                                 new SyncToAsyncProcedure<T>(procedure));
4515         }
4516
4517         @Override
4518         public <T> void forPossibleRelatedValue(Resource subject,
4519                         Resource relation, Binding binding, Procedure<T> procedure) {
4520                 forPossibleRelatedValue(subject, relation, binding,
4521                                 new NoneToAsyncProcedure<T>(procedure));
4522         }
4523
4524         @Override
4525         public void forIsInstanceOf(Resource subject, Resource relation,
4526                         AsyncListener<Boolean> listener) {
4527                 asyncRequest(new IsInstanceOf(subject, relation), listener);
4528         }
4529
4530         @Override
4531         public void forIsInstanceOf(Resource subject, Resource relation,
4532                         SyncListener<Boolean> listener) {
4533                 asyncRequest(new IsInstanceOf(subject, relation), listener);
4534         }
4535
4536         @Override
4537         public void forIsInstanceOf(Resource subject, Resource relation,
4538                         Listener<Boolean> listener) {
4539                 asyncRequest(new IsInstanceOf(subject, relation), listener);
4540         }
4541
4542         @Override
4543         final public void forIsInstanceOf(final Resource resource,
4544                         final Resource type, final AsyncProcedure<Boolean> procedure) {
4545
4546                 assert (resource != null);
4547                 assert (type != null);
4548                 assert (procedure != null);
4549
4550                 forTypes(resource, new AsyncProcedure<Set<Resource>>() {
4551
4552                         @Override
4553                         public void execute(AsyncReadGraph graph, Set<Resource> result) {
4554                                 
4555                                 try {
4556                                         if (result.contains(type))
4557                                                 procedure.execute(graph, true);
4558                                         else
4559                                                 procedure.execute(graph, false);
4560                                 } catch (Throwable t) {
4561                                 Logger.defaultLogError(t);
4562                                 }
4563                         }
4564
4565                         @Override
4566                         public void exception(AsyncReadGraph graph, Throwable t) {
4567                                 try {
4568                                         procedure.exception(graph, t);
4569                                 } catch (Throwable t2) {
4570                                 Logger.defaultLogError(t2);
4571                                 }
4572                         }
4573
4574                         @Override
4575                         public String toString() {
4576                                 return "forIsInstanceOf -> " + procedure;
4577                         }
4578
4579                 });
4580
4581         }
4582
4583         @Override
4584         public void forIsInstanceOf(Resource subject, Resource relation,
4585                         SyncProcedure<Boolean> procedure) {
4586                 forIsInstanceOf(subject, relation, new SyncToAsyncProcedure<Boolean>(
4587                                 procedure));
4588         }
4589
4590         @Override
4591         public void forIsInstanceOf(Resource subject, Resource relation,
4592                         Procedure<Boolean> procedure) {
4593                 forIsInstanceOf(subject, relation, new NoneToAsyncProcedure<Boolean>(
4594                                 procedure));
4595         }
4596
4597         @Override
4598         public void forIsInheritedFrom(Resource subject, Resource relation,
4599                         AsyncListener<Boolean> listener) {
4600                 asyncRequest(new IsInheritedFrom(subject, relation), listener);
4601         }
4602
4603         @Override
4604         public void forIsInheritedFrom(Resource subject, Resource relation,
4605                         SyncListener<Boolean> listener) {
4606                 asyncRequest(new IsInheritedFrom(subject, relation), listener);
4607         }
4608
4609         @Override
4610         public void forIsInheritedFrom(Resource subject, Resource relation,
4611                         Listener<Boolean> listener) {
4612                 asyncRequest(new IsInheritedFrom(subject, relation), listener);
4613         }
4614
4615         @Override
4616         final public void forIsInheritedFrom(final Resource resource,
4617                         final Resource type, final AsyncProcedure<Boolean> procedure) {
4618
4619                 assert (resource != null);
4620                 assert (type != null);
4621                 assert (procedure != null);
4622
4623                 if (resource.equals(type)) {
4624                         try {
4625                                 procedure.execute(this, true);
4626                         } catch (Throwable t) {
4627                         Logger.defaultLogError(t);
4628                         }
4629                         return;
4630                 }
4631
4632                 forSupertypes(resource, new AsyncProcedure<Set<Resource>>() {
4633
4634                         @Override
4635                         public void execute(AsyncReadGraph graph, Set<Resource> result) {
4636                                 try {
4637                                         if (result.contains(type))
4638                                                 procedure.execute(graph, true);
4639                                         else
4640                                                 procedure.execute(graph, false);
4641                                 } catch (Throwable t) {
4642                                 Logger.defaultLogError(t);
4643                                 }
4644                         }
4645
4646                         @Override
4647                         public void exception(AsyncReadGraph graph, Throwable t) {
4648                                 try {
4649                                         procedure.exception(graph, t);
4650                                 } catch (Throwable t2) {
4651                                 Logger.defaultLogError(t2);
4652                                 }
4653                         }
4654
4655                         @Override
4656                         public String toString() {
4657                                 return "forIsInheritedFrom -> " + procedure;
4658                         }
4659
4660                 });
4661
4662         }
4663
4664         @Override
4665         public void forIsInheritedFrom(Resource subject, Resource relation,
4666                         SyncProcedure<Boolean> procedure) {
4667                 forIsInheritedFrom(subject, relation,
4668                                 new SyncToAsyncProcedure<Boolean>(procedure));
4669         }
4670
4671         @Override
4672         public void forIsInheritedFrom(Resource subject, Resource relation,
4673                         Procedure<Boolean> procedure) {
4674                 forIsInheritedFrom(subject, relation,
4675                                 new NoneToAsyncProcedure<Boolean>(procedure));
4676         }
4677
4678         @Override
4679         public void forIsSubrelationOf(Resource subject, Resource relation,
4680                         AsyncListener<Boolean> listener) {
4681                 asyncRequest(new IsSubrelationOf(subject, relation), listener);
4682         }
4683
4684         @Override
4685         public void forIsSubrelationOf(Resource subject, Resource relation,
4686                         SyncListener<Boolean> listener) {
4687                 asyncRequest(new IsSubrelationOf(subject, relation), listener);
4688         }
4689
4690         @Override
4691         public void forIsSubrelationOf(Resource subject, Resource relation,
4692                         Listener<Boolean> listener) {
4693                 asyncRequest(new IsSubrelationOf(subject, relation), listener);
4694         }
4695
4696         @Override
4697         final public void forIsSubrelationOf(final Resource resource,
4698                         final Resource relation, final AsyncProcedure<Boolean> procedure) {
4699
4700                 assert (resource != null);
4701                 assert (relation != null);
4702                 assert (procedure != null);
4703
4704                 if (resource.equals(relation)) {
4705                         procedure.execute(this, true);
4706                         return;
4707                 }
4708
4709                 forSuperrelations(resource, new AsyncProcedure<Set<Resource>>() {
4710
4711                         @Override
4712                         public void execute(AsyncReadGraph graph, Set<Resource> result) {
4713                                 try {
4714                                         if (result.contains(relation))
4715                                                 procedure.execute(graph, true);
4716                                         else
4717                                                 procedure.execute(graph, false);
4718                                 } catch (Throwable t) {
4719                                 Logger.defaultLogError(t);
4720                                 }
4721                         }
4722
4723                         @Override
4724                         public void exception(AsyncReadGraph graph, Throwable t) {
4725                                 try {
4726                                         procedure.exception(graph, t);
4727                                 } catch (Throwable t2) {
4728                                 Logger.defaultLogError(t2);
4729                                 }
4730                         }
4731
4732                         @Override
4733                         public String toString() {
4734                                 return "forIsSubrelationOf -> " + procedure;
4735                         }
4736
4737                 });
4738
4739         }
4740
4741         @Override
4742         public void forIsSubrelationOf(Resource subject, Resource relation,
4743                         SyncProcedure<Boolean> procedure) {
4744                 forIsSubrelationOf(subject, relation,
4745                                 new SyncToAsyncProcedure<Boolean>(procedure));
4746         }
4747
4748         @Override
4749         public void forIsSubrelationOf(Resource subject, Resource relation,
4750                         Procedure<Boolean> procedure) {
4751                 forIsSubrelationOf(subject, relation,
4752                                 new NoneToAsyncProcedure<Boolean>(procedure));
4753         }
4754
4755         @Override
4756         public void forHasStatement(Resource subject,
4757                         AsyncListener<Boolean> listener) {
4758                 asyncRequest(new HasStatementSubject(subject), listener);
4759         }
4760
4761         @Override
4762         public void forHasStatement(Resource subject, SyncListener<Boolean> listener) {
4763                 asyncRequest(new HasStatementSubject(subject), listener);
4764         }
4765
4766         @Override
4767         public void forHasStatement(Resource subject, Listener<Boolean> listener) {
4768                 asyncRequest(new HasStatementSubject(subject), listener);
4769         }
4770
4771         @Override
4772         final public void forHasStatement(final Resource subject,
4773                         final AsyncProcedure<Boolean> procedure) {
4774
4775                 assert (subject != null);
4776                 assert (procedure != null);
4777
4778                 processor.forHasStatement(this, subject, procedure);
4779
4780         }
4781
4782         @Override
4783         public void forHasStatement(Resource subject,
4784                         SyncProcedure<Boolean> procedure) {
4785                 forHasStatement(subject, new SyncToAsyncProcedure<Boolean>(procedure));
4786         }
4787
4788         @Override
4789         public void forHasStatement(Resource subject, Procedure<Boolean> procedure) {
4790                 forHasStatement(subject, new NoneToAsyncProcedure<Boolean>(procedure));
4791         }
4792
4793         @Override
4794         public void forHasStatement(Resource subject, Resource relation,
4795                         AsyncListener<Boolean> listener) {
4796                 asyncRequest(new HasStatement(subject, relation), listener);
4797         }
4798
4799         @Override
4800         public void forHasStatement(Resource subject, Resource relation,
4801                         SyncListener<Boolean> listener) {
4802                 asyncRequest(new HasStatement(subject, relation), listener);
4803         }
4804
4805         @Override
4806         public void forHasStatement(Resource subject, Resource relation,
4807                         Listener<Boolean> listener) {
4808                 asyncRequest(new HasStatement(subject, relation), listener);
4809         }
4810
4811         @Override
4812         final public void forHasStatement(final Resource subject,
4813                         final Resource relation, final AsyncProcedure<Boolean> procedure) {
4814
4815                 assert (subject != null);
4816                 assert (relation != null);
4817                 assert (procedure != null);
4818
4819                 processor.forHasStatement(this, subject, relation, procedure);
4820
4821         }
4822
4823         @Override
4824         public void forHasStatement(Resource subject, Resource relation,
4825                         SyncProcedure<Boolean> procedure) {
4826                 forHasStatement(subject, relation, new SyncToAsyncProcedure<Boolean>(
4827                                 procedure));
4828         }
4829
4830         @Override
4831         public void forHasStatement(Resource subject, Resource relation,
4832                         Procedure<Boolean> procedure) {
4833                 forHasStatement(subject, relation, new NoneToAsyncProcedure<Boolean>(
4834                                 procedure));
4835         }
4836
4837         @Override
4838         public void forHasStatement(Resource subject, Resource relation,
4839                         Resource object, AsyncListener<Boolean> listener) {
4840                 asyncRequest(new HasStatementSubjectObject(subject, relation, object),
4841                                 listener);
4842         }
4843
4844         @Override
4845         public void forHasStatement(Resource subject, Resource relation,
4846                         Resource object, SyncListener<Boolean> listener) {
4847                 asyncRequest(new HasStatementSubjectObject(subject, relation, object),
4848                                 listener);
4849         }
4850
4851         @Override
4852         public void forHasStatement(Resource subject, Resource relation,
4853                         Resource object, Listener<Boolean> listener) {
4854                 asyncRequest(new HasStatementSubjectObject(subject, relation, object),
4855                                 listener);
4856         }
4857
4858         @Override
4859         final public void forHasStatement(final Resource subject,
4860                         final Resource relation, final Resource object,
4861                         final AsyncProcedure<Boolean> procedure) {
4862
4863                 assert (subject != null);
4864                 assert (relation != null);
4865                 assert (object != null);
4866                 assert (procedure != null);
4867
4868                 processor.forHasStatement(this, subject, relation, object, procedure);
4869
4870         }
4871
4872         @Override
4873         public void forHasStatement(Resource subject, Resource relation,
4874                         Resource object, SyncProcedure<Boolean> procedure) {
4875                 forHasStatement(subject, relation, object,
4876                                 new SyncToAsyncProcedure<Boolean>(procedure));
4877         }
4878
4879         @Override
4880         public void forHasStatement(Resource subject, Resource relation,
4881                         Resource object, Procedure<Boolean> procedure) {
4882                 forHasStatement(subject, relation, object,
4883                                 new NoneToAsyncProcedure<Boolean>(procedure));
4884         }
4885
4886         @Override
4887         public void forHasValue(Resource subject, AsyncListener<Boolean> listener) {
4888                 asyncRequest(new HasValue(subject), listener);
4889         }
4890
4891         @Override
4892         public void forHasValue(Resource subject, SyncListener<Boolean> listener) {
4893                 asyncRequest(new HasValue(subject), listener);
4894         }
4895
4896         @Override
4897         public void forHasValue(Resource subject, Listener<Boolean> listener) {
4898                 asyncRequest(new HasValue(subject), listener);
4899         }
4900
4901         @Override
4902         final public void forHasValue(final Resource subject,
4903                         final AsyncProcedure<Boolean> procedure) {
4904
4905                 assert (subject != null);
4906                 assert (procedure != null);
4907
4908                 processor.forValue(this, subject, new AsyncProcedure<byte[]>() {
4909
4910                         @Override
4911                         public void execute(AsyncReadGraph graph, byte[] result) {
4912                                 try {
4913                                         if (result == null)
4914                                                 procedure.execute(graph, false);
4915                                         else
4916                                                 procedure.execute(graph, true);
4917                                 } catch (Throwable t) {
4918                                 Logger.defaultLogError(t);
4919                                 }
4920                         }
4921
4922                         @Override
4923                         public void exception(AsyncReadGraph graph, Throwable t) {
4924                                 try {
4925                                         procedure.exception(graph, t);
4926                                 } catch (Throwable t2) {
4927                                 Logger.defaultLogError(t2);
4928                                 }
4929                         }
4930
4931                         @Override
4932                         public String toString() {
4933                                 return "forHasValue -> " + procedure;
4934                         }
4935
4936                 });
4937
4938         }
4939
4940         @Override
4941         public void forHasValue(Resource subject, SyncProcedure<Boolean> procedure) {
4942                 forHasValue(subject, new SyncToAsyncProcedure<Boolean>(procedure));
4943         }
4944
4945         @Override
4946         public void forHasValue(Resource subject, Procedure<Boolean> procedure) {
4947                 forHasValue(subject, new NoneToAsyncProcedure<Boolean>(procedure));
4948         }
4949
4950         @Override
4951         public void forOrderedSet(Resource subject,
4952                         AsyncMultiListener<Resource> listener) {
4953                 asyncRequest(new OrderedSet(subject), listener);
4954         }
4955
4956         @Override
4957         public void forOrderedSet(Resource subject,
4958                         SyncMultiListener<Resource> listener) {
4959                 asyncRequest(new OrderedSet(subject), listener);
4960         }
4961
4962         @Override
4963         public void forOrderedSet(Resource subject, MultiListener<Resource> listener) {
4964                 asyncRequest(new OrderedSet(subject), listener);
4965         }
4966
4967         @Override
4968         final public void forOrderedSet(final Resource subject,
4969                         final AsyncMultiProcedure<Resource> procedure) {
4970
4971                 assert (subject != null);
4972                 assert (procedure != null);
4973
4974                 processor.forOrderedSet(this, subject,
4975                                 new AsyncMultiProcedure<Resource>() {
4976
4977                                         @Override
4978                                         public void finished(AsyncReadGraph graph) {
4979                                                 try {
4980                                                         procedure.finished(graph);
4981                                                 } catch (Throwable t) {
4982                                                 Logger.defaultLogError(t);
4983                                                 }
4984                                         }
4985
4986                                         @Override
4987                                         public void execute(AsyncReadGraph graph, Resource result) {
4988                                                 try {
4989                                                         procedure.execute(graph, result);
4990                                                 } catch (Throwable t) {
4991                                                 Logger.defaultLogError(t);
4992                                                 }
4993                                         }
4994
4995                                         @Override
4996                                         public void exception(AsyncReadGraph graph, Throwable t) {
4997                                                 try {
4998                                                         procedure.exception(graph, t);
4999                                                 } catch (Throwable t2) {
5000                                                 Logger.defaultLogError(t2);
5001                                                 }
5002                                         }
5003
5004                                         @Override
5005                                         public String toString() {
5006                                                 return "forOrderedSet -> " + procedure;
5007                                         }
5008
5009                                 });
5010
5011         }
5012
5013         @Override
5014         public void forOrderedSet(Resource subject,
5015                         SyncMultiProcedure<Resource> procedure) {
5016                 forOrderedSet(subject, new SyncToAsyncMultiProcedure<Resource>(
5017                                 procedure));
5018         }
5019
5020         @Override
5021         public void forOrderedSet(Resource subject,
5022                         MultiProcedure<Resource> procedure) {
5023                 forOrderedSet(subject, new NoneToAsyncMultiProcedure<Resource>(
5024                                 procedure));
5025         }
5026
5027         @Override
5028         public <T> void forPossibleAdapted(Resource resource, Class<T> clazz,
5029                         AsyncListener<T> listener) {
5030                 asyncRequest(new PossibleAdapter<T>(resource, clazz), listener);
5031         }
5032
5033         @Override
5034         public <T> void forPossibleAdapted(Resource resource, Class<T> clazz,
5035                         SyncListener<T> listener) {
5036                 asyncRequest(new PossibleAdapter<T>(resource, clazz), listener);
5037         }
5038
5039         @Override
5040         public <T> void forPossibleAdapted(Resource resource, Class<T> clazz,
5041                         Listener<T> listener) {
5042                 asyncRequest(new PossibleAdapter<T>(resource, clazz), listener);
5043         }
5044
5045         @Override
5046         final public <T> void forPossibleAdapted(final Resource resource,
5047                         final Class<T> clazz, final AsyncProcedure<T> procedure) {
5048
5049                 assert (resource != null);
5050                 assert (clazz != null);
5051                 assert (procedure != null);
5052
5053                 final AdaptionService service = getSession().peekService(AdaptionService.class);
5054                 if (service == null)
5055                         procedure.exception(this, new ServiceException("No AdaptionService available")); 
5056                 else
5057                         service.adapt(this, resource, resource, Resource.class, clazz, true, procedure);
5058         }
5059
5060         @Override
5061         public <T> void forPossibleAdapted(Resource resource, Class<T> clazz,
5062                         SyncProcedure<T> procedure) {
5063                 forPossibleAdapted(resource, clazz, new SyncToAsyncProcedure<T>(
5064                                 procedure));
5065         }
5066
5067         @Override
5068         public <T> void forPossibleAdapted(Resource resource, Class<T> clazz,
5069                         Procedure<T> procedure) {
5070                 forPossibleAdapted(resource, clazz, new NoneToAsyncProcedure<T>(
5071                                 procedure));
5072         }
5073
5074         @Override
5075         public <T> void forPossibleUniqueAdapted(Resource resource, Class<T> clazz,
5076                         AsyncListener<T> listener) {
5077                 asyncRequest(new PossibleUniqueAdapter<T>(resource, clazz), listener);
5078         }
5079
5080         @Override
5081         public <T> void forPossibleUniqueAdapted(Resource resource, Class<T> clazz,
5082                         SyncListener<T> listener) {
5083                 asyncRequest(new PossibleUniqueAdapter<T>(resource, clazz), listener);
5084         }
5085
5086         @Override
5087         public <T> void forPossibleUniqueAdapted(Resource resource, Class<T> clazz,
5088                         Listener<T> listener) {
5089                 asyncRequest(new PossibleUniqueAdapter<T>(resource, clazz), listener);
5090         }
5091
5092         @Override
5093         final public <T> void forPossibleUniqueAdapted(final Resource resource,
5094                         final Class<T> clazz, final AsyncProcedure<T> procedure) {
5095
5096                 assert (resource != null);
5097                 assert (clazz != null);
5098                 assert (procedure != null);
5099
5100                 final AdaptionService service = getSession().peekService(AdaptionService.class);
5101                 if (service == null)
5102                         procedure.exception(this, new ServiceException("No AdaptionService available")); 
5103                 else
5104                         service.adaptNew(this, resource, clazz, true, procedure);
5105
5106         }
5107
5108         @Override
5109         public <T> void forPossibleUniqueAdapted(Resource resource, Class<T> clazz,
5110                         SyncProcedure<T> procedure) {
5111                 forPossibleUniqueAdapted(resource, clazz, new SyncToAsyncProcedure<T>(
5112                                 procedure));
5113         }
5114
5115         @Override
5116         public <T> void forPossibleUniqueAdapted(Resource resource, Class<T> clazz,
5117                         Procedure<T> procedure) {
5118                 forPossibleUniqueAdapted(resource, clazz, new NoneToAsyncProcedure<T>(
5119                                 procedure));
5120         }
5121
5122         /*
5123          * Implementation of the interface AsyncRequestProcessor
5124          */
5125
5126         @Override
5127         final public Session getSession() {
5128                 return processor.getSession();
5129         }
5130
5131         @Override
5132         public <T> void asyncRequest(final Read<T> request) {
5133
5134                 asyncRequest(request, new AsyncProcedure<T>() {
5135
5136                         @Override
5137                         public void execute(AsyncReadGraph graph, T result) {
5138                         }
5139
5140                         @Override
5141                         public void exception(AsyncReadGraph graph, Throwable t) {
5142                                 Logger.defaultLogError(t);
5143                         }
5144
5145                         @Override
5146                         public String toString() {
5147                                 return "asyncRequest(Read) -> " + request;
5148                         }
5149
5150                 });
5151
5152         }
5153
5154         @Override
5155         public <T> void asyncRequest(Read<T> request, AsyncListener<T> procedure) {
5156                 asyncRequest(request, (AsyncProcedure<T>) procedure);
5157         }
5158
5159         @Override
5160         public <T> void asyncRequest(Read<T> request,
5161                         final SyncListener<T> procedure) {
5162                 asyncRequest(request, new SyncToAsyncListener<T>(procedure));
5163         }
5164
5165         @Override
5166         public <T> void asyncRequest(Read<T> request, final Listener<T> procedure) {
5167                 asyncRequest(request, new NoneToAsyncListener<T>(procedure));
5168         }
5169
5170         @Override
5171         public <T> void asyncRequest(final Read<T> request, final AsyncProcedure<T> procedure) {
5172
5173                 assert (request != null);
5174                 assert (procedure != null);
5175                 
5176                 AsyncBarrierImpl barrier = asyncBarrier;
5177                 if(barrier != null)
5178                     barrier.inc();
5179                 
5180                 processor.scheduleNow(new SessionTask(this) {
5181
5182                         @Override
5183                         public void run0(int thread) {
5184                                 try {
5185                                         final ListenerBase listener = getListenerBase(procedure);
5186                                         QueryCache.runnerReadEntry(ReadGraphImpl.this, request, parent, listener, procedure, false);
5187                                 } catch (DatabaseException e) {
5188                                         Logger.defaultLogError(e);
5189                                 } finally {
5190                                 if(barrier != null)
5191                                     barrier.dec();
5192                                 }
5193                         }
5194                         
5195                 });
5196
5197         }
5198
5199     public static ReadGraphImpl createAsync(QueryProcessor support) {
5200         return new ReadGraphImpl(null, null, support);
5201     }
5202
5203         @Override
5204         public <T> void asyncRequest(Read<T> request, SyncProcedure<T> procedure) {
5205                 asyncRequest(request, new SyncToAsyncProcedure<T>(procedure));
5206         }
5207
5208         @Override
5209         public <T> void asyncRequest(Read<T> request, final Procedure<T> procedure) {
5210                 asyncRequest(request, new NoneToAsyncProcedure<T>(procedure));
5211         }
5212
5213         @Override
5214         final public <T> void asyncRequest(final AsyncRead<T> request) {
5215
5216                 assert (request != null);
5217
5218                 asyncRequest(request, new AsyncProcedure<T>() {
5219
5220                         @Override
5221                         public void execute(AsyncReadGraph graph, T result) {
5222                         }
5223
5224                         @Override
5225                         public void exception(AsyncReadGraph graph, Throwable t) {
5226                         Logger.defaultLogError(t);
5227                         }
5228
5229                         @Override
5230                         public String toString() {
5231                                 return "asyncRequest(AsyncRead) -> " + request;
5232                         }
5233
5234                 });
5235
5236         }
5237
5238         @Override
5239         public <T> void asyncRequest(AsyncRead<T> request,
5240                         AsyncListener<T> procedure) {
5241                 asyncRequest(request, (AsyncProcedure<T>) procedure);
5242         }
5243
5244         @Override
5245         final public <T> void asyncRequest(AsyncRead<T> request,
5246                         final SyncListener<T> procedure) {
5247                 asyncRequest(request, new SyncToAsyncListener<T>(procedure));
5248         }
5249
5250         @Override
5251         final public <T> void asyncRequest(AsyncRead<T> request,
5252                         final Listener<T> procedure) {
5253                 asyncRequest(request, new NoneToAsyncListener<T>(procedure));
5254         }
5255
5256     @Override
5257     final public <T> void asyncRequest(final AsyncRead<T> request,
5258             final AsyncProcedure<T> procedure) {
5259
5260         assert (request != null);
5261         assert (procedure != null);
5262
5263         AsyncBarrierImpl barrier = asyncBarrier;
5264         if(barrier != null)
5265             barrier.inc();
5266
5267         processor.scheduleNow(new SessionTask(this) {
5268
5269             @Override
5270             public void run0(int thread) {
5271
5272                 if(barrier != null)
5273                     barrier.inc();
5274
5275                 try {
5276                     final ListenerBase listener = getListenerBase(procedure);
5277                     QueryCache.runnerAsyncReadEntry(ReadGraphImpl.this, request, parent, listener, new AsyncProcedure<T>() {
5278
5279                         @Override
5280                         public void execute(AsyncReadGraph graph, T result) {
5281                             procedure.execute(graph, result);
5282                             if(barrier != null)
5283                                 barrier.dec();
5284                         }
5285
5286                         @Override
5287                         public void exception(AsyncReadGraph graph, Throwable throwable) {
5288                             procedure.exception(graph, throwable);
5289                             if(barrier != null)
5290                                 barrier.dec();
5291                         }
5292
5293                     }, false);
5294                 } catch (DatabaseException e) {
5295                     LOGGER.error("Error while executing async request", e);
5296                 } finally {
5297                     if(barrier != null)
5298                         barrier.dec();
5299                 }
5300             }
5301
5302         });
5303
5304     }
5305
5306         @Override
5307         public <T> void asyncRequest(AsyncRead<T> request,
5308                         SyncProcedure<T> procedure) {
5309                 asyncRequest(request, new SyncToAsyncProcedure<T>(procedure));
5310         }
5311
5312         @Override
5313         final public <T> void asyncRequest(final AsyncRead<T> request,
5314                         final Procedure<T> procedure) {
5315                 asyncRequest(request, new NoneToAsyncProcedure<T>(procedure));
5316         }
5317
5318         @Override
5319         public <T> void asyncRequest(final MultiRead<T> request) {
5320
5321                 assert (request != null);
5322
5323                 asyncRequest(request, new SyncMultiProcedureAdapter<T>() {
5324                         @Override
5325                         public void exception(ReadGraph graph, Throwable t) {
5326                         Logger.defaultLogError(t);
5327                         }
5328
5329                         @Override
5330                         public String toString() {
5331                                 return "asyncRequest(MultiRead) -> " + request;
5332                         }
5333                 });
5334
5335         }
5336
5337         @Override
5338         public <T> void asyncRequest(MultiRead<T> request,
5339                         SyncMultiListener<T> procedure) {
5340                 asyncRequest(request, (SyncMultiProcedure<T>)procedure);
5341         }
5342
5343         @Override
5344         public <T> void asyncRequest(MultiRead<T> request,
5345                         MultiListener<T> procedure) {
5346                 asyncRequest(request, new NoneToSyncMultiListener<T>(procedure));
5347         }
5348
5349         
5350         @Override
5351         public <T> void asyncRequest(final MultiRead<T> request,
5352                         final SyncMultiProcedure<T> procedure) {
5353
5354                 assert (request != null);
5355                 assert (procedure != null);
5356
5357                 final ListenerBase listener = getListenerBase(procedure);
5358
5359                 if (parent != null || listener != null) {
5360
5361 //                  final ReadGraphImpl newGraph = newSync();
5362                     processor.query(this, request, parent, procedure,listener);
5363
5364                 } else {
5365
5366 //                  final ReadGraphImpl newGraph = newSync();
5367
5368                     try {
5369
5370                         request.perform(this, procedure);
5371
5372                     } catch (Throwable t) {
5373
5374                         try {
5375                                         procedure.exception(this, t);
5376                                 } catch (DatabaseException e) {
5377                                         LOGGER.error("Unexpected exception while handling exception", e);
5378                                 }
5379
5380                     }                           
5381
5382                 }
5383
5384         }
5385
5386         @Override
5387         public <T> void asyncRequest(MultiRead<T> request,
5388                         MultiProcedure<T> procedure) {
5389                 asyncRequest(request, new NoneToSyncMultiProcedure<T>(procedure));
5390         }
5391
5392         @Override
5393         final public <T> void asyncRequest(final AsyncMultiRead<T> request) {
5394
5395                 assert (request != null);
5396
5397                 asyncRequest(request, new AsyncMultiProcedureAdapter<T>() {
5398                         @Override
5399                         public void exception(AsyncReadGraph graph, Throwable t) {
5400                         Logger.defaultLogError(t);
5401                         }
5402
5403                         @Override
5404                         public String toString() {
5405                                 return "asyncRequest(AsyncMultiRead) -> " + request;
5406                         }
5407                 });
5408
5409         }
5410
5411         @Override
5412         public <T> void asyncRequest(AsyncMultiRead<T> request,
5413                         AsyncMultiListener<T> procedure) {
5414                 asyncRequest(request, (AsyncMultiProcedure<T>) procedure);
5415         }
5416
5417         @Override
5418         public <T> void asyncRequest(AsyncMultiRead<T> request,
5419                         SyncMultiListener<T> procedure) {
5420                 asyncRequest(request, new SyncToAsyncMultiListener<T>(procedure));
5421         }
5422
5423         @Override
5424         public <T> void asyncRequest(AsyncMultiRead<T> request,
5425                         MultiListener<T> procedure) {
5426                 asyncRequest(request, new NoneToAsyncMultiListener<T>(procedure));
5427         }
5428
5429         @Override
5430         final public <T> void asyncRequest(AsyncMultiRead<T> request,
5431                         final AsyncMultiProcedure<T> procedure) {
5432
5433                 assert (request != null);
5434                 assert (procedure != null);
5435
5436                 ListenerBase listener = getListenerBase(procedure);
5437
5438                 if (parent != null || listener != null) {
5439
5440                         processor.query(this, request, parent, procedure, listener);
5441
5442                 } else {
5443
5444                         try {
5445
5446                                 request.perform(this, new AsyncMultiProcedure<T>() {
5447
5448                                         @Override
5449                                         public void execute(AsyncReadGraph graph, T result) {
5450                                                 procedure.execute(graph, result);
5451                                         }
5452
5453                                         @Override
5454                                         public void finished(AsyncReadGraph graph) {
5455                                                 procedure.finished(graph);
5456                                         }
5457
5458                                         @Override
5459                                         public void exception(AsyncReadGraph graph, Throwable t) {
5460                                                 procedure.exception(graph, t);
5461                                         }
5462
5463                                         @Override
5464                                         public String toString() {
5465                                                 return "asyncRequest(AsyncMultiRead) -> " + procedure;
5466                                         }
5467
5468                                 });
5469
5470                         } catch (Throwable t) {
5471
5472                                 procedure.exception(this, new DatabaseException(t));
5473
5474                         }
5475                 }
5476
5477         }
5478
5479         @Override
5480         public <T> void asyncRequest(AsyncMultiRead<T> request,
5481                         SyncMultiProcedure<T> procedure) {
5482                 asyncRequest(request, new SyncToAsyncMultiProcedure<T>(procedure));
5483         }
5484
5485         @Override
5486         final public <T> void asyncRequest(AsyncMultiRead<T> request,
5487                         final MultiProcedure<T> procedure) {
5488                 asyncRequest(request, new NoneToAsyncMultiProcedure<T>(procedure));
5489         }
5490
5491         @Override
5492         final public <T> void asyncRequest(final ExternalRead<T> request) {
5493
5494                 assert (request != null);
5495
5496                 asyncRequest(request, new Procedure<T>() {
5497
5498                         @Override
5499                         public void execute(T result) {
5500                         }
5501
5502                         @Override
5503                         public void exception(Throwable t) {
5504                         Logger.defaultLogError(t);
5505                         }
5506
5507                         @Override
5508                         public String toString() {
5509                                 return "asyncRequest(PrimitiveRead) -> " + request;
5510                         }
5511
5512                 });
5513
5514         }
5515
5516         @Override
5517         public <T> void asyncRequest(ExternalRead<T> request,
5518                         final Listener<T> procedure) {
5519                 asyncRequest(request, (Procedure<T>) procedure);
5520         }
5521
5522         @Override
5523         final public <T> void asyncRequest(final ExternalRead<T> request,
5524                         final Procedure<T> procedure) {
5525
5526                 assert (request != null);
5527                 assert (procedure != null);
5528
5529                 final ListenerBase listener = getListenerBase(procedure);
5530
5531                 if (parent != null || listener != null) {
5532
5533                         try {
5534                                 QueryCacheBase.resultExternalReadEntry(this, request, parent, listener, procedure);
5535                         } catch (DatabaseException e) {
5536                                 Logger.defaultLogError(e);
5537                                 // This throwable has already been transferred to procedure at this point - do nothing about it
5538                         }
5539
5540                 } else {
5541
5542                         request.register(this, new Listener<T>() {
5543                                 @Override
5544                                 public void execute(T result) {
5545                                         procedure.execute(result);
5546                                 }
5547
5548                                 @Override
5549                                 public void exception(Throwable t) {
5550                                         procedure.exception(t);
5551                                 }
5552
5553                                 @Override
5554                                 public String toString() {
5555                                         return "asyncRequest(PrimitiveRead) -> " + request;
5556                                 }
5557
5558                                 @Override
5559                                 public boolean isDisposed() {
5560                                         return true;
5561                                 }
5562
5563                         });
5564
5565                 }
5566
5567         }
5568
5569         @Override
5570         public void asyncRequest(final Write request) {
5571
5572                 assert (request != null);
5573                 
5574                 getSession().asyncRequest(request);
5575
5576 //              processor.asyncWrite(request);
5577
5578         }
5579
5580         @Override
5581         public <T> void asyncRequest(final WriteResult<T> request, Procedure<T> procedure) {
5582                 throw new Error("Not implemented.");
5583         }
5584         
5585         @Override
5586         public void asyncRequest(Write request, Consumer<DatabaseException> callback) {
5587                 
5588                 assert (request != null);
5589                 
5590                 getSession().asyncRequest(request, callback);
5591                 
5592         }
5593
5594         @Override
5595         public void asyncRequest(final DelayedWrite request) {
5596
5597                 assert (request != null);
5598
5599                 getSession().asyncRequest(request);
5600
5601         }
5602
5603         @Override
5604         public <T> void asyncRequest(final DelayedWriteResult<T> request, Procedure<T> procedure) {
5605                 throw new Error("Not implemented.");
5606         }
5607         
5608         @Override
5609         public void asyncRequest(DelayedWrite r,
5610                         Consumer<DatabaseException> callback) {
5611                 throw new Error("Not implemented.");
5612         }
5613
5614         @Override
5615         public void asyncRequest(final WriteOnly request) {
5616
5617                 assert (request != null);
5618
5619                 getSession().asyncRequest(request);
5620
5621         }
5622
5623         @Override
5624         public <T> void asyncRequest(final WriteOnlyResult<T> request, Procedure<T> procedure) {
5625                 throw new Error("Not implemented.");
5626         }
5627         
5628         @Override
5629         public void asyncRequest(WriteOnly r, Consumer<DatabaseException> callback) {
5630                 throw new Error("Not implemented.");
5631         }
5632
5633         /*
5634          * Implementation of the interface ServiceLocator
5635          */
5636
5637         @Override
5638         public <T> T getService(Class<T> api) {
5639             if(WriteSupport.class == api) {
5640                 if(this instanceof WriteGraphImpl) {
5641                     WriteGraphImpl impl = (WriteGraphImpl)this;
5642                     return (T)impl.writeSupport;
5643                 }
5644             }
5645                 return getSession().getService(api);
5646         }
5647
5648         @Override
5649         public <T> T peekService(Class<T> api) {
5650                 return getSession().peekService(api);
5651         }
5652
5653         @Override
5654         public boolean hasService(Class<?> api) {
5655                 return getSession().hasService(api);
5656         }
5657
5658         @Override
5659         public <T> void registerService(Class<T> api, T service) {
5660                 getSession().registerService(api, service);
5661         }
5662         
5663         @Override
5664         public boolean isImmutable(Resource resource) throws DatabaseException {
5665                 ResourceImpl impl = (ResourceImpl)resource;
5666                 return processor.isImmutable(impl.id);
5667         }
5668
5669         /*
5670          * Internal routines
5671          */
5672
5673         protected static String INTERNAL_ERROR_STRING = "Transaction aborted due to internal client error.";
5674
5675         /*
5676          * callerThread is the currently running thread state.syncThread is blocking for
5677          * this execution state.syncParent is the blocking request
5678          */
5679
5680         ReadGraphImpl(ReadGraphImpl parentGraph, CacheEntry parent, QueryProcessor support) {
5681                 this.parentGraph = parentGraph;
5682                 this.parent = parent;
5683                 this.processor = support;
5684                 this.asyncBarrier = prepareBarrier(parentGraph, parent, null, false);
5685         }
5686
5687     ReadGraphImpl(ReadGraphImpl parentGraph, CacheEntry parent, QueryProcessor support, AsyncBarrierImpl asyncBarrier) {
5688         this.parentGraph = parentGraph;
5689         this.parent = parent;
5690         this.processor = support;
5691         this.asyncBarrier = asyncBarrier;
5692     }
5693
5694         ReadGraphImpl(ReadGraphImpl graph, CacheEntry parent) {
5695                 this(graph, parent, graph.processor);
5696         }
5697
5698     ReadGraphImpl(ReadGraphImpl parentGraph, CacheEntry parent, Runnable callback, boolean needsToBlock) {
5699         this(parentGraph, parent, parentGraph.processor, prepareBarrier(parentGraph, parent, callback, needsToBlock));
5700     }
5701
5702     static AsyncBarrierImpl prepareBarrier(ReadGraphImpl parentGraph, CacheEntry parent, Runnable callback, boolean needsToBlock) {
5703         return new AsyncBarrierImpl(parentGraph != null ? parentGraph.asyncBarrier : null, parent, callback, needsToBlock);
5704     }
5705     
5706         ReadGraphImpl(ReadGraphImpl graph) {
5707                 this(graph, graph.parent);
5708         }
5709
5710         public ReadGraphImpl withParent(CacheEntry parent, Runnable callback, boolean needsToBlock) {
5711                 return new ReadGraphImpl(this, parent, callback, needsToBlock);
5712         }
5713
5714         public ReadGraphImpl forRecompute(CacheEntry parent) {
5715                 return new ReadGraphImpl(null, parent, processor);
5716         }
5717
5718     public static ReadGraphImpl create(QueryProcessor support) {
5719         ReadGraphImpl result = new ReadGraphImpl(null, null, support);
5720         return result;
5721     }
5722
5723         public ReadGraphImpl newRestart(ReadGraphImpl impl) {
5724
5725                 WriteGraphImpl write = processor.getSession().getService(
5726                                 WriteGraphImpl.class);
5727
5728                 return write;
5729
5730         }
5731
5732         final private ListenerBase getListenerBase(final Object procedure) {
5733                 if (procedure instanceof ListenerBase)
5734                         return (ListenerBase) procedure;
5735                 else
5736                         return null;
5737         }
5738
5739         public <T> void waitAsyncProcedure(AsyncMultiReadProcedure<T> procedure) {
5740                 
5741                 assert(procedure.done());
5742                 
5743         }
5744
5745         public <T> void waitAsyncProcedure(AsyncReadProcedure<T> procedure) {
5746                 
5747                 assert(procedure.done());
5748                 
5749         }
5750
5751         public boolean resumeTasks() {
5752                 return processor.resumeTasks(this);
5753         }
5754
5755         Class<?> singleClass(Set<Resource> types) {
5756                 Class<?> result = null;
5757                 for (Resource type : types) {
5758                         Class<?> clazz = processor.getBuiltinValue(type);
5759                         if (clazz != null) {
5760                                 if (result != null)
5761                                         return null;
5762                                 else
5763                                         result = clazz;
5764                         }
5765                 }
5766                 return result;
5767         }
5768
5769         private String debugString(Resource r) {
5770                 String name = null;
5771                 try {
5772                         name = getPossibleRelatedValue(r, processor.getL0(this).HasName);
5773                 } catch (ManyObjectsForFunctionalRelationException e) {
5774                 Logger.defaultLogError(e);
5775                 } catch (ServiceException e) {
5776                 Logger.defaultLogError(e);
5777                 }
5778                 return "[" + name + " - " + r + "]";
5779         }
5780
5781         @Override
5782         public String toString() {
5783                 return "ReadGraphImpl[thread=" + Thread.currentThread() + "]";
5784         }
5785
5786         @Override
5787         final public int thread() {
5788                 return 0;
5789         }
5790         
5791     static class MultiTripleIntProcedure implements TripleIntProcedure {
5792
5793         final private AsyncMultiProcedure<Statement> procedure;
5794         final private ReadGraphImpl impl;
5795         final private QuerySupport support;
5796         
5797         public MultiTripleIntProcedure(AsyncMultiProcedure<Statement> procedure, ReadGraphImpl impl, QuerySupport support) {
5798                 this.procedure = procedure;
5799                 this.impl = impl;
5800                 this.support = support;
5801         }
5802         
5803         @Override
5804         public void execute(ReadGraphImpl graph, int s, int p, int o) {
5805                 try {
5806                         procedure.execute(graph, support.getStatement(s, p, o));
5807                 } catch (Throwable t2) {
5808                         Logger.defaultLogError(t2);
5809                 }
5810         }
5811
5812         @Override
5813         public void finished(ReadGraphImpl graph) {
5814                 try {
5815                         procedure.finished(graph);
5816 //                      impl.state.barrier.dec("ReadGraphSupportImpl.516");
5817                 } catch (Throwable t2) {
5818                         Logger.defaultLogError(t2);
5819                 }
5820         }
5821
5822         @Override
5823         public void exception(ReadGraphImpl graph, Throwable t) {
5824                 try {
5825                         procedure.exception(graph, t);
5826                 } catch (Throwable t2) {
5827                         Logger.defaultLogError(t2);
5828                 }
5829 //              impl.state.barrier.dec("ReadGraphSupportImpl.516");
5830         }
5831
5832         @Override
5833         public String toString() {
5834                 return "forEachObject with " + procedure;
5835         }
5836         
5837     }
5838
5839 //    private AsyncMultiProcedure<Resource> cacheKey = null;
5840 //    private MultiIntProcedure cacheResult = null;
5841 //    
5842 //    final IntProcedure forMultiProcedure(final AsyncMultiProcedure<Resource> procedure) {
5843 //      
5844 //      if(procedure == cacheKey) return cacheResult; 
5845 //      
5846 //      cacheResult = new MultiIntProcedure(procedure, this, processor.support);
5847 //      cacheKey = procedure;
5848 //      
5849 //      return cacheResult;
5850 //      
5851 //    }
5852 //
5853 //    private AsyncMultiProcedure<Statement> cacheKey2 = null;
5854 //    private MultiTripleIntProcedure cacheResult2 = null;
5855 //
5856 //    final synchronized TripleIntProcedure forMultiProcedure(final AsyncMultiProcedure<Statement> procedure) {
5857 //      
5858 //      if(procedure == cacheKey2) return cacheResult2; 
5859 //      
5860 //      cacheResult2 = new MultiTripleIntProcedure(procedure, this, processor.support);
5861 //      cacheKey2 = procedure;
5862 //      
5863 //      return cacheResult2;
5864 //      
5865 //    }
5866     
5867     @Override
5868     public Datatype getDataType(Resource subject) throws DatabaseException {
5869         for(Resource dataTypeResource : getObjects(subject, processor.getL0(this).HasDataType))
5870                 return getValue(dataTypeResource, Bindings.getBindingUnchecked(Datatype.class));
5871         throw new DoesNotContainValueException("The literal has no data type.");
5872     }
5873     
5874     protected <T extends Accessor> T getAccessor4File(Resource subject)
5875     throws DatabaseException {
5876         return null;
5877         /*        
5878         byte[]  bytes = processor.support.getValue(g, subject);
5879         if (null == bytes)
5880             return null;
5881         try {
5882             BinaryVariant va = (BinaryVariant) Accessors.getAccessor(bytes, Datatypes.VARIANT);
5883             Accessor ca = va.getContentAccessor();
5884             return (T)ca;
5885         } catch (AccessorConstructionException e) {
5886             throw new DatabaseException(e);
5887         }
5888         */
5889         /*
5890         if (null == bytes)
5891             return null;
5892         Binding datatype_binding = Bindings.getBindingUnchecked(DataType.class);
5893         Serializer datatype_serializer = datatype_binding.serializer();
5894         DataType datatype;
5895         try {
5896             BinaryMemory in = new BinaryMemory(ByteBuffer.wrap(bytes));
5897             datatype = (DataType)datatype_serializer.deserialize(in);
5898             Binding data_binding = Bindings.getBinding(datatype);
5899             Serializer data_serializer = data_binding.serializer(BinarySerializationFormat.INSTANCE);
5900             Object o = data_serializer.deserialize(in);
5901             try {
5902                 return (T)Accessors.getAccessor(data_binding, o);
5903             } catch(AccessorConstructionException e) {
5904                 return null;
5905             }
5906         } catch (Exception e) {
5907             throw new DatabaseException(e);
5908         }*/
5909     }
5910     @SuppressWarnings("unchecked")
5911     @Override
5912     public <T extends Accessor> T getAccessor(Resource subject) throws DatabaseException {
5913         RandomAccessBinary rab = getRandomAccessBinary(subject);
5914         try {
5915             return (T)Accessors.getAccessor(rab, getDataType(subject));
5916         } catch(AccessorConstructionException e) {
5917             throw new DatabaseException(e);
5918         }
5919     }
5920     @SuppressWarnings("unchecked")
5921     protected <T extends Accessor> T createAccessor(Resource resource, Datatype datatype, Object intialValue)
5922     throws DatabaseException {
5923         RandomAccessBinary rab = createRandomAccessBinary(resource, datatype, intialValue);
5924         try {
5925             return (T)Accessors.getAccessor(rab, datatype);
5926         } catch(AccessorConstructionException e) {
5927             throw new DatabaseException(e);
5928         }
5929     }
5930     @Override
5931     public RandomAccessBinary getRandomAccessBinary(Resource subject) throws DatabaseException {
5932         RandomAccessValueSupport ravs = getSession().getService(RandomAccessValueSupport.class);
5933         ResourceData rd = ravs.get(subject);
5934         if (null != rd)
5935             return rd;
5936         try {
5937             ExternalValueSupport evs = getService(ExternalValueSupport.class);
5938             long size = evs.getValueSize(this, subject); // Throws DatabaseException if no old external value.
5939             try {
5940                 File platform = Platform.getLocation().toFile();
5941                 File tempFiles = new File(platform, "tempFiles");
5942                 File dbDir = new File(tempFiles, "db");
5943                 dbDir.mkdirs();
5944                 File file = new File(dbDir, "ResourceFile" + subject.getResourceId());
5945                 rd = new ResourceData(new BinaryFile(file), true); // Old external value.
5946                 final int N = 1<<20;
5947                 long left = size;
5948                 long offset = 0;
5949                 while (left > 0) {
5950                     int length = N < left ? N : (int)left;
5951                     byte[] bytes = evs.readValue(this, subject, offset, length);
5952                     offset += bytes.length;
5953                     left -= bytes.length;
5954                     rd.binaryFile.write(bytes);
5955                 }
5956                 ravs.put(subject, rd);
5957                 return rd;
5958             } catch (Exception e) {
5959                 throw new DatabaseException("Resource " + subject + " have value but there was problem with accessing value data.", e);
5960             }
5961         } catch (Exception e) {
5962             if(Development.DEVELOPMENT) {
5963                 if(Development.<Boolean>getProperty(DevelopmentKeys.WRITEGRAPH_EXCEPTION_STACKTRACES, Bindings.BOOLEAN)) {
5964                     e.printStackTrace();
5965                 }
5966             }
5967         }
5968         Datatype datatype = getDataType(subject);
5969         Object value = getPossibleValue(subject, Bindings.getBinding(datatype));
5970         return createRandomAccessBinary(subject, datatype, value);
5971     }
5972     public RandomAccessBinary createRandomAccessBinary(Resource resource, Datatype datatype, Object initialValue)
5973     throws DatabaseException {
5974         RandomAccessValueSupport ravs = getSession().getService(RandomAccessValueSupport.class);
5975         try {
5976             File platform = Platform.getLocation().toFile();
5977             File tempFiles = new File(platform, "tempFiles");
5978             File dbDir = new File(tempFiles, "db");
5979             dbDir.mkdirs();
5980             File file = new File(dbDir, "ResourceFile" + resource.getResourceId());
5981             ResourceData rd = new ResourceData(new BinaryFile(file), false);
5982             Binding binding = Bindings.getBinding(datatype);
5983             if (null == initialValue) {
5984                 initialValue = binding.createDefault();
5985             }
5986             Serializer serializer = binding.serializer();
5987             byte[] bytes = serializer.serialize(initialValue);
5988             // In case the file has been previously accessed and was larger we set the correct size now
5989             rd.binaryFile.setLength(bytes.length);
5990             rd.binaryFile.write(bytes);
5991             ravs.put(resource, rd);
5992             return rd;
5993         } catch (Exception e) {
5994             if (e instanceof DatabaseException)
5995                 throw (DatabaseException)e;
5996             else
5997                 throw new DatabaseException(e);
5998         }
5999     }
6000
6001 //    static class ExternalValueRequest<T> extends ResourceRead<T> {
6002 //
6003 //              public ExternalValueRequest(Resource resource) {
6004 //                      super(resource);
6005 //              }
6006 //
6007 //              @SuppressWarnings("unchecked")
6008 //              @Override
6009 //              public T perform(ReadGraph graph) throws DatabaseException {
6010 //              try {
6011 //                      
6012 //                      String uri = graph.getURI(resource);
6013 //                      if(Layer0.URIs.Functions_functionApplication.equals(uri)) return (T)functionApplication;
6014 //                      
6015 //                      return (T)ReflectionUtils.getValue(uri).getValue();
6016 //                      
6017 //              } catch(ValueNotFoundException e) {
6018 //                      throw new DatabaseException("Couldn't convert to external value (r=" + resource + ")", e);
6019 //              } catch(ClassCastException e) {
6020 //                      throw new DatabaseException("Couldn't convert to external value (r=" + resource + ")", e);
6021 //              }
6022 //              }
6023 //      
6024 //    }
6025     
6026     @SuppressWarnings("unchecked")
6027     @Override
6028     public <T> T getValue2(Resource r, Object context) throws DatabaseException {
6029         Layer0 L0 = processor.getL0(this);
6030         Set<Resource> types = getTypes(r);
6031         
6032         if(types.contains(L0.Literal)) {
6033                 if(isImmutable(r)) {
6034                         return syncRequest(new ValueImplied<T>(r));
6035                 } else {
6036                         return getValue(r);
6037                 }
6038         }
6039         else if(types.contains(L0.ExternalValue)) {
6040                 return (T)syncRequest(new AdaptValue(r), TransientCacheListener.<Object>instance());
6041         }
6042         else {
6043
6044             Function3<ReadGraph,Resource,Object,T> function = requestValueFunction(r);
6045             if(function == null) throw new DoesNotContainValueException("Couldn't convert to a value function " + r);
6046             try {
6047                 return function.apply(this, r, context);
6048             } catch(RuntimeException e) {
6049                 DatabaseException dte = findPossibleRootException(e);
6050                 if(dte != null) throw dte;
6051                 else throw new DatabaseException(e);
6052             }
6053                 
6054         }
6055     }
6056
6057     @Override
6058     public Variant getVariantValue2(Resource r, Object context) throws DatabaseException {
6059         Layer0 L0 = processor.getL0(this);
6060         Set<Resource> types = getTypes(r);
6061         
6062         if(types.contains(L0.Literal)) {
6063             if(isImmutable(r)) {
6064                 return syncRequest(new VariantValueImplied(r));
6065             } else {
6066                 return getVariantValue(r);
6067             }
6068         }
6069         else if(types.contains(L0.ExternalValue)) {
6070             Object value = syncRequest(new AdaptValue(r), TransientCacheListener.<Object>instance());
6071             try {
6072                 return new Variant(Bindings.OBJECT.getContentBinding(value), value);
6073             } catch ( org.simantics.databoard.binding.error.BindingException e ) {
6074                 throw new BindingException( "No binding found for class " + value.getClass().getName(), e );
6075             }
6076         }
6077         else {
6078
6079             Function3<ReadGraph,Resource,Object,Object> function = requestValueFunction(r);
6080             if(function == null) throw new DoesNotContainValueException("Couldn't convert to a value function " + r);
6081             try {
6082                 Object value = function.apply(this, r, context);
6083                 try {
6084                     return new Variant(Bindings.OBJECT.getContentBinding(value), value);
6085                 } catch ( org.simantics.databoard.binding.error.BindingException e ) {
6086                     throw new BindingException( "No binding found for class " + value.getClass().getName(), e );
6087                 }
6088             } catch(RuntimeException e) {
6089                 DatabaseException dte = findPossibleRootException(e);
6090                 if(dte != null) throw dte;
6091                 else throw new DatabaseException(e);
6092             }
6093         }
6094     }
6095     
6096     @Override
6097     public <T> T getPossibleValue2(Resource subject, Object context) throws DatabaseException {
6098         try {
6099                 return getValue2(subject, context);
6100         } catch (DatabaseException e) {
6101                 return null;
6102         }
6103     }
6104
6105     static class PossibleConverterFunction<T> extends ResourceRead<Function3<ReadGraph,Resource,Object,T>> {
6106         
6107         public PossibleConverterFunction(Resource resource) {
6108                         super(resource);
6109                 }
6110
6111         @Override
6112         public Function3<ReadGraph,Resource,Object,T> perform(ReadGraph graph) throws DatabaseException {
6113                 return compute(graph, resource);
6114         }
6115         
6116         @SuppressWarnings("unchecked")
6117                 public static <T> Function3<ReadGraph,Resource,Object,T> compute(ReadGraph graph, Resource resource) throws DatabaseException {
6118             Layer0 L0 = Layer0.getInstance(graph);
6119             for(Resource converter : graph.getObjects(resource, L0.ConvertsToValueWith)) {
6120                 try {
6121                         if(L0.Functions_functionApplication.equals(converter)) {
6122                                 return (Function3<ReadGraph,Resource,Object,T>)graph.syncRequest(new AdaptValue(resource));
6123                         } else {
6124                                 return graph.getValue2(converter, resource);
6125                         }
6126                 } catch(RuntimeException e) {
6127                     DatabaseException dte = findPossibleRootException(e);
6128                     if(dte != null) throw dte;
6129                     else throw new DatabaseException(e);
6130                 }
6131             }
6132             return null;
6133         }
6134         
6135     }
6136     
6137     <T> Function3<ReadGraph,Resource,Object,T> requestValueFunction(Resource r) throws DatabaseException {
6138         if(isImmutable(r))
6139                 return syncRequest(new PossibleConverterFunction<T>(r), TransientCacheAsyncListener.<Function3<ReadGraph,Resource,Object,T>>instance());
6140         else
6141                 return syncRequest(new PossibleConverterFunction<T>(r));
6142     }
6143     
6144     /**
6145      * Get a value associated with a graph {@link Resource}, using a possible context object and
6146      * a desired value binding. The following methods are tried in order to retreive the value:
6147      * <ol>
6148      *   <li>If the given resource is a {@code L0.Literal}, the value of the literal is returned, using the binding specified by {@code binding}.</li>
6149      *   <li>If the resource is a {@code L0.ExternalValue}, the value is acquired using
6150      *       {@link ReflectionUtils#getValue(String)}.</li>
6151      *   <li>If the resource is associated with a suitable value converter with relation {@code L0.ConvertsToValueWith}
6152      *       (see {@link #requestValueFunction(Resource)}), the value function is called with the graph, the resource
6153      *       and the context object.</li>
6154      * </ul>
6155      * 
6156      * @param r  A graph resource with which the value is associated
6157      * @param context  A context object that is used for acquiring the value (only applied in case 3)
6158      * @param binding  A binding for the value type (only applied in case 1)
6159      * @return  The value of the graph node.
6160      * @throws DoesNotContainValueException  No value is associated with the graph node.
6161      * @throws DatabaseException  Other errors, such as an error in casting the value to the return type or
6162      *         a runtime error in the value function.
6163      */
6164     @SuppressWarnings("unchecked")
6165         @Override
6166     public <T> T getValue2(Resource r, Object context, Binding binding) throws DatabaseException {
6167         if (binding instanceof ObjectVariantBinding)
6168                 return getValue2(r, context);
6169         
6170         Layer0 L0 = processor.getL0(this);
6171         Set<Resource> types = getTypes(r);
6172         if(types.contains(L0.Literal)) {
6173                 if(isImmutable(r)) {
6174                         return syncRequest(new Value<T>(r, binding));
6175                 } else {
6176                         return getValue(r, binding);
6177                 }
6178         } else if(types.contains(L0.ExternalValue)) {
6179                 ComputationalValue cv = syncRequest(new PossibleAdapter<ComputationalValue>(r, ComputationalValue.class), TransientCacheAsyncListener.instance());
6180                 if(cv != null) {
6181                         return cv.getValue(this, r);
6182                 } else {
6183                         // This should not even be possible since L0 defines an adapter for all values
6184                         try {
6185                                 return (T)ReflectionUtils.getValue(getURI(r)).getValue();
6186                         } catch(ValueNotFoundException e) {
6187                                 throw new DatabaseException(e);
6188                         } catch(ClassCastException e) {
6189                                 throw new DatabaseException(e);
6190                         }
6191                 }
6192         }
6193         else {
6194             Function3<ReadGraph,Resource,Object,T> function = requestValueFunction(r);
6195             if(function == null) throw new DoesNotContainValueException("Couldn't convert to a value function.");
6196             try {
6197                 Object value = function.apply(this, r, context);
6198                 if(binding.isInstance(value)) return (T)value;
6199                 Binding srcBinding = Bindings.OBJECT.getContentBinding(value);
6200                 return (T)Bindings.adapt(value, srcBinding, binding);
6201             } catch(RuntimeException e) {
6202                 DatabaseException dte = findPossibleRootException(e);
6203                 if(dte != null) throw dte;
6204                 else throw new DatabaseException(e);
6205             } catch (AdaptException e) {
6206                 throw new DatabaseException(e);
6207                         } catch (org.simantics.databoard.binding.error.BindingException e) {
6208                 throw new DatabaseException(e);
6209                         }
6210         }
6211     }
6212     
6213     @Override
6214     public <T> T getPossibleValue2(Resource subject, Object context, Binding binding) throws DatabaseException {
6215         try {
6216                 return getValue2(subject, context, binding);
6217         } catch (DatabaseException e) {
6218                 return null;
6219         }
6220     }
6221     
6222         private static DatabaseException findPossibleRootException(Throwable t) {
6223                 if(t == null) return null;
6224                 if(t instanceof DatabaseException) return (DatabaseException)t;
6225                 if(t instanceof RuntimeException || t instanceof InvocationTargetException) {
6226                         return findPossibleRootException(t.getCause());
6227                 }
6228                 return null;
6229         }
6230     
6231     @Override
6232     public <T> T getRelatedValue2(Resource subject, Resource relation) throws DatabaseException {
6233         return getRelatedValue2(subject, relation, subject);
6234     }
6235     
6236     @Override
6237     public Variant getRelatedVariantValue2(Resource subject, Resource relation) throws DatabaseException {
6238         return getRelatedVariantValue2(subject, relation, subject);
6239     }
6240     
6241     @Override
6242     public <T> T getPossibleRelatedValue2(Resource subject, Resource relation) throws DatabaseException {
6243         try {
6244                 Resource object = getPossibleObject(subject, relation);
6245                 if(object == null) return null;
6246                 else return getValue2(object, subject);
6247         } catch (DatabaseException e) {
6248                 return null;
6249         }
6250     }
6251
6252     @Override
6253     public <T> T getRelatedValue2(Resource subject, Resource relation, Object context) throws DatabaseException {
6254                 if(Development.DEVELOPMENT) {
6255                         if(Development.<Boolean>getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) {
6256                                 String error = L0Validations.checkValueType(this, subject, relation);
6257                                 if(error != null) {
6258                                         Logger.defaultLogError(new ValidationException(error));
6259                                         throw new ValidationException(error);
6260                                 }
6261                         }
6262                 }
6263         return getValue2(getSingleObject(subject, relation), context);
6264     }
6265     
6266     @Override
6267     public Variant getRelatedVariantValue2(Resource subject, Resource relation, Object context) throws DatabaseException {
6268         if(Development.DEVELOPMENT) {
6269                         if(Development.<Boolean>getProperty(DevelopmentKeys.L0_VALIDATION, Bindings.BOOLEAN)) {
6270                                 String error = L0Validations.checkValueType(this, subject, relation);
6271                                 if(error != null) {
6272                                         Logger.defaultLogError(new ValidationException(error));
6273                                         throw new ValidationException(error);
6274                                 }
6275                         }
6276         }
6277         return getVariantValue2(getSingleObject(subject, relation), context);
6278     }
6279     
6280     @Override
6281     public <T> T getPossibleRelatedValue2(Resource subject, Resource relation, Object context) throws DatabaseException {
6282         try {
6283                 Resource object = getPossibleObject(subject, relation);
6284                 if(object == null) return null;
6285                 else return getValue2(object, context);
6286         } catch (DatabaseException e) {
6287                 return null;
6288         }
6289     }
6290
6291     @Override
6292     public <T> T getRelatedValue2(Resource subject, Resource relation, Binding binding) throws DatabaseException {
6293         return getRelatedValue2(subject, relation, subject, binding);
6294     }
6295     
6296     @Override
6297     public <T> T getPossibleRelatedValue2(Resource subject, Resource relation, Binding binding) throws DatabaseException {
6298         try {
6299                 Resource object = getPossibleObject(subject, relation);
6300                 if(object == null) return null;
6301                 return getValue2(object, subject, binding);
6302         } catch (DatabaseException e) {
6303                 return null;
6304         }
6305     }
6306
6307     @Override
6308     public <T> T getRelatedValue2(Resource subject, Resource relation, Object context, Binding binding) throws DatabaseException {
6309         return getValue2(getSingleObject(subject, relation), context, binding);
6310     }
6311     
6312     @Override
6313     public <T> T getPossibleRelatedValue2(Resource subject, Resource relation, Object context, Binding binding) throws DatabaseException {
6314         try {
6315                 Resource object = getPossibleObject(subject, relation);
6316                 if(object == null) return null;
6317                 else return getValue2(object, context, binding);
6318         } catch (DatabaseException e) {
6319                 return null;
6320         }
6321     }
6322     
6323     @Override
6324     public Type getRelatedValueType(Resource subject, Resource relation) throws DatabaseException {
6325         Layer0 L0 = processor.getL0(this);
6326         Resource property = getSingleObject(subject, relation);
6327         String typeText = (String)getRelatedValue(property, L0.HasValueType, Bindings.STRING);
6328         try {
6329             return org.simantics.scl.compiler.types.Types.parseType(typeText);
6330         } catch (SCLTypeParseException e) {
6331             throw new DatabaseException(e);
6332         }
6333     }
6334
6335     private static ThreadLocal<Boolean> syncGraph = new ThreadLocal<Boolean>() {
6336         protected Boolean initialValue() {
6337             return true;
6338         }
6339     };
6340
6341     @Override
6342     public boolean setSynchronous(boolean value) {
6343         boolean old = getSynchronous();
6344         syncGraph.set(value);
6345         return old;
6346     }
6347
6348     @Override
6349     public boolean getSynchronous() {
6350         return syncGraph.get();
6351     }
6352     
6353     public void ensureLoaded(int resource) {
6354         processor.querySupport.ensureLoaded(this, resource);
6355     }
6356     
6357     public void ensureLoaded(int resource, int predicate) {
6358         processor.querySupport.ensureLoaded(this, resource, predicate);
6359     }
6360
6361     public byte[] getValue(int resource) {
6362         return processor.querySupport.getValue(this, resource);
6363     }
6364     
6365     public int thread(int resource) {
6366         return (resource >>> 16) & processor.THREAD_MASK;
6367     }
6368
6369     public int thread(Resource resource) {
6370         return (((ResourceImpl)resource).id >>> 16) & processor.THREAD_MASK;
6371     }
6372     
6373     public ResourceSupport getResourceSupport() {
6374         return processor.getResourceSupport();
6375     }
6376     
6377     @Override
6378     public Object getModificationCounter() {
6379         return processor.getSession().getModificationCounter();
6380     }
6381
6382     @Override
6383     public boolean performPending() {
6384         return processor.performPending(this);
6385     }
6386     
6387     public Set<ReadGraphImpl> ancestorSet() {
6388         HashSet<ReadGraphImpl> result = new HashSet<>();
6389         ReadGraphImpl g = this;
6390         while(g != null) {
6391             result.add(g);
6392             g = g.parentGraph;
6393         }
6394         return result;
6395     }
6396     
6397     public int getLevel() {
6398         return getLevelStatic(this);
6399     }
6400     
6401     private static int getLevelStatic(ReadGraphImpl impl) {
6402         if(impl == null) return 0;
6403         else return 1 + getLevelStatic(impl.parentGraph);
6404     }
6405     
6406     public boolean isParent(ReadGraphImpl impl) {
6407         if(impl == null) return false;
6408         if(this == impl) return true;
6409         return isParent(impl.parentGraph);
6410     }
6411     
6412     public ReadGraphImpl getTopLevelGraph() {
6413         return getTopLevelGraphStatic(this);
6414     }
6415
6416     private static ReadGraphImpl getTopLevelGraphStatic(ReadGraphImpl impl) {
6417         if(impl.parentGraph == null) return impl;
6418         else return getTopLevelGraphStatic(impl.parentGraph);
6419     }
6420
6421     @SuppressWarnings("unchecked")
6422     @Override
6423     public <T> T l0() {
6424         return (T) processor.getL0();
6425     }
6426
6427 }