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