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 result.add(new Entry(graph, resource));
169 graph.syncRequest(new ReadRequest() {
172 public void run(ReadGraph graph) throws DatabaseException {
173 dqs.forEachObjectCompiled(graph, resource, resource, structure);
178 Map<Resource, String> typeStrings = cs.createMap(String.class);
179 for(Entry e : result) {
180 if(e.principalType != null) {
181 String typeString = typeStrings.get(e.principalType);
182 if(typeString == null) {
183 typeString = graph.syncRequest(new SuperTypeString(e.principalType));
184 if (typeString.isEmpty()) {
185 LOGGER.error("No name for type", new DatabaseException("No name for type " + NameUtils.getURIOrSafeNameInternal(graph, e.resource) + " (" + e.resource + ")"));
187 typeStrings.put(e.principalType, typeString);
189 e.types = typeString;
191 e.types = graph.syncRequest(new TypeString(L0, graph.getTypes(e.resource)));
193 GUID id = graph.getPossibleRelatedValue(e.resource, L0.identifier, GUID.BINDING);
195 e.id = id.indexString();
200 //SessionGarbageCollection.gc(null, graph.getSession(), false, null);
206 public ArrayList<Entry> find(ReadGraph graph, final Resource model) throws DatabaseException {
207 return new Process(graph, model).result;
211 public GenericRelation select(String bindingPattern, Object[] constants) {
212 checkSelectionArguments(bindingPattern, constants, new String[] { Dependencies.getBindingPattern() });
213 final long subjectId = (Long)constants[0];
214 return new UnsupportedRelation() {
217 public boolean isRealizable() {
222 final public List<Object[]> realize(ReadGraph graph) throws DatabaseException {
224 long time = System.nanoTime();
226 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
228 Resource subject = ss.getResource(subjectId);
230 Collection<Entry> entries = find(graph, subject);
232 long time2 = System.nanoTime();
235 LOGGER.info("Found " + entries.size() + " dependencies in " + 1e-6 * (time2 - time) + "ms for " + graph.getPossibleURI(subject) + ".");
237 ArrayList<Object[]> result = new ArrayList<Object[]>();
238 for (Entry entry : entries) {
239 if(entry.name == null) continue;
240 result.add(new Object[] { ss.getRandomAccessId(entry.parent), ss.getRandomAccessId(entry.resource), entry.name, entry.types, entry.id, entry.name, entry.types });
250 public Pair<String, String>[] getFields() {
255 public List<Map<String, Object>> query(RequestProcessor session, String search, String bindingPattern, Object[] constants, int maxResultCount) {
256 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffffff'");
257 IndexedRelations indexer = session.getService(IndexedRelations.class);
258 return indexer.query(null, search, session, resource, (Resource)constants[0], maxResultCount);
262 public List<Resource> queryResources(RequestProcessor session, String search, String bindingPattern, Object[] constants, int maxResultCount) {
263 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffffff'");
264 IndexedRelations indexer = session.getService(IndexedRelations.class);
265 return indexer.queryResources(null, search, session, resource, (Resource)constants[0], maxResultCount);
269 public List<Map<String, Object>> list(RequestProcessor session, String bindingPattern, Object[] constants, int maxResultCount) {
270 if(!Dependencies.getBindingPattern().equals(bindingPattern)) throw new IllegalArgumentException("DependenciesRelation supports indexing only with 'bfffffff'");
271 IndexedRelations indexer = session.getService(IndexedRelations.class);
272 return indexer.query(null, null, session, resource, (Resource)constants[0], maxResultCount);
275 public static class DependencyChangesRequest extends UnaryRead<ChangeSet, DependencyChanges> {
277 @SuppressWarnings("unused")
278 final private static boolean LOG = false;
280 public DependencyChangesRequest(ChangeSet parameter) {
285 public DependencyChanges perform(ReadGraph graph) throws DatabaseException {
287 DependencyChangesWriter w = new DependencyChangesWriter(graph);
289 Resource changeInformation = graph.getPossibleResource("http://www.simantics.org/Modeling-1.2/changeInformation/Inverse");
291 for (Resource value : parameter.changedValues()) {
292 if(!value.isPersistent()) continue;
293 Statement modifiedComponent = graph.getPossibleStatement(value, l0.PropertyOf);
294 if (modifiedComponent == null
295 || modifiedComponent.getPredicate().equals(changeInformation))
298 LOGGER.info("+comp modi " + NameUtils.getSafeName(graph, modifiedComponent.getObject(), true));
299 LOGGER.info(" +value " + NameUtils.getSafeName(graph, value, true));
301 w.addComponentModification(modifiedComponent.getObject());
303 for (Resource value : parameter.changedResources()) {
304 // No more info => need to check further
305 if(!graph.isImmutable(value))
306 w.addComponentModification(value);
308 for (StatementChange change : parameter.changedStatements()) {
310 LOGGER.info("-stm " + NameUtils.getSafeName(graph, change.getSubject(), true) + " " + NameUtils.getSafeName(graph, change.getPredicate(), true) + " " + NameUtils.getSafeName(graph, change.getObject(), true));
311 Resource subject = change.getSubject();
312 Resource predicate = change.getPredicate();
313 Resource object = change.getObject();
314 if(!object.isPersistent()) continue;
315 if (predicate.equals(l0.ConsistsOf)) {
316 if (change.isClaim())
317 w.addComponentAddition(subject, object);
319 w.addComponentRemoval(subject, object);
320 } else if (predicate.equals(l0.IsLinkedTo)) {
321 w.addLinkChange(subject);
322 } else /*if (graph.isSubrelationOf(predicate, l0.DependsOn))*/ {
324 LOGGER.info("-modi " + NameUtils.getSafeName(graph, subject, true));
325 w.addComponentModification(subject);
328 return w.getResult();
333 private static int trackers = 0;
335 private static ChangeListener listener;
337 public static void assertFinishedTracking() {
338 if(trackers != 0) throw new IllegalStateException("Trackers should be 0 (was " + trackers + ")");
342 public synchronized void untrack(RequestProcessor processor, final Resource model) {
346 if(trackers < 0) throw new IllegalStateException("Dependency tracking reference count is broken");
350 if(listener == null) throw new IllegalStateException("Dependency tracking was not active");
352 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
353 changeSupport.removeMetadataListener(listener);
361 public synchronized void trackAndIndex(RequestProcessor processor, Resource model__) {
365 if(listener != null) throw new IllegalStateException("Dependency tracking was active");
367 listener = new GenericChangeListener<DependencyChangesRequest, DependencyChanges>() {
370 public boolean preEventRequest() {
371 return !Indexing.isDependenciesIndexingDisabled();
375 public void onEvent(ReadGraph graph, MetadataI metadata, DependencyChanges event) throws DatabaseException {
377 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update processing");
380 LOGGER.info("Adding metadata " + event + " in revision " + graph.getService(ManagementSupport.class).getHeadRevisionId());
382 WriteGraph w = (WriteGraph)graph;
384 w.addMetadata(event);
386 final Session session = graph.getSession();
387 final IndexedRelations indexer = session.getService(IndexedRelations.class);
388 Layer0 L0 = Layer0.getInstance(graph);
389 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
391 for(Map.Entry<Resource, Change[]> modelEntry : event.get().entrySet()) {
393 final Resource model = modelEntry.getKey();
394 final Change[] changes = modelEntry.getValue();
396 boolean linkChange = false;
398 Collection<Object[]> _additions = Collections.emptyList();
399 Collection<Object> _removals = Collections.emptyList();
400 Collection<Object> _replacementKeys = Collections.emptyList();
401 Collection<Object[]> _replacementObjects = Collections.emptyList();
402 Collection<Pair<String, String>> _typeChanges = Collections.emptyList();
404 if(DEBUG) LOGGER.info("MODEL: " + NameUtils.getSafeLabel(graph, model));
405 // final Change[] changes = event.get(model);
406 if(DEBUG) LOGGER.info(" CHANGES: " + Arrays.toString(changes));
407 if (changes != null) {
408 _additions = new ArrayList<Object[]>();
409 _removals = new ArrayList<Object>();
410 _replacementKeys = new ArrayList<Object>();
411 _replacementObjects = new ArrayList<Object[]>();
412 _typeChanges = new HashSet<Pair<String, String>>();
414 for (Change _entry : changes) {
415 if (_entry instanceof ComponentAddition) {
416 ComponentAddition entry = (ComponentAddition)_entry;
417 final String name = graph.getPossibleRelatedValue(entry.component, L0.HasName, Bindings.STRING);
418 final GUID id = graph.getPossibleRelatedValue(entry.component, L0.identifier, GUID.BINDING);
419 final String types = graph.syncRequest(new TypeString(L0, graph.getTypes(entry.component)));
420 if (name != null && types != null) {
421 if(!entry.isValid(graph)) continue;
422 Resource parent = graph.getPossibleObject(entry.component, L0.PartOf);
423 if (parent != null) {
424 _additions.add(new Object[] { ss.getRandomAccessId(parent), ss.getRandomAccessId(entry.component), name, types, id != null ? id.indexString() : "", name, types});
426 //LOGGER.info("resource " + entry.component + ": no parent for entry " + name + " " + types);
429 //LOGGER.info("resource " + entry.component + ": " + name + " " + types);
431 } else if(_entry instanceof ComponentModification) {
432 ComponentModification entry = (ComponentModification)_entry;
433 final String name = graph.getPossibleRelatedValue(entry.component, L0.HasName, Bindings.STRING);
434 final GUID id = graph.getPossibleRelatedValue(entry.component, L0.identifier, GUID.BINDING);
435 if(graph.isInstanceOf(entry.component, L0.Type)) {
436 SerialisationSupport support = session.getService(SerialisationSupport.class);
437 _typeChanges.add(new Pair<String, String>(name, String.valueOf(support.getRandomAccessId((Resource) entry.component))));
439 final String types = graph.syncRequest(new TypeString(L0, graph.getTypes(entry.component)));
440 if (name != null && types != null) {
441 Resource part = graph.getPossibleObject(entry.component, L0.PartOf);
443 _replacementKeys.add(ss.getRandomAccessId(entry.component));
444 _replacementObjects.add(new Object[] { ss.getRandomAccessId(part),
445 ss.getRandomAccessId(entry.component), name, types, id != null ? id.indexString() : "", name, types});
449 } else if (_entry instanceof ComponentRemoval) {
450 ComponentRemoval entry = (ComponentRemoval)_entry;
451 if(!entry.isValid(graph)) continue;
452 _removals.add(ss.getRandomAccessId(((ComponentRemoval)_entry).component));
453 } else if (_entry instanceof LinkChange) {
459 final boolean reset = linkChange || event.hasUnresolved;
460 //LOGGER.info("dependencies(" + NameUtils.getSafeLabel(graph, model) + "): reset=" + reset + " linkChange=" + linkChange + " unresolved=" + event.hasUnresolved );
462 if (reset || !_additions.isEmpty() || !_removals.isEmpty() || !_replacementKeys.isEmpty() || !_typeChanges.isEmpty()) {
464 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: starting index update");
466 final Collection<Object[]> additions = _additions;
467 final Collection<Object> removals = _removals;
468 final Collection<Object> replacementKeys = _replacementKeys;
469 final Collection<Object[]> replacementObjects = _replacementObjects;
470 final boolean typeNameChanges = typeNameChanges(graph, indexer, model, _typeChanges);
472 final UUID pending = Indexing.makeIndexPending();
477 boolean didChange = false;
478 // Unresolved and linkChanges are not relevant any more
479 boolean doReset = typeNameChanges;
484 LOGGER.info("resetIndex " + reset + " " + typeNameChanges);
487 indexer.removeAll(null, graph, DependenciesRelation.this, resource, model);
492 if (!replacementKeys.isEmpty() && (replacementKeys.size() == replacementObjects.size())) {
494 LOGGER.info(replacementKeys.size() + " index replacements: " + replacementKeys);
496 didChange |= indexer.replace(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, replacementKeys, replacementObjects);
498 if (!removals.isEmpty()) {
500 LOGGER.info(removals.size() + " index removals: " + removals);
502 indexer.remove(null, graph, DependenciesRelation.this, resource, model, Dependencies.FIELD_RESOURCE, removals);
505 if (!additions.isEmpty()) {
507 for(Object[] os : additions) LOGGER.info("Adding to index " + model + ": " + Arrays.toString(os));
509 //LOGGER.info(additions.size() + " index insertions");
510 indexer.insert(null, graph, DependenciesRelation.this, resource, model, additions);
517 // TODO: because this data is ran with
518 // ThreadUtils.getBlockingWorkExecutor()
519 // fireListeners needs to use peekService,
520 // not getService since there is no
521 // guarantee that the session isn't being
522 // disposed while this method is executing.
523 fireListeners(graph, model);
525 } catch (Throwable t) {
526 // Just to know if something unexpected happens here.
527 LOGGER.error("Dependencies index update failed for model "
528 + model + " and relation " + resource + ".", t);
530 // NOTE: Last resort: failure to update index
531 // properly results in removal of the whole index.
532 // This is the only thing that can be done
533 // at this point to ensure that the index will
534 // return correct results in the future, through
535 // complete reinitialization.
536 //indexer.removeAll(null, session, DependenciesRelation.this, resource, model);
538 Indexing.releaseIndexPending(pending);
539 Indexing.clearCaches(model);
544 TimeLogger.log(DependenciesRelation.class, "trackAndIndex.onEvent: index update done");
552 GraphChangeListenerSupport changeSupport = processor.getService(GraphChangeListenerSupport.class);
553 changeSupport.addMetadataListener(listener);
561 private boolean typeNameChanges(ReadGraph graph, IndexedRelations indexer,
562 Resource model, final Collection<Pair<String, String>> typeChanges)
563 throws DatabaseException {
564 if (typeChanges.isEmpty())
567 for (Pair<String, String> nr : typeChanges) {
568 String query = Dependencies.FIELD_RESOURCE + ":[" + nr.second + " TO " + nr.second + "]";
569 //LOGGER.info("query: " + query);
570 List<Map<String, Object>> results = indexer.query(null, query, graph, resource, model, Integer.MAX_VALUE);
571 if (results.size() != 1) {
574 Map<String, Object> result = results.get(0);
575 if (!ObjectUtils.objectEquals(result.get(Dependencies.FIELD_NAME), nr.first)) {
579 // LOGGER.info("Type " + nr.first + " was unchanged.");
585 public void addListener(RequestProcessor processor, Resource model, Runnable observer) {
586 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
587 store.addListener(model, observer);
591 public void removeListener(RequestProcessor processor, Resource model, Runnable observer) {
592 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
593 store.removeListener(model, observer);
596 void fireListeners(RequestProcessor processor, Resource model) {
597 DependenciesListenerStore store = processor.getSession().peekService(DependenciesListenerStore.class);
599 store.fireListeners(model);
603 public void reset(RequestProcessor processor, Resource input) {
605 LOGGER.info("DependenciesRelation.reset: " + input);
606 new Exception("DependenciesRelation.reset(" + listener + ")").printStackTrace(System.out);
608 DependenciesListenerStore store = processor.getSession().getService(DependenciesListenerStore.class);
609 store.fireListeners(input);
612 public static void addSubtree(ReadGraph graph, Resource root) throws DatabaseException {
614 Resource indexRoot = graph.syncRequest(new IndexRoot(root));
615 addSubtree(graph, indexRoot, root);
619 public static void addSubtree(ReadGraph graph, Resource indexRoot, Resource subtreeRoot) throws DatabaseException {
621 DependenciesRelation dr = new DependenciesRelation(graph, indexRoot);
622 SerialisationSupport ss = graph.getService(SerialisationSupport.class);
624 ArrayList<Entry> entries = dr.find(graph, subtreeRoot);
625 entries.add(new Entry(graph, subtreeRoot));
627 ArrayList<Object[]> result = new ArrayList<Object[]>(entries.size());
628 for (Entry entry : entries) {
629 result.add(new Object[] { ss.getRandomAccessId(entry.parent), ss.getRandomAccessId(entry.resource), entry.name, entry.types, entry.id, entry.name, entry.types });
632 Layer0X L0X = Layer0X.getInstance(graph);
633 IndexedRelations indexer = graph.getService(IndexedRelations.class);
634 indexer.insert(null, graph, dr, L0X.DependenciesRelation, indexRoot, result);