1 /*******************************************************************************
\r
2 * Copyright (c) 2014, 2016 Association for Decentralized Information Management
\r
3 * in Industry THTH ry.
\r
4 * All rights reserved. This program and the accompanying materials
\r
5 * are made available under the terms of the Eclipse Public License v1.0
\r
6 * which accompanies this distribution, and is available at
\r
7 * http://www.eclipse.org/legal/epl-v10.html
\r
10 * VTT Technical Research Centre of Finland - initial API and implementation
\r
11 *******************************************************************************/
\r
12 package org.simantics.r.scl;
\r
14 import java.util.UUID;
\r
15 import java.util.concurrent.ConcurrentHashMap;
\r
17 import org.rosuda.REngine.Rserve.RConnection;
\r
18 import org.rosuda.REngine.Rserve.RserveException;
\r
19 import org.simantics.scl.runtime.function.Function;
\r
21 public class RSessionManager {
\r
22 static ConcurrentHashMap<String, RSession> CONNECTIONS =
\r
23 new ConcurrentHashMap<String, RSession>();
\r
25 public static RSession getSession(String id) {
\r
26 // CONNECTIONS is ConcurrentHashMap so no synchronization is needed here
\r
27 return CONNECTIONS.get(id);
\r
30 public static RSession createSession(RSessionConfiguration configuration) throws RserveException {
\r
31 synchronized(CONNECTIONS) {
\r
32 String id = UUID.randomUUID().toString();
\r
33 return createSession(configuration, id);
\r
37 public static Object withConfiguration(RSessionConfiguration configuration, @SuppressWarnings("rawtypes") Function f) throws RserveException {
\r
38 RSession session = createSession(configuration);
\r
40 return session.syncExec(f);
\r
41 } catch (InterruptedException e) {
\r
42 throw new RuntimeException(e);
\r
48 public static RSession getOrCreateSession(RSessionConfiguration configuration, String id) throws RserveException {
\r
49 synchronized(CONNECTIONS) {
\r
50 RSession session = getSession(id);
\r
52 return createSession(configuration, id);
\r
58 private static RSession createSession(RSessionConfiguration configuration, String id) throws RserveException {
\r
59 synchronized(CONNECTIONS) {
\r
60 RConnection connection = new RConnection(configuration.host, configuration.port);
\r
61 if(configuration.username != null && !configuration.username.isEmpty())
\r
62 connection.login(configuration.username, configuration.password);
\r
63 RSession managedConnection = new RSession(connection, id);
\r
64 CONNECTIONS.put(id, managedConnection);
\r
65 return managedConnection;
\r