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"),
81 Pair.make(Dependencies.FIELD_NAME_SEARCH, "Text"),
82 Pair.make(Dependencies.FIELD_TYPES_SEARCH, "Text")
85 final Resource resource;
87 public DependenciesRelation(ReadGraph graph, Resource resource) {
88 this.resource = resource;
90 Session session = graph.getSession();
91 DependenciesListenerStore store = session.peekService(DependenciesListenerStore.class);
92 if(store == null) session.registerService(DependenciesListenerStore.class, new DependenciesListenerStore());
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;
103 Process(ReadGraph graph, final Resource resource) throws DatabaseException {
105 final Layer0 L0 = Layer0.getInstance(graph);
106 final DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
107 final CollectionSupport cs = graph.getService(CollectionSupport.class);
109 names = dqs.compilePossibleRelatedValue(graph, L0.HasName, new SyncContextProcedure<Entry, String>() {
112 public void execute(ReadGraph graph, Entry entry, String name) {
117 public void exception(ReadGraph graph, Throwable throwable) {
118 LOGGER.error("Could not compile possible related value for resource {}", resource, throwable);
123 type = new SyncContextProcedure<Entry, Resource>() {
126 public void execute(ReadGraph graph, Entry entry, Resource type) {
127 entry.principalType = type;
131 public void exception(ReadGraph graph, Throwable throwable) {
132 LOGGER.error("Could not find type for resource {}", resource, throwable);
137 structure = dqs.compileForEachObject(graph, L0.ConsistsOf, new SyncContextMultiProcedure<Resource, Resource>() {
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, "", "", "");
145 dqs.forEachObjectCompiled(graph, child, child, structure);
146 dqs.forPossibleRelatedValueCompiled(graph, child, entry, names);
147 dqs.forPossibleDirectType(graph, child, entry, type);
151 public void finished(ReadGraph graph, Resource parent) {
155 public void exception(ReadGraph graph, Throwable throwable) {
156 if (throwable instanceof NoSingleResultException) {
158 if (LOGGER.isDebugEnabled())
159 LOGGER.debug("Could not compile for resource {}", resource, throwable);
161 LOGGER.error("Could not compile for resource {}", resource, throwable);
167 graph.syncRequest(new ReadRequest() {
170 public void run(ReadGraph graph) throws DatabaseException {
171 dqs.forEachObjectCompiled(graph, resource, resource, structure);
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 + ")"));
185 typeStrings.put(e.principalType, typeString);
187 e.types = typeString;
189 e.types = graph.syncRequest(new TypeString(L0, graph.getTypes(e.resource)));
191 GUID id = graph.getPossibleRelatedValue(e.resource, L0.identifier, GUID.BINDING);
193 e.id = id.indexString();
198 //SessionGarbageCollection.gc(null, graph.getSession(), false, null);
204 public ArrayList<Entry> find(ReadGraph graph, final Resource model) throws DatabaseException {
205 return new Process(graph, model).result;
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() {
215 public boolean isRealizable() {
220 final public List<Object[]> realize(ReadGraph graph) throws DatabaseException {
222 long time = System.nanoTime();
224 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
226 Resource subject = ss.getResource(subjectId);
228 Collection<Entry> entries = find(graph, subject);
230 long time2 = System.nanoTime();
233 LOGGER.info("Found " + entries.size() + " dependencies in " + 1e-6 * (time2 - time) + "ms for " + graph.getPossibleURI(subject) + ".");
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 });
248 public Pair<String, String>[] getFields() {
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);
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);
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);
273 public static class DependencyChangesRequest extends UnaryRead<ChangeSet, DependencyChanges> {
275 @SuppressWarnings("unused")
276 final private static boolean LOG = false;
278 public DependencyChangesRequest(ChangeSet parameter) {
283 public DependencyChanges perform(ReadGraph graph) throws DatabaseException {
285 DependencyChangesWriter w = new DependencyChangesWriter(graph);
287 Resource changeInformation = graph.getPossibleResource("http://www.simantics.org/Modeling-1.2/changeInformation/Inverse");
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))
296 LOGGER.info("+comp modi " + NameUtils.getSafeName(graph, modifiedComponent.getObject(), true));
297 LOGGER.info(" +value " + NameUtils.getSafeName(graph, value, true));
299 w.addComponentModification(modifiedComponent.getObject());
301 for (Resource value : parameter.changedResources()) {
302 // No more info => need to check further
303 if(!graph.isImmutable(value))
304 w.addComponentModification(value);
306 for (StatementChange change : parameter.changedStatements()) {
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);
317 w.addComponentRemoval(subject, object);
318 } else if (predicate.equals(l0.IsLinkedTo)) {
319 w.addLinkChange(subject);
320 } else /*if (graph.isSubrelationOf(predicate, l0.DependsOn))*/ {
322 LOGGER.info("-modi " + NameUtils.getSafeName(graph, subject, true));
323 w.addComponentModification(subject);
326 return w.getResult();
331 private static int trackers = 0;
333 private static ChangeListener listener;
335 public static void assertFinishedTracking() {
336 if(trackers != 0) throw new IllegalStateException("Trackers should be 0 (was " + trackers + ")");
340 public synchronized void untrack(RequestProcessor processor, final Resource model) {
344 if(trackers < 0) throw new IllegalStateException("Dependency tracking reference count is broken");
348 if(listener == null) throw new IllegalStateException("Dependency tracking was not active");
350 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
351 changeSupport.removeMetadataListener(listener);
359 public synchronized void trackAndIndex(RequestProcessor processor, Resource model__) {
363 if(listener != null) throw new IllegalStateException("Dependency tracking was active");
365 listener = new GenericChangeListener<DependencyChangesRequest, DependencyChanges>() {
368 public boolean preEventRequest() {
369 return !Indexing.isDependenciesIndexingDisabled();
373 public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
375 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update processing");
378 LOGGER.info("Adding metadata " + event + " in revision " + graph.getService(ManagementSupport.class).getHeadRevisionId());
380 WriteGraph w = (WriteGraph)graph;
382 w.addMetadata(event);
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);
389 for(Map.Entry<Resource, Change[]> modelEntry : event.get().entrySet()) {
391 final Resource model = modelEntry.getKey();
392 final Change[] changes = modelEntry.getValue();
394 boolean linkChange = false;
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();
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>>();
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});
424 //LOGGER.info("resource " + entry.component + ": no parent for entry " + name + " " + types);
427 //LOGGER.info("resource " + entry.component + ": " + name + " " + types);
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))));
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);
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});
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) {
457 final boolean reset = linkChange || event.hasUnresolved;
458 //LOGGER.info("dependencies(" + NameUtils.getSafeLabel(graph, model) + "): reset=" + reset + " linkChange=" + linkChange + " unresolved=" + event.hasUnresolved );
460 if (reset || !_additions.isEmpty() || !_removals.isEmpty() || !_replacementKeys.isEmpty() || !_typeChanges.isEmpty()) {
462 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update");
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);
470 final UUID pending = Indexing.makeIndexPending();
475 boolean didChange = false;
476 // Unresolved and linkChanges are not relevant any more
477 boolean doReset = typeNameChanges;
482 LOGGER.info("resetIndex " + reset + " " + typeNameChanges);
485 indexer.removeAll(null, graph, DependenciesRelation.this, resource, model);
490 if (!replacementKeys.isEmpty() && (replacementKeys.size() == replacementObjects.size())) {
492 LOGGER.info(replacementKeys.size() + " index replacements: " + replacementKeys);
494 didChange |= indexer.replace(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, replacementKeys, replacementObjects);
496 if (!removals.isEmpty()) {
498 LOGGER.info(removals.size() + " index removals: " + removals);
500 indexer.remove(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, removals);
503 if (!additions.isEmpty()) {
505 for(Object[] os : additions) LOGGER.info("Adding to index " + model + ": " + Arrays.toString(os));
507 //LOGGER.info(additions.size() + " index insertions");
508 indexer.insert(null, graph, DependenciesRelation.this, resource, model, additions);
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);
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);
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);
536 Indexing.releaseIndexPending(pending);
537 Indexing.clearCaches(model);
542 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: index update done");
550 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
551 changeSupport.addMetadataListener(listener);
559 private boolean typeNameChanges(ReadGraph graph, IndexedRelations indexer,
560 Resource model, final Collection<Pair<String, String>> typeChanges)
561 throws DatabaseException {
562 if (typeChanges.isEmpty())
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) {
572 Map<String, Object> result = results.get(0);
573 if (!ObjectUtils.objectEquals(result.get(Dependencies.FIELD_NAME), nr.first)) {
577 // LOGGER.info("Type " + nr.first + " was unchanged.");
583 public void addListener(RequestProcessor processor, Resource model, Runnable observer) {
584 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
585 store.addListener(model, observer);
589 public void removeListener(RequestProcessor processor, Resource model, Runnable observer) {
590 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
591 store.removeListener(model, observer);
594 void fireListeners(RequestProcessor processor, Resource model) {
595 DependenciesListenerStore store = processor.getSession().peekService(DependenciesListenerStore.class);
597 store.fireListeners(model);
601 public void reset(RequestProcessor processor, Resource input) {
603 LOGGER.info("DependenciesRelation.reset: " + input);
604 new Exception("DependenciesRelation.reset(" + listener + ")").printStackTrace(System.out);
606 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
607 store.fireListeners(input);
610 public static void addSubtree(ReadGraph graph, Resource root) throws DatabaseException {
612 Resource indexRoot = graph.syncRequest(new IndexRoot(root));
613 addSubtree(graph, indexRoot, root);
617 public static void addSubtree(ReadGraph graph, Resource indexRoot, Resource subtreeRoot) throws DatabaseException {
619 DependenciesRelation dr = new DependenciesRelation(graph, indexRoot);
620 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
622 ArrayList<Entry> entries = dr.find(graph, subtreeRoot);
623 entries.add(new Entry(graph, subtreeRoot));
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 });
630 Layer0X L0X = Layer0X.getInstance(graph);
631 IndexedRelations indexer = graph.getService(IndexedRelations.class);
632 indexer.insert(null, graph, dr, L0X.DependenciesRelation, indexRoot, result);