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