1 package org.simantics.document.server;
\r
3 import java.util.ArrayList;
\r
4 import java.util.Collection;
\r
5 import java.util.Collections;
\r
6 import java.util.List;
\r
7 import java.util.Map;
\r
8 import java.util.TreeMap;
\r
10 import org.simantics.Simantics;
\r
11 import org.simantics.databoard.Bindings;
\r
12 import org.simantics.databoard.Datatypes;
\r
13 import org.simantics.databoard.binding.Binding;
\r
14 import org.simantics.databoard.type.Datatype;
\r
15 import org.simantics.db.ReadGraph;
\r
16 import org.simantics.db.RequestProcessor;
\r
17 import org.simantics.db.Resource;
\r
18 import org.simantics.db.Session;
\r
19 import org.simantics.db.WriteGraph;
\r
20 import org.simantics.db.common.primitiverequest.Adapter;
\r
21 import org.simantics.db.common.procedure.adapter.TransientCacheListener;
\r
22 import org.simantics.db.common.request.UnaryRead;
\r
23 import org.simantics.db.common.request.UniqueRead;
\r
24 import org.simantics.db.common.request.WriteResultRequest;
\r
25 import org.simantics.db.common.utils.Logger;
\r
26 import org.simantics.db.common.utils.NameUtils;
\r
27 import org.simantics.db.exception.DatabaseException;
\r
28 import org.simantics.db.layer0.function.All;
\r
29 import org.simantics.db.layer0.request.ProjectModels;
\r
30 import org.simantics.db.layer0.request.VariableProperty;
\r
31 import org.simantics.db.layer0.request.VariableRead;
\r
32 import org.simantics.db.layer0.request.VariableValue;
\r
33 import org.simantics.db.layer0.variable.ConstantPropertyVariable;
\r
34 import org.simantics.db.layer0.variable.ProxyChildVariable;
\r
35 import org.simantics.db.layer0.variable.ProxySessionRequest;
\r
36 import org.simantics.db.layer0.variable.ProxyVariables;
\r
37 import org.simantics.db.layer0.variable.StandardGraphChildVariable;
\r
38 import org.simantics.db.layer0.variable.Variable;
\r
39 import org.simantics.db.layer0.variable.VariableMap;
\r
40 import org.simantics.db.layer0.variable.VariableMapImpl;
\r
41 import org.simantics.db.layer0.variable.Variables;
\r
42 import org.simantics.document.base.ontology.DocumentationResource;
\r
43 import org.simantics.document.server.bean.Command;
\r
44 import org.simantics.document.server.bean.DataDefinition;
\r
45 import org.simantics.document.server.handler.AbstractEventHandler;
\r
46 import org.simantics.document.server.handler.AbstractResponseHandler;
\r
47 import org.simantics.document.server.handler.EventHandler;
\r
48 import org.simantics.document.server.io.CommandContext;
\r
49 import org.simantics.document.server.io.CommandContextImpl;
\r
50 import org.simantics.document.server.io.CommandContextMutable;
\r
51 import org.simantics.document.server.io.CommandResult;
\r
52 import org.simantics.document.server.request.ServerSCLHandlerValueRequest;
\r
53 import org.simantics.document.server.request.ServerSCLValueRequest;
\r
54 import org.simantics.document.server.serverResponse.ServerResponse;
\r
55 import org.simantics.document.server.serverResponse.SuccessResponse;
\r
56 import org.simantics.modeling.ModelingResources;
\r
57 import org.simantics.modeling.scl.SCLRealm;
\r
58 import org.simantics.modeling.scl.SCLSessionManager;
\r
59 import org.simantics.modeling.services.CaseInsensitiveComponentFunctionNamingStrategy;
\r
60 import org.simantics.modeling.services.ComponentNamingStrategy;
\r
61 import org.simantics.operation.Layer0X;
\r
62 import org.simantics.project.IProject;
\r
63 import org.simantics.scl.compiler.types.TCon;
\r
64 import org.simantics.scl.compiler.types.Type;
\r
65 import org.simantics.scl.compiler.types.Types;
\r
66 import org.simantics.scl.reflection.annotations.SCLValue;
\r
67 import org.simantics.scl.runtime.SCLContext;
\r
68 import org.simantics.scl.runtime.function.Function;
\r
69 import org.simantics.scl.runtime.function.Function1;
\r
70 import org.simantics.scl.runtime.function.FunctionImpl1;
\r
71 import org.simantics.scl.runtime.function.FunctionImpl4;
\r
72 import org.simantics.scl.runtime.reporting.SCLReportingHandler;
\r
73 import org.simantics.scl.runtime.tuple.Tuple;
\r
74 import org.simantics.scl.runtime.tuple.Tuple0;
\r
75 import org.simantics.scl.runtime.tuple.Tuple2;
\r
76 import org.simantics.scl.runtime.tuple.Tuple3;
\r
77 import org.simantics.scl.runtime.tuple.Tuple4;
\r
78 import org.simantics.scl.runtime.tuple.Tuple5;
\r
79 import org.simantics.simulation.experiment.IExperiment;
\r
80 import org.simantics.simulation.ontology.SimulationResource;
\r
81 import org.simantics.simulation.project.IExperimentManager;
\r
82 import org.simantics.structural2.variables.Connection;
\r
83 import org.simantics.structural2.variables.VariableConnectionPointDescriptor;
\r
85 import gnu.trove.map.hash.THashMap;
\r
87 public class Functions {
\r
89 @SCLValue(type = "VariableMap")
\r
90 public static VariableMap inputSpaceChildren = new VariableMapImpl() {
\r
92 private Variable getProxy(ReadGraph graph, Variable context) throws DatabaseException {
\r
93 Variable root = Variables.getRootVariable(graph);
\r
94 return new DocumentProxyChildVariable(context, context, root, ProxyChildVariable.CONTEXT_BEGIN);
\r
98 public Variable getVariable(ReadGraph graph, Variable context, String name) throws DatabaseException {
\r
100 if(ProxyChildVariable.CONTEXT_BEGIN.equals(name)) return getProxy(graph, context);
\r
101 return All.standardChildDomainChildren.getVariable(graph, context, name);
\r
106 public Map<String, Variable> getVariables(ReadGraph graph, Variable context, Map<String, Variable> map) throws DatabaseException {
\r
108 map = All.standardChildDomainChildren.getVariables(graph, context, map);
\r
109 if(map == null) map = new THashMap<String,Variable>();
\r
110 map.put(ProxyChildVariable.CONTEXT_BEGIN, getProxy(graph, context));
\r
117 static class DocumentProxyChildVariable extends ProxyChildVariable {
\r
119 public DocumentProxyChildVariable(Variable base, Variable parent, Variable other, String name) {
\r
120 super(base, parent, other, name);
\r
124 public Variable create(Variable base, Variable parent, Variable other, String name) {
\r
125 return new DocumentProxyChildVariable(base, parent, other, name);
\r
128 public Variable getPossibleChild(ReadGraph graph, String name) throws DatabaseException {
\r
130 if(CONTEXT_END.equals(name)) {
\r
131 if(other instanceof ProxyChildVariable) {
\r
132 // The context is also a proxy - let it do the job
\r
133 return super.getPossibleChild(graph, name);
\r
135 return new RootVariable(this, base.getRepresents(graph));
\r
139 return super.getPossibleChild(graph, name);
\r
143 public Collection<Variable> getChildren(ReadGraph graph) throws DatabaseException {
\r
145 Collection<Variable> result = super.getChildren(graph);
\r
146 if(!(base instanceof ProxyChildVariable)) {
\r
147 result.add(new RootVariable(this, base.getRepresents(graph)));
\r
155 static class RootVariable extends StandardGraphChildVariable {
\r
157 public RootVariable(DocumentProxyChildVariable parent, Resource resource) {
\r
158 super(parent, null, resource);
\r
162 public String getName(ReadGraph graph) throws DatabaseException {
\r
163 return ProxyChildVariable.CONTEXT_END;
\r
166 @SuppressWarnings("deprecation")
\r
168 public Variable getNameVariable(ReadGraph graph) throws DatabaseException {
\r
169 return new ConstantPropertyVariable(this, Variables.NAME, ProxyChildVariable.CONTEXT_END, Bindings.STRING);
\r
174 @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
\r
175 public static Variable input(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
\r
176 Variable session = graph.syncRequest(new ProxySessionRequest(context));
\r
177 DocumentationResource DOC = DocumentationResource.getInstance(graph);
\r
178 String uri = session.getPossiblePropertyValue(graph, DOC.Session_inputURI);
\r
180 // TODO HAXX - Please fix this
\r
181 // we have no URI so this probably means that someone has inserted a non-session
\r
182 // into the proxy variable => return that instead
\r
185 return Variables.getVariable(graph, uri);
\r
188 @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
\r
189 public static Variable state(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
\r
190 Variable session = graph.syncRequest(new ProxySessionRequest(context));
\r
191 return session.getPossibleChild(graph, "__scl__");
\r
194 @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
\r
195 public static Variable icstate(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
\r
196 Variable session = graph.syncRequest(new ProxySessionRequest(context));
\r
197 return session.getPossibleChild(graph, "__icstate__");
\r
200 @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
\r
201 public static Variable session(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
\r
202 return graph.syncRequest(new ProxySessionRequest(context));
\r
205 @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
\r
206 public static Variable experiment(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
\r
207 // Try if experiment (run) has been used as the input
\r
208 Variable var = input(graph, converter, context);
\r
209 SimulationResource SR = SimulationResource.getInstance(graph);
\r
210 while(var != null && !graph.isInstanceOf(var.getRepresents(graph), SR.Run)) {
\r
211 var = var.getParent(graph);
\r
215 IExperiment exp = getExperiment(graph, var);
\r
223 @SCLValue(type = "ReadGraph -> Resource -> Variable -> Variable")
\r
224 public static Variable model(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
\r
225 Variable var = input(graph, converter, context);
\r
226 ModelingResources MOD = ModelingResources.getInstance(graph);
\r
227 while(var != null && !graph.isInstanceOf(var.getRepresents(graph), MOD.StructuralModel)) {
\r
228 var = var.getParent(graph);
\r
234 private static Collection<Variable> getBroadcasted(ReadGraph graph, Variable target) throws DatabaseException {
\r
236 ArrayList<Variable> result = new ArrayList<Variable>();
\r
238 DocumentationResource DOC = DocumentationResource.getInstance(graph);
\r
240 Variable broadcasted = target.getPossibleProperty(graph, DOC.Relations_broadcasted);
\r
241 if(broadcasted != null) result.add(broadcasted);
\r
243 for(Variable child : DocumentServerUtils.getChildrenInOrdinalOrder(graph, target)) {
\r
244 result.addAll(getBroadcasted(graph, child));
\r
251 private static List<Command> getCommands(ReadGraph graph, Collection<Variable> commandVariables, String trigger, CommandContext constants, boolean broadcast) throws DatabaseException {
\r
253 if(commandVariables.isEmpty()) return Collections.emptyList();
\r
255 String t = trigger;
\r
256 TreeMap<Integer, List<Command>> sequences = new TreeMap<Integer, List<Command>>();
\r
258 DocumentationResource DOC = DocumentationResource.getInstance(graph);
\r
261 for (Variable c : commandVariables) {
\r
263 if(trigger == null)
\r
264 t = c.getName(graph);
\r
266 Connection conn = c.getValue(graph);
\r
267 Variable targetConnectionPoint = DocumentServerUtils.getPossibleCommandTriggerConnectionPoint(graph, c, conn);
\r
268 if (targetConnectionPoint != null) {
\r
269 Variable target = targetConnectionPoint.getParent(graph);
\r
270 if (target != null) {
\r
272 Boolean enabled = target.getPossiblePropertyValue(graph, DOC.Properties_exists, Bindings.BOOLEAN);
\r
273 if(enabled != null && !enabled) continue;
\r
281 String o = c.getPossiblePropertyValue(graph, "ordinal");
\r
283 ordinal = Integer.parseInt(o);
\r
284 } catch (NumberFormatException e) {}
\r
287 String constantKey = target.getPossiblePropertyValue(graph, "constantKey");
\r
288 String constantValue = target.getPossiblePropertyValue(graph, "constantValue");
\r
290 CommandContextMutable newConstants = (CommandContextMutable)constants;
\r
291 if(constantKey != null && constantValue != null) {
\r
292 if(!constantKey.isEmpty()) {
\r
293 newConstants = new CommandContextImpl().merge(constants);
\r
294 newConstants.putString(constantKey, constantValue);
\r
298 String requiredKey = target.getPossiblePropertyValue(graph, "requiredKey");
\r
299 if(requiredKey != null && !requiredKey.isEmpty()) {
\r
300 if (newConstants == constants) {
\r
301 newConstants = new CommandContextImpl().merge(constants);
\r
303 newConstants.putRow(CommandContext.REQUIRED_KEYS, Collections.<Object>singletonList(requiredKey));
\r
306 String forbiddenKey = target.getPossiblePropertyValue(graph, "forbiddenKey");
\r
307 if(forbiddenKey != null && !forbiddenKey.isEmpty()) {
\r
308 if (newConstants == constants) {
\r
309 newConstants = new CommandContextImpl().merge(constants);
\r
311 newConstants.putRow(CommandContext.FORBIDDEN_KEYS, Collections.<Object>singletonList(forbiddenKey));
\r
314 if(DOC.Relations_broadcast.equals(targetConnectionPoint.getPredicateResource(graph))) {
\r
316 // This is a broadcast terminal of a container
\r
317 List<Command> broadcastCommands = getCommands(graph, getBroadcasted(graph, target), t, newConstants, true);
\r
318 sequences.put(ordinal, broadcastCommands);
\r
322 Command command = new Command(DocumentServerUtils.getId(graph, target), t,
\r
323 targetConnectionPoint.getName(graph), newConstants);
\r
324 sequences.put(ordinal, Collections.singletonList(command));
\r
332 List<Command> commands = new ArrayList<Command>();
\r
333 for (List<Command> commandList : sequences.values()) {
\r
334 for (Command command : commandList) {
\r
335 commands.add(command);
\r
348 * @throws DatabaseException
\r
350 public static List<Command> commandList(ReadGraph graph, Variable variable) throws DatabaseException {
\r
351 return getCommands(graph, DocumentServerUtils.getTriggerCommands(graph, variable.getParent(graph)), null, new CommandContextImpl(), false);
\r
360 * @throws DatabaseException
\r
362 public static List<DataDefinition> dataDefinitions(ReadGraph graph, Variable variable) throws DatabaseException {
\r
363 DocumentationResource DOC = DocumentationResource.getInstance(graph);
\r
364 ArrayList<DataDefinition> dataDefinitions = new ArrayList<DataDefinition>();
\r
365 // Find data definition connections
\r
366 for (Variable dataDefinitionRelation : DocumentServerUtils.getDataDefinitions(graph, variable.getParent(graph))) {
\r
367 Connection dataDefinitionConnection = dataDefinitionRelation.getValue(graph);
\r
368 // Find data the other end of definition connection
\r
369 Collection<Variable> dataDefinitionProviders = DocumentServerUtils.getPossibleOtherConnectionPoints(graph,
\r
370 dataDefinitionRelation, dataDefinitionConnection);
\r
371 if (dataDefinitionProviders != null) {
\r
373 for(Variable dataDefinitionProvider : dataDefinitionProviders) {
\r
375 Variable dataDefinition = dataDefinitionProvider.getParent(graph);
\r
376 if (dataDefinition != null) {
\r
377 // Found other end. Is should contain ONE data
\r
378 // definition connection to the actual data
\r
379 Collection<Variable> dataCollection = DocumentServerUtils.getDataRelations(graph, dataDefinition);
\r
380 if (dataCollection.size() == 1) {
\r
381 Variable dataRelation = dataCollection.iterator().next();
\r
382 Connection dataConnection = dataRelation.getValue(graph);
\r
383 // Find data the other end of definition connection
\r
384 Variable dataConnectionPoint = DocumentServerUtils.getPossibleOtherConnectionPoint(graph,
\r
385 dataRelation, dataConnection);
\r
386 if (dataConnectionPoint != null) {
\r
387 Variable data = dataConnectionPoint.getParent(graph);
\r
388 Resource type = dataDefinition.getPossibleType(graph, DOC.Components_Component);
\r
390 if (graph.isInheritedFrom(type, DOC.Components_DefVar)) {
\r
392 String sourceProperty = dataDefinition.getPropertyValue(graph, DOC.Properties_source,
\r
394 String targetProperty = dataDefinition.getPropertyValue(graph, DOC.Properties_target,
\r
397 dataDefinitions.add(new DataDefinition(DocumentServerUtils.getId(graph, data),
\r
398 sourceProperty, targetProperty));
\r
400 } else if (graph.isInheritedFrom(type, DOC.Components_DefVars)) {
\r
402 List<String> sourcesProperty = toList(dataDefinition.getPropertyValue(graph, DOC.Properties_sources), String.class);
\r
403 List<String> targetsProperty = toList(dataDefinition.getPropertyValue(graph, DOC.Properties_targets), String.class);
\r
405 for (int i = 0; i < Math.min(sourcesProperty.size(), targetsProperty.size()); i++) {
\r
406 dataDefinitions.add(new DataDefinition(DocumentServerUtils.getId(graph, data),
\r
407 sourcesProperty.get(i), targetsProperty.get(i)));
\r
416 return dataDefinitions;
\r
419 @SuppressWarnings("unchecked")
\r
420 private static <T> List<T> toList(Object o, Class<T> c) {
\r
421 List<T> result = null;
\r
422 if (o instanceof List) {
\r
424 } else if (o instanceof Object[]) {
\r
425 result = new ArrayList<T>(((Object[])o).length);
\r
426 for (T item : (T[])o) {
\r
431 return Collections.<T>emptyList();
\r
435 public static AbstractEventHandler emptyOnClick(ReadGraph graph) throws DatabaseException {
\r
436 return new EventHandler() {
\r
439 public ServerResponse handle(ReadGraph graph, CommandContext parameters) throws DatabaseException {
\r
446 public static AbstractEventHandler writeEventHandler(ReadGraph graph, final Variable variable, final Function fn) {
\r
448 final Session session = graph.getSession();
\r
450 return new AbstractEventHandler() {
\r
453 public CommandResult handle(final CommandContext parameters) {
\r
455 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
\r
459 String result = session.sync(new WriteResultRequest<String>() {
\r
462 public String perform(WriteGraph graph) throws DatabaseException {
\r
463 SCLContext sclContext = SCLContext.getCurrent();
\r
464 Object oldGraph = sclContext.put("graph", graph);
\r
465 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
\r
467 Function1<String,String> pf = new FunctionImpl1<String,String>() {
\r
469 public String apply(String key) {
\r
470 return parameters.getString(key);
\r
473 Object response = (String)fn.apply(variable, pf);
\r
474 if(response instanceof String) {
\r
475 return (String)response;
\r
478 } catch (Throwable t) {
\r
479 t.printStackTrace();
\r
481 sclContext.put("graph", oldGraph);
\r
482 sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
\r
491 return new SuccessResponse(result);
\r
493 } catch (Throwable e) {
\r
494 Logger.defaultLogError(e);
\r
495 return new org.simantics.document.server.serverResponse.Error(e.getMessage());
\r
503 public static AbstractEventHandler readEventHandler(ReadGraph graph, final Variable variable, final Function fn) {
\r
505 final Session session = graph.getSession();
\r
507 return new AbstractEventHandler() {
\r
510 public CommandResult handle(final CommandContext parameters) {
\r
512 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
\r
516 String result = session.sync(new UniqueRead<String>() {
\r
519 public String perform(ReadGraph graph) throws DatabaseException {
\r
520 SCLContext sclContext = SCLContext.getCurrent();
\r
521 Object oldGraph = sclContext.put("graph", graph);
\r
522 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
\r
524 Function1<String,String> pf = new FunctionImpl1<String,String>() {
\r
526 public String apply(String key) {
\r
527 return parameters.getString(key);
\r
530 Object response = (String)fn.apply(variable, pf);
\r
531 if(response instanceof String) {
\r
532 return (String)response;
\r
535 } catch (Throwable t) {
\r
536 t.printStackTrace();
\r
538 sclContext.put("graph", oldGraph);
\r
539 sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
\r
548 return new SuccessResponse(result);
\r
550 } catch (Throwable e) {
\r
551 Logger.defaultLogError(e);
\r
552 return new org.simantics.document.server.serverResponse.Error(e.getMessage());
\r
560 public static AbstractEventHandler readEventHandler2(ReadGraph graph, final Function fn) {
\r
562 final Session session = graph.getSession();
\r
564 return new AbstractEventHandler() {
\r
567 public CommandResult handle(final CommandContext parameters) {
\r
569 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
\r
573 CommandResult result = session.sync(new UniqueRead<CommandResult>() {
\r
576 public CommandResult perform(ReadGraph graph) throws DatabaseException {
\r
577 SCLContext sclContext = SCLContext.getCurrent();
\r
578 Object oldGraph = sclContext.put("graph", graph);
\r
579 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
\r
581 Object response = fn.apply(parameters);
\r
582 if(response instanceof CommandResult) {
\r
583 return (CommandResult)response;
\r
586 } catch (Throwable t) {
\r
587 t.printStackTrace();
\r
589 sclContext.put("graph", oldGraph);
\r
590 sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
\r
601 } catch (Throwable e) {
\r
602 Logger.defaultLogError(e);
\r
603 return new org.simantics.document.server.serverResponse.Error(e.getMessage());
\r
611 public static AbstractEventHandler responseHandler(ReadGraph graph, Variable self, String function) throws DatabaseException {
\r
613 Variable anyFunction = self.browse(graph, ".#" + function);
\r
614 if(anyFunction == null) return null;
\r
616 final List<TCon> effects = ServerSCLHandlerValueRequest.getEffects(graph, anyFunction);
\r
618 final Function1<CommandContext, CommandResult> fn = anyFunction.getValue(graph);
\r
619 String expression = anyFunction.getPropertyValue(graph, "expression");
\r
621 final Session session = graph.getSession();
\r
623 return new AbstractResponseHandler(expression) {
\r
625 private String formatError(RequestProcessor proc, Throwable t) {
\r
629 return proc.syncRequest(new UniqueRead<String>() {
\r
632 public String perform(ReadGraph graph) throws DatabaseException {
\r
633 Variable proxy = ProxyVariables.proxyVariableRoot(graph, anyFunction);
\r
634 String uri2 = proxy.getURI(graph);
\r
635 String uri = self.getParent(graph).getURI(graph);
\r
637 String path = uri.substring(uri2.length());
\r
639 String expr = anyFunction.getPossiblePropertyValue(graph, "expression");
\r
640 StringBuilder message = new StringBuilder();
\r
641 message.append("Handler execution failed\n");
\r
642 message.append(" handler=" + path + "\n");
\r
643 message.append(" expression=" + expr + "\n");
\r
644 message.append(" message=" + t.getMessage() + "\n");
\r
645 return message.toString();
\r
650 } catch (DatabaseException e) {
\r
652 return e.getMessage();
\r
659 public CommandResult handle(final CommandContext parameters) {
\r
661 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
\r
665 Object result = null;
\r
666 if(effects.contains(Types.WRITE_GRAPH)) {
\r
668 result = session.syncRequest(new WriteResultRequest<Object>() {
\r
671 public Object perform(WriteGraph graph)
\r
672 throws DatabaseException {
\r
673 SCLContext sclContext = SCLContext.getCurrent();
\r
674 Object oldGraph = sclContext.put("graph", graph);
\r
675 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
\r
677 Object response = fn.apply(parameters);
\r
679 } catch (Throwable t) {
\r
680 return new org.simantics.document.server.serverResponse.Error(formatError(graph, t));
\r
682 sclContext.put("graph", oldGraph);
\r
683 sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
\r
689 } else if(effects.contains(Types.READ_GRAPH)) {
\r
691 result = session.sync(new UniqueRead<Object>() {
\r
694 public Object perform(ReadGraph graph) throws DatabaseException {
\r
696 SCLContext sclContext = SCLContext.getCurrent();
\r
697 Object oldGraph = sclContext.put("graph", graph);
\r
698 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
\r
701 Object response = fn.apply(parameters);
\r
703 } catch (Throwable t) {
\r
704 return new org.simantics.document.server.serverResponse.Error(formatError(graph, t));
\r
706 sclContext.put("graph", oldGraph);
\r
707 sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
\r
714 result = fn.apply(parameters);
\r
717 if (result instanceof org.simantics.document.server.serverResponse.Error) {
\r
718 return (CommandResult)result;
\r
721 if (result instanceof CommandResult) {
\r
722 return (CommandResult)result;
\r
724 CommandContextMutable assignments = new CommandContextImpl();
\r
725 assignments.putValue("result", result);
\r
726 return new ServerResponse(200, "", assignments);
\r
729 } catch (Throwable e) {
\r
730 return new org.simantics.document.server.serverResponse.Error(formatError(Simantics.getSession(), e));
\r
738 public static AbstractEventHandler writeEventHandler2(ReadGraph graph, final Function fn) {
\r
740 final Session session = graph.getSession();
\r
742 return new AbstractEventHandler() {
\r
745 public CommandResult handle(final CommandContext parameters) {
\r
747 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
\r
751 CommandResult result = session.syncRequest(new WriteResultRequest<CommandResult>() {
\r
754 public CommandResult perform(WriteGraph graph) throws DatabaseException {
\r
755 SCLContext sclContext = SCLContext.getCurrent();
\r
756 Object oldGraph = sclContext.put("graph", graph);
\r
757 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
\r
759 Object response = fn.apply(parameters);
\r
760 if(response instanceof CommandResult) {
\r
761 return (CommandResult)response;
\r
764 } catch (Throwable t) {
\r
765 t.printStackTrace();
\r
767 sclContext.put("graph", oldGraph);
\r
768 sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
\r
779 } catch (Throwable e) {
\r
780 Logger.defaultLogError(e);
\r
781 return new org.simantics.document.server.serverResponse.Error(e.getMessage());
\r
789 public static AbstractEventHandler eventHandler2(ReadGraph graph, final Function fn) {
\r
791 return new AbstractEventHandler() {
\r
794 public CommandResult handle(final CommandContext parameters) {
\r
796 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
\r
800 SCLContext sclContext = SCLContext.getCurrent();
\r
801 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
\r
803 Object response = fn.apply(parameters);
\r
804 if(response instanceof CommandResult) {
\r
805 return (CommandResult)response;
\r
808 } catch (Throwable t) {
\r
809 t.printStackTrace();
\r
811 sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
\r
816 } catch (Throwable e) {
\r
817 Logger.defaultLogError(e);
\r
818 return new org.simantics.document.server.serverResponse.Error(e.getMessage());
\r
826 public static AbstractEventHandler eventHandler(ReadGraph graph, final Function fn) {
\r
828 return new AbstractEventHandler() {
\r
831 public CommandResult handle(final CommandContext parameters) {
\r
833 final SCLReportingHandler printer = (SCLReportingHandler)SCLContext.getCurrent().get(SCLReportingHandler.REPORTING_HANDLER);
\r
837 String result = "";
\r
839 SCLContext sclContext = SCLContext.getCurrent();
\r
840 Object oldPrinter = sclContext.put(SCLReportingHandler.REPORTING_HANDLER, printer);
\r
842 Function1<String,String> pf = new FunctionImpl1<String,String>() {
\r
844 public String apply(String key) {
\r
845 return parameters.getString(key);
\r
848 Object response = (String)fn.apply(pf);
\r
849 if(response instanceof String) {
\r
850 result = (String)response;
\r
852 } catch (Throwable t) {
\r
853 t.printStackTrace();
\r
855 sclContext.put(SCLReportingHandler.REPORTING_HANDLER, oldPrinter);
\r
858 return new SuccessResponse(result);
\r
860 } catch (Throwable e) {
\r
861 Logger.defaultLogError(e);
\r
862 return new org.simantics.document.server.serverResponse.Error(e.getMessage());
\r
870 @SCLValue(type = "ReadGraph -> Resource -> Variable -> a")
\r
871 public static Object sclValue(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
\r
872 return ServerSCLValueRequest.compileAndEvaluate(graph, context);
\r
875 @SCLValue(type = "ReadGraph -> Resource -> Variable -> a")
\r
876 public static Object sclHandlerValue(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
\r
877 return ServerSCLHandlerValueRequest.compileAndEvaluate(graph, context);
\r
880 @SCLValue(type = "ReadGraph -> Resource -> Resource -> ComponentNamingStrategy")
\r
881 public static ComponentNamingStrategy componentNamingStrategy(ReadGraph graph, Resource converter, Resource context) throws DatabaseException {
\r
882 return createComponentNamingStrategy(graph);
\r
885 public static CaseInsensitiveComponentFunctionNamingStrategy createComponentNamingStrategy(ReadGraph graph) throws DatabaseException {
\r
886 Layer0X L0X = Layer0X.getInstance(graph);
\r
887 @SuppressWarnings({ "unchecked", "rawtypes" })
\r
888 final Function dependencies = graph.syncRequest(new Adapter(L0X.DependencyResources, Function.class), TransientCacheListener.<Function>instance());
\r
889 @SuppressWarnings("rawtypes")
\r
890 Function moduleNameFunction = new FunctionImpl4<ReadGraph, Resource, String, Integer, List<Map<String, Object>>>() {
\r
892 public Object apply(ReadGraph p0, Resource p1, String p2) {
\r
893 return apply(p0, p1, p2);
\r
895 @SuppressWarnings("unchecked")
\r
897 public List<Map<String, Object>> apply(ReadGraph graph, Resource model, String search, Integer maxResults) {
\r
898 return (List<Map<String, Object>>)dependencies.apply(graph, model, search, maxResults);
\r
901 return new CaseInsensitiveComponentFunctionNamingStrategy("%s%02d", moduleNameFunction);
\r
904 public static IExperiment getExperiment(ReadGraph graph, Variable variable) throws DatabaseException {
\r
905 if (variable == null)
\r
908 SimulationResource SIMU = SimulationResource.getInstance(graph);
\r
910 Variable var = variable;
\r
911 Resource represents = var.getRepresents(graph);
\r
912 Resource activeRun = null;
\r
913 if (represents != null && graph.isInstanceOf(represents, SIMU.Run)) {
\r
914 activeRun = represents;
\r
917 IProject project = Simantics.peekProject();
\r
918 if (activeRun != null && project != null) {
\r
919 IExperimentManager expMan = project.getHint(IExperimentManager.KEY_EXPERIMENT_MANAGER);
\r
920 if (expMan != null)
\r
921 return expMan.getExperiment(NameUtils.getSafeName(graph, activeRun));
\r
927 public static CommandContextMutable putTuple(CommandContextMutable context, String key, Object tuple) {
\r
928 List<Object> list = new ArrayList<Object>();
\r
929 if (tuple instanceof Tuple) {
\r
930 Collections.addAll(list, ((Tuple)tuple).toArray());
\r
934 context.putRow(key, list);
\r
938 public static List<Object> getTuples(CommandContext context, String key) {
\r
939 List<List<Object>> rows = context.getRows(key);
\r
940 List<Object> tuples = new ArrayList<Object>();
\r
941 if (rows != null) {
\r
942 for (List<Object> row : rows) {
\r
943 switch (row.size()) {
\r
944 case 0: tuples.add(Tuple0.INSTANCE); break;
\r
945 case 1: tuples.add(row.get(1)); break;
\r
946 case 2: tuples.add(new Tuple2(row.get(0), row.get(1))); break;
\r
947 case 3: tuples.add(new Tuple3(row.get(0), row.get(1), row.get(2))); break;
\r
948 case 4: tuples.add(new Tuple4(row.get(0), row.get(1), row.get(2), row.get(3))); break;
\r
949 case 5: tuples.add(new Tuple5(row.get(0), row.get(1), row.get(2), row.get(3), row.get(4))); break;
\r
956 public static String printContext(CommandContext context) {
\r
957 String str = context.toString();
\r
958 System.err.println(str);
\r
962 @SCLValue(type = "AbstractEventHandler")
\r
963 public static AbstractEventHandler emptyEvent = new AbstractEventHandler() {
\r
966 public CommandResult handle(CommandContext context) {
\r
972 public static String sclStateKey(ReadGraph graph, Variable base, Variable self, String ref) throws DatabaseException {
\r
974 String baseURI = base.getURI(graph);
\r
976 String selfURI = self.getURI(graph);
\r
978 String prefix = selfURI.substring(0, selfURI.indexOf(ProxyChildVariable.CONTEXT_BEGIN));
\r
979 String suffix = selfURI.substring(selfURI.lastIndexOf(ProxyChildVariable.CONTEXT_END) + ProxyChildVariable.CONTEXT_END.length());
\r
980 String stripped = prefix + suffix;
\r
982 String relative = Variables.getRelativeRVI(baseURI, stripped);
\r
984 return Variables.getRVI(relative, ref);
\r
988 public static Variable sclStateVariable(ReadGraph graph, Variable base, Variable self, String ref) throws DatabaseException {
\r
990 String id = sclStateKey(graph, base, self, ref);
\r
992 Variable sclVar = base.getPossibleChild(graph, "__scl__");
\r
993 if(sclVar == null) return null;
\r
995 return sclVar.getPossibleProperty(graph, id);
\r
999 public static Object sclStateValueOrDefault(ReadGraph graph, Variable base, Variable self, String ref, Object defaultValue) throws DatabaseException {
\r
1001 Variable stateVariable = sclStateVariable(graph, base, self, ref);
\r
1002 if (stateVariable != null) {
\r
1004 return stateVariable.getValue(graph);
\r
1008 String id = sclStateKey(graph, base, self, ref);
\r
1010 SCLRealm realm = SCLSessionManager.getOrCreateSCLRealm(base.getURI(graph) + "/__scl__");
\r
1011 realm.getConnection().setVariable(id, getSCLType(defaultValue), defaultValue);
\r
1013 return defaultValue;
\r
1018 public static void setSclStateValue(WriteGraph graph, Variable base, Variable self, String ref, Object value) throws DatabaseException {
\r
1020 String id = sclStateKey(graph, base, self, ref);
\r
1022 SCLRealm realm = SCLSessionManager.getOrCreateSCLRealm(base.getURI(graph)+"/__scl__");
\r
1023 realm.getConnection().setVariable(id, getSCLType(value), value);
\r
1024 realm.refreshVariablesSync();
\r
1028 public static Object projectComponentState(ReadGraph graph, Variable self, String ref, Object defaultValue) throws DatabaseException {
\r
1029 Resource project = Simantics.getProjectResource();
\r
1030 Variable component = self.getParent(graph);
\r
1031 Variable projectVariable = Variables.getVariable(graph, project);
\r
1032 return sclStateValueOrDefault(graph, projectVariable, component, ref, defaultValue);
\r
1035 public static void setProjectComponentState(WriteGraph graph, Variable self, String ref, Object value) throws DatabaseException {
\r
1036 Resource project = Simantics.getProjectResource();
\r
1037 Variable component = self.getParent(graph);
\r
1038 Variable projectVariable = Variables.getVariable(graph, project);
\r
1039 setSclStateValue(graph, projectVariable, component, ref, value);
\r
1042 private static Type getSCLType(Object value) throws DatabaseException {
\r
1043 Binding b = Bindings.getBindingUnchecked(value.getClass());
\r
1044 Datatype t = b.type();
\r
1045 if(Datatypes.STRING.equals(t)) return Types.STRING;
\r
1046 if(Datatypes.DOUBLE.equals(t)) return Types.DOUBLE;
\r
1047 throw new DatabaseException("Type not supported");
\r
1050 public static List<Variable> documentModelContribution(ReadGraph graph, Resource doc) throws DatabaseException {
\r
1051 Resource project = Simantics.getProjectResource();
\r
1052 ArrayList<Variable> result = new ArrayList<Variable>();
\r
1053 for(Resource model : graph.syncRequest(new ProjectModels(project))) {
\r
1054 result.add(Variables.getVariable(graph, model));
\r
1059 public static String documentModelContributionLabel(ReadGraph graph, Variable var) throws DatabaseException {
\r
1060 return var.getName(graph);
\r
1063 public static Object getPropertyValueCached(ReadGraph graph, Variable variable, String name, Binding binding) throws DatabaseException {
\r
1064 Variable property = graph.syncRequest(new VariableProperty(variable, name));
\r
1065 return graph.syncRequest(new VariableValue<Object>(property));
\r
1068 public static class ParentExistsRequest extends VariableRead<Boolean> {
\r
1070 public ParentExistsRequest(Variable parent) {
\r
1075 public Boolean perform(ReadGraph graph) throws DatabaseException {
\r
1077 Variable existsProperty = variable.getPossibleProperty(graph, "exists");
\r
1078 if(existsProperty == null) return true;
\r
1080 Boolean exists = existsProperty.getPossibleValue(graph, Bindings.BOOLEAN);
\r
1081 if (exists == null || !exists) return false;
\r
1083 return graph.syncRequest(new ParentExistsRequest(variable.getParent(graph)));
\r
1089 public static class PathExistsRequest extends VariableRead<Boolean> {
\r
1091 public PathExistsRequest(Variable variable) {
\r
1096 public Boolean perform(ReadGraph graph) throws DatabaseException {
\r
1098 Variable widget = variable.getParent(graph);
\r
1100 Boolean exists = widget.getPossiblePropertyValue(graph, "exists");
\r
1101 if (exists == null || !exists) return false;
\r
1103 if (!graph.syncRequest(new ParentExistsRequest(widget.getParent(graph)))) return false;
\r
1105 DocumentationResource DOC = DocumentationResource.getInstance(graph);
\r
1106 Collection <Variable> cps = widget.getProperties(graph, DOC.Relations_parentRelation);
\r
1107 for (Variable cp : cps) {
\r
1109 Connection conn = cp.getValue(graph);
\r
1110 Variable otherCp = DocumentServerUtils.getPossibleOtherConnectionPoint(graph, cp, conn);
\r
1111 if (otherCp != null) {
\r
1112 Variable parentWidget = otherCp.getParent(graph);
\r
1113 if (parentWidget.<Boolean>getPropertyValue(graph, "pathExists")) {
\r
1117 Variable parentCp = graph.sync(new UnaryRead<Connection, Variable>(conn) {
\r
1119 public Variable perform(ReadGraph graph) throws DatabaseException {
\r
1120 DocumentationResource DOC = DocumentationResource.getInstance(graph);
\r
1121 Collection<VariableConnectionPointDescriptor> descs = parameter.getConnectionPointDescriptors(graph, null);
\r
1123 for(VariableConnectionPointDescriptor desc : descs) {
\r
1124 if (DOC.Relations_partN.equals(desc.getConnectionPointResource(graph))) {
\r
1125 return desc.getVariable(graph);
\r
1131 if (parentCp != null) {
\r
1132 Variable parentWidget = parentCp.getParent(graph);
\r
1133 if (parentWidget.<Boolean>getPropertyValue(graph, "pathExists")) {
\r
1140 Resource type = widget.getType(graph);
\r
1141 return graph.isInheritedFrom(type, DOC.Components_ParentlessComponent) ||
\r
1142 (graph.isInheritedFrom(type, DOC.DocumentComponent) && cps.isEmpty());
\r
1146 @SCLValue(type = "ReadGraph -> Resource -> Variable -> Boolean")
\r
1147 public static boolean pathExists(ReadGraph graph, Resource converter, Variable context) throws DatabaseException {
\r
1148 return graph.syncRequest(new PathExistsRequest(context));
\r