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