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 java.util.ArrayList;
15 import java.util.Comparator;
16 import java.util.Formatter;
17 import java.util.List;
19 import java.util.TreeSet;
21 import org.simantics.databoard.Bindings;
22 import org.simantics.db.ReadGraph;
23 import org.simantics.db.Resource;
24 import org.simantics.db.common.Indexing;
25 import org.simantics.db.common.procedure.adapter.TransientCacheAsyncListener;
26 import org.simantics.db.common.request.PossibleIndexRoot;
27 import org.simantics.db.common.request.UnaryRead;
28 import org.simantics.db.common.utils.NameUtils;
29 import org.simantics.db.exception.DatabaseException;
30 import org.simantics.db.layer0.genericrelation.IndexQueries;
31 import org.simantics.db.service.GraphChangeListenerSupport;
32 import org.simantics.layer0.Layer0;
33 import org.simantics.scl.runtime.function.Function;
34 import org.simantics.scl.runtime.function.Function1;
35 import org.simantics.scl.runtime.tuple.Tuple3;
36 import org.simantics.scl.runtime.tuple.Tuple4;
37 import org.simantics.structural.stubs.StructuralResource2;
39 import gnu.trove.set.hash.THashSet;
42 * A component naming strategy implementation for structural models based on an
43 * SCL function that lists used names in a model.
46 * The type of the function is expected to be:
47 * <code>ReadGraph => Resource -> String -> Integer -> List<Map<String,Object>></code>
49 * @author Tuukka Lehtonen
51 * @see ComponentNamingStrategy
53 public class CaseInsensitiveComponentFunctionNamingStrategy extends ComponentNamingStrategyBase {
55 protected static final boolean DEBUG_INDEX_SEARCH = false | DEBUG_ALL;
57 @SuppressWarnings("rawtypes")
58 private final Function index;
61 * A filter that is applied to all user-provided name propositions before
64 private Function1<String, String> propositionPreFilter;
67 * Construct an index-based naming strategy with "%s %d" as the generated
68 * name format. See {@link Formatter} for the format specification.
70 * @param index the index function for looking up used names. The function
72 * <code>ReadGraph => Resource -> String -> Integer -> List<Map<String,Object>></code>
74 @SuppressWarnings("rawtypes")
75 public CaseInsensitiveComponentFunctionNamingStrategy(Function index) {
80 * Construct an index-based naming strategy with the specified format as the
81 * generated name format. See {@link Formatter} for the format
84 * @param generatedNameFormat the format to use for generated names, see
86 * @param index the index function for looking up used names. The function
88 * <code>ReadGraph => Resource -> String -> Integer -> List<Map<String,Object>></code>
90 @SuppressWarnings("rawtypes")
91 public CaseInsensitiveComponentFunctionNamingStrategy(String generatedNameFormat, Function index) {
92 super(generatedNameFormat);
97 * Construct an index-based naming strategy with the specified format as the
98 * generated name format. See {@link Formatter} for the format
101 * @param generatedNameFormat the format to use for generated names, see
103 * @param index the index function for looking up used names. The function
105 * <code>ReadGraph => Resource -> String -> Integer -> List<Map<String,Object>></code>
106 * @param an optional function to
108 @SuppressWarnings("rawtypes")
109 public CaseInsensitiveComponentFunctionNamingStrategy(String generatedNameFormat, Function index, Function1<String, String> propositionPreFilter) {
110 super(generatedNameFormat);
112 this.propositionPreFilter = propositionPreFilter;
115 CaseInsensitiveComponentNamingStrategy2 fallbackStrategy = null;
118 public String validateInstanceName(ReadGraph graph,
119 Resource configurationRoot, Resource component, String proposition, boolean acceptProposition)
120 throws NamingException, DatabaseException {
122 String lowercaseProposition = proposition.toLowerCase();
124 Layer0 L0 = Layer0.getInstance(graph);
125 String name = graph.getPossibleRelatedValue(component, L0.HasName, Bindings.STRING);
128 String lowercaseName = name.toLowerCase();
129 if(lowercaseName.startsWith(lowercaseProposition)) {
131 Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(configurationRoot));
132 if (indexRoot != null) {
134 synchronized (this) {
136 String search = "Name:" + lowercaseName + "*";
137 @SuppressWarnings("unchecked")
138 List<Resource> components = (List<Resource>) index.apply(graph, indexRoot, search, Integer.MAX_VALUE);
140 Set<Resource> rs = new THashSet<Resource>();
141 for (Resource componentResult : components) {
142 if (DEBUG_INDEX_SEARCH)
143 System.out.println(getClass().getSimpleName() + ": found " + componentResult);
144 String n = graph.getPossibleRelatedValue(componentResult, L0.HasName, Bindings.STRING);
145 if (n != null && n.toLowerCase().equals(lowercaseName))
146 rs.add(componentResult);
149 Cache c = getCache(graph, indexRoot);
152 if(!c.getRequested().contains(name)) {
153 c.addRequested(name);
156 } else if(rs.size() == 1) {
157 if(component.equals(rs.iterator().next())) {
170 StructuralResource2 STR = StructuralResource2.getInstance(graph);
171 Resource container = graph.getSingleObject(component, L0.PartOf);
172 Resource componentType = graph.getSingleType(component, STR.Component);
173 return validateInstanceName(graph, configurationRoot, container, componentType, proposition, acceptProposition);
177 static class ComponentsRequest extends UnaryRead<Tuple4, Set<String>>{
179 public ComponentsRequest(Tuple4 parameter) {
184 public Set<String> perform(ReadGraph graph) throws DatabaseException {
186 Resource indexRoot = (Resource)parameter.get(0);
187 Function index = (Function)parameter.get(1);
188 String search = (String)parameter.get(2);
189 Comparator<Object> comparator = (Comparator<Object>)parameter.get(3);
191 List<Resource> components = (List<Resource>) index.apply(graph, indexRoot, search, Integer.MAX_VALUE);
192 Set<String> reserved = new TreeSet<String>(comparator);
194 Layer0 L0 = Layer0.getInstance(graph);
195 for (Resource componentResult : components) {
196 if (DEBUG_INDEX_SEARCH)
197 System.out.println(getClass().getSimpleName() + ": found " + componentResult);
198 String name = graph.getPossibleRelatedValue(componentResult, L0.HasName, Bindings.STRING);
203 System.err.println("found " + reserved.size() + " components");
212 public String validateInstanceName(ReadGraph graph, Resource configurationRoot, Resource container,
213 Resource componentType, String proposition, boolean acceptProposition) throws NamingException, DatabaseException {
214 Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(configurationRoot));
215 if (indexRoot == null) {
216 System.err.println("Could not find index root from configuration root '" + NameUtils.getSafeName(graph, configurationRoot, true) + "'");
217 if(fallbackStrategy == null)
219 new CaseInsensitiveComponentNamingStrategy2(graph.getService(GraphChangeListenerSupport.class), generatedNameFormat);
220 return fallbackStrategy.validateInstanceName(graph, configurationRoot, container, componentType, proposition, acceptProposition);
223 if (propositionPreFilter != null)
224 proposition = propositionPreFilter.apply(proposition);
226 synchronized (this) {
228 String search = "Name:" + proposition + "*";
230 Set<String> reserved = graph.syncRequest(new ComponentsRequest(new Tuple4(indexRoot, index, search, getComparator())), TransientCacheAsyncListener.instance());
232 Cache cache = getCache(graph, indexRoot);
234 findStartsWithMatches(cache.getRequested(), proposition, reserved);
236 String result = findFreshName(reserved, proposition, acceptProposition);
237 cache.addRequested(result);
239 if (DEBUG_INDEX_SEARCH)
240 System.out.println(getClass().getSimpleName() + ": validated instance name " + result);
247 public List<String> validateInstanceNames(
249 Resource configurationRoot,
250 List<String> propositions,
251 boolean acceptProposition,
252 Set<String> externallyReserved) throws NamingException, DatabaseException
254 Resource indexRoot = graph.syncRequest(new PossibleIndexRoot(configurationRoot));
255 if (indexRoot == null)
256 throw new NamingException("Could not find index root from configuration root '" + NameUtils.getSafeName(graph, configurationRoot, true) + "'");
258 Layer0 L0 = Layer0.getInstance(graph);
260 synchronized (this) {
261 List<String> result = new ArrayList<String>(propositions.size());
262 Set<String> reserved = new TreeSet<String>(getComparator());
264 for (String proposition : propositions) {
265 if (propositionPreFilter != null)
266 proposition = propositionPreFilter.apply(proposition);
268 String search = "Name:" + IndexQueries.escape( proposition ) + "*";
269 @SuppressWarnings("unchecked")
270 List<Resource> components = (List<Resource>) index.apply(graph, indexRoot, search, Integer.MAX_VALUE);
272 if (DEBUG_INDEX_SEARCH)
273 System.out.println(getClass().getSimpleName() + ": found " + components.size()
274 + " index results for index root " + indexRoot + " & configurationRoot " + configurationRoot
275 + " & proposition '" + proposition + "':");
278 for (Resource componentResult : components) {
279 if (DEBUG_INDEX_SEARCH)
280 System.out.println(getClass().getSimpleName() + ": found " + componentResult);
281 String name = graph.getPossibleRelatedValue(componentResult, L0.HasName, Bindings.STRING);
286 if (externallyReserved != null)
287 reserved.addAll(externallyReserved);
288 reserved.addAll(result);
289 String name = findFreshName(reserved, proposition, acceptProposition);
293 if (DEBUG_INDEX_SEARCH)
294 System.out.println(getClass().getSimpleName() + ": validated instance name " + proposition + " -> " + name);
297 if (DEBUG_INDEX_SEARCH)
298 System.out.println(getClass().getSimpleName() + ": validated instance names " + propositions + " -> " + result);
304 private Cache getCache(ReadGraph graph, Resource root) throws DatabaseException {
305 Cache cache = Indexing.getCache(root, Cache.class);
306 if(cache != null) return cache;
307 synchronized (this) {
308 cache = Indexing.getCache(root, Cache.class);
309 if(cache != null) return cache;
310 return Indexing.createCache(root, new Cache(caseInsensitive));
316 private final Set<String> requested;
318 Cache(boolean caseInsensitive) {
319 this.requested = new TreeSet<String>(getComparator(caseInsensitive));
322 public Set<String> getRequested() {
326 public void addRequested(String name) {
331 public String toString() {
332 return getClass().getSimpleName() + ": " + requested;