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