]> gerrit.simantics Code Review - simantics/platform.git/blobdiff - bundles/org.simantics.document.server/src/org/simantics/document/server/Functions.java
Let the request processor handle the exceptions
[simantics/platform.git] / bundles / org.simantics.document.server / src / org / simantics / document / server / Functions.java
index 20fa2a71b7b272cec574e351c715a17c25479f04..0a7e004f7dcab5e75740d176100c78d59c3dfb47 100644 (file)
@@ -5,6 +5,7 @@ import java.io.StringWriter;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.TreeMap;
@@ -14,10 +15,13 @@ import org.simantics.databoard.Bindings;
 import org.simantics.databoard.Datatypes;
 import org.simantics.databoard.binding.Binding;
 import org.simantics.databoard.type.Datatype;
+import org.simantics.db.AsyncReadGraph;
+import org.simantics.db.DirectStatements;
 import org.simantics.db.ReadGraph;
 import org.simantics.db.RequestProcessor;
 import org.simantics.db.Resource;
 import org.simantics.db.Session;
+import org.simantics.db.Statement;
 import org.simantics.db.WriteGraph;
 import org.simantics.db.common.primitiverequest.Adapter;
 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
@@ -29,18 +33,25 @@ import org.simantics.db.common.utils.NameUtils;
 import org.simantics.db.exception.DatabaseException;
 import org.simantics.db.layer0.function.All;
 import org.simantics.db.layer0.request.ProjectModels;
+import org.simantics.db.layer0.request.PropertyInfo;
+import org.simantics.db.layer0.request.PropertyInfoRequest;
 import org.simantics.db.layer0.request.VariableProperty;
 import org.simantics.db.layer0.request.VariableRead;
 import org.simantics.db.layer0.request.VariableValueWithBinding;
+import org.simantics.db.layer0.scl.SCLDatabaseException;
 import org.simantics.db.layer0.variable.ConstantPropertyVariable;
 import org.simantics.db.layer0.variable.ProxyChildVariable;
 import org.simantics.db.layer0.variable.ProxySessionRequest;
 import org.simantics.db.layer0.variable.ProxyVariables;
+import org.simantics.db.layer0.variable.StandardAssertedGraphPropertyVariable;
 import org.simantics.db.layer0.variable.StandardGraphChildVariable;
+import org.simantics.db.layer0.variable.StandardGraphPropertyVariable;
 import org.simantics.db.layer0.variable.Variable;
 import org.simantics.db.layer0.variable.VariableMap;
 import org.simantics.db.layer0.variable.VariableMapImpl;
 import org.simantics.db.layer0.variable.Variables;
+import org.simantics.db.procedure.AsyncProcedure;
+import org.simantics.db.service.DirectQuerySupport;
 import org.simantics.document.base.ontology.DocumentationResource;
 import org.simantics.document.server.bean.Command;
 import org.simantics.document.server.bean.DataDefinition;
@@ -52,6 +63,7 @@ import org.simantics.document.server.io.CommandContextImpl;
 import org.simantics.document.server.io.CommandContextMutable;
 import org.simantics.document.server.io.CommandResult;
 import org.simantics.document.server.io.IConsole;
+import org.simantics.document.server.request.NodeRequest;
 import org.simantics.document.server.request.ServerSCLHandlerValueRequest;
 import org.simantics.document.server.request.ServerSCLValueRequest;
 import org.simantics.document.server.serverResponse.ServerResponse;
@@ -63,6 +75,7 @@ import org.simantics.modeling.services.CaseInsensitiveComponentFunctionNamingStr
 import org.simantics.modeling.services.ComponentNamingStrategy;
 import org.simantics.operation.Layer0X;
 import org.simantics.project.IProject;
+import org.simantics.scl.compiler.module.repository.ImportFailureException;
 import org.simantics.scl.compiler.types.TCon;
 import org.simantics.scl.compiler.types.Type;
 import org.simantics.scl.compiler.types.Types;
@@ -83,12 +96,138 @@ import org.simantics.simulation.experiment.IExperiment;
 import org.simantics.simulation.ontology.SimulationResource;
 import org.simantics.simulation.project.IExperimentManager;
 import org.simantics.structural2.variables.Connection;
+import org.simantics.structural2.variables.StandardProceduralChildVariable;
 import org.simantics.structural2.variables.VariableConnectionPointDescriptor;
