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.modeling.services;
14 import gnu.trove.map.hash.THashMap;
16 import java.lang.ref.SoftReference;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Formatter;
21 import java.util.HashSet;
22 import java.util.IdentityHashMap;
25 import java.util.concurrent.ConcurrentMap;
26 import java.util.concurrent.ConcurrentSkipListMap;
27 import java.util.concurrent.ConcurrentSkipListSet;
29 import org.simantics.databoard.Bindings;
30 import org.simantics.db.AsyncReadGraph;
31 import org.simantics.db.ReadGraph;
32 import org.simantics.db.Resource;
33 import org.simantics.db.common.request.AsyncReadRequest;
34 import org.simantics.db.common.utils.NameUtils;
35 import org.simantics.db.event.ChangeEvent;
36 import org.simantics.db.event.ChangeListener;
37 import org.simantics.db.exception.DatabaseException;
38 import org.simantics.db.procedure.AsyncMultiProcedure;
39 import org.simantics.db.procedure.AsyncProcedure;
40 import org.simantics.db.service.GraphChangeListenerSupport;
41 import org.simantics.layer0.Layer0;
42 import org.simantics.modeling.ComponentUtils;
43 import org.simantics.structural.stubs.StructuralResource2;
44 import org.simantics.utils.datastructures.Pair;
45 import org.simantics.utils.ui.ErrorLogger;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * A first-hand component naming strategy implementation for structural models.
52 * This version is somewhat optimized for case-insensitivity by using custom
53 * comparators in maps and sets. It uses a soft-referenced cache of
54 * used/requested names per a single root of a configuration's component
57 * @author Tuukka Lehtonen
59 * @see ComponentNamingStrategy
61 public class CaseInsensitiveComponentNamingStrategy extends ComponentNamingStrategyBase implements ChangeListener {
63 private static final Logger LOGGER = LoggerFactory.getLogger(CaseInsensitiveComponentNamingStrategy.class);
64 private static final boolean DEBUG_ALL = false;
65 private static final boolean DEBUG_GRAPH_UPDATES = false | DEBUG_ALL;
66 private static final boolean DEBUG_CACHE_INITIALIZATION = false | DEBUG_ALL;
67 private static final boolean DEBUG_CACHE_INITIALIZATION_BROWSE = false | DEBUG_ALL;
68 private static final boolean DEBUG_CACHE_UPDATES = false | DEBUG_ALL;
71 private final Resource root;
72 private final Set<String> reserved;
74 // Having cache as soft references should somewhat address the problem
75 // of the amount of requested names growing too large.
76 private final Set<String> requested;
78 // Only internally used data
79 private final ConcurrentMap<Resource, String> r2s;
80 private final ConcurrentMap<String, Set<Resource>> s2r;
82 public Cache(Resource root, Set<String> reserved, ConcurrentMap<Resource, String> r2s, ConcurrentMap<String, Set<Resource>> s2r, boolean caseInsensitive) {
84 assert reserved != null;
88 this.reserved = reserved;
91 this.requested = new ConcurrentSkipListSet<String>(getComparator(caseInsensitive));
95 protected void finalize() throws Throwable {
96 if (DEBUG_CACHE_UPDATES)
101 public Resource getRoot() {
105 public Set<String> getReserved() {
106 // This prevents the map from being retrieved during a cache update.
107 synchronized (this) {
112 public Set<String> getRequested() {
113 // This prevents the map from being retrieved during a cache update.
114 synchronized (this) {
119 public void addRequested(String name) {
123 public void replaceEntries(Collection<Pair<Resource, String>> entries) {
124 if (entries.isEmpty())
127 if (DEBUG_CACHE_UPDATES)
128 debug(" updating " + entries.size() +" cache entries");
130 synchronized (this) {
131 for (Pair<Resource, String> entry : entries) {
132 Resource component = entry.first;
133 String newName = entry.second;
135 assert component != null;
136 assert newName != null;
138 String oldName = r2s.get(component);
139 if (oldName == null) {
140 // This must be an uncached new component.
143 Set<Resource> existingEntries = getMapSet(s2r, newName);
144 if (!existingEntries.isEmpty()) {
145 LOGGER.warn("WARNING: Somebody is screwing the model up with duplicate name: " + newName);
146 // TODO: generate issue or message
149 Object prev = r2s.putIfAbsent(component, newName);
151 addToMapSet(s2r, newName, component);
153 reserved.add(newName);
154 requested.remove(newName);
156 if (DEBUG_CACHE_UPDATES)
157 debug("\tnew component name: " + newName);
159 // This must be a change to an existing cached component.
162 Set<Resource> existingEntries = getMapSet(s2r, newName);
163 if (!existingEntries.isEmpty()) {
164 // Currently changesets can contain multiple entries for a same change.
165 // This picks out one of such cases where the value of a resource has been
166 // set multiple times to the same value.
167 if (existingEntries.contains(component))
170 LOGGER.warn("WARNING: Somebody is screwing the model up with duplicate name: " + newName);
171 // TODO: generate issue or message
174 Set<Resource> resourcesWithOldName = removeFromMapSet(s2r, oldName, component);
175 addToMapSet(s2r, newName, component);
176 boolean updated = r2s.replace(component, oldName, newName);
178 if (resourcesWithOldName.isEmpty()) {
179 reserved.remove(oldName);
181 reserved.add(newName);
182 requested.remove(newName);
184 if (DEBUG_CACHE_UPDATES)
185 debug("\tcomponent name changed: " + oldName + " -> " + newName);
189 if (DEBUG_CACHE_UPDATES) {
190 debug("reserved names after update: " + reserved);
191 debug("requested names after update: " + requested);
196 private void debug(String string) {
197 CaseInsensitiveComponentNamingStrategy.debug(this, string);
201 static class CacheFactory {
202 final ReadGraph graph;
205 final StructuralResource2 sr;
206 final boolean caseInsensitive;
208 final Set<String> reserved;
209 final ConcurrentMap<Resource, String> r2s = new ConcurrentSkipListMap<Resource, String>();
210 final ConcurrentMap<String, Set<Resource>> s2r;
212 CacheFactory(ReadGraph graph, Resource root, boolean caseInsensitive) {
215 this.b = Layer0.getInstance(graph);
216 this.sr = StructuralResource2.getInstance(graph);
217 this.caseInsensitive = caseInsensitive;
219 this.reserved = new ConcurrentSkipListSet<String>(getComparator(caseInsensitive));
220 this.s2r = new ConcurrentSkipListMap<String, Set<Resource>>(getComparator(caseInsensitive));
223 private void debug(String string) {
224 CaseInsensitiveComponentNamingStrategy.debug(this, string);
227 public Cache create() throws DatabaseException {
228 if (DEBUG_CACHE_INITIALIZATION_BROWSE)
229 debug("browsing all components from root " + root);
231 graph.syncRequest(new AsyncReadRequest() {
233 public void run(AsyncReadGraph graph) {
234 browseComposite(graph, root);
238 if (DEBUG_CACHE_INITIALIZATION_BROWSE)
239 debug("browsing completed, results:\n\treserved: " + reserved + "\n\tr2s: " + r2s + "\n\ts2r: " + s2r);
241 return new Cache(root, reserved, r2s, s2r, caseInsensitive);
244 static abstract class MultiProc<T> implements AsyncMultiProcedure<T> {
246 public void finished(AsyncReadGraph graph) {
249 public void exception(AsyncReadGraph graph, Throwable t) {
250 ErrorLogger.defaultLogError(t);
254 static abstract class AsyncProc<T> implements AsyncProcedure<T> {
256 public void exception(AsyncReadGraph graph, Throwable t) {
257 ErrorLogger.defaultLogError(t);
261 private void browseComposite(AsyncReadGraph graph, Resource composite) {
262 if (DEBUG_CACHE_INITIALIZATION_BROWSE)
263 debug("browsing composite " + composite);
264 graph.forEachObject(composite, b.ConsistsOf, new MultiProc<Resource>() {
266 public void execute(AsyncReadGraph graph, Resource component) {
267 browseComponent(graph, component);
270 private void browseComponent(AsyncReadGraph graph, Resource component) {
271 if (DEBUG_CACHE_INITIALIZATION_BROWSE)
272 debug("browsing component " + component);
273 reserveName(graph, component);
274 graph.forPossibleType(component, sr.Component, new AsyncProc<Resource>() {
276 public void execute(AsyncReadGraph graph, Resource componentType) {
277 if (componentType != null)
278 browseComponentType(graph, componentType);
283 private void browseComponentType(AsyncReadGraph graph, Resource componentType) {
284 if (DEBUG_CACHE_INITIALIZATION_BROWSE)
285 debug("browsing user component " + componentType);
286 graph.forPossibleObject(componentType, sr.IsDefinedBy, new AsyncProc<Resource>() {
288 public void execute(AsyncReadGraph graph, Resource composite) {
289 if (composite != null)
290 browseComposite(graph, composite);
295 private void reserveName(AsyncReadGraph graph, final Resource component) {
296 graph.forPossibleRelatedValue(component, b.HasName, new AsyncProc<String>() {
298 public void execute(AsyncReadGraph graph, String componentName) {
299 if (componentName != null) {
300 if (DEBUG_CACHE_INITIALIZATION_BROWSE)
301 debug("reserving name of component " + component + " '" + componentName + "'");
302 Set<Resource> components = addToMapSet(s2r, componentName, component);
303 if (components.size() > 1) {
304 // Found duplicate names in the model !!
305 // TODO: generate issue!
306 LOGGER.warn("WARNING: found multiple components with same name '" + componentName + "': " + components);
307 LOGGER.warn("TODO: generate issue");
309 String prevName = r2s.putIfAbsent(component, componentName);
310 if (prevName == null)
311 reserved.add(componentName);
321 private SoftReference<THashMap<Resource, SoftReference<Cache>>> mapRef =
322 new SoftReference<THashMap<Resource, SoftReference<Cache>>>(new THashMap<Resource, SoftReference<Cache>>());
324 private final GraphChangeListenerSupport changeSupport;
325 private Resource inverseOfHasName;
327 public CaseInsensitiveComponentNamingStrategy(GraphChangeListenerSupport changeSupport) {
328 this(changeSupport, "%s %d");
332 * @param changeSupport
333 * @param generatedNameFormat the format to use for generated names, see
336 public CaseInsensitiveComponentNamingStrategy(GraphChangeListenerSupport changeSupport, String generatedNameFormat) {
337 super(generatedNameFormat);
338 this.changeSupport = changeSupport;
339 changeSupport.addListener(this);
342 public void dispose() {
343 changeSupport.removeListener(this);
346 static class CacheUpdateBundle {
347 IdentityHashMap<Cache, Collection<Pair<Resource, String>>> updates = new IdentityHashMap<Cache, Collection<Pair<Resource, String>>>();
349 public boolean isEmpty() {
350 return updates.isEmpty();
353 public void add(Cache cache, Resource component, String newName) {
354 assert cache != null;
355 assert component != null;
356 assert newName != null;
358 Collection<Pair<Resource, String>> collection = updates.get(cache);
359 if (collection == null) {
360 collection = new ArrayList<Pair<Resource, String>>();
361 updates.put(cache, collection);
364 collection.add(Pair.make(component, newName));
367 public void commitAll() {
368 for (Map.Entry<Cache, Collection<Pair<Resource, String>>> entry : updates.entrySet()) {
369 Cache cache = entry.getKey();
370 cache.replaceEntries(entry.getValue());
375 public String toString() {
376 return getClass().getSimpleName() + " [" + updates.size() + " changed caches]";
381 public void graphChanged(ChangeEvent e) throws DatabaseException {
382 Collection<Resource> changedValues = e.getChanges().changedValues();
383 if (DEBUG_GRAPH_UPDATES)
384 debug("graph updated with " + changedValues.size() + " value changes");
386 ReadGraph graph = e.getGraph();
387 Layer0 b = Layer0.getInstance(graph);
389 // Cache inverse of Has Name relation.
390 if (inverseOfHasName == null) {
391 inverseOfHasName = graph.getInverse(b.HasName);
394 CacheUpdateBundle bundle = new CacheUpdateBundle();
396 for (Resource value : changedValues) {
397 //System.out.println("VALUE CHANGE: " + GraphUtils.getReadableName(graph, value));
398 for (Resource nameOfComponent : graph.getObjects(value, inverseOfHasName)) {
399 if (DEBUG_GRAPH_UPDATES)
400 debug("\tNAME CHANGE: " + NameUtils.getSafeName(graph, value));
401 Resource root = ComponentUtils.tryGetComponentConfigurationRoot(graph, nameOfComponent);
402 Cache cache = peekCache(graph, root);
404 String newName = graph.getPossibleValue(value, Bindings.STRING);
405 if (newName != null) {
406 if (DEBUG_GRAPH_UPDATES)
407 debug("\t\tqueued cache update");
408 bundle.add(cache, nameOfComponent, newName);
414 if (!bundle.isEmpty()) {
415 if (DEBUG_GRAPH_UPDATES)
416 debug("committing " + bundle);
421 private Cache getCache(ReadGraph graph, Resource configurationRoot) throws DatabaseException {
423 THashMap<Resource, SoftReference<Cache>> map = mapRef.get();
426 SoftReference<Cache> cacheRef = map.get(configurationRoot);
427 if (cacheRef != null) {
428 cache = cacheRef.get();
434 // Cache miss, rebuild cache index
435 map = new THashMap<Resource, SoftReference<Cache>>();
436 mapRef = new SoftReference<THashMap<Resource,SoftReference<Cache>>>(map);
439 // Cache miss, rebuild local cache
440 if (DEBUG_CACHE_INITIALIZATION)
441 debug("Constructing new cache for root " + NameUtils.getSafeName(graph, configurationRoot) + " (" + configurationRoot + ")");
442 cache = new CacheFactory(graph, configurationRoot, caseInsensitive).create();
443 if (DEBUG_CACHE_INITIALIZATION)
444 debug("\tInitialized with reservations: " + cache.getReserved());
445 map.put(configurationRoot, new SoftReference<Cache>(cache));
449 private Cache peekCache(ReadGraph graph, Resource configurationRoot) {
450 THashMap<Resource, SoftReference<Cache>> map = mapRef.get();
453 SoftReference<Cache> cacheRef = map.get(configurationRoot);
454 if (cacheRef == null)
456 Cache cache = cacheRef.get();
464 public String validateInstanceName(ReadGraph graph,
465 Resource configurationRoot, Resource component, String proposition, boolean acceptProposition)
466 throws NamingException, DatabaseException {
468 Layer0 L0 = Layer0.getInstance(graph);
469 StructuralResource2 STR = StructuralResource2.getInstance(graph);
470 Resource container = graph.getSingleObject(component, L0.PartOf);
471 Resource componentType = graph.getSingleType(component, STR.Component);
472 return validateInstanceName(graph, configurationRoot, container, componentType, proposition, acceptProposition);
477 public String validateInstanceName(ReadGraph graph, Resource configurationRoot, Resource container,
478 Resource componentType, String proposition, boolean acceptProposition) throws NamingException, DatabaseException {
479 Cache cache = getCache(graph, configurationRoot);
480 synchronized (cache) {
481 String result = findFreshName(cache.getReserved(), cache.getRequested(), proposition, acceptProposition);
482 cache.addRequested(result);
487 private void debug(String string) {
491 private static void debug(Object obj, String string) {
492 LOGGER.info("[" + obj.getClass().getSimpleName() + "(" + System.identityHashCode(obj) + ")] " + string);
495 private static <K,V> Set<V> addToMapSet(ConcurrentMap<K, Set<V>> map, K key, V value) {
496 Set<V> set = map.get(key);
498 set = new HashSet<V>(1);
499 map.putIfAbsent(key, set);
505 private static <K,V> Set<V> getMapSet(ConcurrentMap<K, Set<V>> map, K key) {
506 Set<V> set = map.get(key);
508 return Collections.emptySet();
512 private static <K,V> Set<V> removeFromMapSet(ConcurrentMap<K, Set<V>> map, K key, V value) {
513 Set<V> set = map.get(key);
515 return Collections.emptySet();
516 if (set.remove(value)) {
519 return Collections.emptySet();