Let the request processor handle the exceptions
[simantics/platform.git] / bundles / org.simantics.document.server / src / org / simantics / document / server / Functions.java
1 package org.simantics.document.server;
2
3 import java.io.PrintWriter;
4 import java.io.StringWriter;
5 import java.util.ArrayList;
6 import java.util.Collection;
7 import java.util.Collections;
8 import java.util.HashMap;
9 import java.util.List;
10 import java.util.Map;
11 import java.util.TreeMap;
12
13 import org.simantics.Simantics;
14 import org.simantics.databoard.Bindings;
15 import org.simantics.databoard.Datatypes;
16 import org.simantics.databoard.binding.Binding;
17 import org.simantics.databoard.type.Datatype;
18 import org.simantics.db.AsyncReadGraph;
19 import org.simantics.db.DirectStatements;
20 import org.simantics.db.ReadGraph;
21 import org.simantics.db.RequestProcessor;
22 import org.simantics.db.Resource;
23 import org.simantics.db.Session;
24 import org.simantics.db.Statement;
25 import org.simantics.db.WriteGraph;
26 import org.simantics.db.common.primitiverequest.Adapter;
27 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
28 import org.simantics.db.common.request.UnaryRead;
29 import org.simantics.db.common.request.UniqueRead;
30 import org.simantics.db.common.request.WriteResultRequest;
31 import org.simantics.db.common.utils.Logger;
32 import org.simantics.db.common.utils.NameUtils;
33 import org.simantics.db.exception.DatabaseException;
34 import org.simantics.db.layer0.function.All;
35 import org.simantics.db.layer0.request.ProjectModels;
36 import org.simantics.db.layer0.request.PropertyInfo;
37 import org.simantics.db.layer0.request.PropertyInfoRequest;
38 import org.simantics.db.layer0.request.VariableProperty;
39 import org.simantics.db.layer0.request.VariableRead;
40 import org.simantics.db.layer0.request.VariableValueWithBinding;
41 import org.simantics.db.layer0.scl.SCLDatabaseException;
42 import org.simantics.db.layer0.variable.ConstantPropertyVariable;
43 import org.simantics.db.layer0.variable.ProxyChildVariable;
44 import org.simantics.db.layer0.variable.ProxySessionRequest;
45 import org.simantics.db.layer0.variable.ProxyVariables;
46 import org.simantics.db.layer0.variable.StandardAssertedGraphPropertyVariable;
47 import org.simantics.db.layer0.variable.StandardGraphChildVariable;
48 import org.simantics.db.layer0.variable.StandardGraphPropertyVariable;
49 import org.simantics.db.layer0.variable.Variable;
50 import org.simantics.db.layer0.variable.VariableMap;
51 import org.simantics.db.layer0.variable.VariableMapImpl;
52 import org.simantics.db.layer0.variable.Variables;
53 import org.simantics.db.procedure.AsyncProcedure;
54 import org.simantics.db.service.DirectQuerySupport;
55 import org.simantics.document.base.ontology.DocumentationResource;
56 import org.simantics.document.server.bean.Command;
57 import org.simantics.document.server.bean.DataDefinition;
58 import org.simantics.document.server.handler.AbstractEventHandler;
59 import org.simantics.document.server.handler.AbstractResponseHandler;
60 import org.simantics.document.server.handler.EventHandler;
61 import org.simantics.document.server.io.CommandContext;
62 import org.simantics.document.server.io.CommandContextImpl;
63 import org.simantics.document.server.io.CommandContextMutable;
64 import org.simantics.document.server.io.CommandResult;
65 import org.simantics.document.server.io.IConsole;
66 import org.simantics.document.server.request.NodeRequest;
67 import org.simantics.document.server.request.ServerSCLHandlerValueRequest;
68 import org.simantics.document.server.request.ServerSCLValueRequest;
69 import org.simantics.document.server.serverResponse.ServerResponse;
70 import org.simantics.document.server.serverResponse.SuccessResponse;
71 import org.simantics.modeling.ModelingResources;
72 import org.simantics.modeling.scl.SCLRealm;
73 import org.simantics.modeling.scl.SCLSessionManager;
74 import org.simantics.modeling.services.CaseInsensitiveComponentFunctionNamingStrategy;
75 import org.simantics.modeling.services.ComponentNamingStrategy;
76 import org.simantics.operation.Layer0X;
77 import org.simantics.project.IProject;
78 import org.simantics.scl.compiler.module.repository.ImportFailureException;
79 import org.simantics.scl.compiler.types.TCon;
80 import org.simantics.scl.compiler.types.Type;
81 import org.simantics.scl.compiler.types.Types;
82 import org.simantics.scl.reflection.annotations.SCLValue;
83 import org.simantics.scl.runtime.SCLContext;
84 import org.simantics.scl.runtime.function.Function;
85 import org.simantics.scl.runtime.function.Function1;
86 import org.simantics.scl.runtime.function.FunctionImpl1;
87 import org.simantics.scl.runtime.function.FunctionImpl4;
88 import org.simantics.scl.runtime.reporting.SCLReportingHandler;
89 import org.simantics.scl.runtime.tuple.Tuple;
90 import org.simantics.scl.runtime.tuple.Tuple0;
91 import org.simantics.scl.runtime.tuple.Tuple2;
92 import org.simantics.scl.runtime.tuple.Tuple3;
93 import org.simantics.scl.runtime.tuple.Tuple4;
94 import org.simantics.scl.runtime.tuple.Tuple5;
95 import org.simantics.simulation.experiment.IExperiment;
96 import org.simantics.simulation.ontology.SimulationResource;
97 import org.simantics.simulation.project.IExperimentManager;
98 import org.simantics.structural2.variables.Connection;
99 import org.simantics.structural2.variables.StandardProceduralChildVariable;
100 import org.simantics.structural2.variables.VariableConnectionPointDescriptor;
101 import org.slf4j.LoggerFactory;
102
103 import gnu.trove.map.hash.THashMap;
104
105 public class Functions {
106
107     private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Functions.class);
108     
109     private static class PrimitivePropertyStatementsProcedure implements AsyncProcedure<DirectStatements> {
110
111         public DirectStatements result;
112
113         @Override
114         public void execute(AsyncReadGraph graph, DirectStatements result) {
115             this.result = result;
116         }
117
118         @Override
119         public void exception(AsyncReadGraph graph, Throwable throwable) {
120         }
121
122     }
123
124     @SCLValue(type = "VariableMap")
125     public static VariableMap primitiveProperties = new VariableMapImpl() {
126         private void storePropertyValueAndExceptions(ReadGraph graph, Variable parent, String name, Variable property, Map<String, Variable> map) {
127                 try {
128                         Object value = property.getValue(graph);
129                                 map.put(name, new ConstantPropertyVariable(parent, name, value, null));
130                 } catch (DatabaseException e) {
131                         Variable propertyExceptions = map.get(NodeRequest.PROPERTY_VALUE_EXCEPTIONS);
132                         Map<String, Exception> exceptionMap;
133                         if (propertyExceptions == null) {
134                                 exceptionMap = new TreeMap<String, Exception>();
135                                 propertyExceptions = new ConstantPropertyVariable(parent, NodeRequest.PROPERTY_VALUE_EXCEPTIONS, exceptionMap, null);
136                                 map.put(NodeRequest.PROPERTY_VALUE_EXCEPTIONS, propertyExceptions);
137                         } else {
138                                 try {
139                                                 exceptionMap = propertyExceptions.getValue(graph);
140                                         } catch (DatabaseException e1) {
141                                                 Logger.defaultLogError(e1);
142                                                 return;
143                                         }
144                         }
145                         String label = name;
146                         try {
147                                 label = property.getLabel(graph);
148                         } catch (DatabaseException e2) {
149
150                         }
151                         exceptionMap.put(label, e);
152                 }
153         }
154         
155         @Override
156         public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
157             return All.getStandardPropertyDomainPropertyVariableFromValue(graph, context, name);
158         }
159
160         @Override
161         public Map<String, Variable> getVariables(final ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
162
163             if(map == null) map = new HashMap<String,Variable>();
164
165             Variable parent = context.getParent(graph);
166
167             DocumentationResource DOC = DocumentationResource.getInstance(graph);
168
169             if(parent instanceof StandardProceduralChildVariable) {
170
171                 StandardProceduralChildVariable procedural = (StandardProceduralChildVariable)parent;
172                 for(Variable property : procedural.getProperties(graph/*, DocumentationResource.URIs.Document_AttributeRelation*/)) {
173                     if(property instanceof StandardAssertedGraphPropertyVariable) {
174                         StandardAssertedGraphPropertyVariable ass = (StandardAssertedGraphPropertyVariable)property;
175                         if("dataDefinitions".equals(ass.property.name) || "commands".equals(ass.property.name)  || "pollingFunction".equals(ass.property.name)) {
176                                 storePropertyValueAndExceptions(graph, parent, ass.property.name, property, map);
177                         }
178                         continue;
179                     }
180                     Resource predicate = property.getPossiblePredicateResource(graph);
181                     if(predicate != null) {
182                         PropertyInfo info = graph.syncRequest(new PropertyInfoRequest(predicate));
183                         if(info.hasClassification(DocumentationResource.URIs.Document_AttributeRelation)) {
184                                 Variable prop = parent.getProperty(graph, predicate);
185                             storePropertyValueAndExceptions(graph, parent, info.name, prop, map);
186                         }
187                     }
188                 }
189
190             } else {
191
192                 Resource parentRes = parent.getRepresents(graph);
193                 {
194                         Variable prop = new StandardGraphPropertyVariable(graph, parent, DOC.Properties_commands);
195                         storePropertyValueAndExceptions(graph, parent, "commands", prop, map);
196                 }
197
198                 if (graph.getPossibleObject(parentRes, DOC.Properties_dataDefinitions) != null) {
199                         Variable prop = new StandardGraphPropertyVariable(graph, parent, DOC.Properties_dataDefinitions);
200                         storePropertyValueAndExceptions(graph, parent, "dataDefinitions", prop, map);
201                 }
202                 
203                 DirectQuerySupport dqs = graph.getService(DirectQuerySupport.class);
204                 PrimitivePropertyStatementsProcedure foo = new PrimitivePropertyStatementsProcedure();
205
206                 dqs.forEachDirectPersistentStatement(graph, parentRes, foo);
207
208                 for(Statement stm : foo.result) {
209                     Resource predicate = stm.getPredicate();
210                     PropertyInfo info = graph.syncRequest(new PropertyInfoRequest(predicate));
211
212                     if(info.isHasProperty && info.hasClassification(DocumentationResource.URIs.Document_AttributeRelation)) {
213                         Variable prop = new StandardGraphPropertyVariable(graph, parent, predicate);
214                         storePropertyValueAndExceptions(graph, parent, info.name, prop, map);
215                     } else {
216                         Resource definition = graph.getPossibleObject(predicate, DOC.Document_definesAttributeRelation);
217                         if(definition != null) {
218                                 PropertyInfo info2 = graph.syncRequest(new PropertyInfoRequest(definition));
219                                 Variable prop = new StandardGraphPropertyVariable(graph, parent, definition);
220                             map.put(info2.name, new PrimitiveValueVariable(parent, info2.name, prop));
221                         }
222                     }
223                 }
224             }
225             return map;
226
227         }
228
229     };
230
231     @SCLValue(type = "VariableMap")
232     public static VariableMap inputSpaceChildren = new VariableMapImpl() {
233
234         private Variable getProxy(ReadGraph graph, Variable context) throws DatabaseException {
235             Variable root = Variables.getRootVariable(graph);
236             return new DocumentProxyChildVariable(context, context, root, ProxyChildVariable.CONTEXT_BEGIN);
237         }
238
239         @Override
240         public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
241
242             if(ProxyChildVariable.CONTEXT_BEGIN.equals(name)) return getProxy(graph, context);
243             return All.standardChildDomainChildren.getVariable(graph, context, name);
244
245         }
246
247         @Override
248         public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
249
250             map = All.standardChildDomainChildren.getVariables(graph, context, map);
251             if(map == null) map = new THashMap<String,Variable>();
252             map.put(ProxyChildVariable.CONTEXT_BEGIN, getProxy(graph, context));
253             return map;
254
255         }
256
257     };
258
259     static class DocumentProxyChildVariable extends ProxyChildVariable {
260
261         public DocumentProxyChildVariable(Variable base, Variable parent, Variable other, String name) {
262             super(base, parent, other, name);
263         }
264
265         @Override
266         public Variable create(Variable base, Variable parent, Variable other, String name) {
267             return new DocumentProxyChildVariable(base, parent, other, name);
268         }
269
270         public Variable getPossibleChild(ReadGraph graph, String name) throws DatabaseException {
271
272                 if(CONTEXT_END.equals(name)) {
273                 if(other instanceof ProxyChildVariable) {
274                         // The context is also a proxy - let it do the job
275                     return super.getPossibleChild(graph, name);
276                 } else {
277                         return new RootVariable(this, base.getRepresents(graph));
278                 }
279                 }
280
281             return super.getPossibleChild(graph, name);
282
283         }
284
285         public Collection<Variable> getChildren(ReadGraph graph) throws DatabaseException {
286
287             Collection<Variable> result = super.getChildren(graph);
288             if(!(base instanceof ProxyChildVariable)) {
289                 result.add(new RootVariable(this, base.getRepresents(graph)));
290             }
291             return result;
292
293         }
294
295     }
296
297     static class RootVariable extends StandardGraphChildVariable {
298
299         public RootVariable(DocumentProxyChildVariable parent, Resource resource) {
300             super(parent, null, resource);
301         }
302
303         @Override
304         public String getName(ReadGraph graph) throws DatabaseException {
305             return ProxyChildVariable.CONTEXT_END;
306         }
307
308         @SuppressWarnings("deprecation")
309         @Override
310         public Variable getNameVariable(ReadGraph graph) throws DatabaseException {
311             return new ConstantPropertyVariable(this, Variables.NAME, ProxyChildVariable.CONTEXT_END, Bindings.STRING);
312         }
313
314     }
315
316     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
317     public static Variable input(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
318         Variable session = graph.syncRequest(new ProxySessionRequest(context));
319         DocumentationResource DOC = DocumentationResource.getInstance(graph);
320         String uri = session.getPossiblePropertyValue(graph, DOC.Session_inputURI);
321         if(uri == null) {
322                 // TODO HAXX - Please fix this
323                 // we have no URI so this probably means that someone has inserted a non-session 
324                 // into the proxy variable => return that instead
325                 return session;
326         }
327         return Variables.getVariable(graph, uri);
328     }
329
330     public static Variable stateVariable(ReadGraph graph, Variable self) throws DatabaseException {
331         Variable session = graph.syncRequest(new ProxySessionRequest(self));
332         if (session == null)
333                 throw new DatabaseException("No state for " + self.getURI(graph));
334         return session.getPossibleChild(graph, "__scl__");
335     }
336
337     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
338     public static Variable state(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
339         Variable session = graph.syncRequest(new ProxySessionRequest(context));
340         if (session == null)
341             throw new DatabaseException("No state for " + context.getURI(graph));
342         return session.getPossibleChild(graph, "__scl__");
343     }
344
345     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
346     public static Variable icstate(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
347         Variable session = graph.syncRequest(new ProxySessionRequest(context));
348         return session.getPossibleChild(graph, "__icstate__");
349     }
350
351     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
352     public static Variable session(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
353         return graph.syncRequest(new ProxySessionRequest(context));
354     }
355
356     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
357     public static Variable experiment(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
358         // Try if experiment (run) has been used as the input
359         Variable var = input(graph, converter, context);
360         SimulationResource SR = SimulationResource.getInstance(graph);
361         while(var != null && !graph.isInstanceOf(var.getRepresents(graph), SR.Run)) {
362             var = var.getParent(graph);
363         }
364
365         if(var != null) {
366             IExperiment exp = getExperiment(graph, var);
367             if(exp == null)
368                 return null;
369         }
370
371         return var;
372     }
373
374     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
375     public static Variable model(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
376         Variable var = input(graph, converter, context);
377         ModelingResources MOD = ModelingResources.getInstance(graph);
378         while(var != null && !graph.isInstanceOf(var.getRepresents(graph), MOD.StructuralModel)) {
379             var = var.getParent(graph);
380         }
381
382         return var;
383     }
384
385     private static Collection<Variable> getBroadcasted(ReadGraph graph, Variable target) throws DatabaseException {
386
387         ArrayList<Variable> result = new ArrayList<Variable>();
388
389         DocumentationResource DOC = DocumentationResource.getInstance(graph);
390
391         Variable broadcasted = target.getPossibleProperty(graph, DOC.Relations_broadcasted);
392         if(broadcasted != null) result.add(broadcasted);
393
394         for(Variable child : DocumentServerUtils.getChildrenInOrdinalOrder(graph, target)) {
395                 result.addAll(getBroadcasted(graph, child));
396         }
397
398         return result;
399
400     }
401
402     private static List<Command> getCommands(ReadGraph graph, Collection<Variable> commandVariables, String trigger, CommandContext constants, boolean broadcast) throws DatabaseException {
403
404         if(commandVariables.isEmpty()) return Collections.emptyList();
405
406         String t = trigger;
407         TreeMap<Integer, List<Command>> sequences = new TreeMap<Integer, List<Command>>();
408
409         DocumentationResource DOC = DocumentationResource.getInstance(graph);
410
411         int count = 0;
412         for (Variable c : commandVariables) {
413
414             if(trigger == null)
415                 t = c.getName(graph);
416
417             Connection conn = c.getValue(graph);
418             Variable targetConnectionPoint = DocumentServerUtils.getPossibleCommandTriggerConnectionPoint(graph, c, conn);
419             if (targetConnectionPoint != null) {
420                 Variable target = targetConnectionPoint.getParent(graph);
421                 if (target != null) {
422
423                     Boolean enabled = target.getPossiblePropertyValue(graph, DOC.Properties_exists, Bindings.BOOLEAN);
424                     if(enabled != null && !enabled) continue;
425
426                     Integer ordinal;
427                     if (broadcast) {
428                         ordinal = ++count;
429                     } else {
430                         ordinal = 1;
431                             try {
432                                 String o = c.getPossiblePropertyValue(graph, "ordinal");
433                                 if(o != null)
434                                     ordinal = Integer.parseInt(o);
435                             } catch (NumberFormatException e) {}
436                     }
437
438                     String constantKey = target.getPossiblePropertyValue(graph, "constantKey");
439                     String constantValue = target.getPossiblePropertyValue(graph, "constantValue");
440
441                     CommandContextMutable newConstants = (CommandContextMutable)constants; 
442                     if(constantKey != null && constantValue != null) {
443                         if(!constantKey.isEmpty()) {
444                                 newConstants = new CommandContextImpl().merge(constants);
445                                 newConstants.putString(constantKey, constantValue);
446                         }
447                     }
448
449                     String requiredKey = target.getPossiblePropertyValue(graph, "requiredKey");
450                     if(requiredKey != null && !requiredKey.isEmpty()) {
451                         if (newConstants == constants) {
452                                 newConstants = new CommandContextImpl().merge(constants);
453                         }
454                                 newConstants.putRow(CommandContext.REQUIRED_KEYS, Collections.<Object>singletonList(requiredKey));
455                     }
456
457                     String forbiddenKey = target.getPossiblePropertyValue(graph, "forbiddenKey");
458                     if(forbiddenKey != null && !forbiddenKey.isEmpty()) {
459                         if (newConstants == constants) {
460                                 newConstants = new CommandContextImpl().merge(constants);
461                         }
462                                 newConstants.putRow(CommandContext.FORBIDDEN_KEYS, Collections.<Object>singletonList(forbiddenKey));
463                     }
464
465                     if(DOC.Relations_broadcast.equals(targetConnectionPoint.getPredicateResource(graph))) {
466
467                         // This is a broadcast terminal of a container
468                         List<Command> broadcastCommands = getCommands(graph, getBroadcasted(graph, target), t, newConstants, true);
469                         sequences.put(ordinal, broadcastCommands);
470
471                     } else {
472
473                         Command command = new Command(DocumentServerUtils.getId(graph, target), t, 
474                                         targetConnectionPoint.getName(graph), newConstants);
475                         sequences.put(ordinal, Collections.singletonList(command));
476
477                     }
478
479                 }
480             }
481         }
482
483         List<Command> commands = new ArrayList<Command>();
484         for (List<Command> commandList : sequences.values()) {
485                 for (Command command : commandList) {
486                         commands.add(command);
487                 }
488         }
489
490         return commands;
491     }
492
493     /**
494      * Commands
495      * 
496      * @param graph
497      * @param variable
498      * @return
499      * @throws DatabaseException
500      */
501     public static List<Command> commandList(ReadGraph graph, Variable variable) throws DatabaseException {
502         return getCommands(graph, DocumentServerUtils.getTriggerCommands(graph, variable.getParent(graph)), null, new CommandContextImpl(), false);
503     }
504
505     /**
506      * Data definitions
507      * 
508      * @param graph
509      * @param variable
510      * @return
511      * @throws DatabaseException
512      */
513     public static List<DataDefinition> dataDefinitions(ReadGraph graph, Variable variable) throws DatabaseException {
514         DocumentationResource DOC = DocumentationResource.getInstance(graph); 
515         ArrayList<DataDefinition> dataDefinitions = new ArrayList<DataDefinition>();
516         // Find data definition connections
517         for (Variable dataDefinitionRelation : DocumentServerUtils.getDataDefinitions(graph, variable.getParent(graph))) {
518             Connection dataDefinitionConnection = dataDefinitionRelation.getValue(graph);
519             // Find data the other end of definition connection
520             Collection<Variable> dataDefinitionProviders = DocumentServerUtils.getPossibleOtherConnectionPoints(graph,
521                     dataDefinitionRelation, dataDefinitionConnection);
522             if (dataDefinitionProviders != null) {
523
524                 for(Variable dataDefinitionProvider : dataDefinitionProviders) {
525
526                     Variable dataDefinition = dataDefinitionProvider.getParent(graph);
527                     if (dataDefinition != null) {
528                         // Found other end. Is should contain ONE data
529 // definition connection to the actual data
530                         Collection<Variable> dataCollection = DocumentServerUtils.getDataRelations(graph, dataDefinition);
531                         if (dataCollection.size() == 1) {
532                             Variable dataRelation = dataCollection.iterator().next();
533                             Connection dataConnection = dataRelation.getValue(graph);
534                             // Find data the other end of definition connection
535                             Variable dataConnectionPoint = DocumentServerUtils.getPossibleOtherConnectionPoint(graph,
536                                     dataRelation, dataConnection);
537                             if (dataConnectionPoint != null) {
538                                 Variable data = dataConnectionPoint.getParent(graph);
539                                 Resource type = dataDefinition.getPossibleType(graph, DOC.Components_Component);
540
541                                 if (graph.isInheritedFrom(type, DOC.Components_DefVar)) {
542
543                                         String sourceProperty = dataDefinition.getPropertyValue(graph, DOC.Properties_source,
544                                                 Bindings.STRING);
545                                         String targetProperty = dataDefinition.getPropertyValue(graph, DOC.Properties_target,
546                                                 Bindings.STRING);
547
548                                         dataDefinitions.add(new DataDefinition(DocumentServerUtils.getId(graph, data),
549                                                         sourceProperty, targetProperty));
550
551                                 } else if (graph.isInheritedFrom(type, DOC.Components_DefVars)) {
552
553                                         List<String> sourcesProperty = toList(dataDefinition.getPropertyValue(graph, DOC.Properties_sources), String.class);
554                                         List<String> targetsProperty = toList(dataDefinition.getPropertyValue(graph, DOC.Properties_targets), String.class);
555
556                                         for (int i = 0; i < Math.min(sourcesProperty.size(), targetsProperty.size()); i++) {
557                                                 dataDefinitions.add(new DataDefinition(DocumentServerUtils.getId(graph, data),
558                                                         sourcesProperty.get(i), targetsProperty.get(i)));
559                                         }
560                                 }
561                             }
562                         }
563                     }
564                 }
565             }
566         }
567         return dataDefinitions;
568     }
569
570     @SuppressWarnings("unchecked")
571         private static <T> List<T> toList(Object o, Class<T> c) {
572         List<T> result = null;
573         if (o instanceof List) {
574                 return (List<T>)o;
575         } else if (o instanceof Object[]) {
576                 result = new ArrayList<T>(((Object[])o).length);
577                 for (T item : (T[])o) {
578                         result.add(item);
579                 }
580                 return result;
581         } else {
582                 return Collections.<T>emptyList();
583         }
584     }
585
586     @Deprecated
587     public static AbstractEventHandler emptyOnClick(ReadGraph graph) throws DatabaseException {
588         return new EventHandler() {
589             @Override
590             public ServerResponse handle(ReadGraph graph, CommandContext parameters) throws DatabaseException {
591                 return null;
592             }
593         };
594     }
595
596     @Deprecated
597     public static AbstractEventHandler writeEventHandler(ReadGraph graph, final Variable variable, final Function fn) {
598
599         final Session session = graph.getSession();
600
601         return new AbstractEventHandler() {
602
603                         @Override
604                         public CommandResult handle(final CommandContext parameters) {
605
606                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
607
608                 try {
609
610                                         String result = session.sync(new WriteResultRequest<String>() {
611
612                                             @Override
613                                             public String perform(WriteGraph graph) throws DatabaseException {
614                                                 SCLContext sclContext = SCLContext.getCurrent();
615                                                 Object oldGraph = sclContext.put("graph", graph);
616                                                 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
617                                                 try {
618                                                     Function1<String,String> pf = new FunctionImpl1<String,String>() {
619                                                         @Override
620                                                         public String apply(String key) {
621                                                             return parameters.getString(key);
622                                                         }
623                                                     }; 
624                                                     Object response = (String)fn.apply(variable, pf);
625                                                     if(response instanceof String) {
626                                                         return (String)response;
627                                                     }
628                                                     return null;
629                                                 } finally {
630                                                         sclContext.put("graph", oldGraph);
631                                                         sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
632                                                 }
633
634                                             }
635
636                                         });
637
638                         return new SuccessResponse(result);
639
640                                 } catch (Throwable e) {
641                                         Logger.defaultLogError(e);
642                                         return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
643                                 }
644
645                         }
646
647         };
648     }
649
650     @Deprecated
651     public static AbstractEventHandler readEventHandler(ReadGraph graph, final Variable variable, final Function fn) {
652
653         final Session session = graph.getSession();
654
655         return new AbstractEventHandler() {
656
657                         @Override
658                         public CommandResult handle(final CommandContext parameters) {
659
660                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
661
662                 try {
663
664                                         String result = session.sync(new UniqueRead<String>() {
665
666                                             @Override
667                                             public String perform(ReadGraph graph) throws DatabaseException {
668                                                 SCLContext sclContext = SCLContext.getCurrent();
669                                                 Object oldGraph = sclContext.put("graph", graph);
670                                                 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
671                                                 try {
672                                                     Function1<String,String> pf = new FunctionImpl1<String,String>() {
673                                                         @Override
674                                                         public String apply(String key) {
675                                                             return parameters.getString(key);
676                                                         }
677                                                     }; 
678                                                     Object response = (String)fn.apply(variable, pf);
679                                                     if(response instanceof String) {
680                                                         return (String)response;
681                                                     }
682                                                     return null;
683                                                 } finally {
684                                                         sclContext.put("graph", oldGraph);
685                                                         sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
686                                                 }
687
688                                             }
689
690                                         });
691
692                         return new SuccessResponse(result);
693
694                                 } catch (Throwable e) {
695                                         Logger.defaultLogError(e);
696                                         return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
697                                 }
698
699                         }
700
701         };
702     }
703
704     @Deprecated
705     public static AbstractEventHandler readEventHandler2(ReadGraph graph, final Function fn) {
706
707         final Session session = graph.getSession();
708
709         return new AbstractEventHandler() {
710
711                         @Override
712                         public CommandResult handle(final CommandContext parameters) {
713
714                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
715
716                 try {
717
718                         CommandResult result = session.sync(new UniqueRead<CommandResult>() {
719
720                                             @Override
721                                             public CommandResult perform(ReadGraph graph) throws DatabaseException {
722                                                 SCLContext sclContext = SCLContext.getCurrent();
723                                                 Object oldGraph = sclContext.put("graph", graph);
724                                                 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
725                                                 try {
726                                                     Object response = fn.apply(parameters);
727                                                     if(response instanceof CommandResult) {
728                                                         return (CommandResult)response;
729                                                     }
730                                                     return null;
731                                                 } finally {
732                                                         sclContext.put("graph", oldGraph);
733                                                         sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
734                                                 }
735
736                                             }
737
738                                         });
739
740                         return result;
741
742                                 } catch (Throwable e) {
743                                         Logger.defaultLogError(e);
744                                         return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
745                                 }
746
747                         }
748
749         };
750     }
751
752     public static AbstractEventHandler responseHandler(ReadGraph graph, Variable self, String function) throws DatabaseException {
753
754         Variable anyFunction = self.browse(graph, ".#" + function);
755         if(anyFunction == null) return null;
756
757         final List<TCon> effects = ServerSCLHandlerValueRequest.getEffects(graph, anyFunction);
758
759         final Function1<CommandContext, CommandResult> fn = anyFunction.getValue(graph);
760         String expression = anyFunction.getPropertyValue(graph, "expression");
761
762         final Session session = graph.getSession();
763
764         return new AbstractResponseHandler(expression) {
765
766                 private String formatError(RequestProcessor proc, Throwable t) {
767
768                         try {
769
770                                         return proc.syncRequest(new UniqueRead<String>() {
771
772                                                 @Override
773                                                 public String perform(ReadGraph graph) throws DatabaseException {
774                                                         Variable proxy = ProxyVariables.proxyVariableRoot(graph, anyFunction);
775                                                         String uri2 = proxy.getURI(graph);
776                                                         String uri = self.getParent(graph).getURI(graph);
777
778                                                         String path = uri.substring(uri2.length());
779
780                                                         String expr = anyFunction.getPossiblePropertyValue(graph, "expression");
781                                                         StringBuilder message = new StringBuilder();
782                                                         message.append("Handler execution failed\n");
783                                                         message.append(" handler=" + path + "\n");
784                                                         message.append(" expression=" + expr + "\n");
785                                                         message.append(" message=" + t.getMessage() + "\n");
786
787                                                         StringWriter sw = new StringWriter();
788                                                         t.printStackTrace(new PrintWriter(sw));
789                                                         message.append(" stack trace=" + sw);
790
791                                                         return message.toString();
792                                                 }
793
794                                         });
795
796                                 } catch (DatabaseException e) {
797
798                                         return e.getMessage();
799
800                                 }
801
802                 }
803
804                         @Override
805                         public CommandResult handle(final CommandContext parameters) {
806
807                                 IConsole console = parameters.getValue("__console__");
808                                 SCLReportingHandler printer = (console != null) ? new ConsoleSCLReportingHandler(console)
809                                                 : (SCLReportingHandler) SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
810
811                 try {
812
813                         Object result = null;
814                         if(effects.contains(Types.WRITE_GRAPH)) {
815
816                                 result = session.syncRequest(new WriteResultRequest<Object>() {
817
818                                                         @Override
819                                                         public Object perform(WriteGraph graph)
820                                                                         throws DatabaseException {
821                                                 SCLContext sclContext = SCLContext.getCurrent();
822                                                 Object oldGraph = sclContext.put("graph", graph);
823                                                 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
824                                                 try {
825                                                         return fn.apply(parameters);
826                                                 } finally {
827                                                         sclContext.put("graph", oldGraph);
828                                                         sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
829                                                 }
830
831                                                         }
832                                 });
833
834                         } else if(effects.contains(Types.READ_GRAPH)) {
835
836                                 result = session.sync(new UniqueRead<Object>() {
837
838                                         @Override
839                                         public Object perform(ReadGraph graph) throws DatabaseException {
840
841                                                 SCLContext sclContext = SCLContext.getCurrent();
842                                                 Object oldGraph = sclContext.put("graph", graph);
843                                                 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
844
845                                                 try {
846                                                         return fn.apply(parameters);
847                                                 } finally {
848                                                         sclContext.put("graph", oldGraph);
849                                                         sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
850                                                 }
851
852                                         }
853                                 });
854
855                         } else {
856
857                                                 SCLContext sclContext = SCLContext.getCurrent();
858                                                 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
859                                                 try {
860                                                         result = fn.apply(parameters);
861                                                 } finally {
862                                                         sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
863                                                 }
864
865                         }
866
867                         if (result instanceof org.simantics.document.server.serverResponse.Error) {
868                                 return (CommandResult)result;
869                         }
870
871                         if (result instanceof CommandResult) {
872                                 return (CommandResult)result;
873                         } else {
874                                 CommandContextMutable assignments = new CommandContextImpl();
875                                 assignments.putValue("result", result);
876                                 return new ServerResponse(200, "", assignments);
877                         }
878
879                                 } catch (Throwable e) {
880                                         return new org.simantics.document.server.serverResponse.Error(formatError(Simantics.getSession(), e));
881                                 }
882
883                         }
884
885         };
886     }
887
888     @Deprecated
889     public static AbstractEventHandler writeEventHandler2(ReadGraph graph, final Function fn) {
890
891         final Session session = graph.getSession();
892
893         return new AbstractEventHandler() {
894
895                         @Override
896                         public CommandResult handle(final CommandContext parameters) {
897
898                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
899
900                 try {
901
902                         CommandResult result = session.syncRequest(new WriteResultRequest<CommandResult>() {
903
904                                             @Override
905                                             public CommandResult perform(WriteGraph graph) throws DatabaseException {
906                                                 SCLContext sclContext = SCLContext.getCurrent();
907                                                 Object oldGraph = sclContext.put("graph", graph);
908                                                 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
909                                                 try {
910                                                     Object response = fn.apply(parameters);
911                                                     if(response instanceof CommandResult) {
912                                                         return (CommandResult)response;
913                                                     }
914                                                     return null;
915                                                 } finally {
916                                                         sclContext.put("graph", oldGraph);
917                                                         sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
918                                                 }
919
920                                             }
921
922                                         });
923
924                         return result;
925
926                                 } catch (Throwable e) {
927                                         Logger.defaultLogError(e);
928                                         return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
929                                 }
930
931                         }
932
933         };
934     }
935
936
937     @Deprecated
938     public static AbstractEventHandler eventHandler2(ReadGraph graph, final Function fn) {
939
940         return new AbstractEventHandler() {
941
942                         @Override
943                         public CommandResult handle(final CommandContext parameters) {
944
945                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
946
947                 try {
948
949                         SCLContext sclContext = SCLContext.getCurrent();
950                         Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
951                         try {
952                                 Object response = fn.apply(parameters);
953                                 if(response instanceof CommandResult) {
954                                         return (CommandResult)response;
955                                 }
956                                 return null;
957                         } finally {
958                                 sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
959                         }
960
961                                 } catch (Throwable e) {
962                                         Logger.defaultLogError(e);
963                                         return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
964                                 }
965
966                         }
967
968         };
969     }
970
971     @Deprecated
972     public static AbstractEventHandler eventHandler(ReadGraph graph, final Function fn) {
973
974         return new AbstractEventHandler() {
975
976                         @Override
977                         public CommandResult handle(final CommandContext parameters) {
978
979                 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
980
981                 try {
982
983                         String result = "";
984
985                                 SCLContext sclContext = SCLContext.getCurrent();
986                                 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
987                                 try {
988                                     Function1<String,String> pf = new FunctionImpl1<String,String>() {
989                                         @Override
990                                         public String apply(String key) {
991                                             return parameters.getString(key);
992                                         }
993                                     }; 
994                                     Object response = (String)fn.apply(pf);
995                                     if(response instanceof String) {
996                                         result = (String)response;
997                                     }
998                                 } finally {
999                                         sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
1000                                 }
1001
1002                         return new SuccessResponse(result);
1003
1004                                 } catch (Throwable e) {
1005                                         Logger.defaultLogError(e);
1006                                         return new org.simantics.document.server.serverResponse.Error(e.getMessage()); 
1007                                 }
1008
1009                         }
1010
1011         };
1012     }
1013
1014     @SCLValue(type = "ReadGraph -> Resource -> Variable -> a")
1015     public static Object sclValue(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
1016         return ServerSCLValueRequest.compileAndEvaluate(graph, context);
1017     }
1018
1019     @SCLValue(type = "ReadGraph -> Resource -> Variable -> a")
1020     public static Object sclHandlerValue(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
1021         return ServerSCLHandlerValueRequest.compileAndEvaluate(graph, context);
1022     }
1023
1024     @SCLValue(type = "ReadGraph -> Resource -> Resource -> ComponentNamingStrategy")
1025     public static ComponentNamingStrategy componentNamingStrategy(ReadGraph graph, Resource converter, Resource context) throws DatabaseException {
1026         return createComponentNamingStrategy(graph);
1027     }
1028
1029     public static CaseInsensitiveComponentFunctionNamingStrategy createComponentNamingStrategy(ReadGraph graph) throws DatabaseException {
1030         Layer0X L0X = Layer0X.getInstance(graph);
1031         @SuppressWarnings({ "unchecked", "rawtypes" })
1032         final Function dependencies = graph.syncRequest(new Adapter(L0X.DependencyResources, Function.class), TransientCacheListener.<Function>instance());
1033         @SuppressWarnings("rawtypes")
1034         Function moduleNameFunction = new FunctionImpl4<ReadGraph, Resource, String, Integer, List<Map<String, Object>>>() {
1035             @Override
1036             public Object apply(ReadGraph p0, Resource p1, String p2) {
1037                 return apply(p0, p1, p2);
1038             }
1039             @SuppressWarnings("unchecked")
1040             @Override
1041             public List<Map<String, Object>> apply(ReadGraph graph, Resource model, String search, Integer maxResults) {
1042                 return (List<Map<String, Object>>)dependencies.apply(graph, model, search, maxResults);
1043             }
1044         };
1045         return new CaseInsensitiveComponentFunctionNamingStrategy("%s%02d", moduleNameFunction);
1046     }
1047
1048     public static IExperiment getExperiment(ReadGraph graph, Variable variable) throws DatabaseException {
1049         if (variable == null)
1050             return null;
1051
1052         SimulationResource SIMU = SimulationResource.getInstance(graph);
1053
1054         Variable var = variable;
1055         Resource represents = var.getRepresents(graph);
1056         Resource activeRun = null;
1057         if (represents != null && graph.isInstanceOf(represents, SIMU.Run)) {
1058             activeRun = represents;
1059         }
1060
1061         IProject project = Simantics.peekProject();
1062         if (activeRun != null && project != null) {
1063             IExperimentManager expMan = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
1064             if (expMan != null)
1065                 return expMan.getExperiment(NameUtils.getSafeName(graph, activeRun));
1066         }
1067
1068         return null;
1069     }
1070
1071     public static CommandContextMutable putTuple(CommandContextMutable context, String key, Object tuple) {
1072         List<Object> list = new ArrayList<Object>();
1073         if (tuple instanceof Tuple) {
1074                 Collections.addAll(list, ((Tuple)tuple).toArray());
1075         } else {
1076                 list.add(tuple);
1077         }
1078         context.putRow(key, list);
1079         return context;
1080     }
1081
1082     public static List<Object> getTuples(CommandContext context, String key) {
1083         List<List<Object>> rows = context.getRows(key);
1084         List<Object> tuples = new ArrayList<Object>();
1085         if (rows != null) {
1086                 for (List<Object> row : rows) {
1087                         switch (row.size()) {
1088                         case 0: tuples.add(Tuple0.INSTANCE); break;
1089                         case 1: tuples.add(row.get(1)); break;
1090                         case 2: tuples.add(new Tuple2(row.get(0), row.get(1))); break;
1091                         case 3: tuples.add(new Tuple3(row.get(0), row.get(1), row.get(2))); break;
1092                         case 4: tuples.add(new Tuple4(row.get(0), row.get(1), row.get(2), row.get(3))); break;
1093                         case 5: tuples.add(new Tuple5(row.get(0), row.get(1), row.get(2), row.get(3), row.get(4))); break;
1094                         }
1095                 }
1096         }
1097         return tuples;
1098     }
1099
1100     public static String printContext(CommandContext context) {
1101         return context.toString();
1102     }
1103
1104     @SCLValue(type = "AbstractEventHandler")
1105     public static AbstractEventHandler emptyEvent = new AbstractEventHandler() {
1106
1107                 @Override
1108                 public CommandResult handle(CommandContext context) {
1109                         return null;
1110                 }
1111
1112     };
1113
1114     public static String sclStateKey(ReadGraph graph, Variable base, Variable self, String ref) throws DatabaseException {
1115
1116         String baseURI = base.getURI(graph);
1117
1118         String selfURI = self.getURI(graph);
1119
1120         String prefix = selfURI.substring(0, selfURI.indexOf(ProxyChildVariable.CONTEXT_BEGIN));
1121         String suffix = selfURI.substring(selfURI.lastIndexOf(ProxyChildVariable.CONTEXT_END) + ProxyChildVariable.CONTEXT_END.length());
1122         String stripped = prefix + suffix;
1123
1124         String relative = Variables.getRelativeRVI(baseURI, stripped); 
1125
1126         return Variables.getRVI(relative, ref);
1127
1128     }
1129
1130     public static Variable sclStateVariable(ReadGraph graph, Variable base, Variable self, String ref) throws DatabaseException {
1131
1132         String id = sclStateKey(graph, base, self, ref);
1133
1134         Variable sclVar = base.getPossibleChild(graph, "__scl__");
1135         if(sclVar == null) return null;
1136
1137         return sclVar.getPossibleProperty(graph, id);
1138
1139     }
1140
1141     public static Object sclStateValueOrDefault(ReadGraph graph, Variable base, Variable self, String ref, Object defaultValue) throws DatabaseException {
1142
1143         Variable stateVariable = sclStateVariable(graph, base, self, ref);
1144         if (stateVariable != null) {
1145
1146                 return stateVariable.getValue(graph);
1147
1148         } else {
1149
1150                 String id = sclStateKey(graph, base, self, ref);
1151
1152                 SCLRealm realm = SCLSessionManager.getOrCreateSCLRealm(base.getURI(graph) + "/__scl__");
1153                 realm.getConnection().setVariable(id, getSCLType(defaultValue), defaultValue);
1154
1155                 return defaultValue;
1156
1157         }
1158     }
1159
1160     public static void setSclStateValue(WriteGraph graph, Variable base, Variable self, String ref, Object value) throws DatabaseException {
1161
1162         String id = sclStateKey(graph, base, self, ref);
1163
1164         SCLRealm realm = SCLSessionManager.getOrCreateSCLRealm(base.getURI(graph)+"/__scl__");
1165         realm.getConnection().setVariable(id, getSCLType(value), value);
1166         realm.refreshVariablesSync();
1167
1168     }
1169
1170     public static Object projectComponentState(ReadGraph graph, Variable self, String ref, Object defaultValue) throws DatabaseException {
1171         Resource project = Simantics.getProjectResource();
1172         Variable component = self.getParent(graph);
1173         Variable projectVariable = Variables.getVariable(graph, project);
1174         return sclStateValueOrDefault(graph, projectVariable, component, ref, defaultValue);
1175     }
1176
1177     public static void setProjectComponentState(WriteGraph graph, Variable self, String ref, Object value) throws DatabaseException {
1178         Resource project = Simantics.getProjectResource();
1179         Variable component = self.getParent(graph);
1180         Variable projectVariable = Variables.getVariable(graph, project);
1181         setSclStateValue(graph, projectVariable, component, ref, value);
1182     }
1183
1184     private static Type getSCLType(Object value) throws DatabaseException {
1185         Binding b = Bindings.getBindingUnchecked(value.getClass());
1186         Datatype t = b.type();
1187         if(Datatypes.STRING.equals(t)) return Types.STRING;
1188         if(Datatypes.DOUBLE.equals(t)) return Types.DOUBLE;
1189         throw new DatabaseException("Type not supported");
1190     }
1191
1192     public static List<Variable> documentModelContribution(ReadGraph graph, Resource doc) throws DatabaseException {
1193         Resource project = Simantics.getProjectResource();
1194         ArrayList<Variable> result = new ArrayList<Variable>();
1195         for(Resource model : graph.syncRequest(new ProjectModels(project))) {
1196                 result.add(Variables.getVariable(graph, model));
1197         }
1198         return result;
1199     }
1200
1201     public static String documentModelContributionLabel(ReadGraph graph, Variable var) throws DatabaseException {
1202         return var.getName(graph);
1203     }
1204
1205     public static Object getPropertyValueCached(ReadGraph graph, Variable variable, String name, Binding binding) throws DatabaseException {
1206         Variable property = graph.syncRequest(new VariableProperty(variable, name));
1207         return graph.syncRequest(new VariableValueWithBinding<Object>(property, binding));
1208     }
1209
1210     public static class ParentExistsRequest extends VariableRead<Boolean> {
1211
1212                 public ParentExistsRequest(Variable parent) {
1213                         super(parent);
1214                 }
1215
1216                 @Override
1217                 public Boolean perform(ReadGraph graph) throws DatabaseException {
1218                         
1219                         Variable existsProperty = variable.getPossibleProperty(graph, "exists");
1220                         if(existsProperty == null) return true;
1221                         
1222                         Boolean exists = existsProperty.getPossibleValue(graph, Bindings.BOOLEAN);
1223                         if (exists == null || !exists) return false;
1224
1225                 return graph.syncRequest(new ParentExistsRequest(variable.getParent(graph)));
1226
1227                 }
1228
1229     } 
1230
1231     public static class PathExistsRequest extends VariableRead<Boolean> {
1232
1233                 public PathExistsRequest(Variable variable) {
1234                         super(variable);
1235                 }
1236
1237                 @Override
1238                 public Boolean perform(ReadGraph graph) throws DatabaseException {
1239
1240                         Variable widget = variable.getParent(graph);
1241
1242                 Boolean exists = widget.getPossiblePropertyValue(graph, "exists");
1243                         if (exists == null || !exists) return false;
1244
1245                 if (!graph.syncRequest(new ParentExistsRequest(widget.getParent(graph)))) return false;
1246
1247                 DocumentationResource DOC = DocumentationResource.getInstance(graph);
1248                 Collection <Variable> cps = widget.getProperties(graph, DocumentationResource.URIs.Relations_parentRelation);
1249                 for (Variable cp : cps) {
1250
1251                         Connection conn = cp.getValue(graph);
1252                                 Variable otherCp = DocumentServerUtils.getPossibleChildConnectionPoint(graph, cp, conn);
1253                                 if (otherCp != null) {
1254                                         Variable parentWidget = otherCp.getParent(graph);
1255                                         if (parentWidget.<Boolean>getPropertyValue(graph, "pathExists")) {
1256                                                 return true;
1257                                         }
1258                                 } else {
1259                                         Variable parentCp = graph.sync(new UnaryRead<Connection, Variable>(conn) {
1260                                     @Override
1261                                     public Variable perform(ReadGraph graph) throws DatabaseException {
1262                                         DocumentationResource DOC = DocumentationResource.getInstance(graph);
1263                                         Collection<VariableConnectionPointDescriptor> descs = parameter.getConnectionPointDescriptors(graph, null);
1264
1265                                                 for(VariableConnectionPointDescriptor desc : descs) {
1266                                                         if (DOC.Relations_partN.equals(desc.getConnectionPointResource(graph))) {
1267                                                                 return desc.getVariable(graph);
1268                                                         }
1269                                                 }
1270                                                 return null;
1271                                     }
1272                                 });
1273                                         if (parentCp != null) {
1274                                                 Variable parentWidget = parentCp.getParent(graph);
1275                                                 if (parentWidget.<Boolean>getPropertyValue(graph, "pathExists")) {
1276                                                         return true;
1277                                                 }
1278                                         }
1279                                 }
1280                         }
1281
1282                         Resource type = widget.getType(graph);
1283                         return graph.isInheritedFrom(type, DOC.Components_ParentlessComponent) ||
1284                                 (graph.isInheritedFrom(type, DOC.DocumentComponent) && cps.isEmpty());
1285                 }
1286     }
1287
1288     @SCLValue(type = "ReadGraph -> Resource -> Variable -> Boolean")
1289     public static boolean pathExists(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
1290         return graph.syncRequest(new PathExistsRequest(context));
1291     }
1292
1293     public static String compileDocumentSCLValueExpression(ReadGraph graph, Variable context) {
1294         try {
1295             ServerSCLValueRequest.validate(graph, context);
1296             return "";
1297         } catch (Exception e) {
1298             return resolveIssueMessage(e);
1299         }
1300     }
1301     
1302     private static String resolveIssueMessage(Exception e) {
1303         if (e instanceof ImportFailureException)
1304             return "";
1305         if (e.getCause() != null && e.getCause() instanceof ImportFailureException)
1306             return "";
1307         if (e instanceof SCLDatabaseException) {
1308             SCLDatabaseException ee = (SCLDatabaseException) e;
1309             return ee.getMessage();
1310         }
1311         if (LOGGER.isDebugEnabled())
1312             LOGGER.debug("", e);
1313         return e.getMessage();
1314     }
1315
1316 }