All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.integratedmodelling.engine.rest.RESTManager Maven / Gradle / Ivy

The newest version!
/// *******************************************************************************
// * Copyright (C) 2007, 2015:
// *
// * - Ferdinando Villa 
// * - integratedmodelling.org
// * - any other authors listed in @author annotations
// *
// * All rights reserved. This file is part of the k.LAB software suite,
// * meant to enable modular, collaborative, integrated
// * development of interoperable data and model components. For
// * details, see http://integratedmodelling.org.
// *
// * This program is free software; you can redistribute it and/or
// * modify it under the terms of the Affero General Public License
// * Version 3 or any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but without any warranty; without even the implied warranty of
// * merchantability or fitness for a particular purpose. See the
// * Affero General Public License for more details.
// *
// * You should have received a copy of the Affero General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// * The license is also available at: https://www.gnu.org/licenses/agpl.html
// *******************************************************************************/
// package org.integratedmodelling.engine.rest;
//
// import java.util.ArrayList;
// import java.util.Collection;
// import java.util.Date;
// import java.util.HashMap;
// import java.util.List;
// import java.util.concurrent.Executors;
// import java.util.concurrent.Future;
// import java.util.concurrent.ScheduledExecutorService;
// import java.util.concurrent.TimeUnit;
// import java.util.logging.Level;
//
// import org.integratedmodelling.api.auth.IUser;
// import org.integratedmodelling.api.configuration.IConfiguration;
// import org.integratedmodelling.api.runtime.ILegacySession;
// import org.integratedmodelling.common.auth.RESTUser;
// import org.integratedmodelling.common.configuration.KLAB;
// import org.integratedmodelling.engine.runtime.Session;
// import org.integratedmodelling.exceptions.ThinklabException;
// import org.integratedmodelling.exceptions.ThinklabInternalErrorException;
// import org.integratedmodelling.exceptions.ThinklabValidationException;
// import org.restlet.Component;
// import org.restlet.Context;
// import org.restlet.data.Protocol;
// import org.restlet.resource.ServerResource;
//
// public class RESTManager {
//
// /**
// * check on the status of sessions every this many seconds
// */
// private static final long SESSION_REAPER_PERIOD_SECONDS = 60;
//
// /**
// * remove a session when this timeout has been reached.
// */
// private static long SESSION_TIMEOUT_MINUTES = 60;
//
// RESTApplication _application;
//
// HashMap _components = new HashMap();
// HashMap _commands = new HashMap();
// /*
// * resource classes harvested from plugin code.
// */
// HashMap> _resources = new HashMap>();
//
// int sessionCount;
//
// HashMap _sessions = new HashMap();
// HashMap _authorized = new HashMap();
//
// private ScheduledExecutorService _executor;
// private Future _future;
//
// public static RESTManager _this = null;
// volatile Boolean _monitoring = false;
//
//
// public static class RestCommand {
//
// public String[] options;
// public String[] arguments;
// public String id;
// public String description;
//
// public RestCommand(String path, String description, String argument, String options) {
//
// this.id = path;
// this.description = description;
// this.options = options.isEmpty() ? null : options.split(",");
// this.arguments = argument.isEmpty() ? null : argument.split(",");
// }
//
// public Object asArray() {
// return new Object[] { id, description, arguments, options };
// }
//
// public List asList() {
//
// ArrayList ret = new ArrayList();
// for (Object o : ((Object[]) asArray()))
// ret.add(o);
//
// return ret;
// }
// }
//
// class SessionReaperService implements Runnable {
//
// @Override
// public void run() {
//
// long time = new Date().getTime();
// ArrayList toReap = new ArrayList<>();
// synchronized (_sessions) {
// for (String key : _sessions.keySet()) {
// Session session = (Session) _sessions.get(key);
// if ((time - session.getLastAccess()) > SESSION_TIMEOUT_MINUTES * 60L * 1000L) {
// toReap.add(key);
// }
// }
// for (String key : toReap) {
// terminateSession(key);
// }
// }
// }
// }
//
// /**
// * If query contains the ID of a valid user session, return the ISession
// * allocated to it, otherwise return null.
// *
// * @param hashMap
// * @return
// */
// public ILegacySession getSession(String id) {
// synchronized (_sessions) {
// return _sessions.get(id);
// }
// }
//
// public void terminateSession(String key) {
//
// if (KLAB.NETWORK.isPersonal()) {
// /*
// * no action on a personal server - just acknowledge inactivity.
// *
// * TODO maybe clean up the contexts etc. calling a cleanup() method
// * in the session.
// *
// * TODO maybe this should use a flag in the session instead - probably
// * safer than checking for lock, so we can just keep the locking user and
// * ensure we're actually a preauthenticated personal server if there are others.
// */
// return;
// }
//
// /*
// * TODO remove directory access and clear any modeling done.
// */
// ILegacySession session = _sessions.get(key);
//
// if (session != null && session.getUser() != null) {
// KLAB.info("terminating session owned by " + session.getUser() + " due to inactivity");
// _application.unmapDirectory(session.getUser().getSecurityKey());
// _sessions.remove(key);
// }
// }
//
// public static RESTManager get() {
//
// if (_this == null)
// _this = new RESTManager();
//
// return _this;
// }
//
// public HashMap getComponents() {
// return _components;
// }
//
// public RESTApplication getApplication() {
// return _application;
// }
//
// public void startPolling() {
//
// if (KLAB.CONFIG.getProperties().containsKey(IConfiguration.SESSION_TIMEOUT_MINUTES_PROPERTY)) {
// SESSION_TIMEOUT_MINUTES = Long.parseLong(KLAB.CONFIG.getProperties()
// .getProperty(IConfiguration.SESSION_TIMEOUT_MINUTES_PROPERTY));
// }
//
// if (SESSION_TIMEOUT_MINUTES == 0) {
// KLAB.info("session timeout disabled in configuration");
// return;
// }
//
// KLAB.info("session timeout is " + SESSION_TIMEOUT_MINUTES + " minutes, checked every "
// + SESSION_REAPER_PERIOD_SECONDS + " seconds");
//
// if (_future != null) {
// _future.cancel(false);
// _executor.shutdown();
// }
//
// _executor = Executors.newScheduledThreadPool(24);
// _future = _executor
// .scheduleWithFixedDelay(new SessionReaperService(), 0, SESSION_REAPER_PERIOD_SECONDS, TimeUnit.SECONDS);
// }
//
// /**
// * Stop the polling.
// */
// public void pausePolling() {
//
// if (_future != null) {
// _future.cancel(false);
// _executor.shutdown();
// _future = null;
// }
// }
//
// public void registerService(String path, Class handlerClass, String description,
/// String argument, String options) {
//
// // TODO pass and store all further documentation.
// _resources.put(path, handlerClass);
// _commands.put(path, new RestCommand(path, description, argument, options));
//
// // update any existing servers
// for (Component p : _components.values()) {
// p.getInternalRouter().attach("/" + path, handlerClass);
// }
// }
//
// /**
// * Start the server on specified port. Bound to "rest start" command.
// *
// * @param contextName
// * @param port
// *
// * @throws ThinklabException
// */
// public void start(String contextName, int port) throws ThinklabException {
//
// if (_components.containsKey(port))
// throw new ThinklabValidationException("a REST service is already running on port " + port);
//
// if (!contextName.startsWith("/")) {
// contextName = "/" + contextName;
// }
//
// Component component = new Component();
//
// // without the timeout suppression, the client can hang indefinitely when the socket
// // idles 30+ secs.
// Context context = new Context();
// context.getParameters().add("maxIoIdleTimeMs", "0");
// context.getParameters().add("ioMaxIdleTimeMs", "0");
// component.setContext(context);
//
// component.getServers().add(Protocol.HTTP, port);
// component.getClients().add(Protocol.FILE);
// component.getDefaultHost().attach(contextName, (_application = new RESTApplication()));
// component.getLogger().setLevel(Level.WARNING);
//
// try {
// component.start();
// } catch (Exception e) {
// throw new ThinklabInternalErrorException(e);
// }
// _components.put(port, component);
//
// // /**
// // * If we are the authoritative server for any projects, make them available to anyone who
// // * has our key.
// // *
// // * FIXME remove this - we're doing it project by project now.
// // *
// // */
// // if (Env.CONFIG.getProperties().containsKey(IConfiguration.THINKLAB_ASSETS_DIR_PROPERTY)) {
// //
// // File adir = new File(Env.CONFIG.getProperties()
// // .getProperty(IConfiguration.THINKLAB_ASSETS_DIR_PROPERTY));
// // if (adir.exists() && adir.isDirectory() && adir.canRead()) {
// // getApplication().mapDirectoryToKey(adir, Env.NETWORK.getKey());
// // }
// // }
//
// startPolling();
// }
//
// /**
// * Stop the server on specified port. Bound to "rest stop" command.
// *
// * @param port
// * @throws ThinklabException
// */
// public void stop(int port) throws ThinklabException {
//
// pausePolling();
//
// Component component = _components.get(port);
// if (component == null)
// throw new ThinklabValidationException("no REST service running on port " + port);
// try {
// component.stop();
// } catch (Exception e) {
// throw new ThinklabInternalErrorException(e);
// }
// _components.remove(port);
// _application = null;
//
// }
//
// public ILegacySession createRESTSession(final IUser user)
// throws ThinklabException {
//
// Session ret = new Session(user);
// synchronized (_sessions) {
// _sessions.put(ret.getId(), ret);
// }
//
// return ret;
// }
//
// public Collection getPaths() {
// return _resources.keySet();
// }
//
// public Class getResourceForPath(String path) {
// return _resources.get(path);
// }
//
// public Collection getCommandDescriptors() {
// return _commands.values();
// }
//
// public RestCommand getCommandDescriptor(String id) {
// return _commands.get(id);
// }
//
// public boolean allowPrivilegedLocalConnections() {
// return true;
// }
//
// // public void registerAssetRequest(IUser user, String password, IUserAssets assets) {
// // ((User) user).setLastLogin(new Date().getTime());
// // synchronized (_authorized) {
// // _authorized.put(password, user);
// // }
// // }
//
// public IUser checkAuthorization(String skey) {
// synchronized (_authorized) {
// return _authorized.get(skey);
// }
// }
//
// /**
// * Check if a passed resource ID has been authorized for a specific user.
// *
// * @param string
// * @return
// */
// public boolean checkResourceAuthorization(String string) {
// synchronized (_authorized) {
// for (String s : _authorized.keySet()) {
// if (string.startsWith(s))
// return true;
// }
// }
// return false;
// }
//
// public Collection getActiveUserIds(int maxIdleMinutes) {
//
// long now = new Date().getTime();
// ArrayList ret = new ArrayList<>();
// for (IUser s : _authorized.values()) {
// if ((now - s.getLastLogin().getTime()) < (60000L * maxIdleMinutes)) {
// ret.add(s.getUsername());
// }
// }
// return ret;
// }
//
// public Collection getActiveUsers(int maxIdleMinutes) {
//
// long now = new Date().getTime();
// ArrayList ret = new ArrayList<>();
// for (IUser s : _authorized.values()) {
// if ((now - s.getLastLogin().getTime()) < (60000L * maxIdleMinutes)) {
// ret.add(s);
// }
// }
// return ret;
// }
//
// /**
// * Check an authentication token and turn it into a user profile using our configured
// * authentication endpoint.
// *
// * @param uAuth
// * @return
// */
// public IUser checkAuthentication(String username, String uAuth) {
//
// if (_authorized.containsKey(uAuth)) {
// return _authorized.get(uAuth);
// }
//
// if (KLAB.NETWORK.getAuthenticationEndpoint() != null) {
//
// RESTUser user = (RESTUser) RESTUser
// .authenticateFromToken(KLAB.NETWORK.getAuthenticationEndpoint(), uAuth);
// if (user != null) {
// _authorized.put(uAuth, user);
// return user;
// }
// }
//
// return null;
// }
//
// public Collection getSessionIdsForUser(IUser user) {
//
// List ret = new ArrayList();
// for (String id : _sessions.keySet()) {
// if (_sessions.get(id).getUser().equals(user)) {
// ret.add(id);
// }
// }
// return ret;
// }
// }