/******************************************************************************* * Copyright (c) 2018 Association for Decentralized Information Management in * Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Semantum Oy - initial API and implementation *******************************************************************************/ 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; /** * @author Antti Villberg * @since 1.36.0 */ public abstract 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); } } }; } }