]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/util/Layer0Utils.java
Optimized Layer0Utils.getPossibleDefaultBinding
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / util / Layer0Utils.java
1 /*******************************************************************************
2  * Copyright (c) 2012 Association for Decentralized Information Management in
3  * Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.layer0.util;
13
14 import java.io.IOException;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Comparator;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.TreeSet;
24
25 import org.eclipse.core.runtime.IProgressMonitor;
26 import org.eclipse.core.runtime.NullProgressMonitor;
27 import org.eclipse.core.runtime.SubMonitor;
28 import org.simantics.databoard.Bindings;
29 import org.simantics.databoard.Datatypes;
30 import org.simantics.databoard.adapter.AdaptException;
31 import org.simantics.databoard.adapter.Adapter;
32 import org.simantics.databoard.adapter.AdapterConstructionException;
33 import org.simantics.databoard.binding.Binding;
34 import org.simantics.databoard.binding.NumberBinding;
35 import org.simantics.databoard.binding.StringBinding;
36 import org.simantics.databoard.binding.error.BindingException;
37 import org.simantics.databoard.binding.mutable.MutableStringBinding;
38 import org.simantics.databoard.parser.repository.DataTypeSyntaxError;
39 import org.simantics.databoard.parser.repository.DataValueRepository;
40 import org.simantics.databoard.primitives.MutableString;
41 import org.simantics.databoard.type.ArrayType;
42 import org.simantics.databoard.type.BooleanType;
43 import org.simantics.databoard.type.ByteType;
44 import org.simantics.databoard.type.Datatype;
45 import org.simantics.databoard.type.DoubleType;
46 import org.simantics.databoard.type.FloatType;
47 import org.simantics.databoard.type.IntegerType;
48 import org.simantics.databoard.type.LongType;
49 import org.simantics.databoard.type.MapType;
50 import org.simantics.databoard.type.NumberType;
51 import org.simantics.databoard.type.OptionalType;
52 import org.simantics.databoard.type.RecordType;
53 import org.simantics.databoard.type.StringType;
54 import org.simantics.databoard.type.UnionType;
55 import org.simantics.databoard.type.VariantType;
56 import org.simantics.databoard.util.ObjectUtils;
57 import org.simantics.datatypes.literal.GUID;
58 import org.simantics.db.ChangeSetIdentifier;
59 import org.simantics.db.Operation;
60 import org.simantics.db.ReadGraph;
61 import org.simantics.db.RelationContext;
62 import org.simantics.db.Resource;
63 import org.simantics.db.Session;
64 import org.simantics.db.Statement;
65 import org.simantics.db.WriteGraph;
66 import org.simantics.db.WriteOnlyGraph;
67 import org.simantics.db.common.CommentMetadata;
68 import org.simantics.db.common.Indexing;
69 import org.simantics.db.common.StandardStatement;
70 import org.simantics.db.common.primitiverequest.PossibleRelatedValue;
71 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
72 import org.simantics.db.common.request.DelayedWriteRequest;
73 import org.simantics.db.common.request.ObjectsWithType;
74 import org.simantics.db.common.request.PossibleChild;
75 import org.simantics.db.common.request.PossibleIndexRoot;
76 import org.simantics.db.common.request.WriteRequest;
77 import org.simantics.db.common.utils.NameUtils;
78 import org.simantics.db.event.ChangeListener;
79 import org.simantics.db.exception.CancelTransactionException;
80 import org.simantics.db.exception.DatabaseException;
81 import org.simantics.db.exception.ServiceException;
82 import org.simantics.db.layer0.adapter.CopyHandler;
83 import org.simantics.db.layer0.adapter.CopyHandler2;
84 import org.simantics.db.layer0.adapter.GenericRelationIndex;
85 import org.simantics.db.layer0.adapter.PasteHandler;
86 import org.simantics.db.layer0.adapter.impl.DefaultPasteHandler;
87 import org.simantics.db.layer0.adapter.impl.EntityRemover;
88 import org.simantics.db.layer0.adapter.impl.TGRemover;
89 import org.simantics.db.layer0.genericrelation.IndexedRelations;
90 import org.simantics.db.layer0.internal.SimanticsInternal;
91 import org.simantics.db.layer0.migration.OntologiesFromLibrary;
92 import org.simantics.db.layer0.property.OrderedResource;
93 import org.simantics.db.layer0.request.GlobalOntologies;
94 import org.simantics.db.layer0.request.PossibleVariableIndexRoot;
95 import org.simantics.db.layer0.request.PropertyInfo;
96 import org.simantics.db.layer0.request.PropertyInfoRequest;
97 import org.simantics.db.layer0.util.SimanticsClipboard.Representation;
98 import org.simantics.db.layer0.variable.StandardGraphPropertyVariable;
99 import org.simantics.db.layer0.variable.Variable;
100 import org.simantics.db.service.ClusterCollectorPolicy;
101 import org.simantics.db.service.ClusterControl;
102 import org.simantics.db.service.ClusteringSupport;
103 import org.simantics.db.service.CollectionSupport;
104 import org.simantics.db.service.DebugSupport;
105 import org.simantics.db.service.GraphChangeListenerSupport;
106 import org.simantics.db.service.ManagementSupport;
107 import org.simantics.db.service.UndoRedoSupport;
108 import org.simantics.db.service.XSupport;
109 import org.simantics.graph.db.TransferableGraphSource;
110 import org.simantics.graph.db.TransferableGraphs;
111 import org.simantics.graph.diff.Diff;
112 import org.simantics.graph.diff.TransferableGraphDelta1;
113 import org.simantics.graph.refactoring.GraphRefactoringUtils;
114 import org.simantics.graph.representation.PrettyPrintTG;
115 import org.simantics.graph.representation.TransferableGraph1;
116 import org.simantics.layer0.Layer0;
117 import org.simantics.operation.Layer0X;
118 import org.simantics.scl.compiler.environment.Environments;
119 import org.simantics.scl.compiler.runtime.RuntimeEnvironment;
120 import org.simantics.scl.compiler.top.SCLExpressionCompilationException;
121 import org.simantics.scl.compiler.types.Type;
122 import org.simantics.scl.osgi.SCLOsgi;
123 import org.simantics.scl.runtime.function.Function;
124 import org.simantics.scl.runtime.function.Function1;
125 import org.simantics.scl.runtime.function.FunctionImpl1;
126
127 public class Layer0Utils {
128
129         @SuppressWarnings("rawtypes")
130         public static final ThreadLocal SCL_GRAPH = new ThreadLocal();
131
132         public static Resource literal(WriteGraph g, String value) throws DatabaseException {
133                 Layer0 L0 = Layer0.getInstance(g);
134                 Resource r = g.newResource();
135                 g.claimValue(r, value, Bindings.STRING);
136                 g.claim(r, L0.InstanceOf, L0.String);
137                 return r;
138         }
139
140         public static Resource literal(WriteGraph g, double value) throws DatabaseException {
141                 Layer0 L0 = Layer0.getInstance(g);
142                 Resource r = g.newResource();
143                 g.claimValue(r, value, Bindings.DOUBLE);
144                 g.claim(r, L0.InstanceOf, L0.Double);
145                 return r;
146         }
147
148         public static Resource literal(WriteGraph g, int value) throws DatabaseException {
149                 Layer0 L0 = Layer0.getInstance(g);
150                 Resource r = g.newResource();
151                 g.claimValue(r, value, Bindings.INTEGER);
152                 g.claim(r, L0.InstanceOf, L0.Integer);
153                 return r;
154         }
155
156         public static void assert_(WriteGraph g, Resource type, Resource predicate, Resource object) throws DatabaseException {
157                 Layer0 L0 = Layer0.getInstance(g);
158                 Resource assertion = g.newResource();
159                 g.claim(type, L0.Asserts, assertion);
160                 g.claim(assertion, L0.InstanceOf, L0.Assertion);
161                 g.claim(assertion, L0.HasPredicate, predicate);
162                 g.claim(assertion, L0.HasObject, object);
163         }
164
165         public static Resource relation(WriteGraph g, Resource parent, String name, Resource superrelation) throws DatabaseException {
166                 Layer0 L0 = Layer0.getInstance(g);
167                 Resource relation = g.newResource();
168                 g.claim(relation, L0.SubrelationOf, superrelation);
169                 g.claim(relation, L0.HasName, literal(g, name));
170                 g.claim(parent, L0.ConsistsOf, relation);
171
172                 Resource superrelationInverse = g.getInverse(superrelation);
173                 if(superrelationInverse != null) {
174                         Resource inverse = g.newResource();
175                         g.claim(inverse, L0.SubrelationOf, superrelationInverse);
176                         g.claim(relation, L0.ConsistsOf, inverse);
177                         g.claim(inverse, L0.HasName, literal(g, "Inverse"));
178                 }
179                 return relation;
180         }
181
182         private static Resource getLiteralType(ReadGraph graph, Datatype type) throws DatabaseException {
183                 Layer0 L0 = Layer0.getInstance(graph);
184                 if(type instanceof DoubleType) return L0.Double;
185                 else if(type instanceof StringType) return L0.String;
186                 else if(type instanceof IntegerType) return L0.Integer;
187                 else if(type instanceof LongType) return L0.Long;
188                 else if(type instanceof FloatType) return L0.Float;
189                 else if(type instanceof ByteType) return L0.Byte;
190                 else if(type instanceof BooleanType) return L0.Boolean;
191                 else if(type instanceof ArrayType) {
192                         ArrayType at = (ArrayType)type;
193                         if(at.componentType instanceof DoubleType) return L0.DoubleArray;
194                         else if(at.componentType instanceof StringType) return L0.StringArray;
195                         else if(at.componentType instanceof IntegerType) return L0.IntegerArray;
196                         else if(at.componentType instanceof LongType) return L0.LongArray;
197                         else if(at.componentType instanceof FloatType) return L0.FloatArray;
198                         else if(at.componentType instanceof ByteType) return L0.ByteArray;
199                         else if(at.componentType instanceof BooleanType) return L0.BooleanArray;
200                         else if(at.componentType instanceof VariantType) return L0.VariantArray;
201                 }
202                 throw new DatabaseException("Unidentified literal type for datatype " + type);
203         }
204
205         private static Resource getPossibleLiteralType(ReadGraph graph, String type) throws DatabaseException {
206
207                 Layer0 L0 = Layer0.getInstance(graph);
208                 if("Double".equals(type)) return L0.Double;
209                 else if("String".equals(type)) return L0.String;
210                 else if("Integer".equals(type)) return L0.Integer;
211                 else if("Long".equals(type)) return L0.Long;
212                 else if("Float".equals(type)) return L0.Float;
213                 else if("Byte".equals(type)) return L0.Byte;
214                 else if("Boolean".equals(type)) return L0.Boolean;
215                 else if("[Double]".equals(type)) return L0.DoubleArray;
216                 else if("[String]".equals(type)) return L0.StringArray;
217                 else if("[Integer]".equals(type)) return L0.IntegerArray;
218                 else if("[Long]".equals(type)) return L0.LongArray;
219                 else if("[Float]".equals(type)) return L0.FloatArray;
220                 else if("[Byte]".equals(type)) return L0.ByteArray;
221                 else if("[Boolean]".equals(type)) return L0.BooleanArray;
222                 else if("[Variant]".equals(type)) return L0.VariantArray;
223                 else if("Array Double".equals(type)) return L0.DoubleArray;
224                 else if("Array String".equals(type)) return L0.StringArray;
225                 else if("Array Integer".equals(type)) return L0.IntegerArray;
226                 else if("Array Long".equals(type)) return L0.LongArray;
227                 else if("Array Float".equals(type)) return L0.FloatArray;
228                 else if("Array Byte".equals(type)) return L0.ByteArray;
229                 else if("Array Boolean".equals(type)) return L0.BooleanArray;
230                 else if("Array Variant".equals(type)) return L0.VariantArray;
231                 else if("Vector Double".equals(type)) return L0.DoubleArray;
232                 else if("Vector String".equals(type)) return L0.StringArray;
233                 else if("Vector Integer".equals(type)) return L0.IntegerArray;
234                 else if("Vector Long".equals(type)) return L0.LongArray;
235                 else if("Vector Float".equals(type)) return L0.FloatArray;
236                 else if("Vector Byte".equals(type)) return L0.ByteArray;
237                 else if("Vector Boolean".equals(type)) return L0.BooleanArray;
238                 else if("Vector Variant".equals(type)) return L0.VariantArray;
239                 else if("Datatype".equals(type)) return L0.DataType;
240                 else if("Variant".equals(type)) return L0.Variant;
241                 else return null;
242         }
243
244         public static Resource getPossibleLiteralType(ReadGraph graph, Variable variable) throws DatabaseException {
245                 Resource predicate = variable.getPossiblePredicateResource(graph);
246                 if(predicate == null) return null;
247                 return getPossibleLiteralType(graph, predicate);
248         }
249
250         public static Resource getLiteralType(ReadGraph graph, Variable variable) throws DatabaseException {
251                 Resource result = getPossibleLiteralType(graph, variable);
252                 if(result == null) throw new DatabaseException("Unidentified literal type for variable " + variable.getURI(graph));
253                 return result;
254         }
255
256         public static Resource getLiteralType(ReadGraph graph, Resource property) throws DatabaseException {
257                 Resource result = getPossibleLiteralType(graph, property);
258                 if(result == null) throw new DatabaseException("Unidentified literal type for property " + graph.getURI(property));
259                 return result;
260         }
261
262         public static Resource getPossibleLiteralType(ReadGraph graph, Resource property) throws DatabaseException {
263
264                 Layer0 L0 = Layer0.getInstance(graph);
265                 Layer0X L0X = Layer0X.getInstance(graph);
266
267                 Resource defaultLiteralType = graph.getPossibleObject(property, L0.HasDefaultLiteralType);
268                 if(defaultLiteralType != null) return defaultLiteralType;
269
270                 Resource range = graph.getPossibleObject(property, L0.HasRange);
271                 if(range != null && !L0.Value.equals(range)) return range;
272
273                 Datatype requiredDataType = graph.getPossibleRelatedValue(property, L0X.RequiresDataType, Bindings.DATATYPE);
274                 if(requiredDataType != null) return getLiteralType(graph, requiredDataType);
275
276                 String requiredValueType = graph.getPossibleRelatedValue(property, L0.RequiresValueType, Bindings.STRING);
277                 if(requiredValueType == null) return null;
278
279                 return getPossibleLiteralType(graph, requiredValueType);
280
281         }
282
283         /**
284          * @param type any data type definition
285          * @return SCL type that matches the specified data type on a basic level.
286          *         Data type metadata is/cannot be converted into SCL types.
287          * @throws IllegalArgumentException
288          *             if the input datatype can't be converted into an SCL type
289          */
290         public static String getSCLType(Datatype type) throws IllegalArgumentException {
291                 return buildSCLType(type, null).toString();
292         }
293
294         /**
295          * Only used internally by {@link #buildSCLType(Datatype, StringBuilder)}
296          * @param s
297          * @param toBuilder
298          * @return
299          * @see #buildSCLType(Datatype, StringBuilder)
300          */
301         private static StringBuilder append(StringBuilder toBuilder, String s) {
302                 return toBuilder != null ? toBuilder.append(s) : new StringBuilder(s);
303         }
304
305         private static CharSequence append(CharSequence to, String s) {
306                 if (to instanceof StringBuilder)
307                         return ((StringBuilder) to).append(s);
308                 return new StringBuilder(to.length() + s.length()).append(to).append(s);
309         }
310
311         private static CharSequence stringOrBuilder(StringBuilder toBuilder, String s) {
312                 return toBuilder != null ? toBuilder.append(s) : s;
313         }
314
315         /**
316          * @param type any data type definition
317          * @return SCL type that matches the specified data type on a basic level.
318          *         Data type metadata is/cannot be converted into SCL types.
319          * @throws IllegalArgumentException
320          *             if the input datatype can't be converted into an SCL type
321          */
322         private static CharSequence buildSCLType(Datatype type, StringBuilder result) throws IllegalArgumentException {
323                 if(type instanceof DoubleType) return stringOrBuilder(result, "Double");
324                 else if(type instanceof StringType) return stringOrBuilder(result, "String");
325                 else if(type instanceof IntegerType) return stringOrBuilder(result, "Integer");
326                 else if(type instanceof FloatType) return stringOrBuilder(result, "Float");
327                 else if(type instanceof BooleanType) return stringOrBuilder(result, "Boolean");
328                 else if(type instanceof ByteType) return stringOrBuilder(result, "Byte");
329                 else if(type instanceof LongType) return stringOrBuilder(result, "Long");
330                 else if(type instanceof VariantType) return stringOrBuilder(result, "Variant");
331                 else if(type instanceof ArrayType) {
332                         ArrayType at = (ArrayType) type;
333                         // Optimization to prevent allocations in the most basic array cases
334                         if(at.componentType instanceof DoubleType) return stringOrBuilder(result, "Vector Double");
335                         else if(at.componentType instanceof StringType) return stringOrBuilder(result, "Vector String");
336                         else if(at.componentType instanceof IntegerType) return stringOrBuilder(result, "Vector Integer");
337                         else if(at.componentType instanceof FloatType) return stringOrBuilder(result, "Vector Float");
338                         else if(at.componentType instanceof BooleanType) return stringOrBuilder(result, "Vector Boolean");
339                         else if(at.componentType instanceof ByteType) return stringOrBuilder(result, "Vector Byte");
340                         else if(at.componentType instanceof LongType) return stringOrBuilder(result, "Vector Long");
341                         else if(at.componentType instanceof VariantType) return stringOrBuilder(result, "Vector Variant");
342                         else return buildSCLType(at.componentType, append(result, "Vector "));
343                 } else if(type instanceof OptionalType) {
344                         OptionalType ot = (OptionalType) type;
345                         return append(buildSCLType(ot.componentType, append(result, "Maybe (")), ")");
346                 } else if (type instanceof RecordType) {
347                         throw new IllegalArgumentException("Unable to convert datatype into SCL type: " + type);
348                 } else if (type instanceof MapType) {
349                         throw new IllegalArgumentException("Unable to convert datatype into SCL type: " + type);
350                 } else if (type instanceof UnionType) {
351                         throw new IllegalArgumentException("Unable to convert datatype into SCL type: " + type);
352                 }
353                 throw new IllegalArgumentException("Unable to convert datatype into SCL type: " + type);
354         }
355
356
357         public static Type getSCLType(ReadGraph graph, RuntimeEnvironment runtimeEnvironment, String typeText) throws DatabaseException {
358         try {
359                         return Environments.getType(runtimeEnvironment.getEnvironment(), typeText);
360                 } catch (SCLExpressionCompilationException e) {
361                         throw new DatabaseException(e);
362                 }
363         }
364
365         public static Type getSCLType(ReadGraph graph, Variable property) throws DatabaseException {
366
367                 RuntimeEnvironment runtimeEnvironment = graph.syncRequest(new RuntimeEnvironmentRequest(property.getIndexRoot(graph)));
368                 return getSCLType(graph, runtimeEnvironment, getSCLTypeString(graph, property));
369
370         }
371
372                 
373         public static String getSCLTypeString(ReadGraph graph, Variable context) throws DatabaseException {
374                 return getSCLTypeString(graph, context.getPossiblePredicateResource(graph), context.getRepresents(graph));
375         }
376
377
378         public static String getSCLTypeString(ReadGraph graph, Resource predicate, Resource value) throws DatabaseException {
379
380                 if(predicate != null) {
381                     String requiredValueTypes = graph.getPossibleRelatedValue(predicate, Layer0.getInstance(graph).RequiresValueType, Bindings.STRING);
382                     if(requiredValueTypes != null)
383                         return requiredValueTypes;
384                 }
385
386                 Layer0 L0 = Layer0.getInstance(graph);
387                 Layer0X L0X = Layer0X.getInstance(graph);
388
389                 Datatype literalDatatype = graph.getPossibleRelatedValue(value, L0.HasDataType, Bindings.DATATYPE);
390                 if(literalDatatype != null) return getSCLType(literalDatatype);
391
392                 String literalValueType = graph.getPossibleRelatedValue(value, L0.HasValueType, Bindings.STRING);
393                 if(literalValueType != null) return literalValueType;
394
395                 if(predicate != null) {
396
397                         Datatype requiredDataType = graph.getPossibleRelatedValue(predicate, L0X.RequiresDataType, Bindings.DATATYPE);
398                         if(requiredDataType != null) return getSCLType(requiredDataType);
399
400                         throw new DatabaseException("Unidentified literal data type for property " + NameUtils.getURIOrSafeNameInternal(graph, predicate));
401
402                 }
403
404                 throw new DatabaseException("Unidentified literal data type");
405
406         }
407
408         public static Datatype getDatatype(ReadGraph graph, Variable variable) throws DatabaseException {
409                 Datatype result = getPossibleDatatype(graph, variable);
410                 if(result != null) return result;
411                 throw new DatabaseException("Unidentified literal data type for property " + variable.getURI(graph));
412         }
413
414         public static Datatype getPossibleDatatype(ReadGraph graph, Variable variable) throws DatabaseException {
415                 return getPossibleDatatype(graph, variable, null, true);
416         }
417
418         private static Datatype getPossibleDatatype(ReadGraph graph, Variable variable, PropertyInfo info, boolean checkPropertyDatatype) throws DatabaseException {
419                 Layer0 L0 = Layer0.getInstance(graph);
420                 Layer0X L0X = Layer0X.getInstance(graph);
421
422                 Resource property = variable.getPossiblePredicateResource(graph);
423                 if(checkPropertyDatatype && property != null) {
424                         Datatype requiredDataType = graph.syncRequest(new PossibleRelatedValue<Datatype>(property, L0X.RequiresDataType, Bindings.DATATYPE));
425                         if(requiredDataType != null) return requiredDataType;
426                 }
427
428                 Resource literal = variable.getPossibleRepresents(graph);
429                 if(literal != null) {
430                         Datatype literalDatatype = graph.getPossibleRelatedValue2(literal, L0.HasDataType, new StandardGraphPropertyVariable(graph, variable, null, literal, L0.HasDataType), Bindings.DATATYPE);
431                         if(literalDatatype != null) return literalDatatype;
432                 }
433
434                 if(property != null) {
435
436                         String requiredValueType = info != null
437                                         ? info.requiredValueType
438                                         : graph.getPossibleRelatedValue(property, L0.RequiresValueType, Bindings.STRING);
439                         if(requiredValueType != null) {
440                                 Datatype datatype = getPossibleDatatypeForValueType(requiredValueType);
441                                 if(datatype != null) return datatype;
442                         }
443
444                         Resource subject = variable.getParent(graph).getPossibleRepresents(graph);
445                         if(subject != null) {
446                                 Set<Resource> asses = new HashSet<Resource>();
447                                 for(Resource type : graph.getTypes(subject)) {
448                                         asses.addAll(graph.getAssertedObjects(type, property));
449                                 }
450                                 if(asses.size() == 1) {
451                                         Resource ass = asses.iterator().next();
452                                         Datatype dt = graph.getPossibleRelatedValue(ass, L0.HasDataType, Bindings.getBindingUnchecked(Datatype.class));
453                                         if(dt != null) return dt;
454                                 }
455                         }
456
457                 }
458
459                 return null;
460         }
461
462         private static Datatype getPossibleDatatypeForValueType(String requiredValueType) throws DatabaseException {
463
464                 String[] split = requiredValueType.split(" ");
465                 String arrayType = null;
466                 if(split.length == 2 && "Array".equals(split[0])) {
467                         arrayType = split[1];
468                 } else if(requiredValueType.startsWith("[") && requiredValueType.endsWith("]")) {
469                         arrayType = requiredValueType.substring(1, requiredValueType.length()-1);
470                 }
471
472                 Datatype arrayDataType = getDatatypeForType(arrayType != null ? arrayType : requiredValueType, arrayType != null);
473                 if(arrayDataType != null)
474                         return arrayDataType;
475
476                 Datatype dt = Datatypes.getDatatype(requiredValueType);
477                 if(dt != null) return dt;
478
479                 try {
480                         return Datatypes.translate(requiredValueType);
481                 } catch (DataTypeSyntaxError e) {
482                         return null;
483                 }
484
485         }
486
487         private static Datatype getDatatypeForType(String type, boolean isArray) {
488                 switch (type) {
489                         case "Double":  return isArray ? Datatypes.DOUBLE_ARRAY  : Datatypes.DOUBLE;
490                         case "String":  return isArray ? Datatypes.STRING_ARRAY  : Datatypes.STRING;
491                         case "Integer": return isArray ? Datatypes.INTEGER_ARRAY : Datatypes.INTEGER;
492                         case "Long":    return isArray ? Datatypes.LONG_ARRAY    : Datatypes.LONG;
493                         case "Float":   return isArray ? Datatypes.FLOAT_ARRAY   : Datatypes.FLOAT;
494                         case "Byte":    return isArray ? Datatypes.BYTE_ARRAY    : Datatypes.BYTE;
495                         case "Boolean": return isArray ? Datatypes.BOOLEAN_ARRAY : Datatypes.BOOLEAN;
496                         case "Variant": return isArray ? Datatypes.VARIANT_ARRAY : Datatypes.VARIANT;
497                 }
498                 return null;
499         }
500
501         public static Binding getDefaultBinding(ReadGraph graph, Variable variable) throws DatabaseException {
502
503                 Resource property = variable.getPossiblePredicateResource(graph);
504                 if(property != null) {
505                         PropertyInfo info = graph.syncRequest(new PropertyInfoRequest(property), TransientCacheAsyncListener.<PropertyInfo>instance());
506                         if(info.defaultBinding != null) return info.defaultBinding;
507                 }
508
509                 Datatype type = getDatatype(graph, variable);
510                 return Bindings.getBinding(type);
511
512         }
513
514         public static Binding getPossibleDefaultBinding(ReadGraph graph, Variable variable) throws DatabaseException {
515
516                 Resource property = variable.getPossiblePredicateResource(graph);
517                 PropertyInfo info = null;
518                 if(property != null) {
519                         info = graph.syncRequest(new PropertyInfoRequest(property), TransientCacheAsyncListener.<PropertyInfo>instance());
520                         if(info.defaultBinding != null) return info.defaultBinding;
521                 }
522
523                 Datatype type = getPossibleDatatype(graph, variable, info, false);
524                 if (type == null) return null;
525
526                 return Bindings.getBinding(type);
527
528         }
529
530         public static String getPossibleUnit(Datatype dt) {
531                 if (dt == null)
532                         return null;
533                 else if (dt instanceof NumberType) {
534                         return ((NumberType) dt).getUnit();
535                 } else if (dt instanceof ArrayType) {
536                         ArrayType at = (ArrayType) dt;
537                         Datatype cdt = at.componentType();
538                         if (cdt instanceof NumberType) {
539                                 return ((NumberType) cdt).getUnit();
540                         }
541                 }
542                 return null;
543
544         }
545
546         public static String getUnit(ReadGraph graph, Variable variable) throws DatabaseException {
547
548                 Layer0 L0 = Layer0.getInstance(graph);
549                 Layer0X L0X = Layer0X.getInstance(graph);
550
551                 Resource literal = variable.getPossibleRepresents(graph);
552                 if(literal == null)
553                     return "";
554
555                 Datatype literalDatatype = graph.getPossibleRelatedValue2(literal, L0.HasDataType, new StandardGraphPropertyVariable(graph, variable, null, literal, L0.HasDataType), Bindings.DATATYPE);
556                 if(literalDatatype != null) {
557                         String unit = getPossibleUnit(literalDatatype);
558                         if(unit != null) return unit;
559                 }
560
561                 Resource property = variable.getPossiblePredicateResource(graph);
562                 if(property != null) {
563
564                         Datatype requiredDataType = graph.getPossibleRelatedValue(property, L0X.RequiresDataType, Bindings.DATATYPE);
565                         if(requiredDataType != null) {
566                                 String unit = getPossibleUnit(requiredDataType);
567                                 if(unit != null) return unit;
568                         }
569
570                 }
571
572                 return "";
573
574         }
575
576         public static void claimAdaptedValue(WriteGraph graph, Resource objectResource, Object value, Binding binding, Datatype targetDatatype) throws DatabaseException {
577
578                 try {
579
580                         Datatype sourceDatatype = binding.type();
581                         if(sourceDatatype.equals(targetDatatype)) {
582                                 graph.claimValue(objectResource, value, binding);
583                         } else {
584                                 Binding target = Bindings.getBinding(targetDatatype);
585                                 Adapter adapter = Bindings.getTypeAdapter(binding, target);
586                                 graph.claimValue(objectResource, adapter.adapt(value), target);
587                         }
588
589                 } catch (AdapterConstructionException e) {
590                         throw new DatabaseException(e);
591                 } catch (AdaptException e) {
592                         throw new DatabaseException(e);
593                 }
594
595         }
596
597         public static String toString(Object value, Binding binding) throws DatabaseException {
598                 try {
599                         if(value instanceof String) return (String)value;
600                         StringBuilder sb = new StringBuilder();
601                         DataValueRepository rep = new DataValueRepository();
602                         binding.printValue(value, sb, rep, false);
603                         return sb.toString();
604                 } catch (BindingException e) {
605                         throw new DatabaseException(e);
606                 } catch (IOException e) {
607                         throw new DatabaseException(e);
608                 }
609         }
610
611         public static Object parseValue(String text, Binding binding) throws DatabaseException {
612                 try {
613                         if(binding.isInstance(text)) return text;
614                         DataValueRepository rep = new DataValueRepository();
615                         return binding.parseValue(text, rep);
616                 } catch (BindingException e) {
617                         throw new DatabaseException(e);
618                 } catch (DataTypeSyntaxError e) {
619                         throw new DatabaseException(e);
620                 }
621         }
622
623         @SuppressWarnings("unchecked")
624         public static <T> T getValueAdaptedToBinding(ReadGraph graph, Resource literal, Binding targetBinding) throws DatabaseException {
625                 Datatype sourceDatatype = graph.getDataType(literal);
626                 Datatype targetDatatype = targetBinding.type();
627                 if (sourceDatatype.equals(targetDatatype))
628                         return graph.getValue(literal, targetBinding);
629
630                 Binding sourceBinding = Bindings.getBinding(sourceDatatype);
631                 try {
632                         Adapter adapter = Bindings.adapterFactory.getAdapter(Bindings.getBinding(sourceDatatype), targetBinding, true, false);
633                         Object value = graph.getValue(literal, sourceBinding);
634                         return (T) adapter.adaptUnchecked(value);
635                 } catch (AdapterConstructionException e) {
636                         throw new DatabaseException(e);
637                 }
638         }
639
640         public static Statement getStatementInLocal(Resource subject, Statement statement) {
641                 if(statement.isAsserted(subject)) return new StandardStatement(subject, statement.getPredicate(), statement.getObject());
642                 else return statement;
643         }
644
645         public static Resource browsePossible(ReadGraph graph, Resource root, String suffix) throws DatabaseException {
646                 return graph.getPossibleResource(graph.getURI(root) + suffix);
647         }
648
649         public static Resource getPossibleChild(ReadGraph graph, Resource resource, String name) throws DatabaseException {
650                 return graph.sync(new PossibleChild(resource, name));
651         }
652
653         public static Resource getPossibleChild(ReadGraph graph, Resource resource, Resource type, String name) throws DatabaseException {
654                 Resource child = graph.sync(new PossibleChild(resource, name));
655                 if(child == null) return null;
656                 if(!graph.isInstanceOf(child, type)) return null;
657                 return child;
658         }
659
660         public static RelationContext relationContext(ReadGraph graph, Resource subject, Resource predicate) throws DatabaseException {
661                 Statement stm = graph.getSingleStatement(subject, predicate);
662                 return new RelationContextImpl(subject, stm);
663         }
664
665         public static RelationContext relationContext(Statement stm) throws DatabaseException {
666                 return new RelationContextImpl(stm.getSubject(), stm);
667         }
668
669         public static <T> T valueInRelationContext(ReadGraph graph, Resource subject, Statement stm) throws DatabaseException {
670                 return graph.getValue2(subject, Layer0Utils.relationContext(stm));
671         }
672
673         public static <T> T valueInRelationContext(ReadGraph graph, Resource subject, Statement stm, Binding binding) throws DatabaseException {
674                 return graph.getValue2(subject, Layer0Utils.relationContext(stm), binding);
675         }
676
677         public static <T> T relatedValueInRelationContext(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
678                 Statement stm = getStatementInLocal(subject, graph.getSingleStatement(subject, relation));
679                 return valueInRelationContext(graph, stm.getObject(), stm);
680         }
681
682         public static <T> T relatedValueInRelationContext(ReadGraph graph, Resource subject, Resource relation, Binding binding) throws DatabaseException {
683                 Statement stm = getStatementInLocal(subject, graph.getSingleStatement(subject, relation));
684                 return valueInRelationContext(graph, stm.getObject(), stm, binding);
685         }
686
687         public static Statement possibleObtainedStatementInternal(ReadGraph graph, Resource subject, Resource relation) throws DatabaseException {
688
689                 Layer0X L0X = Layer0X.getInstance(graph);
690
691                 for(Resource ob : graph.getObjects(subject, L0X.DefinesObtainedStatement)) {
692                         Resource pred = graph.getSingleObject(ob, L0X.ObtainedStatement_predicate);
693                         if(graph.isSubrelationOf(pred, relation)) {
694                                 Resource object = graph.getSingleObject(ob, L0X.ObtainedStatement_object);
695                                 return new StandardStatement(subject, pred, object);
696                         }
697                 }
698
699                 ArrayList<OrderedResource> order = new ArrayList<OrderedResource>();
700                 for(Statement stm : graph.getStatements(subject, L0X.ObtainsProperty)) {
701                         Integer position = graph.getRelatedValue(stm.getPredicate(), L0X.NaturalNumberOrderRelation, Bindings.INTEGER);
702                         order.add(new OrderedResource(position, stm.getObject()));
703                 }
704
705                 for(OrderedResource or : order) {
706                         Statement stm = possibleObtainedStatementInternal(graph, or.r, relation);
707                         if(stm != null) return stm;
708                 }
709
710                 return null;
711
712         }
713
714         public static <T> T possibleObtainedValue(ReadGraph graph, RelationContext ctx, Binding binding) throws DatabaseException {
715
716                 Statement stm = ctx.getStatement();
717                 Statement obj = Layer0Utils.possibleObtainedStatementInternal(graph, stm.getSubject(), stm.getPredicate());
718
719                 if(obj != null) {
720                         return Layer0Utils.valueInRelationContext(graph, obj.getObject(), obj, binding);
721                 } else {
722                         return null;
723                 }
724
725         }
726
727         public static void addObtainedStatement(WriteGraph graph, Resource subject, Resource predicate, Resource object) throws DatabaseException {
728                 Layer0 L0 = Layer0.getInstance(graph);
729                 Layer0X L0X = Layer0X.getInstance(graph);
730                 Resource ob = graph.newResource();
731                 graph.claim(ob, L0.InstanceOf, null, L0X.ObtainedStatement);
732                 graph.claim(ob, L0X.ObtainedStatement_predicate, null, predicate);
733                 graph.claim(ob, L0X.ObtainedStatement_object, null, object);
734                 graph.claim(subject, L0X.DefinesObtainedStatement, null, ob);
735         }
736
737         public static void addObtainedValue(WriteGraph graph, Resource subject, Resource predicate, Resource type, Object value, Binding binding) throws DatabaseException {
738                 Layer0 L0 = Layer0.getInstance(graph);
739                 Resource object = graph.newResource();
740                 graph.claim(object, L0.InstanceOf, type);
741                 graph.claimValue(object, value, binding);
742                 Layer0Utils.addObtainedStatement(graph, subject, predicate, object);
743         }
744
745         //-------------------------------------------------------------------------
746         // Indexing state query utilities idle handling utilities
747         //-------------------------------------------------------------------------
748
749         /**
750          * This method waits until the indexing engine becomes idle.
751          * @since 1.8
752          */
753         public static void waitIndexPending() {
754                 Indexing.waitIndexPending();
755         }
756
757         /**
758          * @param graph an active database write handle to prove one is in a write
759          *        transaction and wants to disable dependencies indexing for this
760          *        transaction only.
761          * @return previous value
762          * @since 1.8
763          */
764         public static boolean setDependenciesIndexingDisabled(WriteOnlyGraph graph, boolean disabled) {
765                 return Indexing.setDependenciesIndexingDisabled(graph, disabled);
766         }
767
768         public static String undo() throws DatabaseException {
769
770             Session session = SimanticsInternal.getSession();
771
772         UndoRedoSupport support = session.getService(UndoRedoSupport.class);
773
774         List<Operation> ops = support.undoAndReturnOperations(session, 1);
775         if(ops.isEmpty())
776             return "Undo history is empty.";
777
778         Operation mainOperation = ops.get(0);
779
780         long csId = mainOperation.getCSId();
781
782         ManagementSupport management = session.getService(ManagementSupport.class);
783         Collection<ChangeSetIdentifier> ids = management.getChangeSetIdentifiers(csId, csId);
784
785         return "Undo reverted " + ids.size() + " change sets.";
786
787         }
788
789         public static String undoOperations(int amountOfOperations) throws DatabaseException {
790
791             Session session = SimanticsInternal.getSession();
792
793         UndoRedoSupport support = session.getService(UndoRedoSupport.class);
794
795         List<Operation> ops = support.undoAndReturnOperations(session, amountOfOperations);
796         if(ops.isEmpty())
797             return "Undo history is empty.";
798
799         Operation mainOperation = ops.get(0);
800
801         long csId = mainOperation.getCSId();
802
803         ManagementSupport management = session.getService(ManagementSupport.class);
804         Collection<ChangeSetIdentifier> ids = management.getChangeSetIdentifiers(csId, csId);
805
806         return "Undo reverted " + ids.size() + " change sets.";
807
808         }
809
810         public static String redo() throws DatabaseException {
811
812             Session session = SimanticsInternal.getSession();
813
814         UndoRedoSupport support = session.getService(UndoRedoSupport.class);
815
816         List<Operation> ops = support.redo(session, 1);
817         if(ops.isEmpty())
818             return "Redo history is empty.";
819
820         Operation mainOperation = ops.get(0);
821
822         long csId = mainOperation.getCSId();
823
824         ManagementSupport management = session.getService(ManagementSupport.class);
825         Collection<ChangeSetIdentifier> ids = management.getChangeSetIdentifiers(csId, csId);
826
827         return "Redo redid " + ids.size() + " change sets.";
828
829         }
830
831         public static String getComment(Session session, ChangeSetIdentifier id) {
832             byte[] data = id.getMetadata().get(CommentMetadata.class.getName());
833             if(data == null)
834                 return "Undescribed operation.";
835             String comment = CommentMetadata.deserialise(session, data).toString().trim();
836             if(comment.isEmpty())
837                 return "Undescribed operation.";
838             return comment;
839         }
840
841     /**
842      * This method adds CommentMetadata for write transaction. CommentMetadata is used e.g. in Undo view.
843      * @param graph
844      *    graph handle
845      * @param string
846      *    comment
847      * @throws ServiceException
848      */
849     public static void addCommentMetadata(WriteOnlyGraph graph, String string) throws ServiceException {
850         // Add a comment to metadata.
851         CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
852         graph.addMetadata(cm.add(ObjectUtils.toString(string)));
853     }
854
855         //-------------------------------------------------------------------------
856
857         /**
858          * Copy the specified source resource into the specified container using the
859          * specified write transaction handle.
860          *
861          * @param graph write transaction handle
862          * @param targetContainer target container resource of the created copy. The
863          *        exact logic of how the copy will be contained by the target
864          *        container is up to the PasteHandler to decide
865          * @param source the source resource to copy
866          * @throws DatabaseException
867          * @since 1.8
868          */
869         public static Collection<Resource> copyTo(WriteGraph graph, Resource targetContainer, Resource source) throws DatabaseException {
870                 return copyTo(graph, targetContainer, source, null, null, null);
871         }
872
873         public static Collection<Resource> copyTo(WriteGraph graph, Resource targetContainer, Resource source, PasteEventHandler handler) throws DatabaseException {
874                 return copyTo(graph, targetContainer, source, handler, null, null);
875         }
876
877         public static Collection<Resource> copyTo(WriteGraph graph, Resource targetContainer, Resource source, PasteEventHandler handler, CopyHandler copyHandler, PasteHandler pasteHandler) throws DatabaseException {
878                 if(copyHandler == null) copyHandler = graph.adapt(source, CopyHandler.class);
879                 return copyTo(graph, targetContainer, handler, copyHandler, pasteHandler);
880         }
881
882         public static Collection<Resource> copyTo(WriteGraph graph, Resource targetContainer, PasteEventHandler handler, CopyHandler copyHandler, PasteHandler pasteHandler) throws DatabaseException {
883                 SimanticsClipboardImpl clipboard = new SimanticsClipboardImpl();
884                 copyHandler.copyToClipboard(graph, clipboard, new NullProgressMonitor());
885                 if(targetContainer != null) {
886                         if(pasteHandler == null) pasteHandler = graph.adapt(targetContainer, PasteHandler.class);
887                         return pasteHandler.pasteFromClipboard(graph, clipboard, handler);
888                 } else {
889                         DefaultPasteHandler ph = new DefaultPasteHandler(null);
890                         return ph.pasteFromClipboard(graph, clipboard, handler);
891                 }
892         }
893
894         public static CopyHandler2 getPossibleCopyHandler(ReadGraph graph, Collection<Resource> rs) throws DatabaseException {
895         CopyHandler2 ch = null;
896         for(Resource r : rs) {
897             if(ch == null) {
898                 CopyHandler ch2_ = graph.adapt(r, CopyHandler.class);
899                 if(ch2_ instanceof CopyHandler2) {
900                     ch = (CopyHandler2)ch2_;
901                 }
902             } else {
903                 CopyHandler ch2_ = graph.adapt(r, CopyHandler.class);
904                 if(ch2_ instanceof CopyHandler2) {
905                     CopyHandler2 ch2 = (CopyHandler2)ch2_;
906                     ch = ch.combine(ch2);
907                 }
908             }
909         }
910         return ch;
911         }
912
913         public static ClusterCollectorPolicy setClusterCollectorPolicy(ClusterCollectorPolicy policy) {
914                 Session session = SimanticsInternal.getSession();
915                 ClusterControl cc = session.getService(ClusterControl.class);
916                 return cc.setPolicy(policy);
917         }
918
919         private static String decodeType(ReadGraph graph, Variable variable) throws DatabaseException {
920                 Datatype dt = getDatatype(graph, variable);
921                 return dt.toSingleLineString();
922         }
923
924         private static boolean isAsserted(ReadGraph graph, Resource subject, Resource predicate) throws DatabaseException {
925                 Statement stm = graph.getPossibleStatement(subject, predicate);
926                 return stm != null && stm.isAsserted(subject);
927         }
928
929         /*
930          * Works around problems in WriteGraph methods with similar signature. 
931          * Especially handles better some cases with existing literals.
932          * 
933          */
934         public static void claimLiteral(WriteGraph graph, Resource r, Resource p, Resource i, Resource t, Object value, Binding binding) throws DatabaseException {
935             Statement stm = graph.getPossibleStatement(r, p);
936             if(stm != null && !stm.isAsserted(r)) {
937                 if(graph.isInstanceOf(stm.getObject(), t)) {
938                     // Existing statement is compatible, reuse the literal
939                     graph.claimValue(stm.getObject(), value, binding);
940                     return;
941                 } else {
942                     // Existing statement is incompatible - remove it
943                     graph.deny(stm);
944                 }
945             }
946             // Create new statement
947             graph.claimLiteral(r, p, i, t, value, binding);
948         }
949         
950         public static void setExpression(WriteGraph graph, Variable context, String text, Resource expressionValueType) throws DatabaseException {
951                 
952                 Resource value = context.getRepresents(graph);
953                 Resource predicateResource = context.getPredicateResource(graph);
954                 Variable parent = context.getParent(graph);
955                 Resource parentResource = parent.getRepresents(graph);
956                 setExpression(graph, parentResource, predicateResource, value, text, expressionValueType);
957
958         }
959
960         public static void setExpression(WriteGraph graph, Resource parentResource, Resource predicateResource, Resource value, String text, Resource expressionValueType) throws DatabaseException {
961
962                 Layer0 L0 = Layer0.getInstance(graph);
963                 boolean hasExpression = graph.isInstanceOf(value, expressionValueType);
964                 String t = getSCLTypeString(graph, predicateResource, value);
965                 String expression = text.substring(1).trim();
966                 if(isAsserted(graph, parentResource, predicateResource)) {
967                         Resource newValue = graph.newResource();
968                         graph.claim(newValue, L0.InstanceOf, expressionValueType);
969                         graph.claimLiteral(newValue, L0.HasValueType, t, Bindings.STRING);
970                         graph.claimLiteral(newValue, L0.SCLValue_expression, expression, Bindings.STRING);
971                         graph.claim(parentResource, predicateResource, newValue);
972                 } else {
973                         if(hasExpression) {
974                                 graph.claimLiteral(value, L0.SCLValue_expression, expression, Bindings.STRING);
975                         } else {
976                                 Resource newValue = graph.newResource();
977                                 graph.claim(newValue, L0.InstanceOf, expressionValueType);
978                                 graph.claimLiteral(newValue, L0.HasValueType, t, Bindings.STRING);
979                                 graph.claimLiteral(newValue, L0.SCLValue_expression, expression, Bindings.STRING);
980                                 graph.deny(parentResource, predicateResource);
981                                 graph.claim(parentResource, predicateResource, newValue);
982                         }
983                 }
984
985         }
986
987         public static void clearExpression(WriteGraph graph, Variable property, Resource expressionValueType) throws DatabaseException {
988
989                 Resource object = property.getPossibleRepresents(graph);
990                 if(object != null) {
991                         boolean hasExpression = graph.isInstanceOf(object, expressionValueType);
992                         if(hasExpression) {
993                                 // There was an expression and now we go back to a value
994                                 Resource subject = property.getParent(graph).getPossibleRepresents(graph);
995                                 if(subject != null) {
996                                         Resource predicate = property.getPossiblePredicateResource(graph);
997                                         if(predicate != null) {
998                                                 graph.deny(subject, predicate, object);
999                                                 RemoverUtil.remove(graph, object);
1000                                         }
1001                                 }
1002                         }
1003                 }
1004
1005         }
1006
1007         public static boolean setOrClearExpression(WriteGraph graph, Variable property, String text, Resource expressionValueType) throws DatabaseException {
1008
1009                 if(text.startsWith("=")) {
1010                         setExpression(graph, property, text, expressionValueType);
1011                         return true;
1012                 }
1013
1014                 clearExpression(graph, property, expressionValueType);
1015
1016                 return false;
1017
1018         }
1019
1020         public static void setValueAsString(WriteGraph graph, Variable property, String text, Resource expressionValueType) throws DatabaseException {
1021
1022                 try {
1023
1024                         if (setOrClearExpression(graph, property, text, expressionValueType))
1025                                 return;
1026
1027                         Object value = text;
1028                         Datatype type = property.getPossibleDatatype(graph);
1029                         if (type != null) {
1030
1031                                 Binding binding = Bindings.getBinding(type);
1032
1033                                 if (binding instanceof StringBinding) {
1034
1035                                         if (binding instanceof MutableStringBinding)
1036                                                 value = new MutableString(text);
1037                                         else
1038                                                 value = text;
1039
1040                                 } else {
1041
1042                                         if (binding instanceof NumberBinding) {
1043                                                 text = text.replace(",", ".");
1044                                         }
1045
1046                                         value = binding.parseValue(text, new DataValueRepository());
1047
1048                                 }
1049
1050                                 property.setValue(graph, value, binding);
1051
1052                         } else {
1053
1054                                 property.setValue(graph, value);
1055
1056                         }
1057
1058                         // Add a comment to metadata.
1059                         CommentMetadata cm = graph.getMetadata(CommentMetadata.class);
1060                         graph.addMetadata(cm.add("Set value " + ObjectUtils.toString(value)));
1061
1062                 } catch (DataTypeSyntaxError e) {
1063                         throw new DatabaseException(e);
1064                 } catch (BindingException e) {
1065                         throw new DatabaseException(e);
1066                 }
1067
1068         }
1069
1070
1071     public static String queryDebugSupport(String query) {
1072         Session session = SimanticsInternal.getSession();
1073         DebugSupport ds = session.getService(DebugSupport.class);
1074         return ds.query(session, "exec " + query);
1075     }
1076
1077     public static String queryListSupport (String query) {
1078         Session session = SimanticsInternal.getSession();
1079         DebugSupport ds = session.getService(DebugSupport.class);
1080         return ds.query(session, "list " + query);
1081     }
1082
1083     final public static Function1<Resource,Resource> resourceCluster = new FunctionImpl1<Resource, Resource>() {
1084                 @Override
1085                 public Resource apply(Resource p0) {
1086                         return p0;
1087                 }
1088         };
1089
1090         public static void sort(ReadGraph graph, List<Resource> collection) {
1091         CollectionSupport cos = graph.getService(CollectionSupport.class);
1092         cos.sort(collection);
1093         }
1094
1095         public static List<Resource> sortByCluster(ReadGraph graph, Collection<Resource> collection) {
1096         CollectionSupport cos = graph.getService(CollectionSupport.class);
1097         return cos.asSortedList(collection);
1098         }
1099
1100         public static List<Object> sortByCluster(final ReadGraph graph, List<Object> list, final Function1<Object,Resource> fn) {
1101         final ClusteringSupport cs = graph.getService(ClusteringSupport.class);
1102         ArrayList<Object> result = new ArrayList<Object>(list);
1103         Collections.sort(result, new Comparator<Object>() {
1104
1105                         @Override
1106                         public int compare(Object o1, Object o2) {
1107                                 Resource r1 = fn.apply(o1);
1108                                 Resource r2 = fn.apply(o2);
1109                                 long l1 = cs.getCluster(r1);
1110                                 long l2 = cs.getCluster(r2);
1111                                 if(l1 < l2) return -1;
1112                                 else if (l1 > l2) return 1;
1113                                 else return 0;
1114                         }
1115
1116         });
1117         return result;
1118     }
1119
1120     public static <T> List<T> sortByClusterT(final ReadGraph graph, Collection<T> list, final Function1<T,Resource> fn) {
1121         final ClusteringSupport cs = graph.getService(ClusteringSupport.class);
1122         ArrayList<T> result = new ArrayList<T>(list);
1123         Collections.sort(result, new Comparator<Object>() {
1124
1125             @Override
1126             public int compare(Object o1, Object o2) {
1127                 Resource r1 = fn.apply((T)o1);
1128                 Resource r2 = fn.apply((T)o2);
1129                 long l1 = cs.getCluster(r1);
1130                 long l2 = cs.getCluster(r2);
1131                 if(l1 < l2) return -1;
1132                 else if (l1 > l2) return 1;
1133                 else return 0;
1134             }
1135
1136         });
1137         return result;
1138     }
1139
1140     public static void makeSynchronous(ReadGraph graph, boolean value) throws DatabaseException {
1141         graph.setSynchronous(value);
1142     }
1143
1144     public static Set<Resource> listIndexRoots(ReadGraph graph) throws DatabaseException {
1145         
1146         Layer0 L0 = Layer0.getInstance(graph);
1147         
1148                 Set<Resource> indexRoots = new TreeSet<Resource>();
1149                 indexRoots.addAll(Layer0Utils.listOntologies(graph));
1150                 indexRoots.addAll(graph.syncRequest(new ObjectsWithType(SimanticsInternal.getProject(), L0.ConsistsOf, L0.IndexRoot)));
1151                 return indexRoots;
1152
1153     }
1154     
1155     public static List<Resource> listOntologies(ReadGraph graph) throws DatabaseException {
1156         return graph.syncRequest(new OntologiesFromLibrary(graph.getRootLibrary()));
1157     }
1158
1159     public static List<Resource> listGlobalOntologies(ReadGraph graph) throws DatabaseException {
1160         return graph.syncRequest(new GlobalOntologies(graph.getRootLibrary()));
1161     }
1162
1163     public static <T> T applySCL(String module, String function, ReadGraph graph, Object ... args) throws DatabaseException {
1164
1165                 try {
1166                         SCL_GRAPH.set(graph);
1167                         T t = (T)((Function)SCLOsgi.MODULE_REPOSITORY.getValue(module + "/" + function)).applyArray(args);
1168                         SCL_GRAPH.set(null);
1169                         return t;
1170                 } catch (Throwable t) {
1171                         throw new DatabaseException(t);
1172                 }
1173
1174     }
1175
1176     public static boolean isContainerPublished(ReadGraph graph, Variable variable) throws DatabaseException {
1177
1178         Resource indexRoot = graph.syncRequest(new PossibleVariableIndexRoot(variable));
1179         if(indexRoot == null) return false;
1180         Resource represents = variable.getPossibleRepresents(graph);
1181         if(represents != null && represents.equals(indexRoot)) return false;
1182         return isPublished(graph, indexRoot);
1183
1184     }
1185
1186     public static boolean isContainerPublished(ReadGraph graph, Resource resource) throws DatabaseException {
1187
1188         Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(resource));
1189         if(indexRoot == null) return false;
1190         if(resource.equals(indexRoot)) return false;
1191         return isPublished(graph, indexRoot);
1192
1193     }
1194
1195     public static boolean isPublished(ReadGraph graph, Resource resource) throws DatabaseException {
1196
1197         Layer0 L0 = Layer0.getInstance(graph);
1198         Boolean value = graph.getPossibleRelatedValue(resource, L0.Entity_published, Bindings.BOOLEAN);
1199         if(value != null && value) return true;
1200
1201         // This is safety - root should not be published it child is not
1202         Resource root = graph.syncRequest(new PossibleIndexRoot(resource));
1203         if(root != null) {
1204                 value = graph.getPossibleRelatedValue(root, L0.Entity_published, Bindings.BOOLEAN);
1205                 if(value != null && value) return true;
1206         }
1207
1208         return false;
1209
1210     }
1211
1212     private static TransferableGraph1 makeTG(ReadGraph graph, Resource r) throws DatabaseException {
1213
1214         SimanticsClipboardImpl cp = new SimanticsClipboardImpl();
1215         CopyHandler c1 = graph.adapt(r, CopyHandler.class);
1216         c1.copyToClipboard(graph, cp, null);
1217         Collection<Set<Representation>> reps = cp.getContents();
1218         if(reps.size() != 1) return null;
1219         return ClipboardUtils.accept(graph, reps.iterator().next(), SimanticsKeys.KEY_TRANSFERABLE_GRAPH);
1220
1221     }
1222
1223     public static TransferableGraphSource makeTGSource(ReadGraph graph, Resource r) throws DatabaseException {
1224
1225         SimanticsClipboardImpl cp = new SimanticsClipboardImpl();
1226         CopyHandler c1 = graph.adapt(r, CopyHandler.class);
1227         c1.copyToClipboard(graph, cp, null);
1228         Collection<Set<Representation>> reps = cp.getContents();
1229         if(reps.size() != 1) return null;
1230         return ClipboardUtils.accept(graph, reps.iterator().next(), SimanticsKeys.KEY_TRANSFERABLE_GRAPH_SOURCE);
1231
1232     }
1233
1234     /*
1235      * Modifies target to resemble source.
1236      */
1237     public static boolean merge(WriteGraph graph, Resource source, Resource target) throws DatabaseException {
1238
1239         TransferableGraphSource tgs1 = makeTGSource(graph, target);
1240         TransferableGraph1 tg1 = TransferableGraphs.create(graph, tgs1);
1241         TransferableGraph1 tg2 = makeTG(graph, source);
1242
1243         GraphRefactoringUtils.fixIncorrectRoot(tg1.identities);
1244         GraphRefactoringUtils.fixIncorrectRoot(tg2.identities);
1245
1246         ModelTransferableGraphSource mtgs = (ModelTransferableGraphSource)tgs1;
1247
1248                 Diff diff = new Diff(tg1, tg2);
1249                 TransferableGraphDelta1 delta = diff.diff();
1250
1251                 long[] oldResources = mtgs.getResourceArray(graph);
1252                 if(TransferableGraphs.hasChanges(graph, oldResources, delta)) {
1253                         TransferableGraphs.applyDelta(graph, mtgs.getResourceArray(graph), delta);
1254                         return true;
1255                 } else {
1256                         return false;
1257                 }
1258
1259     }
1260
1261     public static Resource inferLiteralTypeFromString(ReadGraph graph, String text) {
1262         return Layer0.getInstance(graph).String;
1263     }
1264
1265     public static void emptyTrashBin() throws ServiceException {
1266         emptyTrashBin(new NullProgressMonitor());
1267     }
1268
1269     public static void emptyTrashBin(IProgressMonitor monitor) throws ServiceException {
1270         emptyTrashBin(monitor, SimanticsInternal.getSession(), SimanticsInternal.getProject());
1271     }
1272
1273     public static void emptyTrashBin(final IProgressMonitor monitor, Session session, final Resource project)
1274             throws ServiceException {
1275         final SubMonitor mon = SubMonitor.convert(monitor, "Emptying Trash Bin...", 10000);
1276         try {
1277             ArrayList<Resource> unhandled = new ArrayList<Resource>();
1278             session.syncRequest(new DelayedWriteRequest() {
1279                 @Override
1280                 public void perform(WriteGraph graph) throws DatabaseException {
1281                     Layer0Utils.setDependenciesIndexingDisabled(graph, true);
1282                     Layer0 L0 = Layer0.getInstance(graph);
1283                     Layer0X L0X = Layer0X.getInstance(graph);
1284                     Resource parent = graph.getSingleObject(project, L0.PartOf);
1285                     Resource trashBin = Layer0Utils.getPossibleChild(graph, parent, "TrashBin");
1286                     Collection<Resource> trashes = trashBin != null ? graph.getObjects(trashBin, L0.ConsistsOf)
1287                             : Collections.<Resource> emptyList();
1288                     if (trashes.isEmpty())
1289                         throw new CancelTransactionException();
1290                     mon.setWorkRemaining((2 + trashes.size()) * 1000);
1291                     for (Resource trash : trashes) {
1292                         if (mon.isCanceled())
1293                             throw new CancelTransactionException();
1294                         mon.subTask(NameUtils.getSafeName(graph, trash));
1295                         boolean isIndexRoot = graph.isInstanceOf(trash, L0.IndexRoot);
1296                         TGRemover remo = new TGRemover(mon.newChild(1000, SubMonitor.SUPPRESS_ALL_LABELS), trash);
1297                         try {
1298                             remo.remove(graph);
1299                             unhandled.addAll(remo.getRoots());
1300                         } catch (DatabaseException e) {
1301                             // Something went wrong - try to remove this later
1302                             // with EntityRemover
1303                             unhandled.add(trash);
1304                         }
1305                         if (isIndexRoot) {
1306                             // TODO: this should be an utility
1307                             GenericRelationIndex index = graph.adapt(L0X.DependenciesRelation,
1308                                     GenericRelationIndex.class);
1309                             IndexedRelations ir = graph.getService(IndexedRelations.class);
1310                             // Deletes index files
1311                             ir.reset(null, graph, L0X.DependenciesRelation, trash);
1312                             // Notifies DB listeners
1313                             index.reset(graph, trash);
1314                         }
1315                     }
1316                     if (mon.isCanceled())
1317                         throw new CancelTransactionException();
1318                     mon.subTask("Committing Changes");
1319                     mon.newChild(1000);
1320                 }
1321             });
1322
1323             session.syncRequest(new WriteRequest() {
1324                 @Override
1325                 public void perform(WriteGraph graph) throws DatabaseException {
1326                     for (Resource r : unhandled)
1327                         EntityRemover.remove(graph, r);
1328                 }
1329             });
1330
1331             if (mon.isCanceled())
1332                 return;
1333             mon.subTask("Purging Database");
1334             mon.newChild(1000);
1335             purgeDatabase(monitor, session);
1336         } catch (CancelTransactionException e) {
1337             // Ignore.
1338         } catch (DatabaseException e) {
1339             throw new ServiceException(e);
1340         }
1341     }
1342
1343     public static void purgeDatabase() throws ServiceException {
1344         purgeDatabase(new NullProgressMonitor());
1345     }
1346
1347     public static void purgeDatabase(final IProgressMonitor monitor) throws ServiceException {
1348         purgeDatabase(monitor, SimanticsInternal.getSession());
1349     }
1350
1351     public static void purgeDatabase(final IProgressMonitor monitor, Session session) throws ServiceException {
1352         try {
1353                 XSupport xs = session.getService(XSupport.class);
1354                 xs.purge();
1355         } catch (DatabaseException e) {
1356                 throw new ServiceException(e);
1357         }
1358     }
1359
1360     public static Resource getSingleDomainOf(ReadGraph graph, Resource type, Resource target) throws DatabaseException {
1361         Resource result = null;
1362         for(Resource candidate : getDomainOf(graph, type).values()) {
1363                 if(graph.isInstanceOf(candidate, target)) {
1364                         if(result != null) throw new DatabaseException("Multiple relations found for target " + graph.getURI(target) + " in type " + graph.getURI(type));
1365                         else result = candidate;
1366                 }
1367         }
1368         if(result == null) throw new DatabaseException("Multiple relations found for target " + graph.getURI(target) + " in type " + graph.getURI(type));
1369         return result;
1370     }
1371
1372     public static Map<String, Resource> getDomainOf(ReadGraph graph, Resource type) throws DatabaseException {
1373         CollectionSupport cs = graph.getService(CollectionSupport.class);
1374         Map<String, Resource> result = cs.createObjectResourceMap(String.class);
1375         Layer0 L0 = Layer0.getInstance(graph);
1376         for(Resource r : graph.getObjects(type, L0.DomainOf)) {
1377                 String name = graph.getPossibleRelatedValue(r, L0.HasName, Bindings.STRING);
1378                 if(name != null) result.put(name, r);
1379         }
1380         for(Resource t : graph.getSupertypes(type)) {
1381                 for(Resource r : graph.getObjects(t, L0.DomainOf)) {
1382                         String name = graph.getPossibleRelatedValue(r, L0.HasName, Bindings.STRING);
1383                         if(name != null) result.put(name, r);
1384                 }
1385         }
1386         return result;
1387     }
1388
1389     public static Resource getPossiblePredicateByNameFromType(ReadGraph graph, Resource type, String name) throws DatabaseException {
1390         Map<String,Resource> domain = getDomainOf(graph, type);
1391         return domain.get(name); 
1392     }
1393     
1394     public static Resource getPossiblePredicateByName(ReadGraph graph, Resource instance, String predicateName) throws DatabaseException {
1395         for(Resource type : graph.getPrincipalTypes(instance)) {
1396                 Map<String, Resource> domainOf = getDomainOf(graph, type);
1397                 Resource predicate = domainOf.get(predicateName);
1398                 if(predicate != null) return predicate;
1399         }
1400         return null;
1401     }
1402     
1403     public static Resource getPossiblePredicateByLabel(ReadGraph graph, Resource instance, String predicateName) throws DatabaseException {
1404         Layer0 L0 = Layer0.getInstance(graph);
1405         for(Resource type : graph.getPrincipalTypes(instance)) {
1406                 Map<String, Resource> domainOf = getDomainOf(graph, type);
1407                 for(Resource r : domainOf.values()) {
1408                         String label = graph.getPossibleRelatedValue(r, L0.HasLabel, Bindings.STRING);
1409                         if(predicateName.equals(label))
1410                                 return r;
1411                 }
1412         }
1413         return null;
1414     }
1415     
1416     public static void claimLiteralDataboard(WriteGraph graph, Resource container, Resource property, String valueText) throws DatabaseException {
1417
1418         try {
1419                 PropertyInfo pi = graph.syncRequest(new PropertyInfoRequest(property));
1420                 if(pi.literalRange == null) throw new DatabaseException("No suitable literal type defined as range for property.");
1421                 if(pi.defaultBinding == null) throw new DatabaseException("No suitable default binding for property.");
1422                         Object value = pi.defaultBinding.parseValue(valueText, new DataValueRepository());
1423                         graph.claimLiteral(container, property, pi.literalRange, value, pi.defaultBinding);
1424                 } catch (DataTypeSyntaxError e) {
1425                         throw new DatabaseException(e);
1426                 } catch (BindingException e) {
1427                         throw new DatabaseException(e);
1428                 }
1429         
1430     }
1431
1432     public static String prettyPrintResource(ReadGraph graph, Resource resource, boolean ignoreIdentifiers) throws Exception {
1433         TransferableGraphSource source = makeTGSource(graph, resource);
1434         TransferableGraph1 tg = TransferableGraphs.create(graph, source);
1435         GraphRefactoringUtils.fixOntologyExport(tg);
1436         System.out.println("Printing resoure " + graph.getURI(resource));
1437         return PrettyPrintTG.print(tg, ignoreIdentifiers);
1438     }
1439
1440     /**
1441      * Adds a random {@link GUID} as a value for <code>L0.identifier</code>
1442      * 
1443      * @param graph
1444      * @param component
1445      *            for which the identifier is added
1446      * @param add
1447      *            <code>true</code> to invoke addLiteral, <code>false</code> to
1448      *            invoke claimLiteral
1449      * @throws DatabaseException
1450      */
1451     public static void claimNewIdentifier(WriteGraph graph, Resource component, boolean add) throws DatabaseException {
1452         Layer0 L0 = Layer0.getInstance(graph);
1453         GUID guid = GUID.random();
1454         if (add)
1455             graph.addLiteral(component, L0.identifier, L0.identifier_Inverse, L0.GUID, guid, GUID.BINDING);
1456         else
1457             graph.claimLiteral(component, L0.identifier, L0.identifier_Inverse, L0.GUID, guid, GUID.BINDING);
1458     }
1459
1460     /**
1461      * Sets a new random unique identifier for the specified entity if it already
1462      * has an identifier. If the entity does not have a previous identifier, nothing
1463      * is done.
1464      * 
1465      * @param graph
1466      * @param entity
1467      *            for which the identifier is added
1468      * @return <code>true</code> if the identifier was renewed, <code>false</code>
1469      *         otherwise
1470      * @throws DatabaseException
1471      * @see {@link #claimNewIdentifier(WriteGraph, Resource, boolean)}
1472      */
1473     public static boolean renewIdentifier(WriteGraph graph, Resource entity) throws DatabaseException {
1474         Layer0 L0 = Layer0.getInstance(graph);
1475         Statement stm = graph.getPossibleStatement(entity, L0.identifier);
1476         if (stm != null) {
1477             graph.claimValue(stm.getObject(), GUID.random(), GUID.BINDING);
1478             return true;
1479         }
1480         return false;
1481     }
1482
1483     public static void addMetadataListener(ChangeListener listener) {
1484         SimanticsInternal.getSession().getService(GraphChangeListenerSupport.class).addMetadataListener(listener);
1485     }
1486
1487     public static void removeMetadataListener(ChangeListener listener) {
1488         SimanticsInternal.getSession().getService(GraphChangeListenerSupport.class).removeMetadataListener(listener);
1489     }
1490
1491 }