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

org.integratedmodelling.engine.rest.BaseRESTService 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.io.File;
// import java.io.IOException;
// import java.util.ArrayList;
// import java.util.Date;
// import java.util.HashMap;
// import java.util.HashSet;
// import java.util.List;
// import java.util.Map;
// import java.util.Set;
//
// import org.integratedmodelling.api.runtime.ILegacySession;
// import org.integratedmodelling.collections.Pair;
// import org.integratedmodelling.common.configuration.KLAB;
// import org.integratedmodelling.common.network.Endpoints;
// import org.integratedmodelling.common.utils.MiscUtilities;
// import org.integratedmodelling.exceptions.ThinklabAuthorizationException;
// import org.integratedmodelling.exceptions.ThinklabException;
// import org.integratedmodelling.exceptions.ThinklabIOException;
// import org.integratedmodelling.exceptions.ThinklabResourceNotFoundException;
// import org.integratedmodelling.list.Escape;
// import org.json.JSONException;
// import org.restlet.data.Form;
// import org.restlet.data.MediaType;
// import org.restlet.data.Method;
// import org.restlet.data.Parameter;
// import org.restlet.ext.json.JsonRepresentation;
// import org.restlet.representation.Representation;
// import org.restlet.representation.Variant;
// import org.restlet.resource.Get;
// import org.restlet.resource.Post;
// import org.restlet.resource.ResourceException;
// import org.restlet.resource.ServerResource;
// import org.restlet.util.Series;
//
// import com.google.common.collect.ImmutableMap;
//
/// **
// * Default resource handler always responds JSON, with fields pointing to results or
// * further resource URNs. Results are automatically processed into JSON so the subclasses
// * may respond what they like in their process() method.
// *
// * @author Ferdinando
// *
// */
// public abstract class BaseRESTService extends ServerResource {
//
// /*
// * Keys for the map resulting from parsing the headers, found in authInfo if passed.
// */
// public static final String AUTHORIZED_USER = "AuthorizedUser"; // points
// // to a
// // IUser
// public static final String AUTHORIZED_SESSION = "AuthorizedSession"; // points
// // to a
// // ISession
// public static final String REQUESTER_GROUPS = "RequesterGroups"; // points
// // to a
// // Set
// public static final String REQUESTER_ROLES = "RequesterRoles"; // points
// // to a
// // Set
//
// // points to a string we can use for engine calls at the network's authentication point.
// public static final String USER_AUTHENTICATION_TOKEN = "UserToken";
//
// ArrayList _context = new ArrayList<>();
// HashMap _query = new HashMap<>();
// Date _start = null;
// private ArrayList> _downloads = new ArrayList<>();
// boolean _processed = false;
//
// public BaseRESTService() {
// final Set allowedMethods = new HashSet();
// allowedMethods.add(Method.POST);
// getVariants().add(new Variant(MediaType.TEXT_ALL));
// setAnnotated(true);
// setNegotiated(false);
// setAllowedMethods(allowedMethods);
// }
//
// public Map getRecognizedHeaders() throws ThinklabException {
//
// Map ret = new HashMap<>();
// Series headers = (Series) getRequestAttributes().get("org.restlet.http.headers");
//
// String eIden = headers.getFirstValue(Endpoints.CALLING_ENGINE_KEY_HEADER);
// String eAuth = headers.getFirstValue(Endpoints.RECEIVING_ENGINE_KEY_HEADER);
// String aAuth = headers.getFirstValue(Endpoints.ADMIN_AUTHORIZATION_HEADER);
// String sAuth = headers.getFirstValue(Endpoints.SESSION_AUTHORIZATION_HEADER);
// String groups = headers.getFirstValue(Endpoints.REQUESTER_GROUPS_HEADER);
// String roles = headers.getFirstValue(Endpoints.REQUESTER_ROLES_HEADER);
// String uname = headers.getFirstValue(Endpoints.USERNAME_INFO_HEADER);
//
// if (eIden != null) {
// /*
// * this just gets there
// */
// ret.put(Endpoints.CALLING_ENGINE_KEY_HEADER, eIden);
// }
//
// if (uname != null) {
// if (KLAB.NETWORK.isPersonal()) {
// if (!uname.equals(KLAB.NAME)) {
// throw new ThinklabAuthorizationException("user in request does not match the engine user: possible
/// intrusion attempt");
// }
// ret.put(AUTHORIZED_USER, KLAB.NETWORK.getUser());
// }
// ret.put(Endpoints.USERNAME_INFO_HEADER, uname);
// }
//
// if (eAuth != null) {
//
// /*
// * engine must match the passed authorization key. For now use the certified engine key - later
// * we should make this implement a temporary token scheme.
// */
// if (!KLAB.NETWORK.getKey().equals(eAuth)) {
// throw new ThinklabAuthorizationException(KLAB.NAME
// + ": cannot authorize engine services with the provided authentication.");
// }
//
// ret.put(Endpoints.RECEIVING_ENGINE_KEY_HEADER, "Ok");
// }
//
// if (aAuth != null) {
//
// /*
// * engine must match the passed authorization key. For now use the certified engine key - later
// * we should make this implement a temporary token scheme.
// */
// if (!KLAB.CONFIG.getAdminKey().equals(aAuth)) {
// throw new ThinklabAuthorizationException(KLAB.NAME
// + ": cannot authorize administration services with the credentials provided.");
// }
//
// ret.put(Endpoints.ADMIN_AUTHORIZATION_HEADER, "Ok");
// }
//
// if (sAuth != null) {
//
// ILegacySession session = RESTManager.get().getSession(sAuth);
// if (session == null) {
// throw new ThinklabAuthorizationException(KLAB.NAME
// + ": cannot authorize session services: session invalid or expired.");
// }
//
// ret.put(AUTHORIZED_SESSION, session);
// }
//
// if (groups != null) {
//
// Set grps = new HashSet<>();
// for (String s : groups.split(",")) {
// grps.add(s);
// }
// ret.put(REQUESTER_GROUPS, grps);
// }
//
// if (roles != null) {
//
// Set rols = new HashSet<>();
// for (String s : roles.split(",")) {
// rols.add(s);
// }
// ret.put(REQUESTER_ROLES, rols);
// }
//
// return ret;
// }
//
// /**
// * Redefine and skip the Restlet annotations.
// * FIXME have this return objects and ignore JSON; handle JSON translation transparently.
// *
// * @param entity
// * @return
// * @throws Exception
// */
// @Get
// public Representation serviceGET(Representation entity) throws Exception {
//
// Representation ret = null;
// try {
// ret = JSONserializer.wrap(process(getArguments(), getRecognizedHeaders()));
// } catch (Throwable e) {
// KLAB.error(e);
// ret = new JsonRepresentation(JSONserializer.wrapException(e));
// }
// return ret;
// }
//
// protected abstract Object process(Map arguments, Map authInfo)
// throws ThinklabException;
//
// @Post
// public Representation servicePOST(Representation entity) throws Exception {
//
// Representation ret = null;
// try {
// ret = JSONserializer.wrap(process(getPOSTArguments(entity), getRecognizedHeaders()));
// } catch (Throwable e) {
// KLAB.error(e);
// ret = new JsonRepresentation(JSONserializer.wrapException(e));
// }
// return ret;
// }
//
// private Map getPOSTArguments(Representation entity) {
// _processed = true;
// Form form = new Form(entity);
// for (Parameter parameter : form) {
// _query.put(parameter.getName(), parameter.getValue());
// }
// return _query;
// }
//
// // /**
// // * Call this one to ensure that a restricted command is allowed for the
// // * current user. The actual session user is checked against the requested
// // * privilege. If RESTManager returns true to allowPrivilegedLocalConnection
// // * (currently always false) any connection coming from localhost is allowed
// // * privileged access.
// // *
// // * @param concept the user role required for the command. Must resolve to a
// // * valid concept.
// // * @throws ThinklabException if the user is not allowed to run the command or
// // * is undefined
// // */
// // protected void checkPrivileges(String neededRole) throws ThinklabException {
// //
// // String domain = getRequest().getResourceRef().getHostDomain();
// // boolean isLocal = (domain != null && (domain.equals("127.0.0.1") || domain.equals("localhost")));
// //
// // if (isLocal && RESTManager.get().allowPrivilegedLocalConnections())
// // return;
// //
// // if (getSession() == null) {
// // throw new ThinklabAuthorizationException("no user privileges for command " + getServiceName());
// // }
// //
// // IUser user = getSession().getUser();
// // if (user == null || !user.getRoles().contains(neededRole)) {
// // throw new ThinklabAuthorizationException("insufficient user privileges for command "
// // + getServiceName());
// // }
// // }
//
// protected Object ok() {
// return ImmutableMap.of("_status", "0", "_endtime", new Date().toString());
// }
//
// public String getServiceName() {
// return getRequest().getOriginalRef().getLastSegment();
// }
//
// protected void addDownload(String handle, String filename) {
// _downloads.add(new Pair(filename, handle));
// }
//
// // /**
// // * Takes the session from the session parameter, which must be in all
// // * services that require an active session to operate. If the service is tagged as being able
// // * to work without one, it will be allowed to return null without
// // * error, which of course the service must be ready to handle.
// // *
// // * @throws ThinklabInternalErrorException
// // */
// // public ISession getSession() throws ThinklabException {
// //
// // String id = getArgument("session");
// //
// // if (id == null && !(this instanceof IStatelessService))
// // throw new ThinklabInternalErrorException(getServiceName()
// // + ": REST service call did not specify required session ID");
// //
// // return id == null ? null : RESTManager.get().getSession(id);
// // }
//
// /**
// * Return the file correspondent to the handle previously returned by
// * getFileName() and supposedly uploaded by a client.
// *
// * @param argument
// * @return
// * @throws ThinklabException
// */
// protected File getFileForHandle(String handle, boolean mustExist) throws ThinklabException {
//
// File ret = new File(KLAB.CONFIG.getScratchArea() + File.separator + "rest/tmp" + File.separator
// + handle);
//
// if (mustExist && !ret.exists())
// throw new ThinklabResourceNotFoundException(handle);
//
// return ret;
// }
//
// /**
// * Return a file path and "handle" for a file that will be created and returned to the
// * client to retrieve through receive(handle).
//
// * @param fileName the file the user wants us to create
// * @param session current session
// * @return pair - create file in File, return handle to client using
// * addDownload(handle, fileName)
// * @throws ThinklabException
// */
// public static Pair getFileName(String fileName, String prefixDir) throws ThinklabException {
//
// Pair ret = null;
// File sdir = new File(KLAB.CONFIG.getScratchArea() + File.separator + "rest/tmp" + File.separator
// + prefixDir);
// sdir.mkdirs();
//
// String ext = MiscUtilities.getFileExtension(fileName);
// ext = (ext == null || ext.isEmpty()) ? ".tmp" : ("." + ext);
// try {
// File out = File.createTempFile("upl", ext, sdir);
// String handle = prefixDir + File.separator + MiscUtilities.getFileName(out.toString());
// ret = new Pair(out, handle);
// } catch (IOException e) {
// throw new ThinklabIOException(e);
// }
//
// return ret;
// }
//
// /**
// * Return the elements of the request path after the service identifier, in the same
// * order they have in the URL.
// *
// * @return
// * @throws ThinklabException
// */
// public List getRequestPath() throws ThinklabException {
// if (!_processed)
// processRequest();
// return _context;
// }
//
// /**
// * Get a map of all query arguments, no matter what method was used in the request. Entity is
// * only passed for POST requests.
// *
// * @return
// * @throws ThinklabException
// */
// public HashMap getArguments() throws ThinklabException {
// if (!_processed)
// processRequest();
// return _query;
// }
//
// public String getArgument(String id, String defvalue) throws ThinklabException {
// String ret = getArgument(id);
// return ret == null ? defvalue : ret;
// }
//
// public String getArgument(String id) throws ThinklabException {
// return getArguments().get(id);
// }
//
// private void processRequest() {
//
// Form form = getRequest().getResourceRef().getQueryAsForm();
// for (Parameter parameter : form) {
// _query.put(parameter.getName(), Escape.fromURL(parameter.getValue()));
// }
// _processed = true;
// }
//
// @Override
// protected void doInit() throws ResourceException {
// super.doInit();
// _start = new Date();
// }
//
// @Override
// protected void doRelease() throws ResourceException {
//
// Date date = new Date();
// Representation r = getResponseEntity();
//
// if (r instanceof JsonRepresentation) {
// try {
// ((JsonRepresentation) r).getJsonObject()
// .put("__elapsed", (date.getTime() - _start.getTime()) / 1000.0f);
// ((JsonRepresentation) r).getJsonObject().put("__endTime", date.getTime());
//
// } catch (JSONException e) {
// throw new ResourceException(e);
// }
// }
// super.doRelease();
// }
// }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy