]> gerrit.simantics Code Review - simantics/platform.git/blob
fc32222084c0f7e08509c152a882b893e7bd5b61
[simantics/platform.git] /
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.db.layer0.genericrelation;
13
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.HashSet;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.UUID;
22
23 import org.simantics.databoard.Bindings;
24 import org.simantics.databoard.util.ObjectUtils;
25 import org.simantics.datatypes.literal.GUID;
26 import org.simantics.db.AsyncReadGraph;
27 import org.simantics.db.ChangeSet;
28 import org.simantics.db.ChangeSet.StatementChange;
29 import org.simantics.db.MetadataI;
30 import org.simantics.db.ReadGraph;
31 import org.simantics.db.RequestProcessor;
32 import org.simantics.db.Resource;
33 import org.simantics.db.Session;
34 import org.simantics.db.Statement;
35 import org.simantics.db.WriteGraph;
36 import org.simantics.db.common.Indexing;
37 import org.simantics.db.common.changeset.GenericChangeListener;
38 import org.simantics.db.common.request.IndexRoot;
39 import org.simantics.db.common.request.ReadRequest;
40 import org.simantics.db.common.request.SuperTypeString;
41 import org.simantics.db.common.request.TypeString;
42 import org.simantics.db.common.request.UnaryRead;
43 import org.simantics.db.common.utils.NameUtils;
44 import org.simantics.db.event.ChangeListener;
45 import org.simantics.db.exception.DatabaseException;
46 import org.simantics.db.exception.NoSingleResultException;
47 import org.simantics.db.layer0.adapter.GenericRelation;
48 import org.simantics.db.layer0.adapter.GenericRelationIndex;
49 import org.simantics.db.layer0.genericrelation.DependencyChanges.Change;
50 import org.simantics.db.layer0.genericrelation.DependencyChanges.ComponentAddition;
51 import org.simantics.db.layer0.genericrelation.DependencyChanges.ComponentModification;
52 import org.simantics.db.layer0.genericrelation.DependencyChanges.ComponentRemoval;
53 import org.simantics.db.layer0.genericrelation.DependencyChanges.LinkChange;
54 import org.simantics.db.procedure.AsyncContextMultiProcedure;
55 import org.simantics.db.procedure.AsyncContextProcedure;
56 import org.simantics.db.service.CollectionSupport;
57 import org.simantics.db.service.DirectQuerySupport;
58 import org.simantics.db.service.GraphChangeListenerSupport;
59 import org.simantics.db.service.ManagementSupport;
60 import org.simantics.db.service.SerialisationSupport;
61 import org.simantics.layer0.Layer0;
62 import org.simantics.operation.Layer0X;
63 import org.simantics.utils.datastructures.Pair;
64 import org.simantics.utils.logging.TimeLogger;
65 import org.slf4j.LoggerFactory;
66
67 public class DependenciesRelation extends UnsupportedRelation implements GenericRelationIndex {
68
69     private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DependenciesRelation.class);
70         private static final boolean DEBUG = false;
71         static final boolean DEBUG_LISTENERS = false;
72         private static final boolean PROFILE = false;
73
74         @SuppressWarnings("unchecked")
75         private final static Pair<String, String>[] fields = new Pair[] {
76                 Pair.make(Dependencies.FIELD_MODEL, "Long"),
77                 Pair.make(Dependencies.FIELD_PARENT, "Long"),
78                 Pair.make(Dependencies.FIELD_RESOURCE, "Long"),
79                 Pair.make(Dependencies.FIELD_NAME, "String"),
80                 Pair.make(Dependencies.FIELD_TYPES, "Text"),
81                 Pair.make(Dependencies.FIELD_GUID, "Text")
82         };
83
84         final Resource resource;
85
86         public DependenciesRelation(ReadGraph graph, Resource resource) {
87                 this.resource = resource;
88                 synchronized(this) {
89                         Session session = graph.getSession();
90                         DependenciesListenerStore store = session.peekService(DependenciesListenerStore.class);
91                         if(store == null) session.registerService(DependenciesListenerStore.class, new DependenciesListenerStore());
92                 }
93         }
94
95         class Process {
96
97                 final ArrayList<Entry> result = new ArrayList<Entry>();
98                 final AsyncContextMultiProcedure<Resource, Resource> structure;
99                 final AsyncContextProcedure<Entry, String> names;
100                 final AsyncContextProcedure<Entry, Resource> type;
101
102                 Process(ReadGraph graph, final Resource resource) throws DatabaseException {
103
104                         final Layer0 L0 = Layer0.getInstance(graph);
105                         final DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
106                         final CollectionSupport cs = graph.getService(CollectionSupport.class);
107
108                         names = dqs.compilePossibleRelatedValue(graph, L0.HasName, new AsyncContextProcedure<Entry, String>() {
109
110                                 @Override
111                                 public void execute(AsyncReadGraph graph, Entry entry, String name) {
112                                         entry.name = name;
113                                 }
114
115                                 @Override
116                                 public void exception(AsyncReadGraph graph, Throwable throwable) {
117                                         LOGGER.error("Could not compile possible related value for resource {}", resource, throwable);
118                                 }
119
120                         });
121
122                         type = new AsyncContextProcedure<Entry, Resource>() {
123
124                                 @Override
125                                 public void execute(AsyncReadGraph graph, Entry entry, Resource type) {
126                                         entry.principalType = type;
127                                 }
128
129                                 @Override
130                                 public void exception(AsyncReadGraph graph, Throwable throwable) {
131                                         LOGGER.error("Could not find type for resource {}", resource, throwable);
132                                 }
133
134                         };
135
136                         structure = dqs.compileForEachObject(graph, L0.ConsistsOf, new AsyncContextMultiProcedure<Resource, Resource>() {
137
138                                 @Override
139                                 public void execute(AsyncReadGraph graph, Resource parent, Resource child) {
140                                         // WORKAROUND: don't browse virtual child resources
141                                         if(!child.isPersistent()) return;
142                                         Entry entry = new Entry(parent, child, "", "", "");
143                                         result.add(entry);
144                                         dqs.forEachObjectCompiled(graph, child, child, structure);
145                                         dqs.forPossibleRelatedValueCompiled(graph, child, entry, names);
146                                         dqs.forPossibleDirectType(graph, child, entry, type);
147                                 }
148
149                                 @Override
150                                 public void finished(AsyncReadGraph graph, Resource parent) {
151                                 }
152
153                                 @Override
154                                 public void exception(AsyncReadGraph graph, Throwable throwable) {
155                                     if (throwable instanceof NoSingleResultException) {
156                                         // Ignore
157                                         if (LOGGER.isDebugEnabled())
158                                             LOGGER.debug("Could not compile for resource {}", resource, throwable);
159                                     } else {
160                                         LOGGER.error("Could not compile for resource {}", resource, throwable);
161                                     }
162                                 }
163
164                         });
165
166                         graph.syncRequest(new ReadRequest() {
167
168                                 @Override
169                                 public void run(ReadGraph graph) throws DatabaseException {
170                                         dqs.forEachObjectCompiled(graph, resource, resource, structure);
171                                 }
172
173                         });
174
175             Map<Resource, String> typeStrings = cs.createMap(String.class);
176                         for(Entry e : result) {
177                                 if(e.principalType != null) {
178                                     String typeString = typeStrings.get(e.principalType);
179                                     if(typeString == null) {
180                                         typeString = graph.syncRequest(new SuperTypeString(e.principalType));
181                                         if (typeString.isEmpty()) {
182                                             LOGGER.error("No name for type", new DatabaseException("No name for type " + NameUtils.getURIOrSafeNameInternal(graph, e.resource) + " (" + e.resource + ")"));
183                                         }
184                                         typeStrings.put(e.principalType, typeString);
185                                     }
186                                     e.types = typeString;
187                                 } else {
188                                     e.types = graph.syncRequest(new TypeString(L0, graph.getTypes(e.resource)));
189                                 }
190                                 GUID id = graph.getPossibleRelatedValue(e.resource, L0.identifier, GUID.BINDING);
191                                 if(id != null)
192                                         e.id = id.indexString();
193                                 else 
194                                         e.id = "";
195                         }
196
197                         //SessionGarbageCollection.gc(null, graph.getSession(), false, null);
198                         
199                 }
200
201         }
202
203         public ArrayList<Entry> find(ReadGraph graph, final Resource model) throws DatabaseException {
204                 return new Process(graph, model).result;
205         }
206
207         @Override
208         public GenericRelation select(String bindingPattern, Object[] constants) {
209                 checkSelectionArguments(bindingPattern, constants, new String[] { Dependencies.getBindingPattern() });
210                 final long subjectId = (Long)constants[0];
211                 return new UnsupportedRelation() {
212
213                         @Override
214                         public boolean isRealizable() {
215                                 return true;
216                         }
217
218                         @Override
219                         final public List<Object[]> realize(ReadGraph graph) throws DatabaseException {
220
221                                 long time = System.nanoTime();
222
223                 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
224
225                                 Resource subject = ss.getResource(subjectId); 
226                                 
227                                 Collection<Entry> entries = find(graph, subject);
228
229                                 long time2 = System.nanoTime();
230
231                                 if (PROFILE)
232                                         System.out.println("Found " + entries.size() + " dependencies in " + 1e-6 * (time2 - time) + "ms for " + graph.getPossibleURI(subject) + ".");
233
234                                 ArrayList<Object[]> result = new ArrayList<Object[]>();
235                                 for (Entry entry : entries) {
236                                         result.add(new Object[] { ss.getRandomAccessId(entry.parent), ss.getRandomAccessId(entry.resource), entry.name, entry.types, entry.id });
237                                 }
238                                 return result;
239
240                         }
241
242                 };
243         }
244
245         @Override
246         public Pair<String, String>[] getFields() {
247                 return fields;
248         }
249
250         @Override
251         public List<Map<String, Object>> query(RequestProcessor session, String search, String bindingPattern, Object[] constants, int maxResultCount) {
252                 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffff'");
253                 IndexedRelations indexer = session.getService(IndexedRelations.class);
254                 return indexer.query(null, search, session, resource, (Resource)constants[0], maxResultCount);
255         }
256         
257         @Override
258         public List<Resource> queryResources(RequestProcessor session, String search, String bindingPattern, Object[] constants, int maxResultCount) {
259                 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffff'");
260                 IndexedRelations indexer = session.getService(IndexedRelations.class);
261                 return indexer.queryResources(null, search, session, resource, (Resource)constants[0], maxResultCount);
262         }
263
264         @Override
265         public List<Map<String, Object>> list(RequestProcessor session, String bindingPattern, Object[] constants, int maxResultCount) {
266                 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffff'");
267                 IndexedRelations indexer = session.getService(IndexedRelations.class);
268                 return indexer.query(null, null, session, resource, (Resource)constants[0], maxResultCount);
269         }
270
271         public static class DependencyChangesRequest extends UnaryRead<ChangeSet, DependencyChanges> {
272
273                 @SuppressWarnings("unused")
274                 final private static boolean LOG = false;
275
276                 public DependencyChangesRequest(ChangeSet parameter) {
277                         super(parameter);
278                 }
279
280                 @Override
281                 public DependencyChanges perform(ReadGraph graph) throws DatabaseException {
282
283                         DependencyChangesWriter w = new DependencyChangesWriter(graph);
284                         Layer0 l0 = w.l0;
285                         Resource changeInformation = graph.getPossibleResource("http://www.simantics.org/Modeling-1.2/changeInformation/Inverse");
286
287                         for (Resource value : parameter.changedValues()) {
288                                 if(!value.isPersistent()) continue;
289                                 Statement modifiedComponent = graph.getPossibleStatement(value, l0.PropertyOf);
290                                 if (modifiedComponent == null
291                                                 || modifiedComponent.getPredicate().equals(changeInformation))
292                                         continue;
293                                 //System.err.println("+comp modi " + NameUtils.getSafeName(graph, renamedComponent, true));
294                                 w.addComponentModification(modifiedComponent.getObject());
295                         }
296                         for (Resource value : parameter.changedResources()) {
297                                 // No more info => need to check further
298                                 if(!graph.isImmutable(value))
299                                         w.addComponentModification(value);
300                         }
301                         for (StatementChange change : parameter.changedStatements()) {
302                                 //System.err.println("-stm " + NameUtils.getSafeName(graph, change.getSubject(), true) + " " + NameUtils.getSafeName(graph, change.getPredicate(), true) + " " + NameUtils.getSafeName(graph, change.getObject(), true));
303                                 Resource subject = change.getSubject();
304                                 Resource predicate = change.getPredicate();
305                                 Resource object = change.getObject();
306                                 if(!object.isPersistent()) continue;
307                                 if (predicate.equals(l0.ConsistsOf)) {
308                                         if (change.isClaim())
309                                                 w.addComponentAddition(subject, object);
310                                         else 
311                                                 w.addComponentRemoval(subject, object);
312                                 } else if (predicate.equals(l0.IsLinkedTo)) {
313                                         w.addLinkChange(subject);
314                                 } else /*if (graph.isSubrelationOf(predicate, l0.DependsOn))*/ {
315                                         //System.err.println("-modi " + NameUtils.getSafeName(graph, subject, true));
316                                         w.addComponentModification(subject);
317                                 } 
318                         }
319                         return w.getResult();
320                 }
321
322         };
323
324         private static int trackers = 0;
325         
326         private static ChangeListener listener;
327
328         public static void assertFinishedTracking() {
329             if(trackers != 0) throw new IllegalStateException("Trackers should be 0 (was " + trackers + ")");
330         }
331         
332         @Override
333         public synchronized void untrack(RequestProcessor processor, final Resource model) {
334
335             trackers--;
336             
337             if(trackers < 0) throw new IllegalStateException("Dependency tracking reference count is broken");
338             
339             if(trackers == 0) {
340                 
341                 if(listener == null) throw new IllegalStateException("Dependency tracking was not active");
342             
343                 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
344                 changeSupport.removeMetadataListener(listener);
345                 listener = null;
346                         
347             }
348             
349         }
350
351         @Override
352         public synchronized void trackAndIndex(RequestProcessor processor, Resource model__) {
353
354             if(trackers == 0) {
355
356                 if(listener != null) throw new IllegalStateException("Dependency tracking was active");
357
358                 listener = new GenericChangeListener<DependencyChangesRequest, DependencyChanges>() {
359
360                     @Override
361                     public boolean preEventRequest() {
362                         return !Indexing.isDependenciesIndexingDisabled();
363                     }
364
365                     @Override
366                     public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
367
368                         TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update processing");
369
370                         if(DEBUG)
371                             System.err.println("Adding metadata " + event + " in revision " + graph.getService(ManagementSupport.class).getHeadRevisionId());
372
373                         WriteGraph w = (WriteGraph)graph;
374                         if(!event.isEmpty())
375                                 w.addMetadata(event);
376
377                         final Session session = graph.getSession();
378                         final IndexedRelations indexer = session.getService(IndexedRelations.class);
379                         Layer0 L0 = Layer0.getInstance(graph);
380                         SerialisationSupport ss = graph.getService(SerialisationSupport.class);
381
382                         for(Map.Entry<Resource, Change[]>  modelEntry : event.get().entrySet()) {
383
384                             final Resource model = modelEntry.getKey();
385                             final Change[] changes = modelEntry.getValue();
386
387                             boolean linkChange = false;
388
389                             Collection<Object[]> _additions = Collections.emptyList();
390                             Collection<Object> _removals = Collections.emptyList();
391                             Collection<Object> _replacementKeys = Collections.emptyList();
392                             Collection<Object[]> _replacementObjects = Collections.emptyList();
393                             Collection<Pair<String, String>> _typeChanges = Collections.emptyList();
394
395                             if(DEBUG) System.out.println("MODEL: " + NameUtils.getSafeLabel(graph, model));
396                             //                final Change[] changes = event.get(model);
397                             if(DEBUG) System.out.println("  CHANGES: " + Arrays.toString(changes));
398                             if (changes != null) {
399                                 _additions = new ArrayList<Object[]>();
400                                 _removals = new ArrayList<Object>();
401                                 _replacementKeys = new ArrayList<Object>();
402                                 _replacementObjects = new ArrayList<Object[]>();
403                                 _typeChanges = new HashSet<Pair<String, String>>();
404
405                                 for (Change _entry : changes) {
406                                     if (_entry instanceof ComponentAddition) {
407                                         ComponentAddition entry = (ComponentAddition)_entry;
408                                         final String name = graph.getPossibleRelatedValue(entry.component, L0.HasName, Bindings.STRING);
409                                         final GUID id = graph.getPossibleRelatedValue(entry.component, L0.identifier, GUID.BINDING);
410                                         final String types = graph.syncRequest(new TypeString(L0, graph.getTypes(entry.component)));
411                                         if (name != null && types != null) {
412                                                 if(!entry.isValid(graph)) continue;
413                                             Resource parent = graph.getPossibleObject(entry.component, L0.PartOf);
414                                             if (parent != null) {
415                                                 _additions.add(new Object[] { ss.getRandomAccessId(parent), ss.getRandomAccessId(entry.component), name, types, id != null ? id.indexString() : "" });
416                                             } else {
417                                                     //System.err.println("resource " + entry.component + ": no parent for entry " + name + " " + types);
418                                             }
419                                         } else {
420                                             //System.err.println("resource " + entry.component + ": " + name + " " + types);
421                                         }
422                                     } else if(_entry instanceof ComponentModification) {
423                                         ComponentModification entry = (ComponentModification)_entry;
424                                         final String name = graph.getPossibleRelatedValue(entry.component, L0.HasName, Bindings.STRING);
425                                         final GUID id = graph.getPossibleRelatedValue(entry.component, L0.identifier, GUID.BINDING);
426                                         if(graph.isInstanceOf(entry.component, L0.Type)) {
427                                             SerialisationSupport support = session.getService(SerialisationSupport.class);
428                                             _typeChanges.add(new Pair<String, String>(name, String.valueOf(support.getRandomAccessId((Resource) entry.component))));
429                                         } else {
430                                             final String types = graph.syncRequest(new TypeString(L0, graph.getTypes(entry.component)));
431                                             if (name != null && types != null) {
432                                                 Resource part = graph.getPossibleObject(entry.component, L0.PartOf);
433                                                 if(part != null) {
434                                                     _replacementKeys.add(ss.getRandomAccessId(entry.component));
435                                                     _replacementObjects.add(new Object[] { ss.getRandomAccessId(part), 
436                                                             ss.getRandomAccessId(entry.component), name, types, id != null ? id.indexString() : "" });
437                                                 }
438                                             }
439                                         }
440                                     } else if (_entry instanceof ComponentRemoval) {
441                                         ComponentRemoval entry = (ComponentRemoval)_entry;
442                                         if(!entry.isValid(graph)) continue;
443                                         _removals.add(ss.getRandomAccessId(((ComponentRemoval)_entry).component));
444                                     } else if (_entry instanceof LinkChange) {
445                                         linkChange = true;
446                                     }
447                                 }
448                             }
449
450                             final boolean reset = linkChange || event.hasUnresolved;
451                             //System.err.println("dependencies(" + NameUtils.getSafeLabel(graph, model) + "): reset=" + reset + " linkChange=" + linkChange + " unresolved=" + event.hasUnresolved );
452
453                             if (reset || !_additions.isEmpty() || !_removals.isEmpty() || !_replacementKeys.isEmpty() || !_typeChanges.isEmpty()) {
454
455                                 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update");
456
457                                 final Collection<Object[]> additions = _additions;
458                                 final Collection<Object> removals = _removals;
459                                 final Collection<Object> replacementKeys = _replacementKeys;
460                                 final Collection<Object[]> replacementObjects = _replacementObjects; 
461                                 final boolean typeNameChanges = typeNameChanges(graph, indexer, model, _typeChanges);
462
463                             final UUID pending = Indexing.makeIndexPending();
464
465                             {
466                                 {
467                                         try {
468                                             boolean didChange = false;
469                                             // Unresolved and linkChanges are not relevant any more
470                                             boolean doReset = typeNameChanges;
471
472                                             if (doReset) {
473
474                                             if(DEBUG) {
475                                                 System.err.println("resetIndex " + reset + " " + typeNameChanges);
476                                             }
477
478                                                 indexer.removeAll(null, graph, DependenciesRelation.this, resource, model);
479                                                 didChange = true;
480
481                                             } else {
482
483                                                 if (!replacementKeys.isEmpty() && (replacementKeys.size() == replacementObjects.size())) {
484                                                     if(DEBUG) {
485                                                         System.out.println(replacementKeys.size() + " index replacements: " + replacementKeys);
486                                                     }
487                                                     didChange |= indexer.replace(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, replacementKeys, replacementObjects);
488                                                 }
489                                                 if (!removals.isEmpty()) {
490                                                     if(DEBUG) {
491                                                         System.out.println(removals.size() + " index removals: " + removals);
492                                                     }
493                                                     indexer.remove(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, removals);
494                                                     didChange = true;
495                                                 }
496                                                 if (!additions.isEmpty()) {
497                                                     if(DEBUG) {
498                                                         for(Object[] os : additions) System.err.println("Adding to index " + model + ": " + Arrays.toString(os));
499                                                     }
500                                                     //System.out.println(additions.size() + " index insertions");
501                                                     indexer.insert(null, graph, DependenciesRelation.this, resource, model, additions);
502                                                     didChange = true;
503                                                 }
504
505                                             }
506
507                                             if (didChange)
508                                                 // TODO: because this data is ran with
509                                                 // ThreadUtils.getBlockingWorkExecutor()
510                                                 // fireListeners needs to use peekService,
511                                                 // not getService since there is no
512                                                 // guarantee that the session isn't being
513                                                 // disposed while this method is executing.
514                                                 fireListeners(graph, model);
515
516                                         } catch (Throwable t) {
517                                             // Just to know if something unexpected happens here.
518                                             LOGGER.error("Dependencies index update failed for model "
519                                                 + model + " and relation " + resource + ".", t);
520
521                                             // NOTE: Last resort: failure to update index
522                                             // properly results in removal of the whole index.
523                                             // This is the only thing that can be done
524                                             // at this point to ensure that the index will
525                                             // return correct results in the future, through
526                                             // complete reinitialization. 
527                                             //indexer.removeAll(null, session, DependenciesRelation.this, resource, model);
528                                         } finally {
529                                             Indexing.releaseIndexPending(pending);
530                                             Indexing.clearCaches(model);
531                                         }
532                                 }
533                             }
534
535                                 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: index update done");
536                             }
537                         }
538
539                     }
540
541                 };
542
543                 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
544                 changeSupport.addMetadataListener(listener);
545
546             }
547
548             trackers++;
549
550         }
551
552         private boolean typeNameChanges(ReadGraph graph, IndexedRelations indexer,
553                         Resource model, final Collection<Pair<String, String>> typeChanges)
554                         throws DatabaseException {
555                 if (typeChanges.isEmpty())
556                         return false;
557
558                 for (Pair<String, String> nr : typeChanges) {
559                         String query = Dependencies.FIELD_RESOURCE + ":[" + nr.second + " TO " + nr.second + "]";
560                         //System.out.println("query: " + query);
561                         List<Map<String, Object>> results = indexer.query(null, query, graph, resource, model, Integer.MAX_VALUE);
562                         if (results.size() != 1) {
563                                 return true;
564                         } else {
565                                 Map<String, Object> result = results.get(0);
566                                 if (!ObjectUtils.objectEquals(result.get(Dependencies.FIELD_NAME), nr.first)) {
567                                         return true;
568                                 }
569                         }
570 //                      System.err.println("Type " + nr.first + " was unchanged.");
571                 }
572                 return false;
573         }
574
575         @Override
576         public void addListener(RequestProcessor processor, Resource model, Runnable observer) {
577                 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
578                 store.addListener(model, observer);
579         }
580
581         @Override
582         public void removeListener(RequestProcessor processor, Resource model, Runnable observer) {
583                 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
584                 store.removeListener(model, observer);
585         }
586
587         void fireListeners(RequestProcessor processor, Resource model) {
588                 DependenciesListenerStore store = processor.getSession().peekService(DependenciesListenerStore.class);
589                 if (store != null)
590                         store.fireListeners(model);
591         }
592
593         @Override
594         public void reset(RequestProcessor processor, Resource input) {
595                 if (DEBUG) {
596                         System.out.println("DependenciesRelation.reset: " + input);
597                         new Exception("DependenciesRelation.reset(" + listener + ")").printStackTrace(System.out);
598                 }
599                 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
600                 store.fireListeners(input);
601         }
602
603         public static void addSubtree(ReadGraph graph, Resource root) throws DatabaseException {
604
605                 Resource indexRoot = graph.syncRequest(new IndexRoot(root));
606                 addSubtree(graph, indexRoot, root);
607
608         }
609
610         public static void addSubtree(ReadGraph graph, Resource indexRoot, Resource subtreeRoot) throws DatabaseException {
611                 
612                 DependenciesRelation dr = new DependenciesRelation(graph, indexRoot);
613         SerialisationSupport ss = graph.getService(SerialisationSupport.class);
614
615         ArrayList<Entry> entries = dr.find(graph, subtreeRoot);
616         entries.add(new Entry(graph, subtreeRoot));
617
618                 ArrayList<Object[]> result = new ArrayList<Object[]>(entries.size());
619                 for (Entry entry : entries) {
620                         result.add(new Object[] { ss.getRandomAccessId(entry.parent), ss.getRandomAccessId(entry.resource), entry.name, entry.types, entry.id });
621                 }
622
623                 Layer0X L0X = Layer0X.getInstance(graph);
624         IndexedRelations indexer = graph.getService(IndexedRelations.class);
625         indexer.insert(null, graph, dr, L0X.DependenciesRelation, indexRoot, result);
626                 
627         }
628         
629 }