]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/function/All.java
Removed jsonValues since there already is Data/Json
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / function / All.java
1 package org.simantics.db.layer0.function;
2
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.Set;
10 import java.util.concurrent.atomic.AtomicReference;
11
12 import org.simantics.databoard.Bindings;
13 import org.simantics.databoard.accessor.reference.ChildReference;
14 import org.simantics.databoard.accessor.reference.IndexReference;
15 import org.simantics.databoard.adapter.AdaptException;
16 import org.simantics.databoard.binding.Binding;
17 import org.simantics.databoard.binding.error.BindingConstructionException;
18 import org.simantics.databoard.binding.error.BindingException;
19 import org.simantics.databoard.binding.mutable.Variant;
20 import org.simantics.databoard.type.ArrayType;
21 import org.simantics.databoard.type.Datatype;
22 import org.simantics.databoard.type.NumberType;
23 import org.simantics.databoard.util.Range;
24 import org.simantics.db.Issue;
25 import org.simantics.db.ReadGraph;
26 import org.simantics.db.Resource;
27 import org.simantics.db.Statement;
28 import org.simantics.db.WriteGraph;
29 import org.simantics.db.common.issue.StandardIssue;
30 import org.simantics.db.common.primitiverequest.PossibleRelatedValueImplied2;
31 import org.simantics.db.common.primitiverequest.PossibleResource;
32 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
33 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
34 import org.simantics.db.common.request.IsEnumeratedValue;
35 import org.simantics.db.common.uri.UnescapedChildMapOfResource;
36 import org.simantics.db.common.utils.CommonDBUtils;
37 import org.simantics.db.common.utils.Functions;
38 import org.simantics.db.common.utils.ListUtils;
39 import org.simantics.db.common.utils.Logger;
40 import org.simantics.db.common.utils.NameUtils;
41 import org.simantics.db.common.validation.L0Validations;
42 import org.simantics.db.exception.DatabaseException;
43 import org.simantics.db.exception.DoesNotContainValueException;
44 import org.simantics.db.exception.NoSingleResultException;
45 import org.simantics.db.exception.RuntimeDatabaseException;
46 import org.simantics.db.layer0.exception.MissingVariableValueException;
47 import org.simantics.db.layer0.exception.PendingVariableException;
48 import org.simantics.db.layer0.exception.VariableException;
49 import org.simantics.db.layer0.request.PossibleURI;
50 import org.simantics.db.layer0.request.PropertyInfo;
51 import org.simantics.db.layer0.request.PropertyInfoRequest;
52 import org.simantics.db.layer0.request.UnescapedAssertedPropertyMapOfResource;
53 import org.simantics.db.layer0.request.UnescapedMethodMapOfResource;
54 import org.simantics.db.layer0.request.UnescapedPropertyMapOfResource;
55 import org.simantics.db.layer0.scl.CompileResourceValueRequest;
56 import org.simantics.db.layer0.scl.CompileValueRequest;
57 import org.simantics.db.layer0.util.Layer0Utils;
58 import org.simantics.db.layer0.util.PrimitiveValueParser;
59 import org.simantics.db.layer0.variable.AbstractVariable;
60 import org.simantics.db.layer0.variable.ChildVariableMapRequest;
61 import org.simantics.db.layer0.variable.ExternalSetValue;
62 import org.simantics.db.layer0.variable.PropertyVariableMapRequest;
63 import org.simantics.db.layer0.variable.StandardAssertedGraphPropertyVariable;
64 import org.simantics.db.layer0.variable.StandardComposedProperty;
65 import org.simantics.db.layer0.variable.StandardGraphChildVariable;
66 import org.simantics.db.layer0.variable.StandardGraphPropertyVariable;
67 import org.simantics.db.layer0.variable.SubliteralPropertyVariable;
68 import org.simantics.db.layer0.variable.SubliteralPropertyVariableDeprecated;
69 import org.simantics.db.layer0.variable.ValueAccessor;
70 import org.simantics.db.layer0.variable.Variable;
71 import org.simantics.db.layer0.variable.VariableBuilder;
72 import org.simantics.db.layer0.variable.VariableMap;
73 import org.simantics.db.layer0.variable.VariableMapImpl;
74 import org.simantics.db.layer0.variable.VariableNode;
75 import org.simantics.db.layer0.variable.VariableNodeReadRunnable;
76 import org.simantics.db.layer0.variable.VariableUtils;
77 import org.simantics.db.layer0.variable.Variables;
78 import org.simantics.db.layer0.variable.Variables.NodeStructure;
79 import org.simantics.db.service.ClusteringSupport;
80 import org.simantics.db.service.UndoRedoSupport;
81 import org.simantics.issues.ontology.IssueResource;
82 import org.simantics.layer0.Layer0;
83 import org.simantics.scl.reflection.annotations.SCLValue;
84 import org.simantics.scl.runtime.SCLContext;
85 import org.simantics.scl.runtime.function.Function4;
86 import org.simantics.scl.runtime.function.FunctionImpl1;
87 import org.simantics.scl.runtime.function.FunctionImpl2;
88 import org.simantics.simulator.variable.exceptions.NodeManagerException;
89 import org.simantics.utils.Development;
90 import org.simantics.utils.datastructures.Pair;
91 import org.simantics.utils.strings.StringInputValidator;
92
93 import gnu.trove.map.hash.THashMap;
94 import gnu.trove.set.hash.THashSet;
95
96 public class All {
97
98         public static Object standardGetValue1(ReadGraph graph, Variable context) throws DatabaseException {
99
100                 StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context;
101
102         // First from node
103         if(variable.node != null) {
104             Variant value = Variables.requestNodeValue(graph, variable.node);
105             if(Variables.PENDING_NODE_VALUE == value) throw new PendingVariableException("");
106             return value.getValue();
107         }
108                 
109                 try {
110
111             if(variable.property.hasEnumerationRange) {
112                         Resource object = variable.getRepresents(graph);
113                                 if(graph.sync(new IsEnumeratedValue(object))) {
114                             Layer0 L0 = Layer0.getInstance(graph);
115                                         if(graph.isInstanceOf(object, L0.Literal)) {
116                                                 return graph.getValue(object);
117                                         } else {
118                                                 String label = graph.getPossibleRelatedValue2(variable.getRepresents(graph), L0.HasLabel, Bindings.STRING);
119                                                 if(label == null) label = graph.getPossibleRelatedValue(variable.getRepresents(graph), L0.HasName, Bindings.STRING);
120                                                 if(label == null) label = "<no label>";
121                                                 return label;
122                                         }
123                                 }
124             }
125                         
126             if (variable.isAsserted()) {
127                                 if (variable.parentResource != null) {
128                                         Map<String, Pair<PropertyInfo, Resource>> assertions = graph.syncRequest(
129                                                         new UnescapedAssertedPropertyMapOfResource(variable.parentResource),
130                                                         TransientCacheAsyncListener.instance());
131
132                                         // NOTE: This optimization assumes the property
133                                         // variable's representation is the asserted object.
134                                         Resource object = variable.getPossibleRepresents(graph);
135                                         if (object != null) {
136                                                 return graph.getValue2(object, variable);
137                                         } else {
138                                                 for (Pair<PropertyInfo, Resource> assertion : assertions.values()) {
139                                                         if (assertion.first.predicate.equals(variable.property.predicate)) {
140                                                                 return graph.getValue2(assertion.second, variable);
141                                                         }
142                                                 }
143                                         }
144                                 }
145             }
146                 
147                         return graph.getValue2(variable.getRepresents(graph), variable);
148                         
149                 } catch (NoSingleResultException e) {
150                         throw new MissingVariableValueException(variable.getPossibleURI(graph), e);
151                 } catch (DoesNotContainValueException e) {
152                         throw new MissingVariableValueException(variable.getPossibleURI(graph), e);
153                 } catch (DatabaseException e) {
154                         throw new MissingVariableValueException(variable.getPossibleURI(graph), e);
155                 }
156
157         }
158         
159         public static Object standardGetValue2(ReadGraph graph, Variable context, Binding binding) throws DatabaseException {           
160                 StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context;
161
162         // First from node
163         if(variable.node != null) {
164             try {
165                 Variant value = Variables.requestNodeValue(graph, variable.node, binding);
166                 if(Variables.PENDING_NODE_VALUE == value) throw new PendingVariableException("");
167                 if(value == null) throw new MissingVariableValueException(variable.getPossibleURI(graph));
168                 return value.getValue(binding);
169             } catch (AdaptException e) {
170                 throw new DatabaseException(e);
171             }
172         }
173                 
174         try {
175                         
176                 if(variable.property.hasEnumerationRange) {
177                 Resource object = variable.getRepresents(graph);
178                 if(graph.sync(new IsEnumeratedValue(object))) {
179                         Layer0 L0 = Layer0.getInstance(graph);
180                         if(graph.isInstanceOf(object, L0.Literal)) {
181                                 return graph.getValue(object, binding);
182                         } else {
183                                 return graph.getRelatedValue2(variable.getRepresents(graph), L0.HasLabel, binding);
184                         }
185                 }
186             }
187                         
188                 if (variable.isAsserted()) {
189                         if (variable.parentResource != null) {
190                                         Map<String, Pair<PropertyInfo, Resource>> assertions = graph.syncRequest(
191                                                         new UnescapedAssertedPropertyMapOfResource(variable.parentResource),
192                                                         TransientCacheAsyncListener.instance());
193
194                                         // NOTE: This optimization assumes the property
195                                         // variable's representation is the asserted object.
196                                         Resource object = variable.getPossibleRepresents(graph);
197                                         if (object != null) {
198                                                 return graph.getValue2(object, variable, binding);
199                                         } else {
200                                                 for (Pair<PropertyInfo, Resource> assertion : assertions.values()) {
201                                                         if (assertion.first.predicate.equals(variable.property.predicate)) {
202                                                                 return graph.getValue2(assertion.second, variable, binding);
203                                                         }
204                                                 }
205                                         }
206                         }
207                 }
208                         
209                         return graph.getValue2(variable.getRepresents(graph), context, binding);
210                         
211                 } catch (NoSingleResultException e) {
212                         throw new MissingVariableValueException(variable.getPossibleURI(graph));
213                 } catch (DoesNotContainValueException e) {
214                         throw new MissingVariableValueException(variable.getPossibleURI(graph));
215                 } catch (DatabaseException e) {
216                         throw new MissingVariableValueException(variable.getPossibleURI(graph), e);
217                 }
218
219         }
220
221         public static void standardSetValue2(WriteGraph graph, Variable context, final Object value) throws DatabaseException {
222                 
223             if(context instanceof StandardGraphPropertyVariable) {
224
225                 final StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context; 
226                 
227                 // First from node
228             if(variable.node != null) {
229
230                 final Binding binding = Layer0Utils.getDefaultBinding(graph, variable);
231
232                 final AtomicReference<Object> oldValueRef = new AtomicReference<Object>();
233                 try {
234                     variable.node.support.manager.getRealm().syncExec(new Runnable() {
235                         @Override
236                         public void run() {
237                             try {
238                                 oldValueRef.set(getNodeValue(variable, binding));
239                                 setNodeValue(variable, value, binding);
240                             } catch (NodeManagerException e) {
241                                 throw new RuntimeException(e);
242                             } catch (BindingException e) {
243                                     throw new RuntimeException(e);
244                                 }
245                         }
246                     });
247                 } catch(RuntimeException e) {
248                     if(e.getCause() instanceof NodeManagerException || e.getCause() instanceof BindingException)
249                         throw new DatabaseException(e.getCause());
250                     else
251                         throw e;
252                 } catch (InterruptedException e) {
253                     throw new DatabaseException(e);
254                 }
255
256                 ExternalSetValue ext = new ExternalSetValue(variable.node.support.manager, variable.node.node,
257                         oldValueRef.get(), value, binding);
258                 graph.getService(UndoRedoSupport.class).addExternalOperation(graph, ext);
259
260                 return;
261             }
262                 
263             }
264             
265                 Function4<WriteGraph, Variable, Object, Object, String> modifier = context.getPossiblePropertyValue(graph, Variables.INPUT_MODIFIER);
266                 if(modifier == null) modifier = VariableUtils.defaultInputModifier; 
267                 try {
268                         modifier.apply(graph, context, value, Bindings.getBinding(value.getClass()));
269                 } catch (BindingConstructionException e) {
270                         throw new DatabaseException(e);
271                 }
272
273         }
274
275         public static void standardSetValue3(final WriteGraph graph, Variable context, final Object value, final Binding binding) throws DatabaseException {
276
277         // First from node
278         if(context instanceof StandardGraphPropertyVariable) {
279
280             final StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context; 
281             
282             // First from node
283             if(variable.node != null) {
284                 
285                 try {
286                     
287                     variable.node.support.manager.getRealm().syncExec(new Runnable() {
288
289                         @Override
290                         public void run() {
291                             try {
292                                 Object oldValue = getNodeValue(variable, binding);
293                                 setNodeValue(variable, value, binding);
294                                 ExternalSetValue ext = new ExternalSetValue(variable.node.support.manager, variable.node.node, oldValue, value, binding);
295                                 graph.getService(UndoRedoSupport.class).addExternalOperation(graph, ext);
296                             } catch (NodeManagerException | BindingException e) {
297                                 Logger.defaultLogError(e);
298                             }
299                         }
300
301                         
302                     });
303                     
304                     return;
305                     
306                 } catch (InterruptedException e) {
307                     throw new DatabaseException(e);
308                 }
309                 
310             }
311             
312         }
313             
314                 Function4<WriteGraph, Variable, Object, Object, String> modifier = context.getPossiblePropertyValue(graph, Variables.INPUT_MODIFIER);
315                 if(modifier == null) modifier = VariableUtils.defaultInputModifier; 
316                 modifier.apply(graph, context, value, binding);
317
318         }
319
320         public static Datatype getDatatypeFromValue(ReadGraph graph, Variable context) throws DatabaseException {
321                 if (context instanceof AbstractVariable) {
322                         Binding defaultBinding = ((AbstractVariable)context).getPossibleDefaultBinding(graph);
323                         if (defaultBinding != null)
324                                 return defaultBinding.type();
325                 }
326                         
327         Variant value = context.getVariantValue(graph);
328         if (value.getBinding() == null)
329                 throw new DatabaseException("No value binding for " + context.getURI(graph));
330         
331         return value.getBinding().type();
332         }
333
334     @SuppressWarnings("rawtypes")
335     private static class DatatypeGetter implements VariableNodeReadRunnable {
336         final VariableNode node;
337         Datatype type;
338         Exception exception;
339
340         public DatatypeGetter(VariableNode node) {
341             this.node = node;
342         }
343
344         @SuppressWarnings("unchecked")
345         @Override
346         public void run() {
347             try {
348                 type = node.support.manager.getDatatype(node.node);
349             } catch (NodeManagerException e) {
350                 exception = e;
351             }
352         }
353         @Override
354         public String toString() {
355             return "DatatypeGetter(" + node.node + ")";
356         }
357     }
358
359     public static Datatype standardGetDatatype(ReadGraph graph, Variable context) throws DatabaseException {
360         if (context instanceof AbstractVariable) {
361                 final AbstractVariable variable = (AbstractVariable)context;
362                 if (variable.node != null) {
363                         try {
364                                 DatatypeGetter request = new DatatypeGetter(variable.node);
365                                 
366                                         variable.node.support.manager.getRealm().syncExec(request);
367                                         
368                                         if (request.exception != null)
369                                                 throw new DatabaseException(request.exception);
370                                         
371                                         return request.type;
372                                 } catch (InterruptedException e) {
373                                 }
374                 }
375         }
376         
377         return getDatatypeFromValue(graph, context);
378         }
379
380 //      @SCLValue(type = "ValueAccessor")
381 //      public static ValueAccessor standardValueAccessor = new ValueAccessor() {
382 //
383 //              @Override
384 //              public Object getValue(ReadGraph graph, Variable context) throws DatabaseException {
385 //                      return standardGetValue(graph, (StandardGraphPropertyVariable)context);
386 //              }
387 //
388 //              @Override
389 //              public Object getValue(ReadGraph graph, Variable context, Binding binding) throws DatabaseException {
390 //                      return standardGetValue(graph, context, binding);
391 //              }
392 //
393 //              @Override
394 //              public void setValue(WriteGraph graph, Variable context, Object value) throws DatabaseException {
395 //                      standardSetValue(graph, context, value);
396 //              }
397 //
398 //              @Override
399 //              public void setValue(WriteGraph graph, Variable context, Object value, Binding binding) throws DatabaseException {
400 //                      standardSetValue(graph, context, value, binding);
401 //              }
402 //
403 //              @Override
404 //              public Datatype getDatatype(ReadGraph graph, Variable context) throws DatabaseException {
405 //                      return standardGetDatatype(graph, context);
406 //              }
407 //              
408 //      };
409         
410         @SCLValue(type = "ValueAccessor")
411         public static ValueAccessor standardValueAccessor = new ValueAccessor() {
412
413                 @Override
414                 public Object getValue(ReadGraph graph, Variable context) throws DatabaseException {
415                         ValueAccessor accessor = getPossibleValueValueAccessor(graph, context);
416                         if(accessor != null) return accessor.getValue(graph, context);
417                         else 
418                                 return standardGetValue1(graph, context);
419                 }
420
421                 @Override
422                 public Object getValue(ReadGraph graph, Variable context, Binding binding) throws DatabaseException {
423                         ValueAccessor accessor = getPossibleValueValueAccessor(graph, context);
424                         if(accessor != null) return accessor.getValue(graph, context, binding);
425                         else 
426                                 return standardGetValue2(graph, context, binding);
427                 }
428
429                 @Override
430                 public void setValue(WriteGraph graph, Variable context, Object value) throws DatabaseException {
431                         ValueAccessor accessor = getPossibleValueValueAccessor(graph, context);
432                         if(accessor != null) accessor.setValue(graph, context, value);
433                         else 
434                                 standardSetValue2(graph, context, value);
435                 }
436
437                 @Override
438                 public void setValue(WriteGraph graph, Variable context, Object value, Binding binding) throws DatabaseException {
439                         ValueAccessor accessor = getPossibleValueValueAccessor(graph, context);
440                         if(accessor != null) accessor.setValue(graph, context, value, binding);
441                         else 
442                                 standardSetValue3(graph, context, value, binding);
443                 }
444
445                 @Override
446                 public Datatype getDatatype(ReadGraph graph, Variable context)
447                                 throws DatabaseException {
448                         ValueAccessor accessor = getPossibleValueValueAccessor(graph, context);
449                         if(accessor != null) return accessor.getDatatype(graph, context);
450                         else 
451                                 return standardGetDatatype(graph, context);
452                 }
453                 
454         };
455
456         public static Variable getStandardChildDomainPropertyVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
457         StandardGraphChildVariable variable = (StandardGraphChildVariable)context;
458         PropertyInfo graphProperty = getPossiblePropertyInfoFromContext(graph, variable, variable.resource, name);
459         return getStandardChildDomainPropertyVariable(graph, context, graphProperty, name);
460     }
461
462     public static Resource getPossiblePropertyResource(ReadGraph graph, AbstractVariable parent, Object node) throws DatabaseException {
463         if(parent != null && parent.node != null && parent.node.node != null && parent.node.support != null) {
464             String propertyURI = getPossiblePropertyURI(parent, node);
465             if(propertyURI != null)
466                 return graph.getPossibleResource(propertyURI);
467         }
468         return null;
469     }
470
471         public static Variable getStandardChildDomainPropertyVariable(ReadGraph graph, Variable context, PropertyInfo graphProperty, String name) throws DatabaseException {
472         StandardGraphChildVariable variable = (StandardGraphChildVariable)context;
473         Object propertyNode = getPossibleNodeProperty(graph, variable, name, true);
474         if(graphProperty != null && graphProperty.builder != null)
475             return buildPropertyVariable(graph, variable, variable.resource, graphProperty, propertyNode);
476         if(propertyNode != null) {
477             // Fallback: try to ask property resource uri from NodeManager
478             return createStandardGraphPropertyVariable(graph, variable, propertyNode);
479         }
480         // Final fallback: check types corresponding to
481         // node classification(s) and look for asserted
482         // properties from the URIs specified.
483         if (variable.node != null) {
484             try {
485                 @SuppressWarnings("unchecked")
486                 Set<String> classifications = variable.node.support.manager.getClassifications(variable.node.node);
487                 if (!classifications.isEmpty()) {
488                     for (String uri : classifications) {
489                         Resource type = graph.syncRequest(
490                                 new PossibleResource(uri),
491                                 TransientCacheAsyncListener.instance());
492                         if (type == null)
493                             continue;
494                         Map<String, Pair<PropertyInfo, Resource>> pm = graph.syncRequest(
495                                 new UnescapedAssertedPropertyMapOfResource(type),
496                                 TransientCacheAsyncListener.instance());
497                         Pair<PropertyInfo, Resource> pi = pm.get(name);
498                         if (pi != null) {
499                             return new StandardAssertedGraphPropertyVariable(graph, context, null, type, pi.first.predicate, pi.second);
500                         }
501                     }
502                 }
503             } catch(NodeManagerException e) {
504                 throw new DatabaseException(e);
505             }
506         }
507         return null;
508     }
509
510     public static Map<String, Variable> getStandardChildDomainPropertyVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
511         // Get properties with null identification
512         return getStandardChildDomainPropertyVariables(graph, context, null, map);
513     }
514
515     public static Map<String, Variable> getStandardChildDomainPropertyVariables(ReadGraph graph, Variable context, String classification, Map<String, Variable> map) throws DatabaseException {
516         
517         StandardGraphChildVariable variable = (StandardGraphChildVariable)context;
518         
519         Collection<Object> nodeProperties = getPossibleNodeProperties(graph, variable);
520         if(!nodeProperties.isEmpty()) {
521
522             // Get variables for properties read from the graph
523             Map<String,PropertyInfo> graphProperties = collectPropertyInfosFromContext(graph, variable, variable.resource);
524             
525             Set<String> used = new THashSet<String>(nodeProperties.size());
526             
527             map = ensureVariableMap(map, graphProperties.size() + nodeProperties.size());
528             
529             // Process NodeManager property nodes
530             for(Object nodeProperty : nodeProperties) {
531                 String name = getNodeName(variable, nodeProperty);
532                 used.add(name);
533                 
534                 PropertyInfo graphProperty = graphProperties.get(name); 
535                 if(graphProperty != null && graphProperty.builder != null) {
536                     if (classification != null && !graphProperty.hasClassification(classification)) continue;
537                     
538                     // Combine with identically named graph property
539                     map.put(name, buildPropertyVariable(graph, variable, variable.resource, graphProperty, nodeProperty));
540                     continue;
541                 }
542                 
543                 map.put(name, createStandardGraphPropertyVariable(graph, variable, nodeProperty));
544             }
545             
546             // Process graph properties
547             for(PropertyInfo info : graphProperties.values()) {
548                 String name = info.name;
549                 if(used != null && used.contains(name)) continue;
550                 if (classification != null && !info.hasClassification(classification)) continue;
551                 if (info.builder != null) {
552                     map.put(name, buildPropertyVariable(graph, variable, variable.resource, info, null));
553                 }
554             }
555             return map;
556                 
557         } else {
558
559                 if(variable.resource == null) return map;
560
561                 // Only graph properties
562                 Collection<Resource> predicates = graph.getPredicates(variable.resource);
563                 if(predicates.isEmpty()) return map;
564                 
565                 map = ensureVariableMap(map, predicates.size());
566                 
567             // Process graph properties
568             for(Resource predicate : predicates) {
569                 
570                         PropertyInfo info = graph.isImmutable(predicate) ?
571                                         graph.syncRequest(new PropertyInfoRequest(predicate), TransientCacheAsyncListener.<PropertyInfo>instance()) :
572                                                 graph.syncRequest(new PropertyInfoRequest(predicate));
573
574                         if(!info.isHasProperty) continue;
575                                         
576                 if (classification != null && !info.hasClassification(classification)) continue;
577                 if (info.builder != null) {
578                     map.put(info.name, buildPropertyVariable(graph, variable, variable.resource, info, null));
579                 }
580                 
581             }
582             
583             return map;
584                 
585         }
586         
587      }
588         
589     @SCLValue(type = "VariableMap")
590         public static VariableMap standardChildDomainProperties = new VariableMapImpl() {
591         
592                 @Override
593                 public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
594                 return getStandardChildDomainPropertyVariable(graph, context, name);
595                 }
596
597                 @Override
598                 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
599                     return getStandardChildDomainPropertyVariables(graph, context, map);
600                 }
601                 
602         };
603         
604     @SCLValue(type = "VariableMap")
605         public static VariableMap methodsPropertyDomainProperties = new VariableMapImpl() {
606         
607                 @Override
608                 public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
609                         Variable parent = context.getParent(graph);
610                         Resource container = parent.getPossibleRepresents(graph);
611                         Map<String,Resource> methods = graph.syncRequest(new UnescapedMethodMapOfResource(container));
612                         Resource predicate = methods.get(name);
613                         if(predicate != null) {
614                                 Layer0 L0 = Layer0.getInstance(graph);
615                                 PropertyInfo info = graph.syncRequest(new PropertyInfoRequest(L0.Entity_method));
616                                 Resource value = graph.getSingleObject(container, predicate);
617                                 return new StandardGraphPropertyVariable(context, null, container, info, value);
618                         }
619                         return null;
620                 }
621
622                 @Override
623                 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
624                         Variable parent = context.getParent(graph);
625                         Resource container = parent.getPossibleRepresents(graph);
626                         Map<String,Resource> methods = graph.syncRequest(new UnescapedMethodMapOfResource(container));
627                         for(Map.Entry<String, Resource> entry : methods.entrySet()) {
628                                 String name = entry.getKey();
629                                 Resource predicate = entry.getValue();
630                                 Layer0 L0 = Layer0.getInstance(graph);
631                                 PropertyInfo info = graph.syncRequest(new PropertyInfoRequest(L0.Entity_method));
632                                 Resource value = graph.getSingleObject(container, predicate);
633                                 if(map == null) map = new HashMap<>();
634                                 map.put(name, new StandardGraphPropertyVariable(context, null, container, info, value));
635                         }
636                         return map;
637                 }
638                 
639         };
640
641         public static Variable getStandardPropertyDomainPropertyVariableFromValue(ReadGraph graph, Variable context, String name) throws DatabaseException {
642
643                 if(context instanceof StandardGraphPropertyVariable) {
644                 StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context;
645                 Resource literal = variable.getPossibleRepresents(graph);
646                 Object propertyNode = getPossibleNodeProperty(graph, variable, name, false);
647
648                 if(literal != null) {
649                         Variable result = getPossiblePropertyFromContext(graph, variable, literal, name, propertyNode);
650                         if(result != null) return result;
651                 }
652                 
653                 Variable result = getPossibleSubliteralPropertyFromContext(graph, variable, name);
654                 if(result != null) return result;
655                 result = getPossiblePropertyFromContext(graph, variable, variable.property.predicate, name, propertyNode);
656                 if (result != null) return result;
657                 
658                 // Get possible property from NodeManager
659                 if (propertyNode != null)
660                         return createStandardGraphPropertyVariable(graph, variable, propertyNode);
661                 return null;
662                 } else if (context instanceof StandardGraphChildVariable) {
663                         return standardChildDomainProperties.getVariable(graph, context, name);
664                 } else {
665                         throw new DatabaseException("Unknown variable implementation " + context.getClass().getCanonicalName());
666                 }                       
667                 
668         }
669         
670         public static Map<String, Variable> getStandardPropertyDomainPropertyVariablesFromValue(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
671
672                 if(context instanceof StandardGraphPropertyVariable) {
673                         StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context;
674                         map = collectPropertiesFromContext(graph, variable, variable.property.predicate, map);
675                         if (variable.parentResource != null) {
676                                 Resource literal = graph.getPossibleObject(variable.parentResource, variable.property.predicate);
677                                 if(literal != null) map=collectPropertiesFromContext(graph, variable, literal, map);
678                                 map=collectSubliteralProperties(graph, variable, map);
679                         }
680
681                         // Get properties from VariableNode
682                         map = getStandardNodePropertyVariables(graph, context, map);
683                         return map;
684                 } else if (context instanceof StandardGraphChildVariable) {
685                         return standardChildDomainProperties.getVariables(graph, context, map);
686                 } else {
687                         throw new DatabaseException("Unknown variable implementation " + context.getClass().getCanonicalName());
688                 }
689                 
690         }
691         
692         public static Map<String, Variable> getStandardPropertyDomainPropertyVariablesFromValue(ReadGraph graph, Variable context, String classification, Map<String, Variable> map) throws DatabaseException {
693
694                 if(context instanceof StandardGraphPropertyVariable) {
695                         StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context;
696                         map = collectPropertiesFromContext(graph, variable, variable.property.predicate, classification, map);
697                         if (variable.parentResource != null) {
698                                 Resource literal = graph.getPossibleObject(variable.parentResource, variable.property.predicate);
699                                 if(literal != null) map=collectPropertiesFromContext(graph, variable, literal, classification, map);
700                         }
701                         
702                         // Get properties from VariableNode
703                         map = getStandardNodePropertyVariables(graph, context, map);
704                         return map;
705                 } else if (context instanceof StandardGraphChildVariable) {
706                         return standardChildDomainProperties.getVariables(graph, context, map);
707                 } else {
708                         throw new DatabaseException("Unknown variable implementation " + context.getClass().getCanonicalName());
709                 }       
710                 
711         }       
712         
713     @SCLValue(type = "VariableMap")
714         public static VariableMap standardPropertyDomainProperties = new VariableMapImpl() {
715
716         VariableMap getValueVariableMap(ReadGraph graph, Variable context) throws DatabaseException {
717                 Resource represents = context.getPossibleRepresents(graph);
718                 if(represents == null) return null;
719                 
720                 VariableMap map = graph.isImmutable(represents) ?
721                                 graph.syncRequest(new PropertyVariableMapRequest(represents), TransientCacheListener.<VariableMap>instance()) :
722                                         (VariableMap)graph.getPossibleRelatedValue2(represents, Layer0.getInstance(graph).domainProperties, represents);
723                 
724                 if(map == standardPropertyDomainProperties) return null;
725                 else return map;
726                 
727         }
728         
729                 @Override
730                 public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
731                         VariableMap valueMap = getValueVariableMap(graph, context);
732                         if(valueMap != null) return valueMap.getVariable(graph, context, name);
733                         return getStandardPropertyDomainPropertyVariableFromValue(graph, context, name);
734                 }
735
736                 @Override
737                 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
738                         VariableMap valueMap = getValueVariableMap(graph, context);
739                         if(valueMap != null) return valueMap.getVariables(graph, context, map);
740                         else return getStandardPropertyDomainPropertyVariablesFromValue(graph, context, map);
741                 }
742                 
743                 @Override
744                 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, String classification, Map<String, Variable> map) throws DatabaseException {
745                         VariableMap valueMap = getValueVariableMap(graph, context);
746                         if(valueMap != null) return valueMap.getVariables(graph, context, classification, map);
747                         else return getStandardPropertyDomainPropertyVariablesFromValue(graph, context, classification, map);
748                 }
749                 
750         };
751
752     public static Resource getPossibleGraphChild(ReadGraph graph, Variable variable, String name) throws DatabaseException {
753         Resource resource = variable.getPossibleRepresents(graph);
754         if(resource == null) return null;
755         Map<String, Resource> graphChildren = graph.syncRequest(new UnescapedChildMapOfResource(resource));
756         return graphChildren.get(name);
757     }
758
759     public static Map<String,Resource> getPossibleGraphChildren(ReadGraph graph, Variable variable) throws DatabaseException {
760         Resource resource = variable.getPossibleRepresents(graph);
761         if(resource == null) return Collections.emptyMap();
762         return graph.syncRequest(new UnescapedChildMapOfResource(resource));
763     }
764
765     public static Object getPossibleNodeChild(ReadGraph graph, Variable variable, String name) throws DatabaseException {
766         if (!(variable instanceof AbstractVariable)) return null;
767         VariableNode<?> node = ((AbstractVariable)variable).node;
768         if(node == null) return null;
769         NodeStructure structure = Variables.requestNodeStructure(graph, node);
770         if(Variables.PENDING_NODE_STRUCTURE == structure) throw new PendingVariableException("");
771         return structure.children.get(name);
772         }
773         
774     public static Collection<Object> getPossibleNodeChildren(ReadGraph graph, Variable variable) throws DatabaseException {
775         if (!(variable instanceof AbstractVariable)) return null;
776         VariableNode<?> node = ((AbstractVariable)variable).node;
777         if(node == null) return Collections.emptyList();
778         NodeStructure structure = Variables.requestNodeStructure(graph, node);
779         if(Variables.PENDING_NODE_STRUCTURE == structure) throw new PendingVariableException("");
780         return structure.children.values();
781     }
782     
783     public static Object getPossibleNodeProperty(ReadGraph graph, Variable variable, String name, boolean throwPending) throws DatabaseException {
784         if (!(variable instanceof AbstractVariable)) return null;
785         VariableNode<?> node = ((AbstractVariable)variable).node;
786         if(node == null) return null;
787         NodeStructure structure = Variables.requestNodeStructure(graph, node);
788         if(throwPending && Variables.PENDING_NODE_STRUCTURE == structure) throw new PendingVariableException("");
789         return structure.properties.get(name);
790     }
791     
792     public static Collection<Object> getPossibleNodeProperties(ReadGraph graph, Variable variable) throws DatabaseException {
793         if (!(variable instanceof AbstractVariable)) return null;
794         VariableNode<?> node = ((AbstractVariable)variable).node;
795         if(node == null) return Collections.emptyList();
796         NodeStructure structure = Variables.requestNodeStructure(graph, node);
797         if(Variables.PENDING_NODE_STRUCTURE == structure) throw new PendingVariableException("");
798         return structure.properties.values();
799     }
800
801     @SuppressWarnings({ "rawtypes", "unchecked" })
802     public static VariableNode build(VariableNode parent, Object node) {
803         if(node == null) return null;
804         return new VariableNode(parent.support, node);
805     }
806
807     @Deprecated
808     public static Variable getStandardChildDomainChildVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
809         return StandardChildDomainChildren.getStandardChildDomainChildVariable(graph, context, name);
810     }
811
812     @Deprecated
813     public static Variable getStandardChildDomainChildVariable(ReadGraph graph, Variable context, Resource graphChild, String name) throws DatabaseException {
814         return StandardChildDomainChildren.getStandardChildDomainChildVariable(graph, context, graphChild, name);
815     }
816         
817     @Deprecated
818     public static Map<String, Variable> getStandardChildDomainChildVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
819         return StandardChildDomainChildren.getStandardChildDomainChildVariables(graph, context, map);
820     }
821
822     @Deprecated
823     public static Map<String, Variable> getStandardChildDomainChildVariables(ReadGraph graph, Variable context, Map<String,Resource> graphChildren, Map<String, Variable> map) throws DatabaseException {
824         return StandardChildDomainChildren.getStandardChildDomainChildVariables(graph, context, graphChildren, map);
825     }
826     
827     /**
828      * Get a map of child Variables from a node manager-based Variable, combined with the existing variables in #map.
829      * @param graph  The read graph.
830      * @param context  The parent Variable.
831      * @param map  A map of variables into which the new variables are merged.
832      * @return  A map from variable names to instances
833      * @throws DatabaseException
834      */
835     public static Map<String, Variable> getStandardNodeChildVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
836         AbstractVariable variable = (AbstractVariable)context;
837         if (variable.node == null) return map;
838         
839         Collection<Object> nodeChildren = getPossibleNodeChildren(graph, variable);
840         if (nodeChildren.isEmpty()) return map;
841         
842         map = ensureVariableMap(map, nodeChildren.size());
843
844         for(Object nodeChild : nodeChildren) {
845             String name = getNodeName(variable, nodeChild);
846             if (!map.containsKey(name))
847                 map.put(name, createStandardGraphChildVariable(variable, nodeChild));
848         }
849
850         return map;
851     }
852
853     /**
854      * Get a map of property Variables from a node manager-based Variable, combined with the existing variables in #map.
855      * @param graph  The read graph.
856      * @param context  The parent Variable.
857      * @param map  A map of variables into which the new variables are merged.
858      * @return  A map from variable names to instances
859      * @throws DatabaseException
860      */
861     public static Map<String, Variable> getStandardNodePropertyVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
862         AbstractVariable variable = (AbstractVariable)context;
863         if (variable.node == null) return map;
864         
865         Collection<Object> nodeProperties = getPossibleNodeProperties(graph, variable);
866         if (nodeProperties.isEmpty()) return map;
867         
868         map = ensureVariableMap(map, nodeProperties.size());
869
870         for(Object nodeProperty : nodeProperties) {
871             String name = getNodeName(variable, nodeProperty);
872             if (!map.containsKey(name)) {
873                 map.put(name, createStandardGraphPropertyVariable(graph, variable, nodeProperty));
874             }
875         }
876
877         return map;
878     }    
879
880         @SCLValue(type = "VariableMap")
881         public static VariableMap standardChildDomainChildren = new VariableMapImpl() {
882
883                 @Override
884                 public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
885                         return StandardChildDomainChildren.getStandardChildDomainChildVariable(graph, context, name);
886                 }
887
888                 @Override
889                 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
890                     return StandardChildDomainChildren.getStandardChildDomainChildVariables(graph, context, map);
891                 }
892                 
893         };
894
895     @SCLValue(type = "VariableMap")
896         public static VariableMap standardPropertyDomainChildren = new VariableMapImpl() {
897
898         /**
899          * Get a possible non-standard VariableMap defined in the graph.
900          * @param graph  The graph
901          * @param context  The context node
902          * @return  A non-standard VariableMap instance for the context node,
903          *          or null, if not defined or defined as this instance.
904          * @throws DatabaseException
905          */
906         VariableMap getValueVariableMap(ReadGraph graph, Variable context) throws DatabaseException {
907                 Resource represents = context.getPossibleRepresents(graph);
908                 if(represents == null) return null;
909                         VariableMap map = graph.syncRequest(new ChildVariableMapRequest(represents));
910                 if(map == standardPropertyDomainChildren) return null;
911                 else return map;
912         }
913         
914                 @Override
915                 public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
916                         // Delegate call to a non-standard variable map?
917                         VariableMap valueMap = getValueVariableMap(graph, context);
918                         if(valueMap != null) return valueMap.getVariable(graph, context, name);
919                         
920                         if(context instanceof StandardGraphPropertyVariable) {
921                                 StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context;
922                                 Datatype dt = variable.getDatatype(graph);
923                                 if (dt instanceof ArrayType) {
924                                         ChildReference ref = getPossibleIndexReference(name);
925                                         if (ref != null)
926                                                 return new SubliteralPropertyVariableDeprecated(variable, ref);
927                                 }
928                                 
929                                 // Check for a child node provided by the NodeManager
930                                 if (variable.node != null) {
931                                         Object childNode = getPossibleNodeChild(graph, variable, name);
932                                         if (childNode != null)
933                                                 return createStandardGraphChildVariable(variable, childNode);
934                                 }
935                                 return standardChildDomainChildren.getVariable(graph, context, name);
936                         } else if (context instanceof StandardGraphChildVariable) {
937                                 return standardChildDomainChildren.getVariable(graph, context, name);
938                         } else {
939                                 throw new DatabaseException("Unknown variable implementation " + context.getClass().getCanonicalName());
940                         }
941                 }
942
943                 @Override
944                 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
945                         // Delegate call to a non-standard variable map?
946                         VariableMap valueMap = getValueVariableMap(graph, context);
947                         if(valueMap != null) return valueMap.getVariables(graph, context, map);
948                         
949                         if(context instanceof StandardGraphPropertyVariable) {
950                                 // Get child variables provided by the NodeManager
951                                 Map<String, Variable> result = getStandardNodeChildVariables(graph, context, map); 
952                                 return standardChildDomainChildren.getVariables(graph, context, result);
953                         } else if (context instanceof StandardGraphChildVariable) {
954                                 return standardChildDomainChildren.getVariables(graph, context, map);
955                         } else {
956                                 throw new DatabaseException("Unknown variable implementation " + context.getClass().getCanonicalName());
957                         }       
958                 }
959                 
960         };
961         
962         protected static ChildReference getPossibleIndexReference(String name) {
963                 if (name.startsWith("i-")) {
964                     try {
965                         int index = Integer.parseInt(name.substring(2));
966                         return new IndexReference(index);
967                     } catch (NumberFormatException e) {}
968                 }
969                 return null;
970         }
971
972         protected static ValueAccessor getPossiblePropertyValueAccessor(ReadGraph graph, StandardGraphPropertyVariable variable) throws DatabaseException {
973             if(variable.property == null) return null;
974             return variable.property.valueAccessor;
975 //        return graph.syncRequest(new PropertyValueAccessorRequest(variable.property), TransientCacheAsyncListener.<ValueAccessor>instance());
976 //              return graph.syncRequest(new PossibleRelatedValueImplied2<ValueAccessor>(variable.property, Layer0.getInstance(graph).valueAccessor));
977         }
978
979         public static ValueAccessor getPossibleValueValueAccessor(ReadGraph graph, Variable variable) throws DatabaseException {
980             Resource value = variable.getPossibleRepresents(graph);
981             if(value == null) return null;
982             //return graph.syncRequest(new PropertyValueAccessorRequest(value));
983                 return graph.syncRequest(new PossibleRelatedValueImplied2<ValueAccessor>(value, Layer0.getInstance(graph).valueAccessor));      
984         }
985         
986         public static PropertyInfo getPossiblePropertyInfoFromContext(ReadGraph graph, Variable variable, Resource context, String name) throws DatabaseException {
987             if(context == null) return null;
988                 Map<String, PropertyInfo> predicates = graph.syncRequest(new UnescapedPropertyMapOfResource(context));
989                 return predicates.get(name);
990         }
991
992     public static Variable getPossiblePropertyFromContext(ReadGraph graph, Variable variable, Resource context, String name, Object propertyNode) throws DatabaseException {
993         PropertyInfo info = getPossiblePropertyInfoFromContext(graph, variable, context, name);
994         if(info == null || info.builder == null) return null;
995         return buildPropertyVariable(graph, variable, context, info, propertyNode);
996     }
997     
998     public static Variable getPossibleSubliteralPropertyFromContext(ReadGraph graph, StandardGraphPropertyVariable variable, String name) throws DatabaseException {
999         
1000                 Resource predicate = variable.property.predicate;
1001                 if(predicate == null) return null;
1002
1003         PropertyInfo info = getPropertyInfo(graph, predicate);
1004         Pair<Resource, ChildReference> p = info.subliteralPredicates.get(name);
1005         if(p == null) return null;
1006         
1007                 return new SubliteralPropertyVariable(graph, variable, p.first, p.second);
1008         
1009     }
1010
1011     public static Map<String, PropertyInfo> collectPropertyInfosFromContext(ReadGraph graph, Variable variable, Resource context) throws DatabaseException {
1012         if(context == null) return Collections.emptyMap();
1013                 return graph.isImmutable(context) ?
1014                                 graph.syncRequest(new UnescapedPropertyMapOfResource(context), TransientCacheAsyncListener.<Map<String,PropertyInfo>>instance()) :
1015                                 graph.syncRequest(new UnescapedPropertyMapOfResource(context));
1016     }
1017
1018         public static Map<String, Variable> collectPropertiesFromContext(ReadGraph graph, Variable variable, Resource context, Map<String, Variable> map) throws DatabaseException {
1019
1020                 Map<String,PropertyInfo> properties = graph.isImmutable(context) ?
1021                                 graph.syncRequest(new UnescapedPropertyMapOfResource(context), TransientCacheAsyncListener.<Map<String,PropertyInfo>>instance()) :
1022                                 graph.syncRequest(new UnescapedPropertyMapOfResource(context));
1023                                 
1024                 if(properties.isEmpty()) return map;
1025                 
1026                 map = ensureVariableMap(map, properties.size());
1027                 
1028                 for(PropertyInfo info : properties.values()) {
1029                         String name = info.name;
1030                         if (info.builder != null) {
1031                                 Variable v = info.builder.buildProperty(graph, variable, null, context, info.predicate);
1032                                 map.put(name, v);
1033                         }
1034                 }
1035                 
1036                 return map;
1037                 
1038         }
1039
1040         public static Map<String, Variable> collectSubliteralProperties(ReadGraph graph, StandardGraphPropertyVariable variable, Map<String, Variable> map) throws DatabaseException {
1041
1042                 Resource predicate = variable.property.predicate;
1043                 if(predicate == null) return map;
1044                 
1045                 PropertyInfo info = getPropertyInfo(graph, predicate);
1046                 if(info.subliteralPredicates.isEmpty()) return map;
1047                 
1048                 map = ensureVariableMap(map, info.subliteralPredicates.size());
1049                 
1050                 for(Map.Entry<String, Pair<Resource, ChildReference>> entry : info.subliteralPredicates.entrySet()) {
1051                         String key = entry.getKey();
1052                         Pair<Resource, ChildReference> p = entry.getValue();
1053                         if(map == null) map = new THashMap<String,Variable>();
1054                         map.put(key, new SubliteralPropertyVariable(graph, variable, p.first, p.second));
1055                 }
1056         
1057         return map;
1058                 
1059         }
1060
1061         public static Map<String, Variable> collectPropertiesFromContext(ReadGraph graph, Variable variable, Resource context, String classification, Map<String, Variable> map) throws DatabaseException {
1062
1063                 if(graph.isImmutable(context)) {
1064
1065                         Map<String,PropertyInfo> properties = graph.syncRequest(new UnescapedPropertyMapOfResource(context), TransientCacheAsyncListener.<Map<String,PropertyInfo>>instance());
1066                         for(PropertyInfo info : properties.values()) {
1067
1068                                 if(info.classifications.contains(classification) && info.builder != null) {
1069                                         String name = info.name;
1070                                         Variable v = info.builder.buildProperty(graph, variable, null, context, info.predicate);
1071                                         if(map == null) map = new THashMap<String,Variable>();
1072                                         map.put(name, v);
1073                                 }
1074
1075                         }
1076
1077                 } else {
1078                                 
1079                         Collection<Resource> predicates = graph.getPredicates(context);
1080                                         
1081                         if(predicates.isEmpty()) return map;
1082                         
1083                         map = ensureVariableMap(map, predicates.size());
1084                 
1085                         for(Resource predicate : predicates) {
1086                                 
1087                                 PropertyInfo info = graph.isImmutable(predicate) ?
1088                                                 graph.syncRequest(new PropertyInfoRequest(predicate), TransientCacheAsyncListener.<PropertyInfo>instance()) :
1089                                                         graph.syncRequest(new PropertyInfoRequest(predicate));
1090                                                 
1091                                 if(!info.isHasProperty) continue;
1092         
1093                                 if(info.classifications.contains(classification) && info.builder != null) {
1094                                         String name = info.name;
1095                                         Variable v = info.builder.buildProperty(graph, variable, null, context, info.predicate);
1096                                         if(map == null) map = new THashMap<String,Variable>();
1097                                         map.put(name, v);
1098                                 }
1099                                 
1100                         }
1101                         
1102                 }
1103                 
1104                 return map;
1105                 
1106         }       
1107         
1108     @SCLValue(type = "ReadGraph -> Resource -> a -> String")
1109     public static String entityLabel(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1110         if(context instanceof Resource) {
1111                 return NameUtils.getSafeLabel(graph, ((Resource)context));      
1112         } else if (context instanceof Variable) {
1113                 Variable parent = ((Variable)context).getParent(graph);
1114                 Resource represents = parent.getRepresents(graph);
1115                 return NameUtils.getSafeLabel(graph, represents);
1116         } else {
1117                 throw new DatabaseException("Unknown context " + context);
1118         }
1119     }
1120
1121     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
1122     public static Object listResources(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1123         return ListUtils.toList(graph, resource);
1124     }
1125
1126     @SCLValue(type = "ReadGraph -> Resource -> Variable -> [String]")
1127     public static List<String> standardClassifications(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
1128         ArrayList<String> result = new ArrayList<String>();
1129         Resource predicate = context.getParent(graph).getPossiblePredicateResource(graph);
1130         if(predicate != null) {
1131                 for(Resource type : graph.getTypes(predicate)) {
1132                         String uri = graph.getPossibleURI(type);
1133                         if(uri != null) result.add(uri);
1134                 }
1135         }
1136         return result;
1137     }
1138
1139     @SCLValue(type = "ReadGraph -> Resource -> a -> Boolean")
1140     public static Boolean standardValidValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1141         return Boolean.TRUE;
1142     }
1143
1144     @SCLValue(type = "ReadGraph -> Resource -> a -> StringInputValidator")
1145     public static StringInputValidator standardValidator(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1146         return StringInputValidator.PASS;
1147     }
1148
1149     @SCLValue(type = "ReadGraph -> Resource -> a -> Boolean")
1150     public static Boolean standardRequiredValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1151         return Boolean.FALSE;
1152     }
1153
1154     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Boolean")
1155     public static Boolean standardDefaultValue(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
1156         Variable property = context.getParent(graph);
1157         if(property instanceof StandardGraphPropertyVariable) {
1158                 StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)property;
1159                 if (variable.parentResource != null) {
1160                         Statement stm = graph.getPossibleStatement(variable.parentResource, variable.property.predicate);
1161                         return stm != null && stm.isAsserted(variable.parentResource);
1162                         }
1163         }
1164         return Boolean.FALSE;
1165     }
1166
1167     @SCLValue(type = "ReadGraph -> Resource -> a -> Boolean")
1168     public static Boolean standardReadOnlyValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1169         return Boolean.FALSE;
1170     }
1171
1172     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
1173     public static Object resourceAsValue(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1174         return resource;
1175     }
1176     
1177     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
1178     public static Object functionApplication(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1179         return Functions.exec(graph, resource, graph, resource, context);
1180     }
1181
1182     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
1183     public static Object computeExpression(ReadGraph graph, Resource converter, Object context) throws DatabaseException {
1184         if(context instanceof Variable) {
1185             return CompileValueRequest.compileAndEvaluate(graph, (Variable)context);
1186         } if (context instanceof Resource) {
1187             return CompileResourceValueRequest.compileAndEvaluate(graph, (Resource)converter);
1188         } else {
1189                 throw new IllegalStateException("Unknown context " + context);
1190         }
1191     }
1192
1193     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
1194     public static Object composedPropertyValue(ReadGraph graph, Resource converter, Object context) throws DatabaseException {
1195         if(context instanceof Variable) {
1196                 return new StandardComposedProperty();
1197         } if (context instanceof Resource) {
1198                 return new StandardComposedProperty();
1199         } else {
1200                 throw new IllegalStateException("Unknown context " + context);
1201         }
1202     }
1203     
1204     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
1205     public static Object numberInputValidator(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1206         
1207         class Validator extends FunctionImpl1<String, String> {
1208
1209             private final Datatype datatype;
1210             
1211             public Validator(Datatype datatype) {
1212                 this.datatype = datatype;
1213             }
1214             
1215             @Override
1216             public String apply(String input) {
1217                 
1218                 if(datatype == null) return null;
1219                 
1220                 try {
1221
1222                     if(datatype instanceof NumberType) {
1223                         
1224                         Number number = (Number)PrimitiveValueParser.parse(input, datatype);
1225                         NumberType nt = (NumberType)datatype;
1226                         Range r = nt.getRange();
1227                         if(r != null) {
1228                             if(!r.contains(number)) return "Value is out of valid range";
1229                         }
1230                     }
1231                     return null;
1232                     
1233                 } catch (NumberFormatException e) {
1234                     return "Not a valid floating-point number";
1235                 } catch (IllegalArgumentException e) {
1236                     return "Not a valid floating-point number";
1237                 }
1238                 
1239             }
1240             
1241         }
1242
1243         if(context instanceof Variable) {
1244             
1245             Variable variable = (Variable)context;
1246             Variable property = variable.getParent(graph);
1247             Datatype datatype = property.getPossibleDatatype(graph);
1248             return new Validator(datatype);
1249             
1250         } else if (context instanceof Resource) {
1251
1252             Layer0 L0 = Layer0.getInstance(graph);
1253             Resource literal = (Resource)context;
1254             Datatype datatype = graph.getRelatedValue(literal, L0.HasDataType, Bindings.getBindingUnchecked(Datatype.class));
1255             return new Validator(datatype);
1256             
1257         } else {
1258             
1259             return new Validator(null);
1260             
1261         }
1262         
1263     }
1264     
1265     @SCLValue(type = "ReadGraph -> Resource -> a -> b")
1266     public static Object booleanInputValidator(ReadGraph graph, Resource resource, Object context) throws DatabaseException {
1267         
1268         return new FunctionImpl1<String, String>() {
1269
1270             @Override
1271             public String apply(String input) {
1272                 
1273                 String lower = input.toLowerCase();
1274                 if("true".equals(lower) || "false".equals(lower)) return null;
1275
1276                 return "Not a valid boolean: " + input;
1277                 
1278             }
1279             
1280         };
1281         
1282     }
1283
1284     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Resource")
1285     public static Resource hasStandardResource(ReadGraph graph, Resource resource, Variable context) throws DatabaseException {
1286         Variable parent = context.getParent(graph);
1287         if(parent instanceof StandardGraphChildVariable) {
1288                 StandardGraphChildVariable variable = (StandardGraphChildVariable)parent;
1289                 return variable.resource;
1290         }
1291         return null;
1292     }
1293
1294
1295     @SCLValue(type = "ReadGraph -> Resource -> Variable -> a")
1296         public static Object valueWithoutBinding(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
1297
1298         StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context;
1299                 
1300                 if(graph.sync(new IsEnumeratedValue(variable.getRepresents(graph)))) {
1301                         Layer0 L0 = Layer0.getInstance(graph);
1302                         return graph.getRelatedValue2(variable.getRepresents(graph), L0.HasLabel);
1303                 }
1304
1305                 if (variable.parentResource == null)
1306                         throw new VariableException("Variable is not represented by any resource (URI=" + variable.getPossibleURI(graph) + ").");
1307
1308                 try {
1309                         return graph.getRelatedValue2(variable.parentResource, variable.property.predicate, variable);
1310                 } catch (NoSingleResultException e) {
1311                         throw new MissingVariableValueException(variable.getPossibleURI(graph));
1312                 } catch (DoesNotContainValueException e) {
1313                         throw new MissingVariableValueException(variable.getPossibleURI(graph));
1314                 }
1315                 
1316         }
1317
1318     @SCLValue(type = "ReadGraph -> Variable -> Binding -> a")
1319         public static Object valueWithBinding(ReadGraph graph, Variable context, Binding binding) throws DatabaseException {
1320
1321         StandardGraphPropertyVariable variable = (StandardGraphPropertyVariable)context;
1322                 
1323                 if(graph.sync(new IsEnumeratedValue(variable.getRepresents(graph)))) {
1324                         Layer0 L0 = Layer0.getInstance(graph);
1325                         return graph.getRelatedValue2(variable.getRepresents(graph), L0.HasLabel, binding);
1326                 }
1327
1328                 if (variable.parentResource == null)
1329                         throw new VariableException("Variable is not represented by any resource (URI=" + variable.getPossibleURI(graph) + ").");
1330
1331                 try {
1332                         return graph.getRelatedValue2(variable.parentResource, variable.property.predicate, variable);
1333                 } catch (NoSingleResultException e) {
1334                         throw new MissingVariableValueException(variable.getPossibleURI(graph));
1335                 } catch (DoesNotContainValueException e) {
1336                         throw new MissingVariableValueException(variable.getPossibleURI(graph));
1337                 }
1338                 
1339         }
1340
1341     @SCLValue(type = "WriteGraph -> Variable -> a -> Binding -> b")
1342         public static Object valueSetterWithBinding(WriteGraph graph, Variable variable, Object value, Binding binding) throws DatabaseException {
1343                 
1344                 Function4<WriteGraph, Variable, Object, Object, String> modifier = variable.getPossiblePropertyValue(graph, Variables.INPUT_MODIFIER);
1345                 if(modifier == null) modifier = VariableUtils.defaultInputModifier; 
1346                 modifier.apply(graph, variable, value, binding);
1347                 return null;
1348                 
1349         }
1350     
1351     static class L0Issue extends StandardIssue {
1352         
1353         private final String description;
1354         
1355         public L0Issue(String description, Resource type, Resource ... contexts) {
1356             super(type, contexts);
1357             this.description = description;
1358         }
1359
1360         @Override
1361         public Resource write(WriteGraph graph, Resource source) throws DatabaseException {
1362             Layer0 L0 = Layer0.getInstance(graph);
1363             IssueResource IR = IssueResource.getInstance(graph);
1364             Resource issue = super.write(graph, source);
1365             graph.claim(issue, IR.Issue_HasSeverity, IR.Severity_Fatal);
1366             graph.addLiteral(issue, L0.HasDescription, L0.HasDescription_Inverse, description, Bindings.STRING);
1367             return issue;
1368         }
1369         
1370     }
1371     
1372         private static List<Issue> reportInconsistency(ReadGraph graph, Resource subject, String description, List<Issue> issues) throws DatabaseException {
1373             if(issues == null) issues = new ArrayList<Issue>();
1374                 System.err.println("Change set validation reports the following issue: " + NameUtils.getSafeName(graph, subject, true) + ": " + description);
1375                 IssueResource IR = IssueResource.getInstance(graph);
1376                 issues.add(new L0Issue(description, IR.Issue, subject));
1377                 return issues;
1378         }
1379     
1380     @SCLValue(type = "ReadGraph -> Resource -> [Issue]")
1381     public static List<Issue> relationValidator(ReadGraph graph, Resource resource) throws DatabaseException {
1382
1383         Layer0 L0 = Layer0.getInstance(graph);
1384
1385         List<Issue> issues = null;
1386         
1387         for(Statement stm : graph.getStatements(resource, L0.IsWeaklyRelatedTo)) {
1388                 Resource predicate = stm.getPredicate();
1389                 Resource object = stm.getObject();
1390                 if(!isRelation(graph, L0, predicate)) {
1391                         issues = reportInconsistency(graph, resource, "The predicate of a statement must be a relation: " + NameUtils.toString(graph, stm), issues);
1392                 }
1393                 if(graph.isInstanceOf(predicate, L0.FunctionalRelation)) {
1394                         if(graph.getObjects(resource, predicate).size() > 1)
1395                                 issues = reportInconsistency(graph, resource, 
1396                                                 "Relation " +
1397                                                                 NameUtils.getSafeName(graph, predicate)
1398                                                                 + " is functional.", issues);
1399                 }
1400                 {
1401                         Collection<Resource> domain = graph.getObjects(predicate, L0.HasDomain);
1402                         if (!isInstanceOfAny(graph, resource, domain, true)) {
1403                                 StringBuilder sb = new StringBuilder()
1404                                 .append("The domain of ")
1405                                 .append(NameUtils.getSafeName(graph, predicate))
1406                                 .append(" relation is ");
1407                                 orString(graph, sb, domain).append(".");
1408                                 issues = reportInconsistency(graph, resource, sb.toString(), issues);
1409                         }
1410                 }
1411                 {
1412                         Collection<Resource> range = graph.getObjects(predicate, L0.HasRange);
1413                         if (!isInstanceOfAny(graph, object, range, true) && !graph.isInstanceOf(object, L0.SCLValue)) {
1414                                 StringBuilder sb = new StringBuilder()
1415                                 .append("The range of ")
1416                                 .append(NameUtils.getSafeName(graph, predicate))
1417                                 .append(" relation is ");
1418                                 orString(graph, sb, range).append(" but current object is ")
1419                                 .append(NameUtils.getSafeName(graph, object)).append(".");
1420                                 issues = reportInconsistency(graph, resource, sb.toString(), issues);
1421                         }
1422                 }               
1423         }
1424                 
1425                 return issues != null ? issues : Collections.<Issue>emptyList();
1426
1427     }
1428
1429     @SCLValue(type = "ReadGraph -> Resource -> [Issue]")
1430     public static List<Issue> propertyValidator(ReadGraph graph, Resource resource) throws DatabaseException {
1431
1432         List<Issue> issues = null;
1433
1434         Layer0 L0 = Layer0.getInstance(graph);
1435         for(Statement stm : graph.getStatements(resource, L0.HasProperty)) {
1436                 Resource subject = stm.getSubject();
1437                 Resource predicate = stm.getPredicate();
1438                 String error = L0Validations.checkValueType(graph, subject, predicate);
1439                 if(error != null) issues = reportInconsistency(graph, subject, error, issues);
1440         }
1441                 
1442         return issues != null ? issues : Collections.<Issue>emptyList();
1443
1444     }
1445     
1446     
1447     @SCLValue(type = "ReadGraph -> Resource -> [Issue]")
1448     public static List<Issue> valueValidator(ReadGraph graph, Resource resource) throws DatabaseException {
1449
1450         List<Issue> issues = null;
1451
1452         Layer0 L0 = Layer0.getInstance(graph);
1453         if(graph.hasValue(resource)) {
1454                 if(!graph.isInstanceOf(resource, L0.Literal)) {
1455                         issues = reportInconsistency(graph, resource, 
1456                                         "Resource has a value but it is not a literal.", issues);
1457                 }
1458                 else {
1459                         // TODO check that the value is valid for the data type
1460                 }
1461         }
1462         else {
1463                 if(graph.isInstanceOf(resource, L0.Literal)) {
1464                         issues = reportInconsistency(graph, resource, 
1465                                         "Resource is a literal but it does not have a value.", issues);
1466                 }
1467         }
1468         
1469         return issues != null ? issues : Collections.<Issue>emptyList();
1470         
1471     }
1472
1473     
1474     @SCLValue(type = "ReadGraph -> Resource -> [Issue]")
1475     public static List<Issue> uriValidator(ReadGraph graph, Resource resource) throws DatabaseException {
1476         
1477         List<Issue> issues = null;
1478
1479         Layer0 L0 = Layer0.getInstance(graph);
1480         Resource parent = graph.getPossibleObject(resource, L0.PartOf);
1481         if(parent != null) {
1482             String parentURI = graph.syncRequest(new PossibleURI(parent));
1483             if(parentURI != null) {
1484                         String name = graph.getPossibleRelatedValue(resource, L0.HasName);
1485                         if(name == null) {
1486                                 issues = reportInconsistency(graph, resource, "Resource has a parent with URI but has no valid HasName.", issues);
1487                         }
1488             }
1489         }
1490
1491         return issues != null ? issues : Collections.<Issue>emptyList();
1492         
1493     }
1494     
1495     private static Resource getPossibleNearestClusterSet(ReadGraph graph, Resource base, Resource resource) throws DatabaseException {
1496
1497         ClusteringSupport cs = graph.getService(ClusteringSupport.class);
1498         if(cs.isClusterSet(resource) && !base.equals(resource)) return resource;
1499         
1500         Resource nearest = CommonDBUtils.getNearestOwner(graph, Collections.singletonList(resource));
1501         if(nearest == null) return null;
1502         
1503         return getPossibleNearestClusterSet(graph, base, nearest);
1504
1505     }
1506
1507     private static boolean quirks(ReadGraph graph, Resource resource) throws DatabaseException {
1508
1509         if(!resource.isPersistent()) return true;
1510         if(graph.isImmutable(resource)) return true;
1511         if(resource.getResourceId() < 0x2000) return true;
1512
1513         return false;
1514         
1515     }
1516     
1517     @SCLValue(type = "ReadGraph -> Resource -> [Issue]")
1518     public static List<Issue> clusterValidator(ReadGraph graph, Resource resource) throws DatabaseException {
1519
1520         if(!Development.DEVELOPMENT) return Collections.<Issue>emptyList();
1521         
1522         if(quirks(graph, resource)) return Collections.<Issue>emptyList();
1523         
1524         List<Issue> issues = null;
1525
1526         ClusteringSupport cs = graph.getService(ClusteringSupport.class);
1527         Resource set = cs.getClusterSetOfCluster(resource);
1528         
1529         if(set == null) return reportInconsistency(graph, resource, "Resource cluster is not part of any cluster set", issues);
1530         
1531         Resource nearestSet = getPossibleNearestClusterSet(graph, resource, resource);
1532         if(nearestSet == null) {
1533                 // This means that there is no owner since RootLibrary is a cluster set
1534                 return Collections.<Issue>emptyList();
1535         }
1536         
1537         if(!set.equals(nearestSet)) return reportInconsistency(graph, resource, "The cluster set of a resource is not the nearest owner set", issues);
1538
1539         return Collections.<Issue>emptyList();
1540         
1541     }
1542
1543     private static boolean isInstanceOfAny(ReadGraph graph, Resource r, Collection<Resource> types, boolean ifEmpty) throws DatabaseException {
1544                 if (types.isEmpty())
1545                         return ifEmpty;
1546                 for (Resource type : types) {
1547                         if (graph.isInstanceOf(r, type)) {
1548                                 return true;
1549                         }
1550                 }
1551                 return false;
1552         }
1553
1554         private static StringBuilder orString(ReadGraph graph, StringBuilder sb, Collection<Resource> rs) throws DatabaseException {
1555                 sb.append("(");
1556                 boolean first = true;
1557                 for (Resource r : rs) {
1558                         if (!first)
1559                                 sb.append(" | ");
1560                         first = false;
1561                         sb.append(NameUtils.getSafeName(graph, r));
1562                 }
1563                 sb.append(")");
1564                 return sb;
1565         }
1566
1567     public static boolean isRelation(ReadGraph g, Layer0 l0, Resource relation) throws DatabaseException {
1568                 return g.hasStatement(relation, l0.SubrelationOf) || relation == l0.IsWeaklyRelatedTo;
1569         }
1570         
1571         public static boolean isType(ReadGraph g, Layer0 l0, Resource type) throws DatabaseException {
1572                 return g.hasStatement(type, l0.Inherits) || type == l0.Entity;
1573         }
1574         
1575     public static Variable buildChildVariable(ReadGraph graph, Variable context, Resource graphChild, Object nodeChild) throws DatabaseException {
1576         VariableBuilder builder = graph.adapt(graphChild, VariableBuilder.class);
1577         return builder.buildChild(graph, context, build(((AbstractVariable)context).node, nodeChild), graphChild);
1578         }
1579
1580         private static Variable buildPropertyVariable(ReadGraph graph, Variable variable, Resource parentResource, PropertyInfo graphProperty, Object propertyNode) throws DatabaseException {
1581                 VariableNode<?> node = variable instanceof AbstractVariable ? build(((AbstractVariable)variable).node, propertyNode) : null;
1582                 return graphProperty.builder.buildProperty(graph, variable, node, parentResource, graphProperty.predicate);
1583         }
1584         
1585         static StandardGraphChildVariable createStandardGraphChildVariable(
1586                         AbstractVariable parent, Object child) {
1587                 return new StandardGraphChildVariable(parent, build(parent.node, child), null);
1588         }
1589
1590         private static StandardGraphPropertyVariable createStandardGraphPropertyVariable(
1591                         ReadGraph graph, AbstractVariable variable, Object nodeProperty) throws DatabaseException {
1592         Resource propertyResource = getPossiblePropertyResource(graph, variable, nodeProperty);
1593         return new StandardGraphPropertyVariable(graph, variable, build(variable.node, nodeProperty), null, propertyResource);
1594         }
1595         
1596         static Map<String, Variable> ensureVariableMap(
1597                         Map<String, Variable> map, int size) {
1598                 if(map == null) map = new THashMap<String,Variable>(size);
1599                 return map;
1600         }
1601
1602         private static PropertyInfo getPropertyInfo(ReadGraph graph, Resource predicate) throws DatabaseException {
1603                 return graph.syncRequest(new PropertyInfoRequest(predicate));
1604         }
1605
1606         @SuppressWarnings("unchecked")
1607         static String getNodeName(AbstractVariable parent, Object child) {
1608                 return parent.node.support.manager.getName(child);
1609         }
1610
1611         @SuppressWarnings("unchecked")
1612         private static Object getNodeValue(final AbstractVariable variable, final Binding binding) throws NodeManagerException, BindingException {
1613                 return variable.node.support.manager.getValue(variable.node.node, binding);
1614         }
1615
1616         @SuppressWarnings("unchecked")
1617         private static void setNodeValue(final AbstractVariable variable, final Object value, final Binding binding) throws NodeManagerException, BindingException {
1618                 variable.node.support.manager.setValue(variable.node.node, value, binding);
1619         }
1620         
1621         @SuppressWarnings("unchecked")
1622         private static String getPossiblePropertyURI(AbstractVariable parent, Object node) {
1623                 return parent.node.support.manager.getPropertyURI(parent.node.node, node);
1624         }
1625     
1626
1627     @SCLValue(type = "ReadGraph -> Resource -> Variable -> a")
1628     public static Object defaultInstantiateUnder(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
1629         return new FunctionImpl2<Resource, Resource, Resource>() {
1630             public Resource apply(Resource container, Resource type) {
1631                 try {
1632                     WriteGraph graph = (WriteGraph)SCLContext.getCurrent().get("graph");
1633
1634                     Layer0 L0 = Layer0.getInstance(graph);
1635                     CommonDBUtils.selectClusterSet(graph, container);
1636                     Resource result = graph.newResource();
1637                     String name = NameUtils.findFreshInstanceName(graph, type, container);
1638                     graph.claim(result, L0.InstanceOf, type);
1639                     graph.addLiteral(result, L0.HasName, L0.NameOf, name, Bindings.STRING);
1640                     graph.claim(container, L0.ConsistsOf, L0.PartOf, result);
1641
1642                     return result;
1643                 } catch (DatabaseException e) {
1644                     throw new RuntimeDatabaseException(e);
1645                 }
1646             }
1647         };
1648     }
1649
1650 }