+import org.slf4j.LoggerFactory;
 
 import gnu.trove.map.hash.THashMap;
 
 public class Functions {
-       
+
+    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Functions.class);
+    
+    private static class PrimitivePropertyStatementsProcedure implements AsyncProcedure<DirectStatements> {
+
+        public DirectStatements result;
+
+        @Override
+        public void execute(AsyncReadGraph graph, DirectStatements result) {
+            this.result = result;
+        }
+
+        @Override
+        public void exception(AsyncReadGraph graph, Throwable throwable) {
+        }
+
+    }
+
+    @SCLValue(type = "VariableMap")
+    public static VariableMap primitiveProperties = new VariableMapImpl() {
+       private void storePropertyValueAndExceptions(ReadGraph graph, Variable parent, String name, Variable property, Map<String, Variable> map) {
+               try {
+                       Object value = property.getValue(graph);
+                               map.put(name, new ConstantPropertyVariable(parent, name, value, null));
+               } catch (DatabaseException e) {
+                       Variable propertyExceptions = map.get(NodeRequest.PROPERTY_VALUE_EXCEPTIONS);
+                       Map<String, Exception> exceptionMap;
+                       if (propertyExceptions == null) {
+                               exceptionMap = new TreeMap<String, Exception>();
+                               propertyExceptions = new ConstantPropertyVariable(parent, NodeRequest.PROPERTY_VALUE_EXCEPTIONS, exceptionMap, null);
+                               map.put(NodeRequest.PROPERTY_VALUE_EXCEPTIONS, propertyExceptions);
+                       } else {
+                               try {
+                                               exceptionMap = propertyExceptions.getValue(graph);
+                                       } catch (DatabaseException e1) {
+                                               Logger.defaultLogError(e1);
+                                               return;
+                                       }
+                       }
+                       String label = name;
+                       try {
+                               label = property.getLabel(graph);
+                       } catch (DatabaseException e2) {
+
+                       }
+                       exceptionMap.put(label, e);
+               }
+       }
+       
+        @Override
+        public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
+            return All.getStandardPropertyDomainPropertyVariableFromValue(graph, context, name);
+        }
+
+        @Override
+        public Map<String, Variable> getVariables(final ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
+
+            if(map == null) map = new HashMap<String,Variable>();
+
+            Variable parent = context.getParent(graph);
+
+            DocumentationResource DOC = DocumentationResource.getInstance(graph);
+
+            if(parent instanceof StandardProceduralChildVariable) {
+
+                StandardProceduralChildVariable procedural = (StandardProceduralChildVariable)parent;
+                for(Variable property : procedural.getProperties(graph/*, DocumentationResource.URIs.Document_AttributeRelation*/)) {
+                    if(property instanceof StandardAssertedGraphPropertyVariable) {
+                        StandardAssertedGraphPropertyVariable ass = (StandardAssertedGraphPropertyVariable)property;
+                        if("dataDefinitions".equals(ass.property.name) || "commands".equals(ass.property.name)  || "pollingFunction".equals(ass.property.name)) {
+                               storePropertyValueAndExceptions(graph, parent, ass.property.name, property, map);
+                        }
+                        continue;
+                    }
+                    Resource predicate = property.getPossiblePredicateResource(graph);
+                    if(predicate != null) {
+                        PropertyInfo info = graph.syncRequest(new PropertyInfoRequest(predicate));
+                        if(info.hasClassification(DocumentationResource.URIs.Document_AttributeRelation)) {
+                               Variable prop = parent.getProperty(graph, predicate);
+                            storePropertyValueAndExceptions(graph, parent, info.name, prop, map);
+                        }
+                    }
+                }
+
+            } else {
+
+                Resource parentRes = parent.getRepresents(graph);
+                {
+                       Variable prop = new StandardGraphPropertyVariable(graph, parent, DOC.Properties_commands);
+                       storePropertyValueAndExceptions(graph, parent, "commands", prop, map);
+                }
+
+                if (graph.getPossibleObject(parentRes, DOC.Properties_dataDefinitions) != null) {
+                       Variable prop = new StandardGraphPropertyVariable(graph, parent, DOC.Properties_dataDefinitions);
+                       storePropertyValueAndExceptions(graph, parent, "dataDefinitions", prop, map);
+                }
+                
+                DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
+                PrimitivePropertyStatementsProcedure foo = new PrimitivePropertyStatementsProcedure();
+
+                dqs.forEachDirectPersistentStatement(graph, parentRes, foo);
+
+                for(Statement stm : foo.result) {
+                    Resource predicate = stm.getPredicate();
+                    PropertyInfo info = graph.syncRequest(new PropertyInfoRequest(predicate));
+
+                    if(info.isHasProperty && info.hasClassification(DocumentationResource.URIs.Document_AttributeRelation)) {
+                       Variable prop = new StandardGraphPropertyVariable(graph, parent, predicate);
+                       storePropertyValueAndExceptions(graph, parent, info.name, prop, map);
+                    } else {
+                        Resource definition = graph.getPossibleObject(predicate, DOC.Document_definesAttributeRelation);
+                        if(definition != null) {
+                               PropertyInfo info2 = graph.syncRequest(new PropertyInfoRequest(definition));
+                               Variable prop = new StandardGraphPropertyVariable(graph, parent, definition);
+                            map.put(info2.name, new PrimitiveValueVariable(parent, info2.name, prop));
+                        }
+                    }
+                }
+            }
+            return map;
+
+        }
+
+    };
+
     @SCLValue(type = "VariableMap")
     public static VariableMap inputSpaceChildren = new VariableMapImpl() {
 
@@ -96,13 +235,13 @@ public class Functions {
             Variable root = Variables.getRootVariable(graph);
             return new DocumentProxyChildVariable(context, context, root, ProxyChildVariable.CONTEXT_BEGIN);
         }
-        
+
         @Override
         public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
 
             if(ProxyChildVariable.CONTEXT_BEGIN.equals(name)) return getProxy(graph, context);
             return All.standardChildDomainChildren.getVariable(graph, context, name);
-            
+
         }
 
         @Override
