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