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.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;
66 public class DependenciesRelation extends UnsupportedRelation implements GenericRelationIndex {
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;
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")
83 final Resource resource;
85 public DependenciesRelation(ReadGraph graph, Resource resource) {
86 this.resource = resource;
88 Session session = graph.getSession();
89 DependenciesListenerStore store = session.peekService(DependenciesListenerStore.class);
90 if(store == null) session.registerService(DependenciesListenerStore.class, new DependenciesListenerStore());
96 final ArrayList<Entry> result = new ArrayList<Entry>();
97 final SyncContextMultiProcedure<Resource, Resource> structure;
98 final SyncContextProcedure<Entry, String> names;
99 final SyncContextProcedure<Entry, Resource> type;
101 Process(ReadGraph graph, final Resource resource) throws DatabaseException {
103 final Layer0 L0 = Layer0.getInstance(graph);
104 final DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
105 final CollectionSupport cs = graph.getService(CollectionSupport.class);
107 names = dqs.compilePossibleRelatedValue(graph, L0.HasName, new SyncContextProcedure<Entry, String>() {
110 public void execute(ReadGraph graph, Entry entry, String name) {
115 public void exception(ReadGraph graph, Throwable throwable) {
116 LOGGER.error("Could not compile possible related value for resource {}", resource, throwable);
121 type = new SyncContextProcedure<Entry, Resource>() {
124 public void execute(ReadGraph graph, Entry entry, Resource type) {
125 entry.principalType = type;
129 public void exception(ReadGraph graph, Throwable throwable) {
130 LOGGER.error("Could not find type for resource {}", resource, throwable);
135 structure = dqs.compileForEachObject(graph, L0.ConsistsOf, new SyncContextMultiProcedure<Resource, Resource>() {
138 public void execute(ReadGraph graph, Resource parent, Resource child) {
139 // WORKAROUND: don't browse virtual child resources
140 if(!child.isPersistent()) return;
141 Entry entry = new Entry(parent, child, "", "", "");
143 dqs.forEachObjectCompiled(graph, child, child, structure);
144 dqs.forPossibleRelatedValueCompiled(graph, child, entry, names);
145 dqs.forPossibleDirectType(graph, child, entry, type);
149 public void finished(ReadGraph graph, Resource parent) {
153 public void exception(ReadGraph graph, Throwable throwable) {
154 if (throwable instanceof NoSingleResultException) {
156 if (LOGGER.isDebugEnabled())
157 LOGGER.debug("Could not compile for resource {}", resource, throwable);
159 LOGGER.error("Could not compile for resource {}", resource, throwable);
165 graph.syncRequest(new ReadRequest() {
168 public void run(ReadGraph graph) throws DatabaseException {
169 dqs.forEachObjectCompiled(graph, resource, resource, structure);
174 Map<Resource, String> typeStrings = cs.createMap(String.class);
175 for(Entry e : result) {
176 if(e.principalType != null) {
177 String typeString = typeStrings.get(e.principalType);
178 if(typeString == null) {
179 typeString = graph.syncRequest(new SuperTypeString(e.principalType));
180 if (typeString.isEmpty()) {
181 LOGGER.error("No name for type", new DatabaseException("No name for type " + NameUtils.getURIOrSafeNameInternal(graph, e.resource) + " (" + e.resource + ")"));
183 typeStrings.put(e.principalType, typeString);
185 e.types = typeString;
187 e.types = graph.syncRequest(new TypeString(L0, graph.getTypes(e.resource)));
189 GUID id = graph.getPossibleRelatedValue(e.resource, L0.identifier, GUID.BINDING);
191 e.id = id.indexString();
196 //SessionGarbageCollection.gc(null, graph.getSession(), false, null);
202 public ArrayList<Entry> find(ReadGraph graph, final Resource model) throws DatabaseException {
203 return new Process(graph, model).result;
207 public GenericRelation select(String bindingPattern, Object[] constants) {
208 checkSelectionArguments(bindingPattern, constants, new String[] { Dependencies.getBindingPattern() });
209 final long subjectId = (Long)constants[0];
210 return new UnsupportedRelation() {
213 public boolean isRealizable() {
218 final public List<Object[]> realize(ReadGraph graph) throws DatabaseException {
220 long time = System.nanoTime();
222 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
224 Resource subject = ss.getResource(subjectId);
226 Collection<Entry> entries = find(graph, subject);
228 long time2 = System.nanoTime();
231 System.out.println("Found " + entries.size() + " dependencies in " + 1e-6 * (time2 - time) + "ms for " + graph.getPossibleURI(subject) + ".");
233 ArrayList<Object[]> result = new ArrayList<Object[]>();
234 for (Entry entry : entries) {
235 result.add(new Object[] { ss.getRandomAccessId(entry.parent), ss.getRandomAccessId(entry.resource), entry.name, entry.types, entry.id });
245 public Pair<String, String>[] getFields() {
250 public List<Map<String, Object>> query(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.query(null, search, session, resource, (Resource)constants[0], maxResultCount);
257 public List<Resource> queryResources(RequestProcessor session, String search, 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.queryResources(null, search, session, resource, (Resource)constants[0], maxResultCount);
264 public List<Map<String, Object>> list(RequestProcessor session, String bindingPattern, Object[] constants, int maxResultCount) {
265 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffff'");
266 IndexedRelations indexer = session.getService(IndexedRelations.class);
267 return indexer.query(null, null, session, resource, (Resource)constants[0], maxResultCount);
270 public static class DependencyChangesRequest extends UnaryRead<ChangeSet, DependencyChanges> {
272 @SuppressWarnings("unused")
273 final private static boolean LOG = false;
275 public DependencyChangesRequest(ChangeSet parameter) {
280 public DependencyChanges perform(ReadGraph graph) throws DatabaseException {
282 DependencyChangesWriter w = new DependencyChangesWriter(graph);
284 Resource changeInformation = graph.getPossibleResource("http://www.simantics.org/Modeling-1.2/changeInformation/Inverse");
286 for (Resource value : parameter.changedValues()) {
287 if(!value.isPersistent()) continue;
288 Statement modifiedComponent = graph.getPossibleStatement(value, l0.PropertyOf);
289 if (modifiedComponent == null
290 || modifiedComponent.getPredicate().equals(changeInformation))
292 //System.err.println("+comp modi " + NameUtils.getSafeName(graph, renamedComponent, true));
293 w.addComponentModification(modifiedComponent.getObject());
295 for (Resource value : parameter.changedResources()) {
296 // No more info => need to check further
297 if(!graph.isImmutable(value))
298 w.addComponentModification(value);
300 for (StatementChange change : parameter.changedStatements()) {
301 //System.err.println("-stm " + NameUtils.getSafeName(graph, change.getSubject(), true) + " " + NameUtils.getSafeName(graph, change.getPredicate(), true) + " " + NameUtils.getSafeName(graph, change.getObject(), true));
302 Resource subject = change.getSubject();
303 Resource predicate = change.getPredicate();
304 Resource object = change.getObject();
305 if(!object.isPersistent()) continue;
306 if (predicate.equals(l0.ConsistsOf)) {
307 if (change.isClaim())
308 w.addComponentAddition(subject, object);
310 w.addComponentRemoval(subject, object);
311 } else if (predicate.equals(l0.IsLinkedTo)) {
312 w.addLinkChange(subject);
313 } else /*if (graph.isSubrelationOf(predicate, l0.DependsOn))*/ {
314 //System.err.println("-modi " + NameUtils.getSafeName(graph, subject, true));
315 w.addComponentModification(subject);
318 return w.getResult();
323 private static int trackers = 0;
325 private static ChangeListener listener;
327 public static void assertFinishedTracking() {
328 if(trackers != 0) throw new IllegalStateException("Trackers should be 0 (was " + trackers + ")");
332 public synchronized void untrack(RequestProcessor processor, final Resource model) {
336 if(trackers < 0) throw new IllegalStateException("Dependency tracking reference count is broken");
340 if(listener == null) throw new IllegalStateException("Dependency tracking was not active");
342 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
343 changeSupport.removeMetadataListener(listener);
351 public synchronized void trackAndIndex(RequestProcessor processor, Resource model__) {
355 if(listener != null) throw new IllegalStateException("Dependency tracking was active");
357 listener = new GenericChangeListener<DependencyChangesRequest, DependencyChanges>() {
360 public boolean preEventRequest() {
361 return !Indexing.isDependenciesIndexingDisabled();
365 public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
367 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update processing");
370 System.err.println("Adding metadata " + event + " in revision " + graph.getService(ManagementSupport.class).getHeadRevisionId());
372 WriteGraph w = (WriteGraph)graph;
374 w.addMetadata(event);
376 final Session session = graph.getSession();
377 final IndexedRelations indexer = session.getService(IndexedRelations.class);
378 Layer0 L0 = Layer0.getInstance(graph);
379 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
381 for(Map.Entry<Resource, Change[]> modelEntry : event.get().entrySet()) {
383 final Resource model = modelEntry.getKey();
384 final Change[] changes = modelEntry.getValue();
386 boolean linkChange = false;
388 Collection<Object[]> _additions = Collections.emptyList();
389 Collection<Object> _removals = Collections.emptyList();
390 Collection<Object> _replacementKeys = Collections.emptyList();
391 Collection<Object[]> _replacementObjects = Collections.emptyList();
392 Collection<Pair<String, String>> _typeChanges = Collections.emptyList();
394 if(DEBUG) System.out.println("MODEL: " + NameUtils.getSafeLabel(graph, model));
395 // final Change[] changes = event.get(model);
396 if(DEBUG) System.out.println(" CHANGES: " + Arrays.toString(changes));
397 if (changes != null) {
398 _additions = new ArrayList<Object[]>();
399 _removals = new ArrayList<Object>();
400 _replacementKeys = new ArrayList<Object>();
401 _replacementObjects = new ArrayList<Object[]>();
402 _typeChanges = new HashSet<Pair<String, String>>();
404 for (Change _entry : changes) {
405 if (_entry instanceof ComponentAddition) {
406 ComponentAddition entry = (ComponentAddition)_entry;
407 final String name = graph.getPossibleRelatedValue(entry.component, L0.HasName, Bindings.STRING);
408 final GUID id = graph.getPossibleRelatedValue(entry.component, L0.identifier, GUID.BINDING);
409 final String types = graph.syncRequest(new TypeString(L0, graph.getTypes(entry.component)));
410 if (name != null && types != null) {
411 if(!entry.isValid(graph)) continue;
412 Resource parent = graph.getPossibleObject(entry.component, L0.PartOf);
413 if (parent != null) {
414 _additions.add(new Object[] { ss.getRandomAccessId(parent), ss.getRandomAccessId(entry.component), name, types, id != null ? id.indexString() : "" });
416 //System.err.println("resource " + entry.component + ": no parent for entry " + name + " " + types);
419 //System.err.println("resource " + entry.component + ": " + name + " " + types);
421 } else if(_entry instanceof ComponentModification) {
422 ComponentModification entry = (ComponentModification)_entry;
423 final String name = graph.getPossibleRelatedValue(entry.component, L0.HasName, Bindings.STRING);
424 final GUID id = graph.getPossibleRelatedValue(entry.component, L0.identifier, GUID.BINDING);
425 if(graph.isInstanceOf(entry.component, L0.Type)) {
426 SerialisationSupport support = session.getService(SerialisationSupport.class);
427 _typeChanges.add(new Pair<String, String>(name, String.valueOf(support.getRandomAccessId((Resource) entry.component))));
429 final String types = graph.syncRequest(new TypeString(L0, graph.getTypes(entry.component)));
430 if (name != null && types != null) {
431 Resource part = graph.getPossibleObject(entry.component, L0.PartOf);
433 _replacementKeys.add(ss.getRandomAccessId(entry.component));
434 _replacementObjects.add(new Object[] { ss.getRandomAccessId(part),
435 ss.getRandomAccessId(entry.component), name, types, id != null ? id.indexString() : "" });
439 } else if (_entry instanceof ComponentRemoval) {
440 ComponentRemoval entry = (ComponentRemoval)_entry;
441 if(!entry.isValid(graph)) continue;
442 _removals.add(ss.getRandomAccessId(((ComponentRemoval)_entry).component));
443 } else if (_entry instanceof LinkChange) {
449 final boolean reset = linkChange || event.hasUnresolved;
450 //System.err.println("dependencies(" + NameUtils.getSafeLabel(graph, model) + "): reset=" + reset + " linkChange=" + linkChange + " unresolved=" + event.hasUnresolved );
452 if (reset || !_additions.isEmpty() || !_removals.isEmpty() || !_replacementKeys.isEmpty() || !_typeChanges.isEmpty()) {
454 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update");
456 final Collection<Object[]> additions = _additions;
457 final Collection<Object> removals = _removals;
458 final Collection<Object> replacementKeys = _replacementKeys;
459 final Collection<Object[]> replacementObjects = _replacementObjects;
460 final boolean typeNameChanges = typeNameChanges(graph, indexer, model, _typeChanges);
462 final UUID pending = Indexing.makeIndexPending();
467 boolean didChange = false;
468 // Unresolved and linkChanges are not relevant any more
469 boolean doReset = typeNameChanges;
474 System.err.println("resetIndex " + reset + " " + typeNameChanges);
477 indexer.removeAll(null, graph, DependenciesRelation.this, resource, model);
482 if (!replacementKeys.isEmpty() && (replacementKeys.size() == replacementObjects.size())) {
484 System.out.println(replacementKeys.size() + " index replacements: " + replacementKeys);
486 didChange |= indexer.replace(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, replacementKeys, replacementObjects);
488 if (!removals.isEmpty()) {
490 System.out.println(removals.size() + " index removals: " + removals);
492 indexer.remove(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, removals);
495 if (!additions.isEmpty()) {
497 for(Object[] os : additions) System.err.println("Adding to index " + model + ": " + Arrays.toString(os));
499 //System.out.println(additions.size() + " index insertions");
500 indexer.insert(null, graph, DependenciesRelation.this, resource, model, additions);
507 // TODO: because this data is ran with
508 // ThreadUtils.getBlockingWorkExecutor()
509 // fireListeners needs to use peekService,
510 // not getService since there is no
511 // guarantee that the session isn't being
512 // disposed while this method is executing.
513 fireListeners(graph, model);
515 } catch (Throwable t) {
516 // Just to know if something unexpected happens here.
517 LOGGER.error("Dependencies index update failed for model "
518 + model + " and relation " + resource + ".", t);
520 // NOTE: Last resort: failure to update index
521 // properly results in removal of the whole index.
522 // This is the only thing that can be done
523 // at this point to ensure that the index will
524 // return correct results in the future, through
525 // complete reinitialization.
526 //indexer.removeAll(null, session, DependenciesRelation.this, resource, model);
528 Indexing.releaseIndexPending(pending);
529 Indexing.clearCaches(model);
534 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: index update done");
542 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
543 changeSupport.addMetadataListener(listener);
551 private boolean typeNameChanges(ReadGraph graph, IndexedRelations indexer,
552 Resource model, final Collection<Pair<String, String>> typeChanges)
553 throws DatabaseException {
554 if (typeChanges.isEmpty())
557 for (Pair<String, String> nr : typeChanges) {
558 String query = Dependencies.FIELD_RESOURCE + ":[" + nr.second + " TO " + nr.second + "]";
559 //System.out.println("query: " + query);
560 List<Map<String, Object>> results = indexer.query(null, query, graph, resource, model, Integer.MAX_VALUE);
561 if (results.size() != 1) {
564 Map<String, Object> result = results.get(0);
565 if (!ObjectUtils.objectEquals(result.get(Dependencies.FIELD_NAME), nr.first)) {
569 // System.err.println("Type " + nr.first + " was unchanged.");
575 public void addListener(RequestProcessor processor, Resource model, Runnable observer) {
576 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
577 store.addListener(model, observer);
581 public void removeListener(RequestProcessor processor, Resource model, Runnable observer) {
582 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
583 store.removeListener(model, observer);
586 void fireListeners(RequestProcessor processor, Resource model) {
587 DependenciesListenerStore store = processor.getSession().peekService(DependenciesListenerStore.class);
589 store.fireListeners(model);
593 public void reset(RequestProcessor processor, Resource input) {
595 System.out.println("DependenciesRelation.reset: " + input);
596 new Exception("DependenciesRelation.reset(" + listener + ")").printStackTrace(System.out);
598 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
599 store.fireListeners(input);
602 public static void addSubtree(ReadGraph graph, Resource root) throws DatabaseException {
604 Resource indexRoot = graph.syncRequest(new IndexRoot(root));
605 addSubtree(graph, indexRoot, root);
609 public static void addSubtree(ReadGraph graph, Resource indexRoot, Resource subtreeRoot) throws DatabaseException {
611 DependenciesRelation dr = new DependenciesRelation(graph, indexRoot);
612 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
614 ArrayList<Entry> entries = dr.find(graph, subtreeRoot);
615 entries.add(new Entry(graph, subtreeRoot));
617 ArrayList<Object[]> result = new ArrayList<Object[]>(entries.size());
618 for (Entry entry : entries) {
619 result.add(new Object[] { ss.getRandomAccessId(entry.parent), ss.getRandomAccessId(entry.resource), entry.name, entry.types, entry.id });
622 Layer0X L0X = Layer0X.getInstance(graph);
623 IndexedRelations indexer = graph.getService(IndexedRelations.class);
624 indexer.insert(null, graph, dr, L0X.DependenciesRelation, indexRoot, result);