@@ -112,24 +251,24 @@ public class Functions {
             if(map == null) map = new THashMap<String,Variable>();
             map.put(ProxyChildVariable.CONTEXT_BEGIN, getProxy(graph, context));
             return map;
-            
+
         }
-        
+
     };
-    
+
     static class DocumentProxyChildVariable extends ProxyChildVariable {
 
         public DocumentProxyChildVariable(Variable base, Variable parent, Variable other, String name) {
             super(base, parent, other, name);
         }
-    
+
         @Override
         public Variable create(Variable base, Variable parent, Variable other, String name) {
             return new DocumentProxyChildVariable(base, parent, other, name);
         }
-        
+
         public Variable getPossibleChild(ReadGraph graph, String name) throws DatabaseException {
-            
+
                if(CONTEXT_END.equals(name)) {
                if(other instanceof ProxyChildVariable) {
                        // The context is also a proxy - let it do the job
@@ -138,11 +277,11 @@ public class Functions {
                        return new RootVariable(this, base.getRepresents(graph));
                }
                }
-            
+
             return super.getPossibleChild(graph, name);
-            
+
         }
-        
+
         public Collection<Variable> getChildren(ReadGraph graph) throws DatabaseException {
 
             Collection<Variable> result = super.getChildren(graph);
@@ -150,28 +289,28 @@ public class Functions {
                result.add(new RootVariable(this, base.getRepresents(graph)));
             }
             return result;
-            
-        }       
-        
+
+        }
+
     }
-    
+
     static class RootVariable extends StandardGraphChildVariable {
 
         public RootVariable(DocumentProxyChildVariable parent, Resource resource) {
             super(parent, null, resource);
         }
-        
+
         @Override
         public String getName(ReadGraph graph) throws DatabaseException {
             return ProxyChildVariable.CONTEXT_END;
         }
-        
+
         @SuppressWarnings("deprecation")
         @Override
         public Variable getNameVariable(ReadGraph graph) throws DatabaseException {
             return new ConstantPropertyVariable(this, Variables.NAME, ProxyChildVariable.CONTEXT_END, Bindings.STRING);
         }
-        
+
     }
 
     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
@@ -187,14 +326,14 @@ public class Functions {
        }
        return Variables.getVariable(graph, uri);
     }
-    
+
     public static Variable stateVariable(ReadGraph graph, Variable self) throws DatabaseException {
        Variable session = graph.syncRequest(new ProxySessionRequest(self));
        if (session == null)
                throw new DatabaseException("No state for " + self.getURI(graph));
        return session.getPossibleChild(graph, "__scl__");
     }
