1 package org.simantics.scenegraph.loader;
3 import java.lang.reflect.Field;
4 import java.lang.reflect.Method;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.Collections;
8 import java.util.HashMap;
11 import org.simantics.Simantics;
12 import org.simantics.databoard.Bindings;
13 import org.simantics.databoard.binding.Binding;
14 import org.simantics.db.ReadGraph;
15 import org.simantics.db.RequestProcessor;
16 import org.simantics.db.Resource;
17 import org.simantics.db.common.NamedResource;
18 import org.simantics.db.common.procedure.adapter.ListenerAdapter;
19 import org.simantics.db.common.request.BinaryRead;
20 import org.simantics.db.common.request.ParametrizedPrimitiveRead;
21 import org.simantics.db.common.request.ResourceRead;
22 import org.simantics.db.common.request.UnaryRead;
23 import org.simantics.db.exception.AssumptionException;
24 import org.simantics.db.exception.DatabaseException;
25 import org.simantics.db.layer0.exception.VariableException;
26 import org.simantics.db.layer0.request.VariableName;
27 import org.simantics.db.layer0.request.VariableURI;
28 import org.simantics.db.layer0.variable.Variable;
29 import org.simantics.db.layer0.variable.VariableBuilder;
30 import org.simantics.db.layer0.variable.Variables;
31 import org.simantics.db.procedure.Listener;
32 import org.simantics.layer0.Layer0;
33 import org.simantics.scenegraph.INode;
34 import org.simantics.scenegraph.LoaderNode;
35 import org.simantics.scenegraph.ParentNode;
36 import org.simantics.scenegraph.ontology.ScenegraphResources;
37 import org.simantics.scenegraph.utils.NodeUtil;
38 import org.simantics.scl.runtime.function.Function1;
39 import org.simantics.scl.runtime.function.FunctionImpl2;
40 import org.simantics.utils.DataContainer;
41 import org.simantics.utils.datastructures.Pair;
42 import org.simantics.utils.threads.IThreadWorkQueue;
43 import org.simantics.utils.threads.ThreadUtils;
45 public class ScenegraphLoaderUtils {
47 static Map<Pair<Variable, String>, Collection<Listener<Object>>> externalMap = new HashMap<Pair<Variable, String>, Collection<Listener<Object>>>();
48 static Map<Pair<Variable, String>, Object> externalValueMap = new HashMap<Pair<Variable, String>, Object>();
50 final public static class ScenegraphPropertyReference<T> {
52 static class ExternalRead<T> extends ParametrizedPrimitiveRead<Pair<Variable, String>, T> {
54 public ExternalRead(Variable base, String path) {
55 super(Pair.make(base, path));
59 public void register(ReadGraph graph, final Listener<T> procedure) {
60 Object value = externalValueMap.get(parameter);
61 procedure.execute((T)value);
62 Collection<Listener<Object>> listeners = externalMap.get(parameter);
63 if(listeners == null) {
64 listeners = new ArrayList<Listener<Object>>();
65 externalMap.put(parameter, listeners);
67 listeners.add(new ListenerAdapter<Object>() {
70 public void execute(Object result) {
71 procedure.execute((T)result);
78 public void unregistered() {
79 externalMap.remove(parameter);
84 Variable baseVariable;
85 IThreadWorkQueue thread;
90 public ScenegraphPropertyReference(IThreadWorkQueue thread, INode root, String reference, Variable baseVariable) {
94 this.reference = reference;
95 this.baseVariable = baseVariable;
98 public T getExternalValue(RequestProcessor processor) throws DatabaseException {
99 return processor.sync(new ExternalRead<T>(baseVariable, reference));
102 public T getValue() {
104 final Pair<INode, String> ref = NodeUtil.browsePossibleReference(root, reference);
106 final DataContainer<T> result = new DataContainer<T>();
108 ThreadUtils.syncExec(thread, new Runnable() {
112 T value = ScenegraphLoaderUtils.getNodeProperty((LoaderNode)ref.first, ref.second);
122 public void setValue(final T value) {
124 final Pair<INode, String> ref = NodeUtil.browsePossibleReference(root, reference);
126 ThreadUtils.asyncExec(thread, new Runnable() {
130 Function1<Object, Boolean> function = ScenegraphLoaderUtils.getPropertyFunction((LoaderNode)ref.first, ref.second);
131 if(function != null) {
132 function.apply(value);
134 new Exception("no function for ref " + ref).printStackTrace();
140 //new Exception("no reference for " + root + " " + reference).printStackTrace();
147 public static Collection<Variable> computeChildren(ReadGraph graph, Variable configuration) throws DatabaseException {
148 ScenegraphResources SG = ScenegraphResources.getInstance(graph);
149 Resource represents = configuration.getRepresents(graph);
150 Collection<Resource> children = graph.getPossibleRelatedValue2(represents, SG.Node_children, configuration);
151 if(children == null) return Collections.emptyList();
152 ArrayList<Variable> result = new ArrayList<Variable>();
153 for(Resource item : children) {
154 VariableBuilder variableBuilder = graph.adapt(item, VariableBuilder.class);
155 Variable child = variableBuilder.buildChild(graph, configuration, null, item);
156 if(child != null) result.add(child);
161 public static Collection<Variable> getChildren(RequestProcessor processor, Variable configuration) throws DatabaseException {
163 return processor.sync(new UnaryRead<Variable, Collection<Variable>>(configuration) {
166 public Collection<Variable> perform(ReadGraph graph) throws DatabaseException {
167 return parameter.browseChildren(graph);
174 public static Collection<Variable> getChildren(Resource configuration) throws DatabaseException {
176 return Simantics.getSession().sync(new ResourceRead<Collection<Variable>>(configuration) {
179 public Collection<Variable> perform(ReadGraph graph) throws DatabaseException {
180 return computeChildren(graph, Variables.getVariable(graph, resource));
187 public static Collection<NamedResource> getProperties(RequestProcessor processor, Resource configuration) throws DatabaseException {
189 return processor.sync(new ResourceRead<Collection<NamedResource>>(configuration) {
192 public Collection<NamedResource> perform(ReadGraph graph) throws DatabaseException {
193 Layer0 L0 = Layer0.getInstance(graph);
194 ScenegraphResources SG = ScenegraphResources.getInstance(graph);
195 ArrayList<NamedResource> result = new ArrayList<NamedResource>();
196 for(Resource predicate : graph.getPredicates(resource)) {
197 if(graph.isSubrelationOf(predicate, SG.Node_HasProperty)) {
198 String name = graph.getRelatedValue(predicate, L0.HasName, Bindings.STRING);
199 result.add(new NamedResource(name, predicate));
210 * A custom exception for indicating that the a (runtime) resource has been
211 * disposed of (i.e. its statements have been removed). Optimized by
212 * nullifying {@link #fillInStackTrace()} since this is only used customly
214 * {@link ScenegraphLoaderUtils#listen(RequestProcessor, Variable, String, Function1)}
215 * to dispose of the DB listeners it creates.
217 * @author Tuukka Lehtonen
219 static class DisposedRuntimeException extends AssumptionException {
221 private static final long serialVersionUID = 5213099691410928157L;
223 public DisposedRuntimeException(String message) {
228 public synchronized Throwable fillInStackTrace() {
234 public static <T> void listen(RequestProcessor processor, final ScenegraphLoaderProcess process, final Variable context, final String property, final Function1<T, Boolean> function) throws DatabaseException {
238 processor.syncRequest(new BinaryRead<Variable, String, T> (context, property) {
240 @SuppressWarnings("unchecked")
242 public T perform(ReadGraph graph) throws DatabaseException {
243 // FIXME: this must throw a dedicated exception in the case where the runtime variable has been deleted which implies this listener should be disposed of
244 SceneGraphContext vc = getContext(graph, context);
246 throw new DisposedRuntimeException("No scene graph context");
247 Resource runtime = vc.getRuntime();
248 if (runtime == null || !graph.hasStatement(runtime))
249 throw new DisposedRuntimeException("Scene graph runtime disposed");
251 return (T)parameter.getPropertyValue(graph, parameter2);
254 }, new Listener<T>() {
256 private boolean disposed = false;
259 public void exception(Throwable t) {
260 if (t instanceof DisposedRuntimeException) {
261 //System.out.println("ScenegraphLoaderUtils(" + this + ").listen: runtime disposed");
264 //t.printStackTrace();
269 public void execute(T result) {
271 disposed = function.apply(result);
275 public boolean isDisposed() {
276 return process.isDisposed() | disposed;
280 public String toString() {
281 return "Scenegraph Property Listener for " + process;
286 } catch (DatabaseException e) {
292 public static Resource getRuntime(ReadGraph graph, Variable context) throws DatabaseException {
293 SceneGraphContext vc = getContext(graph, context);
294 if(vc != null) return vc.getRuntime();
295 Variable parent = context.getParent(graph);
296 if(parent == null) throw new DatabaseException("Runtime resource was not found from context Variable.");
297 return getRuntime(graph, parent);
300 public static SceneGraphContext getContext(ReadGraph graph, Variable context) throws DatabaseException {
301 SceneGraphContext vc = context.adaptPossible(graph, SceneGraphContext.class);
302 if(vc != null) return vc;
304 Variable parent = context.getParent(graph);
305 if(parent != null) return getContext(graph, parent);
310 public static Variable getRuntimeVariable(ReadGraph graph, Variable context) throws DatabaseException {
311 SceneGraphContext vc = getContext(graph, context);
312 if(vc == null) return null;
313 else return vc.getRuntimeVariable();
316 public static Variable getBaseVariable(ReadGraph graph, Variable context) throws DatabaseException {
318 Variable parent = context.getParent(graph);
319 if(parent == null) return null;
320 if(context instanceof ScenegraphVariable && !(parent instanceof ScenegraphVariable)) return context;
321 else return getBaseVariable(graph, parent);
325 static class ScenegraphReference extends UnaryRead<Variable, Pair<Variable, String>> {
327 public ScenegraphReference(Variable var) {
333 public Pair<Variable, String> perform(ReadGraph graph) throws DatabaseException {
334 Variable base = getBaseVariable(graph, parameter);
335 return Pair.make(base, Variables.getRVI(graph, base, parameter));
340 public static INode create(RequestProcessor processor, ScenegraphLoaderProcess process, ParentNode<?> parent, Resource configuration, final Variable context, Class<?> clazz) throws DatabaseException {
342 final String name = processor.sync(new VariableName(context));
344 final String uri = processor.sync(new VariableURI(context));
346 LoaderNode node = (LoaderNode)parent.addNode(name, clazz);
348 final Pair<Variable, String> reference = processor.sync(new ScenegraphReference(context));
350 node.setPropertyCallback(new FunctionImpl2<String, Object, Boolean>() {
353 public Boolean apply(String property, Object value) {
354 Pair<Variable, String> key = Pair.make(reference.first, reference.second + "#" + property);
355 externalValueMap.put(key, value);
356 Collection<Listener<Object>> listeners = externalMap.get(key);
357 if(listeners != null) {
358 for(Listener<Object> listener : listeners) listener.execute(value);
365 for(NamedResource property : ScenegraphLoaderUtils.getProperties(processor, configuration)) {
367 Function1<Object, Boolean> func = node.getPropertyFunction(property.getName());
369 ScenegraphLoaderUtils.listen(processor, process, context, property.getName(), func);
371 // System.out.println("NO FUNCTION FOR PROPERTY: " + property.getName() + " (" + node + ")");
372 } catch (Exception e) {
381 public static Variable getVariableSelection(ReadGraph graph, Variable context) throws DatabaseException {
383 Variable runtimeVariable = getRuntimeVariable(graph, context);
384 if (runtimeVariable == null)
385 throw new VariableException("no runtime variable for context " + context.getURI(graph));
386 return runtimeVariable.getPropertyValue(graph, "variable");
390 public static Variable getPossibleVariableSelection(ReadGraph graph, Variable context) throws DatabaseException {
391 Variable runtimeVariable = getRuntimeVariable(graph, context);
392 return runtimeVariable == null ? null : (Variable) runtimeVariable.getPossiblePropertyValue(graph, "variable");
395 public static Resource getResourceSelection(ReadGraph graph, Variable context) throws DatabaseException {
397 Variable runtimeVariable = getRuntimeVariable(graph, context);
398 if (runtimeVariable == null)
399 throw new VariableException("no runtime variable for context " + context.getURI(graph));
400 Resource sel = runtimeVariable.getPropertyValue(graph, "resource");
405 public static Resource getPossibleResourceSelection(ReadGraph graph, Variable context) throws DatabaseException {
407 Variable runtimeVariable = getRuntimeVariable(graph, context);
408 return runtimeVariable == null ? null : (Resource) runtimeVariable.getPossiblePropertyValue(graph, "resource");
412 public static INode getNode(ReadGraph graph, Variable location) throws DatabaseException {
413 Variable runtime = getRuntimeVariable(graph, location);
414 INode root = runtime.adapt(graph, INode.class);
415 Variable base = getBaseVariable(graph, location);
416 String rvi = Variables.getRVI(graph, base, location);
417 return NodeUtil.browsePossible(root, rvi);
420 // public static <T> ScenegraphPropertyReference<T> getPropertyReference(final IThreadWorkQueue thread, final Variable context, final String path) throws DatabaseException {
421 // return Simantics.getSession().sync(new UniqueRead<ScenegraphPropertyReference<T>>() {
424 // public ScenegraphPropertyReference<T> perform(ReadGraph graph) throws DatabaseException {
425 // return getRelativePropertyReference(thread, graph, context, path);
431 // public static <T> T getRelativeProperty(final IThreadWorkQueue thread, ReadGraph graph, Variable context, String path) throws DatabaseException {
432 // ScenegraphPropertyReference<T> ref = getRelativePropertyReference(thread, graph, context, path);
433 // return ref.getExternalValue(graph);
436 public static <T> T getProperty(final IThreadWorkQueue thread, INode _root, String reference) {
438 INode root = ((ParentNode<INode>)_root).getNodes().iterator().next();
440 final Pair<INode, String> ref = NodeUtil.browsePossibleReference(root, reference);
442 final DataContainer<T> result = new DataContainer<T>();
444 ThreadUtils.syncExec(thread, new Runnable() {
448 T value = ScenegraphLoaderUtils.getNodeProperty((LoaderNode)ref.first, ref.second);
458 public static <T> ScenegraphPropertyReference<T> getRelativePropertyReference(final IThreadWorkQueue thread, ReadGraph graph, Variable context, String path) throws DatabaseException {
460 Variable runtime = getRuntimeVariable(graph, context);
461 INode root = runtime.adapt(graph, INode.class);
462 Variable base = getBaseVariable(graph, context);
463 INode baseNode = NodeUtil.findChildById((ParentNode)root, base.getName(graph));
464 String contextRVI = Variables.getRVI(graph, base, context);
465 String rvi = Variables.getRVI(contextRVI, path);
466 return new ScenegraphPropertyReference<T>(thread, baseNode, rvi, base);
470 public static <T> ScenegraphPropertyReference<T> getPropertyReference(final IThreadWorkQueue thread, ReadGraph graph, Variable context, String path) throws DatabaseException {
472 Variable runtime = getRuntimeVariable(graph, context);
473 INode root = runtime.adapt(graph, INode.class);
474 Variable base = getBaseVariable(graph, context);
475 return new ScenegraphPropertyReference<T>(thread, root, path, base);
479 public static Method getSynchronizeMethod(INode node, String propertyName) {
481 String methodName = "synchronize" + propertyName.substring(0,1).toUpperCase() + propertyName.substring(1);
482 for(Method m : node.getClass().getMethods()) {
483 if(m.getName().equals(methodName)) return m;
486 } catch (SecurityException e) {
492 public static Method getReadMethod(INode node, String propertyName) {
494 String methodName = "read" + propertyName.substring(0,1).toUpperCase() + propertyName.substring(1);
495 return node.getClass().getMethod(methodName);
496 } catch (SecurityException e) {
498 } catch (NoSuchMethodException e) {
504 public static Field getPropertyField(INode node, String propertyName) {
506 return node.getClass().getField(propertyName);
507 } catch (SecurityException e) {
509 } catch (NoSuchFieldException e) {
510 System.err.println("node:" + node);
516 public static Class<?> getPropertyType(Field field) {
517 return field.getType();
520 public static Class<?> getArgumentType(Method method) {
521 return (Class<?>)method.getGenericParameterTypes()[0];
524 public static Class<?> getReturnType(Method method) {
525 return method.getReturnType();
528 public static Binding getPropertyBinding(Class<?> clazz) {
530 return Bindings.getBindingUnchecked(clazz);
531 } catch (Throwable t) {
536 public static Binding getGenericPropertyBinding(Binding binding) {
538 return Bindings.getBinding(binding.type());
539 } catch (Throwable t) {
544 public static Function1<Object, Boolean> getPropertyFunction(final LoaderNode node, final String propertyName) {
545 return node.getPropertyFunction(propertyName);
548 public static <T> T getNodeProperty(final LoaderNode node, final String propertyName) {
549 return node.getProperty(propertyName);
552 public static String getPath(ReadGraph graph, Variable context) throws DatabaseException {
553 Variable base = getBaseVariable(graph, context);
554 return Variables.getRVI(graph, base, context);