1 /*******************************************************************************
2 * Copyright (c) 2018 Association for Decentralized Information Management in
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 * Semantum Oy - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.db.layer0.adapter;
14 import org.simantics.db.ConverterComputationalValue;
15 import org.simantics.db.ReadGraph;
16 import org.simantics.db.Resource;
17 import org.simantics.db.exception.DatabaseException;
18 import org.simantics.db.exception.RuntimeDatabaseException;
19 import org.simantics.db.layer0.variable.Variable;
20 import org.simantics.scl.runtime.SCLContext;
21 import org.simantics.scl.runtime.function.Function1;
22 import org.simantics.scl.runtime.function.FunctionImpl3;
25 * @author Antti Villberg
28 public abstract class ContextualRelatedValue implements ConverterComputationalValue {
30 @SuppressWarnings("unchecked")
32 public <T> T getValue(ReadGraph graph, Resource resource) throws DatabaseException {
33 return (T) new FunctionImpl3<ReadGraph, Resource, Object, Object>() {
35 public Object apply(ReadGraph graph, Resource converter, Object context) {
36 SCLContext sclContext = SCLContext.getCurrent();
37 Object oldGraph = sclContext.get("graph");
39 if (context instanceof Variable) {
40 Variable variable = (Variable)context;
42 Function1<Object,Object> fn = getFunction(graph, variable.getParent(graph).getRepresents(graph), variable.getRepresents(graph), variable.getPredicateResource(graph));
43 sclContext.put("graph", graph);
44 return fn.apply(variable);
45 } catch (DatabaseException e) {
46 throw new RuntimeDatabaseException(e);
48 } if (context instanceof Resource) {
49 Resource resource = (Resource)context;
51 // Here converter is the object and context is the subject
52 Function1<Object,Object> fn = getFunction(graph, resource, converter, null);
53 return fn.apply(resource);
54 } catch (DatabaseException e) {
55 throw new RuntimeDatabaseException(e);
58 throw new IllegalStateException("Unknown context " + context);
61 sclContext.put("graph", oldGraph);