package org.simantics.db.layer0.adapter; import org.simantics.db.ConverterComputationalValue; import org.simantics.db.ReadGraph; import org.simantics.db.Resource; import org.simantics.db.exception.DatabaseException; import org.simantics.db.exception.RuntimeDatabaseException; import org.simantics.db.layer0.variable.Variable; import org.simantics.scl.runtime.SCLContext; import org.simantics.scl.runtime.function.Function1; import org.simantics.scl.runtime.function.FunctionImpl3; abstract public class ContextualRelatedValue implements ConverterComputationalValue { @SuppressWarnings("unchecked") @Override public T getValue(ReadGraph graph, Resource resource) throws DatabaseException { return (T)new FunctionImpl3() { @Override public Object apply(ReadGraph graph, Resource converter, Object context) { SCLContext sclContext = SCLContext.getCurrent(); Object oldGraph = sclContext.get("graph"); try { if(context instanceof Variable) { Variable variable = (Variable)context; try { Function1 fn = getFunction(graph, variable.getParent(graph).getRepresents(graph), variable.getRepresents(graph), variable.getPredicateResource(graph)); sclContext.put("graph", graph); return fn.apply(variable); } catch (DatabaseException e) { throw new RuntimeDatabaseException(e); } } if (context instanceof Resource) { Resource resource = (Resource)context; try { /* * Here converter is the object and context is the subject */ Function1 fn = getFunction(graph, resource, converter, null); return fn.apply(resource); } catch (DatabaseException e) { throw new RuntimeDatabaseException(e); } } else { throw new IllegalStateException("Unknown context " + context); } } finally { sclContext.put("graph", oldGraph); } } }; } }