]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.db.layer0/src/org/simantics/db/layer0/adapter/ContextualRelatedValue.java
b5f939aaa70690dc2296c3f467d4fad683dd6f9c
[simantics/platform.git] / bundles / org.simantics.db.layer0 / src / org / simantics / db / layer0 / adapter / ContextualRelatedValue.java
1 package org.simantics.db.layer0.adapter;
2
3 import org.simantics.db.ConverterComputationalValue;
4 import org.simantics.db.ReadGraph;
5 import org.simantics.db.Resource;
6 import org.simantics.db.exception.DatabaseException;
7 import org.simantics.db.exception.RuntimeDatabaseException;
8 import org.simantics.db.layer0.variable.Variable;
9 import org.simantics.scl.runtime.SCLContext;
10 import org.simantics.scl.runtime.function.Function1;
11 import org.simantics.scl.runtime.function.FunctionImpl3;
12
13 abstract public class ContextualRelatedValue implements ConverterComputationalValue {
14
15     @SuppressWarnings("unchecked")
16         @Override
17     public <T> T getValue(ReadGraph graph, Resource resource) throws DatabaseException {
18         
19         return (T)new FunctionImpl3<ReadGraph, Resource, Object, Object>() {
20
21             @Override
22             public Object apply(ReadGraph graph, Resource converter, Object context) {
23                 SCLContext sclContext = SCLContext.getCurrent();
24                 Object oldGraph = sclContext.get("graph");
25                 try {
26                     if(context instanceof Variable) {
27                         Variable variable = (Variable)context;
28                         try {
29                             Function1<Object,Object> fn = getFunction(graph, variable.getParent(graph).getRepresents(graph), variable.getRepresents(graph), variable.getPredicateResource(graph));
30                             sclContext.put("graph", graph);
31                             return fn.apply(variable);
32                         } catch (DatabaseException e) {
33                             throw new RuntimeDatabaseException(e);
34                         }
35                     } if (context instanceof Resource) {
36                         Resource resource = (Resource)context;
37                         try {
38                                 Function1<Object,Object> fn = getFunction(graph, null, resource, null);
39                             return fn.apply(resource);
40                         } catch (DatabaseException e) {
41                             throw new RuntimeDatabaseException(e);
42                         }
43                     } else {
44                         throw new IllegalStateException("Unknown context " + context);
45                     }
46                 } finally {
47                     sclContext.put("graph", oldGraph);
48                 }
49             }
50
51         };
52         
53     }
54
55 }