1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
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
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.db.layer0.genericrelation;
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;
21 import java.util.UUID;
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.Logger;
44 import org.simantics.db.common.utils.NameUtils;
45 import org.simantics.db.event.ChangeListener;
46 import org.simantics.db.exception.DatabaseException;
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;
66 public class DependenciesRelation extends UnsupportedRelation implements GenericRelationIndex {
68 private static final boolean DEBUG = false;
69 static final boolean DEBUG_LISTENERS = false;
70 private static final boolean PROFILE = false;
72 @SuppressWarnings("unchecked")
73 private final static Pair<String, String>[] fields = new Pair[] {
74 Pair.make(Dependencies.FIELD_MODEL, "Long"),
75 Pair.make(Dependencies.FIELD_PARENT, "Long"),
76 Pair.make(Dependencies.FIELD_RESOURCE, "Long"),
77 Pair.make(Dependencies.FIELD_NAME, "String"),
78 Pair.make(Dependencies.FIELD_TYPES, "Text"),
79 Pair.make(Dependencies.FIELD_GUID, "Text")
82 final Resource resource;
84 public DependenciesRelation(ReadGraph graph, Resource resource) {
85 this.resource = resource;
87 Session session = graph.getSession();
88 DependenciesListenerStore store = session.peekService(DependenciesListenerStore.class);
89 if(store == null) session.registerService(DependenciesListenerStore.class, new DependenciesListenerStore());
95 final ArrayList<Entry> result = new ArrayList<Entry>();
96 final AsyncContextMultiProcedure<Resource, Resource> structure;
97 final AsyncContextProcedure<Entry, String> names;
98 final AsyncContextProcedure<Entry, Resource> type;
100 Process(ReadGraph graph, final Resource resource) throws DatabaseException {
102 final Layer0 L0 = Layer0.getInstance(graph);
103 final DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
104 final CollectionSupport cs = graph.getService(CollectionSupport.class);
106 names = dqs.compilePossibleRelatedValue(graph, L0.HasName, new AsyncContextProcedure<Entry, String>() {
109 public void execute(AsyncReadGraph graph, Entry entry, String name) {
114 public void exception(AsyncReadGraph graph, Throwable throwable) {
115 Logger.defaultLogError(throwable);
120 type = new AsyncContextProcedure<Entry, Resource>() {
123 public void execute(AsyncReadGraph graph, Entry entry, Resource type) {
124 entry.principalType = type;
128 public void exception(AsyncReadGraph graph, Throwable throwable) {
129 Logger.defaultLogError(throwable);
134 structure = dqs.compileForEachObject(graph, L0.ConsistsOf, new AsyncContextMultiProcedure<Resource, Resource>() {
137 public void execute(AsyncReadGraph graph, Resource parent, Resource child) {
138 // WORKAROUND: don't browse virtual child resources
139 if(!child.isPersistent()) return;
140 Entry entry = new Entry(parent, child, "", "", "");
142 dqs.forEachObjectCompiled(graph, child, child, structure);
143 dqs.forPossibleRelatedValueCompiled(graph, child, entry, names);
144 dqs.forPossibleDirectType(graph, child, entry, type);
148 public void finished(AsyncReadGraph graph, Resource parent) {
152 public void exception(AsyncReadGraph graph, Throwable throwable) {
153 Logger.defaultLogError(throwable);
158 graph.syncRequest(new ReadRequest() {
161 public void run(ReadGraph graph) throws DatabaseException {
162 dqs.forEachObjectCompiled(graph, resource, resource, structure);
167 Map<Resource, String> typeStrings = cs.createMap(String.class);
168 for(Entry e : result) {
169 if(e.principalType != null) {
170 String typeString = typeStrings.get(e.principalType);
171 if(typeString == null) {
172 typeString = graph.syncRequest(new SuperTypeString(e.principalType));
173 if (typeString.isEmpty()) {
174 Logger.defaultLogError(new DatabaseException("No name for type " + NameUtils.getURIOrSafeNameInternal(graph, e.resource) + " (" + e.resource + ")"));
176 typeStrings.put(e.principalType, typeString);
178 e.types = typeString;
180 e.types = graph.syncRequest(new TypeString(L0, graph.getTypes(e.resource)));
182 GUID id = graph.getPossibleRelatedValue(e.resource, L0.identifier, GUID.BINDING);
184 e.id = id.indexString();
189 //SessionGarbageCollection.gc(null, graph.getSession(), false, null);
195 public ArrayList<Entry> find(ReadGraph graph, final Resource model) throws DatabaseException {
196 return new Process(graph, model).result;
200 public GenericRelation select(String bindingPattern, Object[] constants) {
201 checkSelectionArguments(bindingPattern, constants, new String[] { Dependencies.getBindingPattern() });
202 final long subjectId = (Long)constants[0];
203 return new UnsupportedRelation() {
206 public boolean isRealizable() {
211 final public List<Object[]> realize(ReadGraph graph) throws DatabaseException {
213 long time = System.nanoTime();
215 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
217 Resource subject = ss.getResource(subjectId);
219 Collection<Entry> entries = find(graph, subject);
221 long time2 = System.nanoTime();
224 System.out.println("Found " + entries.size() + " dependencies in " + 1e-6 * (time2 - time) + "ms for " + graph.getPossibleURI(subject) + ".");
226 ArrayList<Object[]> result = new ArrayList<Object[]>();
227 for (Entry entry : entries) {
228 result.add(new Object[] { ss.getRandomAccessId(entry.parent), ss.getRandomAccessId(entry.resource), entry.name, entry.types, entry.id });
238 public Pair<String, String>[] getFields() {
243 public List<Map<String, Object>> query(RequestProcessor session, String search, String bindingPattern, Object[] constants, int maxResultCount) {
244 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffff'");
245 IndexedRelations indexer = session.getService(IndexedRelations.class);
246 return indexer.query(null, search, session, resource, (Resource)constants[0], maxResultCount);
250 public List<Resource> queryResources(RequestProcessor session, String search, String bindingPattern, Object[] constants, int maxResultCount) {
251 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffff'");
252 IndexedRelations indexer = session.getService(IndexedRelations.class);
253 return indexer.queryResources(null, search, session, resource, (Resource)constants[0], maxResultCount);
257 public List<Map<String, Object>> list(RequestProcessor session, String bindingPattern, Object[] constants, int maxResultCount) {
258 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffff'");
259 IndexedRelations indexer = session.getService(IndexedRelations.class);
260 return indexer.query(null, null, session, resource, (Resource)constants[0], maxResultCount);
263 public static class DependencyChangesRequest extends UnaryRead<ChangeSet, DependencyChanges> {
265 @SuppressWarnings("unused")
266 final private static boolean LOG = false;
268 public DependencyChangesRequest(ChangeSet parameter) {
273 public DependencyChanges perform(ReadGraph graph) throws DatabaseException {
275 DependencyChangesWriter w = new DependencyChangesWriter(graph);
277 Resource changeInformation = graph.getPossibleResource("http://www.simantics.org/Modeling-1.2/changeInformation/Inverse");
279 for (Resource value : parameter.changedValues()) {
280 Statement modifiedComponent = graph.getPossibleStatement(value, l0.PropertyOf);
281 if (modifiedComponent == null
282 || modifiedComponent.getPredicate().equals(changeInformation))
284 //System.err.println("+comp modi " + NameUtils.getSafeName(graph, renamedComponent, true));
285 w.addComponentModification(modifiedComponent.getObject());
287 for (Resource value : parameter.changedResources()) {
288 // No more info => need to check further
289 if(!graph.isImmutable(value))
290 w.addComponentModification(value);
292 for (StatementChange change : parameter.changedStatements()) {
293 //System.err.println("-stm " + NameUtils.getSafeName(graph, change.getSubject(), true) + " " + NameUtils.getSafeName(graph, change.getPredicate(), true) + " " + NameUtils.getSafeName(graph, change.getObject(), true));
294 Resource subject = change.getSubject();
295 Resource predicate = change.getPredicate();
296 Resource object = change.getObject();
297 if(!object.isPersistent()) continue;
298 if (predicate.equals(l0.ConsistsOf)) {
299 if (change.isClaim())
300 w.addComponentAddition(subject, object);
302 w.addComponentRemoval(subject, object);
303 } else if (predicate.equals(l0.IsLinkedTo)) {
304 w.addLinkChange(subject);
305 } else /*if (graph.isSubrelationOf(predicate, l0.DependsOn))*/ {
306 //System.err.println("-modi " + NameUtils.getSafeName(graph, subject, true));
307 w.addComponentModification(subject);
310 return w.getResult();
315 private static int trackers = 0;
317 private static ChangeListener listener;
319 public static void assertFinishedTracking() {
320 if(trackers != 0) throw new IllegalStateException("Trackers should be 0 (was " + trackers + ")");
324 public synchronized void untrack(RequestProcessor processor, final Resource model) {
328 if(trackers < 0) throw new IllegalStateException("Dependency tracking reference count is broken");
332 if(listener == null) throw new IllegalStateException("Dependency tracking was not active");
334 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
335 changeSupport.removeMetadataListener(listener);
343 public synchronized void trackAndIndex(RequestProcessor processor, Resource model__) {
347 if(listener != null) throw new IllegalStateException("Dependency tracking was active");
349 listener = new GenericChangeListener<DependencyChangesRequest, DependencyChanges>() {
352 public boolean preEventRequest() {
353 return !Indexing.isDependenciesIndexingDisabled();
357 public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
359 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update processing");
362 System.err.println("Adding metadata " + event + " in revision " + graph.getService(ManagementSupport.class).getHeadRevisionId());
364 WriteGraph w = (WriteGraph)graph;
366 w.addMetadata(event);
368 final Session session = graph.getSession();
369 final IndexedRelations indexer = session.getService(IndexedRelations.class);
370 Layer0 L0 = Layer0.getInstance(graph);
371 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
373 for(Map.Entry<Resource, Change[]> modelEntry : event.get().entrySet()) {
375 final Resource model = modelEntry.getKey();
376 final Change[] changes = modelEntry.getValue();
378 boolean linkChange = false;
380 Collection<Object[]> _additions = Collections.emptyList();
381 Collection<Object> _removals = Collections.emptyList();
382 Collection<Object> _replacementKeys = Collections.emptyList();
383 Collection<Object[]> _replacementObjects = Collections.emptyList();
384 Collection<Pair<String, String>> _typeChanges = Collections.emptyList();
386 if(DEBUG) System.out.println("MODEL: " + NameUtils.getSafeLabel(graph, model));
387 // final Change[] changes = event.get(model);
388 if(DEBUG) System.out.println(" CHANGES: " + Arrays.toString(changes));
389 if (changes != null) {
390 _additions = new ArrayList<Object[]>();
391 _removals = new ArrayList<Object>();
392 _replacementKeys = new ArrayList<Object>();
393 _replacementObjects = new ArrayList<Object[]>();
394 _typeChanges = new HashSet<Pair<String, String>>();
396 for (Change _entry : changes) {
397 if (_entry instanceof ComponentAddition) {
398 ComponentAddition entry = (ComponentAddition)_entry;
399 final String name = graph.getPossibleRelatedValue(entry.component, L0.HasName, Bindings.STRING);
400 final GUID id = graph.getPossibleRelatedValue(entry.component, L0.identifier, GUID.BINDING);
401 final String types = graph.syncRequest(new TypeString(L0, graph.getTypes(entry.component)));
402 if (name != null && types != null) {
403 if(!entry.isValid(graph)) continue;
404 Resource parent = graph.getPossibleObject(entry.component, L0.PartOf);
405 if (parent != null) {
406 _additions.add(new Object[] { ss.getRandomAccessId(parent), ss.getRandomAccessId(entry.component), name, types, id != null ? id.indexString() : "" });
408 //System.err.println("resource " + entry.component + ": no parent for entry " + name + " " + types);
411 //System.err.println("resource " + entry.component + ": " + name + " " + types);
413 } else if(_entry instanceof ComponentModification) {
414 ComponentModification entry = (ComponentModification)_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 if(graph.isInstanceOf(entry.component, L0.Type)) {
418 SerialisationSupport support = session.getService(SerialisationSupport.class);
419 _typeChanges.add(new Pair<String, String>(name, String.valueOf(support.getRandomAccessId((Resource) entry.component))));
421 final String types = graph.syncRequest(new TypeString(L0, graph.getTypes(entry.component)));
422 if (name != null && types != null) {
423 Resource part = graph.getPossibleObject(entry.component, L0.PartOf);
425 _replacementKeys.add(ss.getRandomAccessId(entry.component));
426 _replacementObjects.add(new Object[] { ss.getRandomAccessId(part),
427 ss.getRandomAccessId(entry.component), name, types, id != null ? id.indexString() : "" });
431 } else if (_entry instanceof ComponentRemoval) {
432 ComponentRemoval entry = (ComponentRemoval)_entry;
433 if(!entry.isValid(graph)) continue;
434 _removals.add(ss.getRandomAccessId(((ComponentRemoval)_entry).component));
435 } else if (_entry instanceof LinkChange) {
441 final boolean reset = linkChange || event.hasUnresolved;
442 //System.err.println("dependencies(" + NameUtils.getSafeLabel(graph, model) + "): reset=" + reset + " linkChange=" + linkChange + " unresolved=" + event.hasUnresolved );
444 if (reset || !_additions.isEmpty() || !_removals.isEmpty() || !_replacementKeys.isEmpty() || !_typeChanges.isEmpty()) {
446 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update");
448 final Collection<Object[]> additions = _additions;
449 final Collection<Object> removals = _removals;
450 final Collection<Object> replacementKeys = _replacementKeys;
451 final Collection<Object[]> replacementObjects = _replacementObjects;
452 final boolean typeNameChanges = typeNameChanges(graph, indexer, model, _typeChanges);
454 final UUID pending = Indexing.makeIndexPending();
459 boolean didChange = false;
460 // Unresolved and linkChanges are not relevant any more
461 boolean doReset = typeNameChanges;
466 System.err.println("resetIndex " + reset + " " + typeNameChanges);
469 indexer.removeAll(null, graph, DependenciesRelation.this, resource, model);
474 if (!replacementKeys.isEmpty() && (replacementKeys.size() == replacementObjects.size())) {
476 System.out.println(replacementKeys.size() + " index replacements: " + replacementKeys);
478 didChange |= indexer.replace(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, replacementKeys, replacementObjects);
480 if (!removals.isEmpty()) {
482 System.out.println(removals.size() + " index removals: " + removals);
484 indexer.remove(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, removals);
487 if (!additions.isEmpty()) {
489 for(Object[] os : additions) System.err.println("Adding to index " + model + ": " + Arrays.toString(os));
491 //System.out.println(additions.size() + " index insertions");
492 indexer.insert(null, graph, DependenciesRelation.this, resource, model, additions);
499 // TODO: because this data is ran with
500 // ThreadUtils.getBlockingWorkExecutor()
501 // fireListeners needs to use peekService,
502 // not getService since there is no
503 // guarantee that the session isn't being
504 // disposed while this method is executing.
505 fireListeners(graph, model);
507 } catch (Throwable t) {
508 // Just to know if something unexpected happens here.
509 Logger.defaultLogError("Dependencies index update failed for model "
510 + model + " and relation " + resource + ".", t);
513 // NOTE: Last resort: failure to update index
514 // properly results in removal of the whole index.
515 // This is the only thing that can be done
516 // at this point to ensure that the index will
517 // return correct results in the future, through
518 // complete reinitialization.
519 //indexer.removeAll(null, session, DependenciesRelation.this, resource, model);
521 Indexing.releaseIndexPending(pending);
522 Indexing.clearCaches(model);
527 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: index update done");
535 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
536 changeSupport.addMetadataListener(listener);
544 private boolean typeNameChanges(ReadGraph graph, IndexedRelations indexer,
545 Resource model, final Collection<Pair<String, String>> typeChanges)
546 throws DatabaseException {
547 if (typeChanges.isEmpty())
550 for (Pair<String, String> nr : typeChanges) {
551 String query = Dependencies.FIELD_RESOURCE + ":[" + nr.second + " TO " + nr.second + "]";
552 //System.out.println("query: " + query);
553 List<Map<String, Object>> results = indexer.query(null, query, graph, resource, model, Integer.MAX_VALUE);
554 if (results.size() != 1) {
557 Map<String, Object> result = results.get(0);
558 if (!ObjectUtils.objectEquals(result.get(Dependencies.FIELD_NAME), nr.first)) {
562 // System.err.println("Type " + nr.first + " was unchanged.");
568 public void addListener(RequestProcessor processor, Resource model, Runnable observer) {
569 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
570 store.addListener(model, observer);
574 public void removeListener(RequestProcessor processor, Resource model, Runnable observer) {
575 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
576 store.removeListener(model, observer);
579 void fireListeners(RequestProcessor processor, Resource model) {
580 DependenciesListenerStore store = processor.getSession().peekService(DependenciesListenerStore.class);
582 store.fireListeners(model);
586 public void reset(RequestProcessor processor, Resource input) {
588 System.out.println("DependenciesRelation.reset: " + input);
589 new Exception("DependenciesRelation.reset(" + listener + ")").printStackTrace(System.out);
591 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
592 store.fireListeners(input);
595 public static void addSubtree(ReadGraph graph, Resource root) throws DatabaseException {
597 Resource indexRoot = graph.syncRequest(new IndexRoot(root));
598 addSubtree(graph, indexRoot, root);
602 public static void addSubtree(ReadGraph graph, Resource indexRoot, Resource subtreeRoot) throws DatabaseException {
604 DependenciesRelation dr = new DependenciesRelation(graph, indexRoot);
605 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
607 ArrayList<Entry> entries = dr.find(graph, subtreeRoot);
608 entries.add(new Entry(graph, subtreeRoot));
610 ArrayList<Object[]> result = new ArrayList<Object[]>(entries.size());
611 for (Entry entry : entries) {
612 result.add(new Object[] { ss.getRandomAccessId(entry.parent), ss.getRandomAccessId(entry.resource), entry.name, entry.types, entry.id });
615 Layer0X L0X = Layer0X.getInstance(graph);
616 IndexedRelations indexer = graph.getService(IndexedRelations.class);
617 indexer.insert(null, graph, dr, L0X.DependenciesRelation, indexRoot, result);