]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.rest/src/org/simantics/scl/rest/SCLAPI.java
Fixed multiple issues causing dangling references to discarded queries
[simantics/platform.git] / bundles / org.simantics.scl.rest / src / org / simantics / scl / rest / SCLAPI.java
1 package org.simantics.scl.rest;
2
3 import java.io.Reader;
4 import java.io.Writer;
5 import java.util.concurrent.ConcurrentHashMap;
6
7 import org.simantics.scl.compiler.commands.CommandSessionWithModules;
8 import org.simantics.scl.osgi.SCLOsgi;
9
10 public class SCLAPI {
11
12     private static SCLAPI INSTANCE;
13     
14     private ConcurrentHashMap<String, CommandSessionWithModules> commandSessions;
15     
16     private SCLAPI() {
17         this.commandSessions = new ConcurrentHashMap<>();
18     }
19     
20     public static SCLAPI getInstance() {
21         if (INSTANCE == null) {
22             synchronized (SCLAPI.class) {
23                 if (INSTANCE == null) {
24                     INSTANCE = new SCLAPI();
25                 }
26             }
27         }
28         return INSTANCE;
29     }
30
31     public CommandSessionWithModules getOrCreateCommandSession(String sessionId) {
32         return commandSessions.computeIfAbsent(sessionId, key -> new CommandSessionWithModules(SCLOsgi.MODULE_REPOSITORY));
33     }
34
35     public void execute(String sessionId, Reader reader, Writer writer) {
36         CommandSessionWithModules session = commandSessions.get(sessionId);
37         if (session == null)
38             throw new IllegalArgumentException("CommandSession for sessionId " + sessionId + " does not exist!");
39         session.runCommands(reader, writer);
40     }
41
42     public void deleteCommandSession(String sessionId) {
43         commandSessions.computeIfPresent(sessionId, (key, session) -> {
44             // session could be flushed or closed here to release possible resources?
45             return null;
46         });
47     }
48
49     public Object variableValue(String sessionId, String variableName) {
50         CommandSessionWithModules session = commandSessions.get(sessionId);
51         if (session == null)
52             throw new IllegalArgumentException("CommandSession for sessionId " + sessionId + " does not exist!");
53         return session.getCommandSession().getVariableValue(variableName);
54     }
55
56     public String putModule(String sessionId, String moduleName, String moduleText) {
57         CommandSessionWithModules session = commandSessions.get(sessionId);
58         if (session == null)
59             throw new IllegalArgumentException("CommandSession for sessionId " + sessionId + " does not exist!");
60         return session.putModule(moduleName, moduleText);
61     }
62 }