-    
+
     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
     public static Variable state(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
        Variable session = graph.syncRequest(new ProxySessionRequest(context));
@@ -213,7 +352,7 @@ public class Functions {
     public static Variable session(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
        return graph.syncRequest(new ProxySessionRequest(context));
     }
-    
+
     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
     public static Variable experiment(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
         // Try if experiment (run) has been used as the input
@@ -222,16 +361,16 @@ public class Functions {
         while(var != null && !graph.isInstanceOf(var.getRepresents(graph), SR.Run)) {
             var = var.getParent(graph);
         }
-        
+
         if(var != null) {
             IExperiment exp = getExperiment(graph, var);
             if(exp == null)
                 return null;
         }
-        
+
         return var;
     }
-    
+
     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
     public static Variable model(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
         Variable var = input(graph, converter, context);
@@ -239,51 +378,51 @@ public class Functions {
         while(var != null && !graph.isInstanceOf(var.getRepresents(graph), MOD.StructuralModel)) {
             var = var.getParent(graph);
         }
-        
+
         return var;
     }
-    
+
     private static Collection<Variable> getBroadcasted(ReadGraph graph, Variable target) throws DatabaseException {
-       
+
        ArrayList<Variable> result = new ArrayList<Variable>();
-       
+
         DocumentationResource DOC = DocumentationResource.getInstance(graph);
 
        Variable broadcasted = target.getPossibleProperty(graph, DOC.Relations_broadcasted);
        if(broadcasted != null) result.add(broadcasted);
-       
+
        for(Variable child : DocumentServerUtils.getChildrenInOrdinalOrder(graph, target)) {
                result.addAll(getBroadcasted(graph, child));
        }
-       
+
        return result;
-       
+
     }
 
     private static List<Command> getCommands(ReadGraph graph, Collection<Variable> commandVariables, String trigger, CommandContext constants, boolean broadcast) throws DatabaseException {
-       
+
        if(commandVariables.isEmpty()) return Collections.emptyList();
-       
+
         String t = trigger;
         TreeMap<Integer, List<Command>> sequences = new TreeMap<Integer, List<Command>>();
-        
+
         DocumentationResource DOC = DocumentationResource.getInstance(graph);
-        
+
         int count = 0;
         for (Variable c : commandVariables) {
-               
+
             if(trigger == null)
                t = c.getName(graph);
-            
+
             Connection conn = c.getValue(graph);
             Variable targetConnectionPoint = DocumentServerUtils.getPossibleCommandTriggerConnectionPoint(graph, c, conn);
             if (targetConnectionPoint != null) {
                 Variable target = targetConnectionPoint.getParent(graph);
                 if (target != null) {
-                    
+
                     Boolean enabled = target.getPossiblePropertyValue(graph, DOC.Properties_exists, Bindings.BOOLEAN);
                     if(enabled != null && !enabled) continue;
-                       
+
                     Integer ordinal;
                     if (broadcast) {
                        ordinal = ++count;
@@ -295,10 +434,10 @@ public class Functions {
                                    ordinal = Integer.parseInt(o);
                            } catch (NumberFormatException e) {}
                     }
-                    
+
                     String constantKey = target.getPossiblePropertyValue(graph, "constantKey");
                     String constantValue = target.getPossiblePropertyValue(graph, "constantValue");
-                    
+
                     CommandContextMutable newConstants = (CommandContextMutable)constants; 
                     if(constantKey != null && constantValue != null) {
                        if(!constantKey.isEmpty()) {
@@ -306,7 +445,7 @@ public class Functions {
                                newConstants.putString(constantKey, constantValue);
                        }
                     }
-                    
+
                     String requiredKey = target.getPossiblePropertyValue(graph, "requiredKey");
                     if(requiredKey != null && !requiredKey.isEmpty()) {
                        if (newConstants == constants) {
@@ -314,7 +453,7 @@ public class Functions {
                        }
                                newConstants.putRow(CommandContext.REQUIRED_KEYS, Collections.<Object>singletonList(requiredKey));
                     }
-                    
+
                     String forbiddenKey = target.getPossiblePropertyValue(graph, "forbiddenKey");
                     if(forbiddenKey != null && !forbiddenKey.isEmpty()) {
                        if (newConstants == constants) {
@@ -334,7 +473,7 @@ public class Functions {
                        Command command = new Command(DocumentServerUtils.getId(graph, target), t, 
                                        targetConnectionPoint.getName(graph), newConstants);
                        sequences.put(ordinal, Collections.singletonList(command));
-                       
+
                     }
 
                 }
@@ -347,7 +486,7 @@ public class Functions {
                        commands.add(command);
                }
         }
-        
+
         return commands;
     }
 
@@ -408,7 +547,7 @@ public class Functions {
 
                                        dataDefinitions.add(new DataDefinition(DocumentServerUtils.getId(graph, data),
                                                        sourceProperty, targetProperty));
-                                
+
                                 } else if (graph.isInheritedFrom(type, DOC.Components_DefVars)) {
 
                                        List<String> sourcesProperty = toList(dataDefinition.getPropertyValue(graph, DOC.Properties_sources), String.class);
@@ -443,33 +582,33 @@ public class Functions {
                return Collections.<T>emptyList();
        }
     }
-    
+
+    @Deprecated
     public static AbstractEventHandler emptyOnClick(ReadGraph graph) throws DatabaseException {
         return new EventHandler() {
-
             @Override
             public ServerResponse handle(ReadGraph graph, CommandContext parameters) throws DatabaseException {
                 return null;
             }
-
         };
     }
-    
+
+    @Deprecated
     public static AbstractEventHandler writeEventHandler(ReadGraph graph, final Variable variable, final Function fn) {
-        
+
        final Session session = graph.getSession();
-       
+
         return new AbstractEventHandler() {
-            
+
                        @Override
                        public CommandResult handle(final CommandContext parameters) {
-                               
+
                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
-                
+
                 try {
-                       
+
                                        String result = session.sync(new WriteResultRequest<String>() {
-                                           
+
                                            @Override
                                            public String perform(WriteGraph graph) throws DatabaseException {
                                                SCLContext sclContext = SCLContext.getCurrent();
@@ -487,46 +626,43 @@ public class Functions {
                                                        return (String)response;
                                                    }
                                                    return null;
-                                               } catch (Throwable t) {
-                                                   t.printStackTrace();
                                                } finally {
                                                        sclContext.put("graph", oldGraph);
                                                        sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
                                                }
-                                               
-                                               return null;
-                                               
+
                                            }
-                                           
+
                                        });
-                                       
+
                        return new SuccessResponse(result);
-                                       
+
                                } catch (Throwable e) {
                                        Logger.defaultLogError(e);
                                        return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
                                }
-                
+
                        }
-            
+
         };
     }
-    
+
+    @Deprecated
     public static AbstractEventHandler readEventHandler(ReadGraph graph, final Variable variable, final Function fn) {
-        
+
        final Session session = graph.getSession();
-       
+
         return new AbstractEventHandler() {
-            
+
                        @Override
                        public CommandResult handle(final CommandContext parameters) {
-                               
+
                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
-                
+
                 try {
-                       
+
                                        String result = session.sync(new UniqueRead<String>() {
-                                           
+
                                            @Override
                                            public String perform(ReadGraph graph) throws DatabaseException {
                                                SCLContext sclContext = SCLContext.getCurrent();
@@ -544,46 +680,43 @@ public class Functions {
                                                        return (String)response;
                                                    }
                                                    return null;
-                                               } catch (Throwable t) {
-                                                   t.printStackTrace();
                                                } finally {
                                                        sclContext.put("graph", oldGraph);
                                                        sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
                                                }
-                                               
-                                               return null;
-                                               
+
                                            }
-                                           
+
                                        });
-                                       
+
                        return new SuccessResponse(result);
-                                       
+
                                } catch (Throwable e) {
                                        Logger.defaultLogError(e);
                                        return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
                                }
-                
+
                        }
-            
+
         };
     }
 
+    @Deprecated
     public static AbstractEventHandler readEventHandler2(ReadGraph graph, final Function fn) {
-        
+
        final Session session = graph.getSession();
-       
+
         return new AbstractEventHandler() {
-            
+
                        @Override
                        public CommandResult handle(final CommandContext parameters) {
-                               
+
                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
-                
+
                 try {
-                       
+
                        CommandResult result = session.sync(new UniqueRead<CommandResult>() {
-                                           
+
                                            @Override
                                            public CommandResult perform(ReadGraph graph) throws DatabaseException {
                                                SCLContext sclContext = SCLContext.getCurrent();
@@ -595,28 +728,24 @@ public class Functions {
                                                        return (CommandResult)response;
                                                    }
                                                    return null;
-                                               } catch (Throwable t) {
-                                                   t.printStackTrace();
                                                } finally {
                                                        sclContext.put("graph", oldGraph);
                                                        sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
                                                }
-                                               
-                                               return null;
-                                               
+
                                            }
-                                           
+
                                        });
-                                       
+
                        return result;
-                                       
+
                                } catch (Throwable e) {
                                        Logger.defaultLogError(e);
                                        return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
                                }
-                
+
                        }
-            
+
         };
     }
 
@@ -626,18 +755,18 @@ public class Functions {
         if(anyFunction == null) return null;
 
         final List<TCon> effects = ServerSCLHandlerValueRequest.getEffects(graph, anyFunction);
-       
+
        final Function1<CommandContext, CommandResult> fn = anyFunction.getValue(graph);
         String expression = anyFunction.getPropertyValue(graph, "expression");
-        
+
        final Session session = graph.getSession();
-       
+
         return new AbstractResponseHandler(expression) {
-            
+
                private String formatError(RequestProcessor proc, Throwable t) {
-                       
+
                        try {
-                               
+
                                        return proc.syncRequest(new UniqueRead<String>() {
 
                                                @Override
@@ -654,33 +783,33 @@ public class Functions {
                                                        message.append(" handler=" + path + "\n");
                                                        message.append(" expression=" + expr + "\n");
                                                        message.append(" message=" + t.getMessage() + "\n");
-                                                       
+
                                                        StringWriter sw = new StringWriter();
                                                        t.printStackTrace(new PrintWriter(sw));
                                                        message.append(" stack trace=" + sw);
-                                                       
+
                                                        return message.toString();
                                                }
-                                               
+
                                        });
-                                       
+
                                } catch (DatabaseException e) {
-                                       
+
                                        return e.getMessage();
-                                       
+
                                }
-                       
+
                }
-               
+
                        @Override
                        public CommandResult handle(final CommandContext parameters) {
-                               
+
                                IConsole console = parameters.getValue("__console__");
                                SCLReportingHandler printer = (console != null) ? new ConsoleSCLReportingHandler(console)
                                                : (SCLReportingHandler) SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
-                
+
                 try {
-                       
+
                        Object result = null;
                        if(effects.contains(Types.WRITE_GRAPH)) {
 
@@ -693,10 +822,7 @@ public class Functions {
                                                Object oldGraph = sclContext.put("graph", graph);
                                                Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
                                                try {
-                                                       Object response = fn.apply(parameters);
-                                                       return response;
-                                               } catch (Throwable t) {
-                                                       return new org.simantics.document.server.serverResponse.Error(formatError(graph, t));
+                                                       return fn.apply(parameters);
                                                } finally {
                                                        sclContext.put("graph", oldGraph);
                                                        sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
@@ -704,33 +830,30 @@ public class Functions {
 
                                                        }
                                });
-                               
+
                        } else if(effects.contains(Types.READ_GRAPH)) {
 
                                result = session.sync(new UniqueRead<Object>() {
 
                                        @Override
                                        public Object perform(ReadGraph graph) throws DatabaseException {
-                                               
+
                                                SCLContext sclContext = SCLContext.getCurrent();
                                                Object oldGraph = sclContext.put("graph", graph);
                                                Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
-                                               
+
                                                try {
-                                                       Object response = fn.apply(parameters);
-                                                       return response;
-                                               } catch (Throwable t) {
-                                                       return new org.simantics.document.server.serverResponse.Error(formatError(graph, t));
+                                                       return fn.apply(parameters);
                                                } finally {
                                                        sclContext.put("graph", oldGraph);
                                                        sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
                                                }
-                                               
+
                                        }
                                });
 
                        } else {
-                               
+
                                                SCLContext sclContext = SCLContext.getCurrent();
                                                Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
                                                try {
@@ -744,39 +867,40 @@ public class Functions {
                        if (result instanceof org.simantics.document.server.serverResponse.Error) {
                                return (CommandResult)result;
                        }
-                       
+
                        if (result instanceof CommandResult) {
                                return (CommandResult)result;
                        } else {
                                CommandContextMutable assignments = new CommandContextImpl();
                                assignments.putValue("result", result);
                                return new ServerResponse(200, "", assignments);
-                       }                       
-                                       
+                       }
+
                                } catch (Throwable e) {
                                        return new org.simantics.document.server.serverResponse.Error(formatError(Simantics.getSession(), e));
                                }
-                
+
                        }
-            
+
         };
     }
-    
+
+    @Deprecated
     public static AbstractEventHandler writeEventHandler2(ReadGraph graph, final Function fn) {
-        
+
        final Session session = graph.getSession();
-       
+
         return new AbstractEventHandler() {
-            
+
                        @Override
                        public CommandResult handle(final CommandContext parameters) {
-                               
+
                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
-                
+
                 try {
-                       
+
                        CommandResult result = session.syncRequest(new WriteResultRequest<CommandResult>() {
-                                           
+
                                            @Override
                                            public CommandResult perform(WriteGraph graph) throws DatabaseException {
                                                SCLContext sclContext = SCLContext.getCurrent();
@@ -788,42 +912,40 @@ public class Functions {
                                                        return (CommandResult)response;
                                                    }
                                                    return null;
-                                               } catch (Throwable t) {
-                                                   t.printStackTrace();
                                                } finally {
                                                        sclContext.put("graph", oldGraph);
                                                        sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
                                                }
-                                               
-                                               return null;
-                                               
+
                                            }
-                                           
+
                                        });
-                                       
+
                        return result;
-                                       
+
                                } catch (Throwable e) {
                                        Logger.defaultLogError(e);
                                        return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
                                }
-                
+
                        }
-            
+
         };
     }
 
+
+    @Deprecated
     public static AbstractEventHandler eventHandler2(ReadGraph graph, final Function fn) {
-        
+
         return new AbstractEventHandler() {
-            
+
                        @Override
                        public CommandResult handle(final CommandContext parameters) {
-                               
+
                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
-                
+
                 try {
-                       
+
                        SCLContext sclContext = SCLContext.getCurrent();
                        Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
                        try {
@@ -832,37 +954,34 @@ public class Functions {
                                        return (CommandResult)response;
                                }
                                return null;
-                       } catch (Throwable t) {
-                               t.printStackTrace();
                        } finally {
                                sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
                        }
 
-                       return null;
-                                               
                                } catch (Throwable e) {
                                        Logger.defaultLogError(e);
                                        return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
                                }
-                
+
                        }
-            
+
         };
     }
 
+    @Deprecated
     public static AbstractEventHandler eventHandler(ReadGraph graph, final Function fn) {
-       
+
         return new AbstractEventHandler() {
-            
+
                        @Override
                        public CommandResult handle(final CommandContext parameters) {
-                               
+
                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
-                
+
                 try {
 
                        String result = "";
-                       
+
                                SCLContext sclContext = SCLContext.getCurrent();
                                Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
                                try {
@@ -876,21 +995,19 @@ public class Functions {
                                    if(response instanceof String) {
                                        result = (String)response;
                                    }
-                               } catch (Throwable t) {
-                                   t.printStackTrace();
                                } finally {
                                        sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
                                }
-                                       
+
                        return new SuccessResponse(result);
-                                       
+
                                } catch (Throwable e) {
                                        Logger.defaultLogError(e);
                                        return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
                                }
-                
+
                        }
-            
+
         };
     }
 
@@ -950,18 +1067,18 @@ public class Functions {
 
         return null;
     }
-    
+
     public static CommandContextMutable putTuple(CommandContextMutable context, String key, Object tuple) {
        List<Object> list = new ArrayList<Object>();
        if (tuple instanceof Tuple) {
                Collections.addAll(list, ((Tuple)tuple).toArray());
        } else {
-               list.add(tuple);                
+               list.add(tuple);
        }
        context.putRow(key, list);
        return context;
     }
-    
+
     public static List<Object> getTuples(CommandContext context, String key) {
        List<List<Object>> rows = context.getRows(key);
        List<Object> tuples = new ArrayList<Object>();
@@ -979,11 +1096,11 @@ public class Functions {
        }
        return tuples;
     }
-    
+
     public static String printContext(CommandContext context) {
        return context.toString();
     }
-    
+
     @SCLValue(type = "AbstractEventHandler")
     public static AbstractEventHandler emptyEvent = new AbstractEventHandler() {
 
@@ -995,75 +1112,75 @@ public class Functions {
     };
 
     public static String sclStateKey(ReadGraph graph, Variable base, Variable self, String ref) throws DatabaseException {
-       
+
        String baseURI = base.getURI(graph);
-       
+
        String selfURI = self.getURI(graph);
-       
+
        String prefix = selfURI.substring(0, selfURI.indexOf(ProxyChildVariable.CONTEXT_BEGIN));
        String suffix = selfURI.substring(selfURI.lastIndexOf(ProxyChildVariable.CONTEXT_END) + ProxyChildVariable.CONTEXT_END.length());
        String stripped = prefix + suffix;
-       
+
        String relative = Variables.getRelativeRVI(baseURI, stripped); 
-       
+
        return Variables.getRVI(relative, ref);
-       
+
     }
-    
+
     public static Variable sclStateVariable(ReadGraph graph, Variable base, Variable self, String ref) throws DatabaseException {
-       
+
        String id = sclStateKey(graph, base, self, ref);
 
        Variable sclVar = base.getPossibleChild(graph, "__scl__");
        if(sclVar == null) return null;
-       
+
        return sclVar.getPossibleProperty(graph, id);
-       
+
     }
-    
+
     public static Object sclStateValueOrDefault(ReadGraph graph, Variable base, Variable self, String ref, Object defaultValue) throws DatabaseException {
-       
+
        Variable stateVariable = sclStateVariable(graph, base, self, ref);
        if (stateVariable != null) {
-               
+
                return stateVariable.getValue(graph);
-               
+
        } else {
-               
+
                String id = sclStateKey(graph, base, self, ref);
 
                SCLRealm realm = SCLSessionManager.getOrCreateSCLRealm(base.getURI(graph) + "/__scl__");
                realm.getConnection().setVariable(id, getSCLType(defaultValue), defaultValue);
-               
+
                return defaultValue;
-               
+
        }
     }
-    
+
     public static void setSclStateValue(WriteGraph graph, Variable base, Variable self, String ref, Object value) throws DatabaseException {
-       
+
        String id = sclStateKey(graph, base, self, ref);
 
        SCLRealm realm = SCLSessionManager.getOrCreateSCLRealm(base.getURI(graph)+"/__scl__");
        realm.getConnection().setVariable(id, getSCLType(value), value);
        realm.refreshVariablesSync();
-               
+
     }
-    
+
     public static Object projectComponentState(ReadGraph graph, Variable self, String ref, Object defaultValue) throws DatabaseException {
        Resource project = Simantics.getProjectResource();
        Variable component = self.getParent(graph);
        Variable projectVariable = Variables.getVariable(graph, project);
        return sclStateValueOrDefault(graph, projectVariable, component, ref, defaultValue);
     }
-    
+
     public static void setProjectComponentState(WriteGraph graph, Variable self, String ref, Object value) throws DatabaseException {
        Resource project = Simantics.getProjectResource();
        Variable component = self.getParent(graph);
        Variable projectVariable = Variables.getVariable(graph, project);
        setSclStateValue(graph, projectVariable, component, ref, value);
     }
-    
+
     private static Type getSCLType(Object value) throws DatabaseException {
        Binding b = Bindings.getBindingUnchecked(value.getClass());
        Datatype t = b.type();
@@ -1084,7 +1201,7 @@ public class Functions {
     public static String documentModelContributionLabel(ReadGraph graph, Variable var) throws DatabaseException {
        return var.getName(graph);
     }
-    
+
     public static Object getPropertyValueCached(ReadGraph graph, Variable variable, String name, Binding binding) throws DatabaseException {
        Variable property = graph.syncRequest(new VariableProperty(variable, name));
        return graph.syncRequest(new VariableValueWithBinding<Object>(property, binding));
@@ -1108,7 +1225,7 @@ public class Functions {
                return graph.syncRequest(new ParentExistsRequest(variable.getParent(graph)));
 
                }
-       
+
     } 
 
     public static class PathExistsRequest extends VariableRead<Boolean> {
@@ -1119,20 +1236,20 @@ public class Functions {
 
                @Override
                public Boolean perform(ReadGraph graph) throws DatabaseException {
-                       
+
                        Variable widget = variable.getParent(graph);
-               
+
                Boolean exists = widget.getPossiblePropertyValue(graph, "exists");
                        if (exists == null || !exists) return false;
-               
+
                if (!graph.syncRequest(new ParentExistsRequest(widget.getParent(graph)))) return false;
-               
+
                DocumentationResource DOC = DocumentationResource.getInstance(graph);
-               Collection <Variable> cps = widget.getProperties(graph, DOC.Relations_parentRelation);
+               Collection <Variable> cps = widget.getProperties(graph, DocumentationResource.URIs.Relations_parentRelation);
                for (Variable cp : cps) {
-                       
+
                        Connection conn = cp.getValue(graph);
-                               Variable otherCp = DocumentServerUtils.getPossibleOtherConnectionPoint(graph, cp, conn);
+                               Variable otherCp = DocumentServerUtils.getPossibleChildConnectionPoint(graph, cp, conn);
                                if (otherCp != null) {
                                        Variable parentWidget = otherCp.getParent(graph);
                                        if (parentWidget.<Boolean>getPropertyValue(graph, "pathExists")) {
@@ -1161,47 +1278,39 @@ public class Functions {
                                        }
                                }
                        }
-               
+
                        Resource type = widget.getType(graph);
                        return graph.isInheritedFrom(type, DOC.Components_ParentlessComponent) ||
                                (graph.isInheritedFrom(type, DOC.DocumentComponent) && cps.isEmpty());
                }
-    } 
-    
+    }
+
     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Boolean")
     public static boolean pathExists(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
        return graph.syncRequest(new PathExistsRequest(context));
     }
-    
-       static class ConsoleSCLReportingHandler implements SCLReportingHandler {
-
-               private final IConsole console;
 
-               ConsoleSCLReportingHandler(IConsole console) {
-                       this.console = console;
-               }
-
-               @Override
-               public void print(String text) {
-                       console.addMessage(text);
-               }
-
-               @Override
-               public void printError(String error) {
-                       console.addMessage(error);
-               }
-
-               @Override
-               public void printCommand(String command) {
-                       console.addMessage(command);
-               }
-
-               @Override
-               public void didWork(double amount) {
-                       console.addMessage("didWork " + amount);
-               }
-
-       }
-    
+    public static String compileDocumentSCLValueExpression(ReadGraph graph, Variable context) {
+        try {
+            ServerSCLValueRequest.validate(graph, context);
+            return "";
+        } catch (Exception e) {
+            return resolveIssueMessage(e);
+        }
+    }
     
+    private static String resolveIssueMessage(Exception e) {
+        if (e instanceof ImportFailureException)
+            return "";
+        if (e.getCause() != null && e.getCause() instanceof ImportFailureException)
+            return "";
+        if (e instanceof SCLDatabaseException) {
+            SCLDatabaseException ee = (SCLDatabaseException) e;
+            return ee.getMessage();
+        }
+        if (LOGGER.isDebugEnabled())
+            LOGGER.debug("", e);
+        return e.getMessage();
+    }
+
 }
\ No newline at end of file